diff --git a/dmp-migration-tool/Docker/dmp-backend.env b/dmp-migration-tool/Docker/dmp-backend.env new file mode 100644 index 000000000..50fb7881d --- /dev/null +++ b/dmp-migration-tool/Docker/dmp-backend.env @@ -0,0 +1 @@ +PROFILE=docker \ No newline at end of file diff --git a/dmp-migration-tool/Dockerfile b/dmp-migration-tool/Dockerfile new file mode 100644 index 000000000..54c70beae --- /dev/null +++ b/dmp-migration-tool/Dockerfile @@ -0,0 +1,23 @@ +FROM maven:3-jdk-11 AS MAVEN_BUILD + + + +COPY pom.xml /build/ +COPY data /build/data/ +COPY elastic /build/elastic/ +#COPY logging /build/logging/ +COPY queryable /build/queryable/ +COPY web /build/web/ + + + +WORKDIR /build/ +RUN mvn package -q + + + +FROM amazoncorretto:11 +WORKDIR /app + +COPY --from=MAVEN_BUILD /build/web/target/web-1.0-SNAPSHOT.jar /app.jar +ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom" ,"-Dspring.profiles.active=${PROFILE}","-jar","/app.jar"] \ No newline at end of file diff --git a/dmp-migration-tool/Dockerfile.CI b/dmp-migration-tool/Dockerfile.CI new file mode 100644 index 000000000..5747c9969 --- /dev/null +++ b/dmp-migration-tool/Dockerfile.CI @@ -0,0 +1,15 @@ +FROM maven:3-openjdk-11 AS MAVEN_BUILD + +COPY pom.xml /build/ +COPY data /build/data/ +COPY elastic /build/elastic/ +COPY queryable /build/queryable/ +COPY web /build/web/ + +WORKDIR /build/ +RUN mvn package + +FROM adoptopenjdk/openjdk11:alpine-jre +WORKDIR /app +COPY --from=MAVEN_BUILD /build/web/target/web-1.0-SNAPSHOT.jar /app/app.jar +ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-Dspring.profiles.active=${PROF}", "-Dspring.config.additional-location=/files/config/", "-cp", "/app/app.jar", "-Dloader.path=/files/repo-jars", "org.springframework.boot.loader.PropertiesLauncher"] diff --git a/dmp-migration-tool/data/pom.xml b/dmp-migration-tool/data/pom.xml new file mode 100644 index 000000000..6c162868f --- /dev/null +++ b/dmp-migration-tool/data/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + + data + 1.0-SNAPSHOT + jar + + + eu.eudat + dmp-backend + 1.0.0-SNAPSHOT + + + + + dmp-backend + queryable + 1.0-SNAPSHOT + + + eu.eudat + elastic + 1.0.0-SNAPSHOT + + + io.swagger + swagger-annotations + 1.5.20 + + + \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/converters/DateToUTCConverter.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/converters/DateToUTCConverter.java new file mode 100644 index 000000000..6748be7c1 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/converters/DateToUTCConverter.java @@ -0,0 +1,48 @@ +package eu.eudat.old.data.converters; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +/** + * Created by ikalyvas on 9/25/2018. + */ +@Converter +public class DateToUTCConverter implements AttributeConverter { + private static final Logger logger = LoggerFactory.getLogger(DateToUTCConverter.class); + + @Override + public Date convertToDatabaseColumn(Date attribute) { + if(attribute == null) return null; + DateFormat formatterIST = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + formatterIST.setTimeZone(TimeZone.getTimeZone("UTC")); + try { + String date = formatterIST.format(attribute); + return formatterIST.parse(date); + } catch (ParseException e) { + logger.error(e.getMessage(), e); + } + return null; + } + + @Override + public Date convertToEntityAttribute(Date dbData) { + if(dbData == null) return null; + DateFormat formatterIST = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + formatterIST.setTimeZone(TimeZone.getTimeZone("UTC")); + try { + String date = formatterIST.format(dbData); + return formatterIST.parse(date); + } catch (ParseException e) { + logger.error(e.getMessage(), e); + } + return null; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/DatabaseAccess.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/DatabaseAccess.java new file mode 100644 index 000000000..bbda433ee --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/DatabaseAccess.java @@ -0,0 +1,22 @@ +package eu.eudat.old.data.dao; + +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.queryable.queryableentity.DataEntity; + + +public class DatabaseAccess { + + public DatabaseAccess(DatabaseService databaseService) { + this.databaseService = databaseService; + } + + private DatabaseService databaseService; + + public DatabaseService getDatabaseService() { + return databaseService; + } + + public void setDatabaseService(DatabaseService databaseService) { + this.databaseService = databaseService; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/DatabaseAccessLayer.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/DatabaseAccessLayer.java new file mode 100644 index 000000000..bc0b46772 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/DatabaseAccessLayer.java @@ -0,0 +1,21 @@ +package eu.eudat.old.data.dao; + + +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.queryableentity.DataEntity; + +import java.util.concurrent.CompletableFuture; + +public interface DatabaseAccessLayer { + T createOrUpdate(T item); + + CompletableFuture createOrUpdateAsync(T item); + + T find(I id); + + T find(I id, String hint); + + void delete(T item); + + QueryableList asQueryable(); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/Criteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/Criteria.java new file mode 100644 index 000000000..e38a72b36 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/Criteria.java @@ -0,0 +1,18 @@ +package eu.eudat.old.data.dao.criteria; + +import io.swagger.annotations.ApiModelProperty; + +public abstract class Criteria { + @ApiModelProperty(value = "like", name = "like", dataType = "String", allowEmptyValue = true, example = "\"\"") + private String like; + + public String getLike() { + return like; + } + + public void setLike(String like) { + this.like = like; + } + + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanBlueprintCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanBlueprintCriteria.java new file mode 100644 index 000000000..cfdbd39dc --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanBlueprintCriteria.java @@ -0,0 +1,16 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.DMPProfile; + +public class DataManagementPlanBlueprintCriteria extends Criteria { + + private Integer status; + + public Integer getStatus() { + return status; + } + public void setStatus(Integer status) { + this.status = status; + } + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanCriteria.java new file mode 100644 index 000000000..b02b728b2 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanCriteria.java @@ -0,0 +1,135 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.DMPProfile; +import eu.eudat.old.data.entities.Grant; + +import java.util.Date; +import java.util.List; +import java.util.UUID; + +public class DataManagementPlanCriteria extends Criteria { + private Date periodStart; + private Date periodEnd; + private DMPProfile profile; + private List grants; + private boolean allVersions; + private List groupIds; + private Integer status; + private List organisations; + private Integer role; + private List collaborators; + private List datasetTemplates; + private boolean isPublic; + private boolean onlyPublic; + private Short grantStatus; + private boolean hasDoi; + + public Date getPeriodStart() { + return periodStart; + } + public void setPeriodStart(Date periodStart) { + this.periodStart = periodStart; + } + + public Date getPeriodEnd() { + return periodEnd; + } + public void setPeriodEnd(Date periodEnd) { + this.periodEnd = periodEnd; + } + + public DMPProfile getProfile() { + return profile; + } + public void setProfile(DMPProfile profile) { + this.profile = profile; + } + + public List getGrants() { + return grants; + } + public void setGrants(List grants) { + this.grants = grants; + } + + public boolean getAllVersions() { + return allVersions; + } + public void setAllVersions(boolean allVersions) { + this.allVersions = allVersions; + } + + public List getGroupIds() { + return groupIds; + } + public void setGroupIds(List groupIds) { + this.groupIds = groupIds; + } + + public Integer getStatus() { + return status; + } + public void setStatus(Integer status) { + this.status = status; + } + + public List getOrganisations() { + return organisations; + } + public void setOrganisations(List organisations) { + this.organisations = organisations; + } + + public Integer getRole() { + return role; + } + public void setRole(Integer role) { + this.role = role; + } + + public List getCollaborators() { + return collaborators; + } + public void setCollaborators(List collaborators) { + this.collaborators = collaborators; + } + + public List getDatasetTemplates() { + return datasetTemplates; + } + public void setDatasetTemplates(List datasetTemplates) { + this.datasetTemplates = datasetTemplates; + } + + public boolean getIsPublic() { + return isPublic; + } + public void setIsPublic(boolean isPublic) { + this.isPublic = isPublic; + } + + public boolean isOnlyPublic() { + return onlyPublic; + } + + public void setOnlyPublic(boolean onlyPublic) { + this.onlyPublic = onlyPublic; + } + + public Short getGrantStatus() { + return grantStatus; + } + + public void setGrantStatus(Short grantStatus) { + this.grantStatus = grantStatus; + } + + public boolean hasDoi() { + return hasDoi; + } + + public void setHasDoi(boolean hasDoi) { + this.hasDoi = hasDoi; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanProfileCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanProfileCriteria.java new file mode 100644 index 000000000..32663ed57 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanProfileCriteria.java @@ -0,0 +1,9 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.DMPProfile; + +/** + * Created by ikalyvas on 3/21/2018. + */ +public class DataManagementPlanProfileCriteria extends Criteria { +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanPublicCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanPublicCriteria.java new file mode 100644 index 000000000..211dcc9fd --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataManagementPlanPublicCriteria.java @@ -0,0 +1,66 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.types.grant.GrantStateType; + +import java.util.List; +import java.util.UUID; + +public class DataManagementPlanPublicCriteria extends Criteria { + private GrantStateType grantStatus; + private List grants; + public List datasetProfile; + private List dmpOrganisations; + private Integer role; + private boolean allVersions; + private List groupIds; + + public GrantStateType getGrantStatus() { + return grantStatus; + } + public void setGrantStatus(GrantStateType grantStatus) { + this.grantStatus = grantStatus; + } + + public List getGrants() { + return grants; + } + public void setGrants(List grants) { + this.grants = grants; + } + + public List getDatasetProfile() { + return datasetProfile; + } + public void setDatasetProfile(List datasetProfile) { + this.datasetProfile = datasetProfile; + } + + public List getDmpOrganisations() { + return dmpOrganisations; + } + public void setDmpOrganisations(List dmpOrganisations) { + this.dmpOrganisations = dmpOrganisations; + } + + public Integer getRole() { + return role; + } + public void setRole(Integer role) { + this.role = role; + } + + public boolean getAllVersions() { + return allVersions; + } + public void setAllVersions(boolean allVersions) { + this.allVersions = allVersions; + } + + public List getGroupIds() { + return groupIds; + } + public void setGroupIds(List groupIds) { + this.groupIds = groupIds; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataRepositoryCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataRepositoryCriteria.java new file mode 100644 index 000000000..3be8df837 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DataRepositoryCriteria.java @@ -0,0 +1,17 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.DataRepository; + +import java.util.UUID; + +public class DataRepositoryCriteria extends Criteria { + + private UUID creationUserId; + + public UUID getCreationUserId() { + return creationUserId; + } + public void setCreationUserId(UUID creationUserId) { + this.creationUserId = creationUserId; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetCriteria.java new file mode 100644 index 000000000..4a0511d3c --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetCriteria.java @@ -0,0 +1,143 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.elastic.entities.Tag; + +import java.util.Date; +import java.util.List; +import java.util.UUID; + + +public class DatasetCriteria extends Criteria { + private Integer status; + private Date periodStart; + private Date periodEnd; + private List dmpIds; + private List tags; + private boolean allVersions; + private UUID profileDatasetId; + private List organisations; + private Integer role; + private List grants; + private List collaborators; + private List datasetTemplates; + private List groupIds; + private Boolean isPublic; + private Short grantStatus; + private boolean hasDoi; + + public boolean getAllVersions() { + return allVersions; + } + public void setAllVersions(boolean allVersions) { + this.allVersions = allVersions; + } + + public Integer getStatus() { + return status; + } + public void setStatus(Integer status) { + this.status = status; + } + + public Date getPeriodStart() { + return periodStart; + } + public void setPeriodStart(Date periodStart) { + this.periodStart = periodStart; + } + + public Date getPeriodEnd() { + return periodEnd; + } + public void setPeriodEnd(Date periodEnd) { + this.periodEnd = periodEnd; + } + + public List getDmpIds() { + return dmpIds; + } + public void setDmpIds(List dmpIds) { + this.dmpIds = dmpIds; + } + + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + public UUID getProfileDatasetId() { + return profileDatasetId; + } + public void setProfileDatasetId(UUID profileDatasetId) { + this.profileDatasetId = profileDatasetId; + } + + public List getOrganisations() { + return organisations; + } + public void setOrganisations(List organisations) { + this.organisations = organisations; + } + + public Integer getRole() { + return role; + } + public void setRole(Integer role) { + this.role = role; + } + + public List getGrants() { + return grants; + } + public void setGrants(List grants) { + this.grants = grants; + } + + public List getCollaborators() { + return collaborators; + } + public void setCollaborators(List collaborators) { + this.collaborators = collaborators; + } + + public List getDatasetTemplates() { + return datasetTemplates; + } + public void setDatasetTemplates(List datasetTemplates) { + this.datasetTemplates = datasetTemplates; + } + + public List getGroupIds() { + return groupIds; + } + public void setGroupIds(List groupIds) { + this.groupIds = groupIds; + } + + public Boolean getIsPublic() { + return isPublic; + } + + public void setIsPublic(Boolean isPublic) { + this.isPublic = isPublic; + } + + public Short getGrantStatus() { + return grantStatus; + } + + public void setGrantStatus(Short grantStatus) { + this.grantStatus = grantStatus; + } + + public boolean hasDoi() { + return hasDoi; + } + + public void setHasDoi(boolean hasDoi) { + this.hasDoi = hasDoi; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetProfileCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetProfileCriteria.java new file mode 100644 index 000000000..77ce28595 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetProfileCriteria.java @@ -0,0 +1,101 @@ +package eu.eudat.old.data.dao.criteria; + + +import eu.eudat.old.data.entities.DescriptionTemplate; + +import java.util.Date; +import java.util.List; +import java.util.UUID; + +public class DatasetProfileCriteria extends Criteria { + + public enum DatasetProfileFilter { + DMPs((short) 0), Datasets((short) 1); + + private short value; + private DatasetProfileFilter(short value) { + this.value = value; + } + public short getValue() { return value; } + + public static DatasetProfileFilter fromInteger(short value) { + switch (value) { + case 0: + return DMPs; + case 1: + return Datasets; + default: + throw new RuntimeException("Unsupported DescriptionTemplate filter"); + } + } + } + + private boolean allVersions; + private List groupIds; + private Short filter; + private UUID userId; + private boolean finalized; + private Integer status; + private Integer role; + private List ids; + private Date periodStart; + + public boolean getAllVersions() { return allVersions; } + public void setAllVersions(boolean allVersions) { this.allVersions = allVersions; } + + public List getGroupIds() { return groupIds; } + public void setGroupIds(List groupIds) { this.groupIds = groupIds; } + + public Short getFilter() { + return filter; + } + public void setFilter(Short filter) { + this.filter = filter; + } + + public UUID getUserId() { + return userId; + } + public void setUserId(UUID userId) { + this.userId = userId; + } + + public boolean getFinalized() { + return finalized; + } + public void setFinalized(boolean finalized) { + this.finalized = finalized; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public Integer getRole() { + return role; + } + + public void setRole(Integer role) { + this.role = role; + } + + public List getIds() { + return ids; + } + + public void setIds(List ids) { + this.ids = ids; + } + + public Date getPeriodStart() { + return periodStart; + } + + public void setPeriodStart(Date periodStart) { + this.periodStart = periodStart; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetProfileWizardCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetProfileWizardCriteria.java new file mode 100644 index 000000000..7fc2f17bd --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetProfileWizardCriteria.java @@ -0,0 +1,18 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.DescriptionTemplate; + +import java.util.UUID; + + +public class DatasetProfileWizardCriteria extends Criteria { + private UUID id; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetPublicCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetPublicCriteria.java new file mode 100644 index 000000000..e8eb86304 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetPublicCriteria.java @@ -0,0 +1,70 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.elastic.entities.Tag; +import eu.eudat.old.types.grant.GrantStateType; + +import java.util.List; +import java.util.UUID; + +/** + * Created by ikalyvas on 10/2/2018. + */ +public class DatasetPublicCriteria extends Criteria{ + private GrantStateType grantStatus; + private List grants; + private List datasetProfile; + private List dmpOrganisations; + private List tags; + private List dmpIds; + private Integer role; + + public GrantStateType getGrantStatus() { + return grantStatus; + } + public void setGrantStatus(GrantStateType grantStatus) { + this.grantStatus = grantStatus; + } + + public List getGrants() { + return grants; + } + public void setGrants(List grants) { + this.grants = grants; + } + + public List getDatasetProfile() { + return datasetProfile; + } + public void setDatasetProfile(List datasetProfile) { + this.datasetProfile = datasetProfile; + } + + public List getDmpOrganisations() { + return dmpOrganisations; + } + public void setDmpOrganisations(List dmpOrganisations) { + this.dmpOrganisations = dmpOrganisations; + } + + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + public List getDmpIds() { + return dmpIds; + } + public void setDmpIds(List dmpIds) { + this.dmpIds = dmpIds; + } + + public Integer getRole() { + return role; + } + public void setRole(Integer role) { + this.role = role; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetWizardUserDmpCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetWizardUserDmpCriteria.java new file mode 100644 index 000000000..fb513f962 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DatasetWizardUserDmpCriteria.java @@ -0,0 +1,17 @@ +package eu.eudat.old.data.dao.criteria; + + +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.UserInfo; + +public class DatasetWizardUserDmpCriteria extends Criteria { + private UserInfo userInfo; + + public UserInfo getUserInfo() { + return userInfo; + } + + public void setUserInfo(UserInfo userInfo) { + this.userInfo = userInfo; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DynamicFieldsCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DynamicFieldsCriteria.java new file mode 100644 index 000000000..bfb839a2b --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/DynamicFieldsCriteria.java @@ -0,0 +1,51 @@ +package eu.eudat.old.data.dao.criteria; + +import java.util.List; + +/** + * Created by ikalyvas on 3/26/2018. + */ +public class DynamicFieldsCriteria extends Criteria { + public static class DynamicFieldDependencyCriteria { + private String property; + private String value; + + public DynamicFieldDependencyCriteria() { + } + + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } + + private String id; + private List dynamicFields; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public List getDynamicFields() { + return dynamicFields; + } + + public void setDynamicFields(List dynamicFields) { + this.dynamicFields = dynamicFields; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/EmailConfirmationCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/EmailConfirmationCriteria.java new file mode 100644 index 000000000..67b5ca172 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/EmailConfirmationCriteria.java @@ -0,0 +1,6 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.EmailConfirmation; + +public class EmailConfirmationCriteria extends Criteria{ +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ExternalDatasetCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ExternalDatasetCriteria.java new file mode 100644 index 000000000..9ff2bb9cb --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ExternalDatasetCriteria.java @@ -0,0 +1,15 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.ExternalDataset; +import java.util.UUID; + +public class ExternalDatasetCriteria extends Criteria { + private UUID creationUserId; + + public UUID getCreationUserId() { + return creationUserId; + } + public void setCreationUserId(UUID creationUserId) { + this.creationUserId = creationUserId; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/FunderCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/FunderCriteria.java new file mode 100644 index 000000000..df848b339 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/FunderCriteria.java @@ -0,0 +1,34 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.Funder; + +import java.util.Date; + +public class FunderCriteria extends Criteria { + private String reference; + private String exactReference; + private Date periodStart; + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public String getExactReference() { + return exactReference; + } + + public void setExactReference(String exactReference) { + this.exactReference = exactReference; + } + + public Date getPeriodStart() { + return periodStart; + } + + public void setPeriodStart(Date periodStart) { + this.periodStart = periodStart; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/GrantCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/GrantCriteria.java new file mode 100644 index 000000000..cbde37d7a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/GrantCriteria.java @@ -0,0 +1,82 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.Grant; + +import java.util.Date; + +public class GrantCriteria extends Criteria { + private Date periodStart; + private Date periodEnd; + private String reference; + private Integer grantStateType; + private boolean isPublic; + private String funderId; + private String funderReference; + private String exactReference; + private boolean isActive; + + public Date getPeriodStart() { + return periodStart; + } + public void setPeriodStart(Date periodStart) { + this.periodStart = periodStart; + } + + public Date getPeriodEnd() { + return periodEnd; + } + public void setPeriodEnd(Date periodEnd) { + this.periodEnd = periodEnd; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public Integer getGrantStateType() { + return grantStateType; + } + public void setGrantStateType(Integer grantStateType) { + this.grantStateType = grantStateType; + } + + public boolean isPublic() { + return isPublic; + } + public void setPublic(boolean aPublic) { + isPublic = aPublic; + } + + public String getFunderId() { + return funderId; + } + public void setFunderId(String funderId) { + this.funderId = funderId; + } + + public String getFunderReference() { + return funderReference; + } + public void setFunderReference(String funderReference) { + this.funderReference = funderReference; + } + + public String getExactReference() { + return exactReference; + } + + public void setExactReference(String exactReference) { + this.exactReference = exactReference; + } + + public boolean isActive() { + return isActive; + } + + public void setActive(boolean active) { + isActive = active; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/InvitationCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/InvitationCriteria.java new file mode 100644 index 000000000..bcb9625a5 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/InvitationCriteria.java @@ -0,0 +1,6 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.Invitation; + +public class InvitationCriteria extends Criteria { +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/LockCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/LockCriteria.java new file mode 100644 index 000000000..2cdc14020 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/LockCriteria.java @@ -0,0 +1,38 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.Lock; +import eu.eudat.old.data.entities.UserInfo; + +import java.util.Date; +import java.util.UUID; + +public class LockCriteria extends Criteria { + + private UUID target; + private UserInfo lockedBy; + private Date touchedAt; + + public UUID getTarget() { + return target; + } + + public void setTarget(UUID target) { + this.target = target; + } + + public UserInfo getLockedBy() { + return lockedBy; + } + + public void setLockedBy(UserInfo lockedBy) { + this.lockedBy = lockedBy; + } + + public Date getTouchedAt() { + return touchedAt; + } + + public void setTouchedAt(Date touchedAt) { + this.touchedAt = touchedAt; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/NotificationCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/NotificationCriteria.java new file mode 100644 index 000000000..11d4de3be --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/NotificationCriteria.java @@ -0,0 +1,26 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.enumeration.notification.NotifyState; +import eu.eudat.old.data.enumeration.notification.ActiveStatus; + +public class NotificationCriteria { + + private ActiveStatus isActive; + private NotifyState notifyState; + + public ActiveStatus getIsActive() { + return isActive; + } + + public void setIsActive(ActiveStatus isActive) { + this.isActive = isActive; + } + + public NotifyState getNotifyState() { + return notifyState; + } + + public void setNotifyState(NotifyState notifyState) { + this.notifyState = notifyState; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/OrganisationCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/OrganisationCriteria.java new file mode 100644 index 000000000..db3448cae --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/OrganisationCriteria.java @@ -0,0 +1,31 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.Organisation; + +public class OrganisationCriteria extends Criteria { + private String labelLike; + private Boolean isPublic; + private boolean isActive; + + 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; + } + + public boolean isActive() { + return isActive; + } + + public void setActive(boolean active) { + isActive = active; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ProjectCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ProjectCriteria.java new file mode 100644 index 000000000..707b46076 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ProjectCriteria.java @@ -0,0 +1,34 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.Project; + +import java.util.Date; + +public class ProjectCriteria extends Criteria { + private String reference; + private String exactReference; + private Date periodStart; + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public String getExactReference() { + return exactReference; + } + + public void setExactReference(String exactReference) { + this.exactReference = exactReference; + } + + public Date getPeriodStart() { + return periodStart; + } + + public void setPeriodStart(Date periodStart) { + this.periodStart = periodStart; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/RegistryCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/RegistryCriteria.java new file mode 100644 index 000000000..061d98032 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/RegistryCriteria.java @@ -0,0 +1,17 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.Registry; + +import java.util.UUID; + +public class RegistryCriteria extends Criteria { + + private UUID creationUserId; + + public UUID getCreationUserId() { + return creationUserId; + } + public void setCreationUserId(UUID creationUserId) { + this.creationUserId = creationUserId; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/RequestItem.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/RequestItem.java new file mode 100644 index 000000000..94138bd2f --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/RequestItem.java @@ -0,0 +1,16 @@ +package eu.eudat.old.data.dao.criteria; + +/** + * Created by ikalyvas on 3/26/2018. + */ +public class RequestItem { + T criteria; + + public T getCriteria() { + return criteria; + } + + public void setCriteria(T criteria) { + this.criteria = criteria; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ResearcherCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ResearcherCriteria.java new file mode 100644 index 000000000..b1a5130d1 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ResearcherCriteria.java @@ -0,0 +1,35 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.Researcher; + +import java.util.Date; + +public class ResearcherCriteria extends Criteria { + private String name; + private String reference; + private Date periodStart; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getReference() { + return reference; + } + + public void setReference(String reference) { + this.reference = reference; + } + + public Date getPeriodStart() { + return periodStart; + } + + public void setPeriodStart(Date periodStart) { + this.periodStart = periodStart; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ServiceCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ServiceCriteria.java new file mode 100644 index 000000000..192304f81 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/ServiceCriteria.java @@ -0,0 +1,17 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.Service; + +import java.util.UUID; + +public class ServiceCriteria extends Criteria { + + private UUID creationUserId; + + public UUID getCreationUserId() { + return creationUserId; + } + public void setCreationUserId(UUID creationUserId) { + this.creationUserId = creationUserId; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/UserInfoCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/UserInfoCriteria.java new file mode 100644 index 000000000..1913f511c --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/UserInfoCriteria.java @@ -0,0 +1,33 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.UserInfo; + +import java.util.List; + + +public class UserInfoCriteria extends Criteria { + private String email; + private List appRoles; + private String collaboratorLike; + + public List getAppRoles() { + return appRoles; + } + public void setAppRoles(List appRoles) { + this.appRoles = appRoles; + } + + 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; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/UserRoleCriteria.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/UserRoleCriteria.java new file mode 100644 index 000000000..ab672febf --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/criteria/UserRoleCriteria.java @@ -0,0 +1,20 @@ +package eu.eudat.old.data.dao.criteria; + +import eu.eudat.old.data.entities.UserRole; + +import java.util.List; + +/** + * Created by ikalyvas on 2/1/2018. + */ +public class UserRoleCriteria extends Criteria { + private List appRoles; + + public List getAppRoles() { + return appRoles; + } + + public void setAppRoles(List appRoles) { + this.appRoles = appRoles; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/databaselayer/context/DatabaseContext.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/databaselayer/context/DatabaseContext.java new file mode 100644 index 000000000..8a944ad16 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/databaselayer/context/DatabaseContext.java @@ -0,0 +1,49 @@ +package eu.eudat.old.data.dao.databaselayer.context; + +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.jpa.hibernatequeryablelist.QueryableHibernateList; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceContext; + + +@Repository("databaseCtx") +public class DatabaseContext { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + public DatabaseContext(EntityManagerFactory entityManagerFactory) { + this.entityManager = entityManagerFactory.createEntityManager(); + } + + public QueryableList getQueryable(Class type) { + return new QueryableHibernateList<>(this.entityManager, type).setEntity(type); + } + + @Transactional + public T createOrUpdate(T item, Class type) { + EntityManager entityManager = this.entityManager; + if (item.getKeys() != null) { + T oldItem = entityManager.find(type, item.getKeys()); + if (oldItem != null) { + oldItem.update(item); + entityManager.merge(oldItem); + return oldItem; + } else { + entityManager.persist(item); + } + } else entityManager.persist(item); + return item; + } + + public void delete(T item) { + this.entityManager.remove(item); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/databaselayer/service/DatabaseService.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/databaselayer/service/DatabaseService.java new file mode 100644 index 000000000..ecad37a81 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/databaselayer/service/DatabaseService.java @@ -0,0 +1,41 @@ +package eu.eudat.old.data.dao.databaselayer.service; + + +import eu.eudat.old.data.dao.databaselayer.context.DatabaseContext; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import java.util.Set; + + +@Service("databaseService") +public class DatabaseService { + + private DatabaseContext databaseCtx; + + @Autowired + public DatabaseService(DatabaseContext databaseCtx) { + this.databaseCtx = databaseCtx; + } + + public QueryableList getQueryable(Class tClass) { + return this.databaseCtx.getQueryable(tClass); + } + + public QueryableList getQueryable(Set hints, Class tClass) { + return this.databaseCtx.getQueryable(tClass); + } + + @Transactional + public T createOrUpdate(T item, Class tClass) { + return this.databaseCtx.createOrUpdate(item, tClass); + } + + public void delete(T item) { + this.databaseCtx.delete(item); + } + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ContentDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ContentDao.java new file mode 100644 index 000000000..fd9cc8f25 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ContentDao.java @@ -0,0 +1,12 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.Content; + +import java.util.UUID; + +/** + * Created by ikalyvas on 3/16/2018. + */ +public interface ContentDao extends DatabaseAccessLayer { +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ContentDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ContentDaoImpl.java new file mode 100644 index 000000000..db4468c8a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ContentDaoImpl.java @@ -0,0 +1,55 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.Content; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * Created by ikalyvas on 3/16/2018. + */ +@Service("contentDao") +public class ContentDaoImpl extends DatabaseAccess implements ContentDao { + + @Autowired + public ContentDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public Content createOrUpdate(Content item) { + return this.getDatabaseService().createOrUpdate(item, Content.class); + } + + @Override + @Async + public CompletableFuture createOrUpdateAsync(Content item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public Content find(UUID id) { + return this.getDatabaseService().getQueryable(Content.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public Content find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + + @Override + public void delete(Content item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Content.class); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPDao.java new file mode 100644 index 000000000..945356035 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPDao.java @@ -0,0 +1,21 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.criteria.DataManagementPlanCriteria; +import eu.eudat.old.data.dao.criteria.DatasetWizardUserDmpCriteria; + +import java.util.List; +import java.util.UUID; + +public interface DMPDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(DataManagementPlanCriteria criteria); + + QueryableList getUserDmps(DatasetWizardUserDmpCriteria datasetWizardAutocompleteRequest, UserInfo userInfo); + + QueryableList getAuthenticated(QueryableList query, UUID principalId, List roles); + +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPDaoImpl.java new file mode 100644 index 000000000..f58ec313a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPDaoImpl.java @@ -0,0 +1,151 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; +import eu.eudat.old.data.dao.criteria.DataManagementPlanCriteria; +import eu.eudat.old.data.dao.criteria.DatasetWizardUserDmpCriteria; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.types.grant.GrantStateType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.transaction.Transactional; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("dMPDao") +public class DMPDaoImpl extends DatabaseAccess implements DMPDao { + + @Autowired + public DMPDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(DataManagementPlanCriteria criteria) { + QueryableList query = getDatabaseService().getQueryable(DMP.getHints(), DMP.class); + if (criteria.getLike() != null && !criteria.getLike().isEmpty()) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"), + builder.like(builder.upper(root.get("description")), "%" + criteria.getLike().toUpperCase() + "%"))); + if (criteria.getPeriodEnd() != null) + query.where((builder, root) -> builder.lessThan(root.get("created"), criteria.getPeriodEnd())); + if (criteria.getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThan(root.get("created"), criteria.getPeriodStart())); + if (criteria.getProfile() != null) + query.where((builder, root) -> builder.equal(root.get("profile"), criteria.getProfile())); + if (criteria.getGrants() != null && !criteria.getGrants().isEmpty()) + query.where(((builder, root) -> root.get("grant").in(criteria.getGrants()))); + if (!criteria.getAllVersions()) + query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("version"), + query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.and( + builder1.equal(externalRoot.get("groupId"), nestedRoot.get("groupId")), + builder1.notEqual(nestedRoot.get("status"), DMP.DMPStatus.DELETED.getValue())), 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.getIsPublic()) { + query.where(((builder, root) -> builder.equal(root.get("isPublic"), criteria.getIsPublic()))); + } + /*if (criteria.getRole() != null) { + if (criteria.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())) { + query.where((builder, root) -> builder.equal(root.join("users", JoinType.LEFT).get("role"), UserDMP.UserDMPRoles.OWNER.getValue())); + } else if (criteria.getRole().equals(UserDMP.UserDMPRoles.USER.getValue())) { + query.where((builder, root) -> builder.equal(root.join("users", JoinType.LEFT).get("role"), UserDMP.UserDMPRoles.USER.getValue())); + } + }*/ + if (criteria.getOrganisations() != null && !criteria.getOrganisations().isEmpty()) { + query.where((builder, root) -> root.join("organisations").get("reference").in(criteria.getOrganisations())); + } + if (criteria.getCollaborators() != null && !criteria.getCollaborators().isEmpty()) { + query.where((builder, root) -> root.join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id").in(criteria.getCollaborators())); + } + if (criteria.getDatasetTemplates() != null && !criteria.getDatasetTemplates().isEmpty()) { + query.where((builder, root) -> root.join("associatedDmps", JoinType.LEFT).get("datasetprofile").get("id").in(criteria.getDatasetTemplates())); + } + if (criteria.getGrantStatus() != null) { + if (criteria.getGrantStatus().equals(GrantStateType.FINISHED.getValue().shortValue())) + query.where((builder, root) -> builder.lessThan(root.get("grant").get("enddate"), new Date())); + if (criteria.getGrantStatus().equals(GrantStateType.ONGOING.getValue().shortValue())) + query.where((builder, root) -> + builder.or(builder.greaterThan(root.get("grant").get("enddate"), new Date()) + , builder.isNull(root.get("grant").get("enddate")))); + } + + if (criteria.hasDoi()) { + query.where((builder, root) -> builder.not(builder.isNull(root.join("dois").get("id")))); + } + query.where((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue())); + return query; + } + + public QueryableList getAuthenticated(QueryableList query, UUID principal, List roles) { + if (roles != null && !roles.isEmpty()) { + query.where((builder, root) -> { + Join userJoin = root.join("users", JoinType.LEFT); + return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal), userJoin.get("role").in(roles)); + }); + } else { + query.where((builder, root) -> builder.equal(root.join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), principal)); + } + + return query; + } + + @Override + @Transactional + public DMP createOrUpdate(DMP item) { + return this.getDatabaseService().createOrUpdate(item, DMP.class); + } + + @Override + public DMP find(UUID id) { + return getDatabaseService().getQueryable(DMP.class).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle(); + } + + @Override + public QueryableList getUserDmps(DatasetWizardUserDmpCriteria datasetWizardUserDmpCriteria, UserInfo userInfo) { + QueryableList query = getDatabaseService().getQueryable(DMP.class).where((builder, root) -> builder.or(builder.equal(root.get("creator"), userInfo), builder.isMember(userInfo, root.get("users")))); + if (datasetWizardUserDmpCriteria.getLike() != null && !datasetWizardUserDmpCriteria.getLike().isEmpty()) { + query.where((builder, root) -> builder.like(root.get("label"), "%" + datasetWizardUserDmpCriteria.getLike() + "%")); + } + return query; + } + + @Override + public void delete(DMP item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(DMP.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(DMP item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public DMP find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPProfileDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPProfileDao.java new file mode 100644 index 000000000..9d49b1593 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPProfileDao.java @@ -0,0 +1,20 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.dao.criteria.DataManagementPlanBlueprintCriteria; +import eu.eudat.old.data.dao.criteria.DataManagementPlanProfileCriteria; +import eu.eudat.old.data.entities.DMPProfile; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +/** + * Created by ikalyvas on 3/21/2018. + */ +public interface DMPProfileDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(DataManagementPlanProfileCriteria criteria); + + QueryableList getWithCriteriaBlueprint(DataManagementPlanBlueprintCriteria criteria); + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPProfileDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPProfileDaoImpl.java new file mode 100644 index 000000000..cec8f41d1 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DMPProfileDaoImpl.java @@ -0,0 +1,85 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.criteria.DataManagementPlanBlueprintCriteria; +import eu.eudat.old.data.dao.criteria.DataManagementPlanProfileCriteria; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.DMPProfile; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * Created by ikalyvas on 3/21/2018. + */ +@Service("dmpProfileDao") +public class DMPProfileDaoImpl extends DatabaseAccess implements DMPProfileDao { + + @Autowired + public DMPProfileDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(DMPProfile item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public DMPProfile createOrUpdate(DMPProfile item) { + return this.getDatabaseService().createOrUpdate(item, DMPProfile.class); + } + + + @Override + public DMPProfile find(UUID id) { + return getDatabaseService().getQueryable(DMPProfile.class).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle(); + } + + @Override + public DMPProfile find(UUID id, String hint) { + return getDatabaseService().getQueryable(DMPProfile.class).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle(); + } + + @Override + public void delete(DMPProfile item) { + this.getDatabaseService().delete(item); + } + + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(DMPProfile.class); + } + + + @Override + public QueryableList getWithCriteria(DataManagementPlanProfileCriteria criteria) { + QueryableList 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; + } + + @Override + public QueryableList getWithCriteriaBlueprint(DataManagementPlanBlueprintCriteria criteria){ + QueryableList 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() + "%")); + if (criteria.getStatus() != null) { + if (criteria.getStatus() == DMPProfile.Status.FINALIZED.getValue()) { + query.where((builder, root) -> builder.equal(root.get("status"), DMPProfile.Status.FINALIZED.getValue())); + } else if (criteria.getStatus() == DMPProfile.Status.SAVED.getValue()) { + query.where((builder, root) -> builder.equal(root.get("status"), DMPProfile.Status.SAVED.getValue())); + } + } + query.where(((builder, root) -> builder.notEqual(root.get("status"), DMPProfile.Status.DELETED.getValue()))); + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DataRepositoryDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DataRepositoryDao.java new file mode 100644 index 000000000..e88ca2fa0 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DataRepositoryDao.java @@ -0,0 +1,12 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.DataRepositoryCriteria; +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.DataRepository; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public interface DataRepositoryDao extends DatabaseAccessLayer { + QueryableList getWithCriteria(DataRepositoryCriteria criteria); +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DataRepositoryDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DataRepositoryDaoImpl.java new file mode 100644 index 000000000..bd9f81828 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DataRepositoryDaoImpl.java @@ -0,0 +1,65 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.DataRepositoryCriteria; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.DataRepository; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("dataRepositoryDao") +public class DataRepositoryDaoImpl extends DatabaseAccess implements DataRepositoryDao { + + @Autowired + public DataRepositoryDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(DataRepositoryCriteria criteria) { + QueryableList query = this.getDatabaseService().getQueryable(DataRepository.class); + if (criteria.getLike() != null) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("reference")), "%" + criteria.getLike().toUpperCase() + "%"), + builder.equal(builder.upper(root.get("label")), criteria.getLike().toUpperCase()))); + if (criteria.getCreationUserId() != null) + query.where((builder, root) -> builder.equal(root.get("creationUser").get("id"), criteria.getCreationUserId())); + return query; + } + + @Override + public DataRepository find(UUID id) { + return this.getDatabaseService().getQueryable(DataRepository.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public DataRepository createOrUpdate(DataRepository item) { + return getDatabaseService().createOrUpdate(item, DataRepository.class); + } + + @Override + @Async + public CompletableFuture createOrUpdateAsync(DataRepository item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public DataRepository find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + + @Override + public void delete(DataRepository item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(DataRepository.class); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetDao.java new file mode 100644 index 000000000..04a89667b --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetDao.java @@ -0,0 +1,22 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.dao.criteria.DatasetCriteria; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; + +import java.util.List; +import java.util.UUID; + +public interface DatasetDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(DatasetCriteria criteria); + + QueryableList filterFromElastic(DatasetCriteria criteria, List ids); + + QueryableList getAuthenticated(QueryableList query, UserInfo principal, List roles); + + Dataset isPublicDataset(UUID id); + +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetDaoImpl.java new file mode 100644 index 000000000..c0320dfb7 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetDaoImpl.java @@ -0,0 +1,152 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.DatasetCriteria; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.SelectionField; +import eu.eudat.old.types.grant.GrantStateType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("datasetDao") +public class DatasetDaoImpl extends DatabaseAccess implements DatasetDao { + + @Autowired + public DatasetDaoImpl(DatabaseService databaseService) { super(databaseService); } + + @Override + public QueryableList getWithCriteria(DatasetCriteria criteria) { + QueryableList query = getDatabaseService().getQueryable(Dataset.getHints(), Dataset.class); + if (criteria.getIsPublic() != null && criteria.getIsPublic()) { + query.where((builder, root) -> builder.equal(root.get("dmp").get("isPublic"), true)); + query.where((builder, root) -> builder.equal(root.get("status"), Dataset.Status.FINALISED.getValue())); + /*query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), + query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("dmp").get("groupId"), nestedRoot.get("dmp").get("groupId")), + Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:version")), String.class)));*/ + } + if (criteria.getLike() != null && !criteria.getLike().isEmpty()) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"), + builder.like(builder.upper(root.get("description")), "%" + criteria.getLike().toUpperCase() + "%"))); + if (criteria.getStatus() != null) + query.where((builder, root) -> builder.equal(root.get("status"), criteria.getStatus())); + if (criteria.getProfileDatasetId() != null) + query.where((builder, root) -> builder.equal(root.get("profile").get("id"), criteria.getProfileDatasetId())); + if (criteria.getPeriodEnd() != null) + query.where((builder, root) -> builder.lessThan(root.get("created"), criteria.getPeriodEnd())); + if (criteria.getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThan(root.get("created"), criteria.getPeriodStart())); + if (!criteria.getAllVersions()) + query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.and(builder1.equal(externalRoot.get("dmp").get("groupId"), nestedRoot.get("dmp").get("groupId")), builder1.notEqual(nestedRoot.get("dmp").get("status"), DMP.DMPStatus.DELETED.getValue())), Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:version")), String.class))); + if (criteria.getGroupIds() != null && !criteria.getGroupIds().isEmpty()) + query.where((builder, root) -> root.get("dmp").get("groupId").in(criteria.getGroupIds())); + if (criteria.getDmpIds() != null && !criteria.getDmpIds().isEmpty()) + query.where((builder, root) -> root.get("dmp").get("id").in(criteria.getDmpIds())); + /*if (criteria.getRole() != null) { + query.where((builder, root) -> builder.equal(root.join("dmp").join("users").get("role"), criteria.getRole())); + } else { + query.where((builder, root) -> root.join("dmp").join("users").get("role").in(UserDMP.UserDMPRoles.getAllValues())); + }*/ + if (criteria.getOrganisations() != null && !criteria.getOrganisations().isEmpty()) + query.where((builder, root) -> root.join("dmp").join("organisations").get("reference").in(criteria.getOrganisations())); + if (criteria.getGrants() != null && !criteria.getGrants().isEmpty()) + query.where((builder, root) -> root.join("dmp").join("grant").get("id").in(criteria.getGrants())); + if (criteria.getGrantStatus() != null) { + if (criteria.getGrantStatus().equals(GrantStateType.FINISHED.getValue().shortValue())) + query.where((builder, root) -> builder.lessThan(root.get("dmp").get("grant").get("enddate"), new Date())); + if (criteria.getGrantStatus().equals(GrantStateType.ONGOING.getValue().shortValue())) + query.where((builder, root) -> + builder.or(builder.greaterThan(root.get("dmp").get("grant").get("enddate"), new Date()) + , builder.isNull(root.get("dmp").get("grant").get("enddate")))); + } + if (criteria.getCollaborators() != null && !criteria.getCollaborators().isEmpty()) + query.where((builder, root) -> root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id").in(criteria.getCollaborators())); + if (criteria.getDatasetTemplates() != null && !criteria.getDatasetTemplates().isEmpty()) + query.where((builder, root) -> root.get("profile").get("id").in(criteria.getDatasetTemplates())); + + if (criteria.hasDoi()) { + query.where((builder, root) -> builder.not(builder.isNull(root.join("dmp").join("dois").get("id")))); + } + query.where((builder, root) -> builder.notEqual(root.get("status"), Dataset.Status.DELETED.getValue())); + query.where((builder, root) -> builder.notEqual(root.get("status"), Dataset.Status.CANCELED.getValue())); + return query; + } + + public QueryableList filterFromElastic(DatasetCriteria criteria, List ids) { + QueryableList query = getDatabaseService().getQueryable(Dataset.getHints(), Dataset.class); + + query.where(((builder, root) -> root.get("id").in(ids))); + if (!criteria.getAllVersions()) + query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.and(builder1.equal(externalRoot.get("dmp").get("groupId"), nestedRoot.get("dmp").get("groupId")), builder1.notEqual(nestedRoot.get("dmp").get("status"), DMP.DMPStatus.DELETED.getValue())), Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:version")), String.class))); + + return query; + } + + @Override + public Dataset createOrUpdate(Dataset item) { + return getDatabaseService().createOrUpdate(item, Dataset.class); + } + + @Override + public Dataset find(UUID id) { + return getDatabaseService().getQueryable(Dataset.class) + .where((builder, root) -> builder.and(builder.notEqual(root.get("status"),Dataset.Status.DELETED.getValue()), builder.notEqual(root.get("status"),Dataset.Status.CANCELED.getValue()), builder.equal((root.get("id")), id))).getSingle(); + } + + @Override + public Dataset find(UUID id, String hint) { + return getDatabaseService().getQueryable(Dataset.getHints(), Dataset.class).withHint(hint) + .where((builder, root) -> builder.and(builder.notEqual(root.get("status"),Dataset.Status.DELETED.getValue()), builder.notEqual(root.get("status"),Dataset.Status.CANCELED.getValue()), builder.equal((root.get("id")), id))).getSingle(); + } + + @Override + public Dataset isPublicDataset(UUID id) { + QueryableList 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 getAuthenticated(QueryableList query, UserInfo principal, List roles) { + if (roles != null && !roles.isEmpty()) { + query.where((builder, root) -> { + Join userJoin = root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT); + return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal.getId()), userJoin.get("role").in(roles)); + }); + } else { + query.where((builder, root) -> builder.equal(root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), principal.getId())); + + } + return query; + } + + @Override + public void delete(Dataset item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Dataset.class); + } + + @Async + public CompletableFuture createOrUpdateAsync(Dataset item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetExternalDatasetDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetExternalDatasetDao.java new file mode 100644 index 000000000..dcf38ac08 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetExternalDatasetDao.java @@ -0,0 +1,13 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.entities.DatasetExternalDataset; +import eu.eudat.old.data.dao.DatabaseAccessLayer; + +import java.util.UUID; + +/** + * Created by ikalyvas on 5/22/2018. + */ +public interface DatasetExternalDatasetDao extends DatabaseAccessLayer { + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetExternalDatasetDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetExternalDatasetDaoImpl.java new file mode 100644 index 000000000..5896b16e7 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetExternalDatasetDaoImpl.java @@ -0,0 +1,56 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.DatasetExternalDataset; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * Created by ikalyvas on 5/22/2018. + */ +@Component("datasetExternalDatasetDao") +public class DatasetExternalDatasetDaoImpl extends DatabaseAccess implements DatasetExternalDatasetDao { + + @Autowired + public DatasetExternalDatasetDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public DatasetExternalDataset createOrUpdate(DatasetExternalDataset item) { + return this.getDatabaseService().createOrUpdate(item,DatasetExternalDataset.class); + } + + @Override + public CompletableFuture createOrUpdateAsync(DatasetExternalDataset item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + @Async + public DatasetExternalDataset find(UUID id) { + return getDatabaseService().getQueryable(DatasetExternalDataset.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public DatasetExternalDataset find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + + + @Override + public void delete(DatasetExternalDataset item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(DatasetExternalDataset.class); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetProfileDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetProfileDao.java new file mode 100644 index 000000000..8f616c615 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetProfileDao.java @@ -0,0 +1,24 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.entities.DescriptionTemplateType; +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.dao.criteria.DatasetProfileCriteria; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.queryable.QueryableList; + +import java.util.List; +import java.util.UUID; + +public interface DatasetProfileDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(DatasetProfileCriteria criteria); + + QueryableList getAll(); + + QueryableList getAuthenticated(QueryableList query, UUID principal, List roles); + + List getAllIds(); + + Long countWithType(DescriptionTemplateType type); + +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetProfileDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetProfileDaoImpl.java new file mode 100644 index 000000000..9e72f926f --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetProfileDaoImpl.java @@ -0,0 +1,134 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.data.entities.DescriptionTemplateType; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.criteria.DatasetProfileCriteria; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.SelectionField; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("datasetProfileDao") +public class DatasetProfileDaoImpl extends DatabaseAccess implements DatasetProfileDao { + + @Autowired + public DatasetProfileDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(DatasetProfileCriteria criteria) { + QueryableList query = getDatabaseService().getQueryable(DescriptionTemplate.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.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())); + if (criteria.getFilter() != null && criteria.getUserId() != null) { + if (criteria.getFilter().equals(DatasetProfileCriteria.DatasetProfileFilter.DMPs.getValue())) { + query.initSubQuery(UUID.class).where((builder, root) -> + builder.and(root.get("id").in( + query.subQuery((builder1, root1) -> builder1.equal(root1.join("dmps", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), criteria.getUserId()), + Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id")))), + builder.notEqual(root.get("id"), criteria.getUserId()))); + //query.where(((builder, root) -> builder.equal(root.join("dmps", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), criteria.getUserId()))); + } + if (criteria.getFilter().equals(DatasetProfileCriteria.DatasetProfileFilter.Datasets.getValue())) { + query.initSubQuery(UUID.class).where((builder, root) -> + builder.and(root.get("id").in( + query.subQuery((builder1, root1) -> builder1.equal(root1.join("dataset", JoinType.LEFT).join("dmp", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), criteria.getUserId()), + Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id")))), + builder.notEqual(root.get("id"), criteria.getUserId()))); + } + } + if (criteria.getStatus() != null) { + query.where(((builder, root) -> builder.equal(root.get("status"), criteria.getStatus()))); + } + if (criteria.getIds() != null) { + query.where(((builder, root) -> root.get("id").in(criteria.getIds()))); + } + if (criteria.getFinalized()) { + query.where(((builder, root) -> builder.equal(root.get("status"), DescriptionTemplate.Status.FINALIZED.getValue()))); + } else { + query.where(((builder, root) -> builder.notEqual(root.get("status"), DescriptionTemplate.Status.DELETED.getValue()))); + } + if (criteria.getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThanOrEqualTo(root.get("created"), criteria.getPeriodStart())); + return query; + } + + @Override + public DescriptionTemplate createOrUpdate(DescriptionTemplate item) { + return this.getDatabaseService().createOrUpdate(item, DescriptionTemplate.class); + } + + @Override + public DescriptionTemplate find(UUID id) { + return getDatabaseService().getQueryable(DescriptionTemplate.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public QueryableList getAll() { + return getDatabaseService().getQueryable(DescriptionTemplate.class); + } + + @Override + public List getAllIds(){ + return getDatabaseService().getQueryable(DescriptionTemplate.class).withFields(Collections.singletonList("id")).toList(); + } + + @Override + public void delete(DescriptionTemplate item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(DescriptionTemplate.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(DescriptionTemplate item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public DescriptionTemplate find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + + @Override + public QueryableList getAuthenticated(QueryableList query, UUID principal, List roles) { + if (roles != null && !roles.isEmpty()) { + query.where((builder, root) -> { + Join userJoin = root.join("users", JoinType.LEFT); + return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal), userJoin.get("role").in(roles)); + }); + } else { + query.where((builder, root) -> builder.equal(root.join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), principal)); + } + + return query; + } + + @Override + public Long countWithType(DescriptionTemplateType type) { + return this.getDatabaseService().getQueryable(DescriptionTemplate.class).where((builder, root) -> builder.equal(root.get("type"), type)).count(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetServiceDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetServiceDao.java new file mode 100644 index 000000000..cfdbec078 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetServiceDao.java @@ -0,0 +1,12 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.DatasetService; + +import java.util.UUID; + +/** + * Created by ikalyvas on 5/22/2018. + */ +public interface DatasetServiceDao extends DatabaseAccessLayer { +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetServiceDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetServiceDaoImpl.java new file mode 100644 index 000000000..a5e6663c2 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DatasetServiceDaoImpl.java @@ -0,0 +1,55 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.entities.DatasetService; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * Created by ikalyvas on 5/22/2018. + */ +@Component("datasetServiceDao") +public class DatasetServiceDaoImpl extends DatabaseAccess implements DatasetServiceDao { + + @Autowired + public DatasetServiceDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public DatasetService createOrUpdate(DatasetService item) { + return this.getDatabaseService().createOrUpdate(item, DatasetService.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(DatasetService item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public DatasetService find(UUID id) { + return getDatabaseService().getQueryable(DatasetService.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public DatasetService find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + + @Override + public void delete(DatasetService item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(DatasetService.class); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DescriptionTemplateTypeDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DescriptionTemplateTypeDao.java new file mode 100644 index 000000000..1eb60a24d --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DescriptionTemplateTypeDao.java @@ -0,0 +1,10 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.DescriptionTemplateType; + +import java.util.UUID; + +public interface DescriptionTemplateTypeDao extends DatabaseAccessLayer { + DescriptionTemplateType findFromName(String name); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DescriptionTemplateTypeDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DescriptionTemplateTypeDaoImpl.java new file mode 100644 index 000000000..86651ab94 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DescriptionTemplateTypeDaoImpl.java @@ -0,0 +1,65 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.entities.DescriptionTemplateType; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.transaction.Transactional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("descriptionTemplateTypeDao") +public class DescriptionTemplateTypeDaoImpl extends DatabaseAccess implements DescriptionTemplateTypeDao { + + @Autowired + public DescriptionTemplateTypeDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public DescriptionTemplateType findFromName(String name){ + try { + return this.getDatabaseService().getQueryable(DescriptionTemplateType.class).where((builder, root) -> builder.and(builder.equal(root.get("name"), name), builder.notEqual(root.get("status"), DescriptionTemplateType.Status.DELETED.getValue()))).getSingle(); + } + catch(Exception e){ + return null; + } + } + + @Override + @Transactional + public DescriptionTemplateType createOrUpdate(DescriptionTemplateType item) { + return this.getDatabaseService().createOrUpdate(item, DescriptionTemplateType.class); + } + + @Override + public DescriptionTemplateType find(UUID id) { + return getDatabaseService().getQueryable(DescriptionTemplateType.class).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle(); + } + + @Override + public void delete(DescriptionTemplateType item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(DescriptionTemplateType.class).where((builder, root) -> builder.notEqual((root.get("status")), DescriptionTemplateType.Status.DELETED.getValue())); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(DescriptionTemplateType item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public DescriptionTemplateType find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DmpDatasetProfileDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DmpDatasetProfileDao.java new file mode 100644 index 000000000..b2e2b3917 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DmpDatasetProfileDao.java @@ -0,0 +1,9 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.DMPDatasetProfile; + +import java.util.UUID; + +public interface DmpDatasetProfileDao extends DatabaseAccessLayer { +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DmpDatasetProfileDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DmpDatasetProfileDaoImpl.java new file mode 100644 index 000000000..0cb02ac11 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/DmpDatasetProfileDaoImpl.java @@ -0,0 +1,51 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.DMPDatasetProfile; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Service("dmpDatasetProfileDao") +public class DmpDatasetProfileDaoImpl extends DatabaseAccess implements DmpDatasetProfileDao { + @Autowired + public DmpDatasetProfileDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public DMPDatasetProfile createOrUpdate(DMPDatasetProfile item) { + return this.getDatabaseService().createOrUpdate(item, DMPDatasetProfile.class); + } + + @Override + @Async + public CompletableFuture createOrUpdateAsync(DMPDatasetProfile item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public DMPDatasetProfile find(UUID id) { + return this.getDatabaseService().getQueryable(DMPDatasetProfile.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public DMPDatasetProfile find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + + @Override + public void delete(DMPDatasetProfile item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(DMPDatasetProfile.class); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EmailConfirmationDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EmailConfirmationDao.java new file mode 100644 index 000000000..764ef9662 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EmailConfirmationDao.java @@ -0,0 +1,13 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.EmailConfirmation; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.criteria.EmailConfirmationCriteria; + +import java.util.UUID; + +public interface EmailConfirmationDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(EmailConfirmationCriteria criteria); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EmailConfirmationDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EmailConfirmationDaoImpl.java new file mode 100644 index 000000000..5a6cc9f2a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EmailConfirmationDaoImpl.java @@ -0,0 +1,56 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.criteria.EmailConfirmationCriteria; +import eu.eudat.old.data.entities.EmailConfirmation; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Service("LoginConfirmationEmailDao") +public class EmailConfirmationDaoImpl extends DatabaseAccess implements EmailConfirmationDao { + + @Autowired + public EmailConfirmationDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(EmailConfirmationCriteria criteria) { + return null; + } + + @Override + public EmailConfirmation createOrUpdate(EmailConfirmation item) { + return this.getDatabaseService().createOrUpdate(item, EmailConfirmation.class); + } + + @Override + public CompletableFuture createOrUpdateAsync(EmailConfirmation item) { + return null; + } + + @Override + public EmailConfirmation find(UUID id) { + return this.getDatabaseService().getQueryable(EmailConfirmation.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public EmailConfirmation find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + + @Override + public void delete(EmailConfirmation item) { + throw new UnsupportedOperationException(); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(EmailConfirmation.class); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EntityDoiDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EntityDoiDao.java new file mode 100644 index 000000000..d967160c2 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EntityDoiDao.java @@ -0,0 +1,10 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.EntityDoi; + +import java.util.UUID; + +public interface EntityDoiDao extends DatabaseAccessLayer { + EntityDoi findFromDoi(String doi); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EntityDoiDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EntityDoiDaoImpl.java new file mode 100644 index 000000000..67d95a129 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/EntityDoiDaoImpl.java @@ -0,0 +1,56 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.EntityDoi; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("EntityDoiDao") +public class EntityDoiDaoImpl extends DatabaseAccess implements EntityDoiDao { + + @Autowired + public EntityDoiDaoImpl(DatabaseService databaseService){ + super(databaseService); + } + + + @Override + public EntityDoi createOrUpdate(EntityDoi item) { + return this.getDatabaseService().createOrUpdate(item, EntityDoi.class); + } + + @Override + public CompletableFuture createOrUpdateAsync(EntityDoi item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public EntityDoi find(UUID id) { + return this.getDatabaseService().getQueryable(EntityDoi.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public EntityDoi findFromDoi(String doi) { + return this.getDatabaseService().getQueryable(EntityDoi.class).where((builder, root) -> builder.equal(root.get("doi"), doi)).getSingle(); + } + + @Override + public EntityDoi find(UUID id, String hint) { + return null; + } + + @Override + public void delete(EntityDoi item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(EntityDoi.class); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ExternalDatasetDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ExternalDatasetDao.java new file mode 100644 index 000000000..f61b713e8 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ExternalDatasetDao.java @@ -0,0 +1,15 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.ExternalDatasetCriteria; +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.ExternalDataset; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + + +public interface ExternalDatasetDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(ExternalDatasetCriteria criteria); + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ExternalDatasetDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ExternalDatasetDaoImpl.java new file mode 100644 index 000000000..40e7a0275 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ExternalDatasetDaoImpl.java @@ -0,0 +1,66 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.ExternalDatasetCriteria; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.ExternalDataset; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + + +@Component("externalDatasetDao") +public class ExternalDatasetDaoImpl extends DatabaseAccess implements ExternalDatasetDao { + + @Autowired + public ExternalDatasetDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(ExternalDatasetCriteria criteria) { + QueryableList query = this.getDatabaseService().getQueryable(ExternalDataset.class); + if (criteria.getLike() != null && !criteria.getLike().isEmpty()) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("reference")), "%" + criteria.getLike().toUpperCase() + "%"), + builder.equal(builder.upper(root.get("label")), criteria.getLike().toUpperCase()))); + if (criteria.getCreationUserId() != null) + query.where((builder, root) -> builder.equal(root.join("creationUser").get("id"), criteria.getCreationUserId())); + return query; + } + + @Override + public ExternalDataset createOrUpdate(ExternalDataset item) { + return this.getDatabaseService().createOrUpdate(item, ExternalDataset.class); + } + + @Override + public ExternalDataset find(UUID id) { + return this.getDatabaseService().getQueryable(ExternalDataset.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public void delete(ExternalDataset item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(ExternalDataset.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(ExternalDataset item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public ExternalDataset find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FileUploadDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FileUploadDao.java new file mode 100644 index 000000000..faf4220c9 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FileUploadDao.java @@ -0,0 +1,11 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.FileUpload; + +import java.util.List; +import java.util.UUID; + +public interface FileUploadDao extends DatabaseAccessLayer { + List getFileUploads(UUID entityId); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FileUploadDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FileUploadDaoImpl.java new file mode 100644 index 000000000..2acdc34db --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FileUploadDaoImpl.java @@ -0,0 +1,56 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.entities.FileUpload; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("FileUploadDao") +public class FileUploadDaoImpl extends DatabaseAccess implements FileUploadDao { + + @Autowired + public FileUploadDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public FileUpload createOrUpdate(FileUpload item) { + return getDatabaseService().createOrUpdate(item, FileUpload.class); + } +// + @Override + public CompletableFuture createOrUpdateAsync(FileUpload item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public FileUpload find(UUID id) { + return getDatabaseService().getQueryable(FileUpload.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public List getFileUploads(UUID entityId) { + return this.getDatabaseService().getQueryable(FileUpload.class).where((builder, root) -> builder.equal(root.get("entityId"), entityId)).toList(); + } + + @Override + public FileUpload find(UUID id, String hint) { + return null; + } + + @Override + public void delete(FileUpload item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(FileUpload.class); + } +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FunderDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FunderDao.java new file mode 100644 index 000000000..2c07c80da --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FunderDao.java @@ -0,0 +1,16 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.dao.criteria.FunderCriteria; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.entities.Funder; +import eu.eudat.old.data.entities.UserInfo; + +import java.util.UUID; + +public interface FunderDao extends DatabaseAccessLayer { + + QueryableList getWithCritetia(FunderCriteria criteria); + + QueryableList getAuthenticated(QueryableList query, UserInfo principal); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FunderDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FunderDaoImpl.java new file mode 100644 index 000000000..fb4f9258a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/FunderDaoImpl.java @@ -0,0 +1,75 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.FunderCriteria; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.Funder; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("funderDao") +public class FunderDaoImpl extends DatabaseAccess implements FunderDao { + + @Autowired + public FunderDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCritetia(FunderCriteria criteria) { + QueryableList query = getDatabaseService().getQueryable(Funder.class); + if (criteria.getLike() != null && !criteria.getLike().isEmpty()) + query.where((builder, root) -> + builder.or(builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"), + builder.or(builder.like(builder.upper(root.get("definition")), "%" + criteria.getLike().toUpperCase() + "%")))); + if (criteria.getReference() != null) + query.where((builder, root) -> builder.like(builder.upper(root.get("reference")), "%" + criteria.getReference().toUpperCase() + "%")); + if (criteria.getExactReference() != null) + query.where((builder, root) -> builder.like(builder.upper(root.get("reference")), criteria.getExactReference().toUpperCase())); + if (criteria.getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThanOrEqualTo(root.get("created"), criteria.getPeriodStart())); + query.where((builder, root) -> builder.notEqual(root.get("status"), Funder.Status.DELETED.getValue())); + return query; + } + + @Override + public QueryableList getAuthenticated(QueryableList query, UserInfo principal) { + query.where((builder, root) -> builder.equal(root.get("creationUser"), principal)); + return query; + } + + @Override + public Funder createOrUpdate(Funder item) { + return this.getDatabaseService().createOrUpdate(item, Funder.class); + } + + @Override + public CompletableFuture createOrUpdateAsync(Funder item) { + return null; + } + + @Override + public Funder find(UUID id) { + return this.getDatabaseService().getQueryable(Funder.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public Funder find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + + @Override + public void delete(Funder item) { + throw new UnsupportedOperationException(); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Funder.class); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/GrantDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/GrantDao.java new file mode 100644 index 000000000..02fcd1f76 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/GrantDao.java @@ -0,0 +1,17 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.Grant; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.criteria.GrantCriteria; +import eu.eudat.old.data.entities.UserInfo; + +import java.util.UUID; + +public interface GrantDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(GrantCriteria criteria); + + QueryableList getAuthenticated(QueryableList query, UserInfo principal); + +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/GrantDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/GrantDaoImpl.java new file mode 100644 index 000000000..b9b93d50f --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/GrantDaoImpl.java @@ -0,0 +1,101 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.criteria.GrantCriteria; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.Grant; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.types.grant.GrantStateType; +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.Date; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("grantDao") +public class GrantDaoImpl extends DatabaseAccess implements GrantDao { + + @Autowired + public GrantDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(GrantCriteria criteria) { + QueryableList query = getDatabaseService().getQueryable(Grant.class); + if (criteria.getLike() != null && !criteria.getLike().isEmpty()) + query.where((builder, root) -> + builder.or(builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"), + builder.or(builder.like(builder.upper(root.get("description")), "%" + criteria.getLike().toUpperCase() + "%")))); + if (criteria.getPeriodEnd() != null) + query.where((builder, root) -> builder.lessThan(root.get("enddate"), criteria.getPeriodEnd())); + if (criteria.getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThan(root.get("startdate"), criteria.getPeriodStart())); + if (criteria.getReference() != null) + query.where((builder, root) -> builder.like(root.get("reference"), "%" + criteria.getReference() + "%")); + if (criteria.getExactReference() != null) + query.where((builder, root) -> builder.like(root.get("reference"), criteria.getExactReference())); + if (criteria.getGrantStateType() != null) { + if (criteria.getGrantStateType().equals(GrantStateType.FINISHED.getValue())) + query.where((builder, root) -> builder.lessThan(root.get("enddate"), new Date())); + if (criteria.getGrantStateType().equals(GrantStateType.ONGOING.getValue())) + query.where((builder, root) -> + 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(); + } + + if (criteria.isActive()) { + query.where((builder, root) -> builder.notEqual(root.join("dmps").get("status"), DMP.DMPStatus.DELETED.getValue())).distinct(); + } + if (criteria.getFunderId() != null && !criteria.getFunderId().trim().isEmpty()) + query.where((builder, root) -> builder.equal(root.get("funder").get("id"), UUID.fromString(criteria.getFunderId()))); + if (criteria.getFunderReference() != null && !criteria.getFunderReference().isEmpty()) + query.where((builder, root) -> builder.or(builder.like(root.join("funder", JoinType.LEFT).get("reference"), "%" + criteria.getFunderReference()))); + query.where((builder, root) -> builder.notEqual(root.get("status"), Grant.Status.DELETED.getValue())); + return query; + } + + @Override + public Grant createOrUpdate(Grant item) { + return getDatabaseService().createOrUpdate(item, Grant.class); + } + + @Override + public Grant find(UUID id) { + return getDatabaseService().getQueryable(Grant.class).where((builder, root) -> builder.equal((root.get("id")), id)).getSingle(); + } + + @Override + public void delete(Grant item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Grant.class); + } + + public QueryableList getAuthenticated(QueryableList query, UserInfo principal) { + query.where((builder, root) -> builder.equal(root.get("creationUser").get("id"), principal.getId())).distinct(); + return query; + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(Grant item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public Grant find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/InvitationDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/InvitationDao.java new file mode 100644 index 000000000..e9ea78c5b --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/InvitationDao.java @@ -0,0 +1,15 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.InvitationCriteria; +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.Invitation; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + + +public interface InvitationDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(InvitationCriteria criteria); + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/InvitationDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/InvitationDaoImpl.java new file mode 100644 index 000000000..320e5ad22 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/InvitationDaoImpl.java @@ -0,0 +1,59 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.InvitationCriteria; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.Invitation; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + + +@Service("invitationDao") +public class InvitationDaoImpl extends DatabaseAccess implements InvitationDao { + + @Autowired + public InvitationDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(InvitationCriteria criteria) { + return null; + } + + @Override + public Invitation createOrUpdate(Invitation item) { + return this.getDatabaseService().createOrUpdate(item, Invitation.class); + } + + @Override + public Invitation find(UUID id) { + return this.getDatabaseService().getQueryable(Invitation.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public void delete(Invitation item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Invitation.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(Invitation item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public Invitation find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/LockDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/LockDao.java new file mode 100644 index 000000000..aec9063f9 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/LockDao.java @@ -0,0 +1,13 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.dao.criteria.LockCriteria; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.entities.Lock; + +import java.util.UUID; + +public interface LockDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(LockCriteria criteria); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/LockDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/LockDaoImpl.java new file mode 100644 index 000000000..6bc8dc252 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/LockDaoImpl.java @@ -0,0 +1,65 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.criteria.LockCriteria; +import eu.eudat.old.data.entities.Lock; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Service("LockDao") +public class LockDaoImpl extends DatabaseAccess implements LockDao { + + @Autowired + public LockDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(LockCriteria criteria) { + QueryableList query = this.getDatabaseService().getQueryable(Lock.class); + if (criteria.getTouchedAt() != null) + query.where((builder, root) -> builder.equal(root.get("touchedAt"), criteria.getTouchedAt())); + if (criteria.getLockedBy() != null) + query.where(((builder, root) -> builder.equal(root.get("lockedBy"), criteria.getLockedBy()))); + if (criteria.getTarget() != null) + query.where(((builder, root) -> builder.equal(root.get("target"), criteria.getTarget()))); + return query; + } + + @Override + public Lock createOrUpdate(Lock item) { + return this.getDatabaseService().createOrUpdate(item, Lock.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(Lock item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public Lock find(UUID id) { + return this.getDatabaseService().getQueryable(Lock.class).where(((builder, root) -> builder.equal(root.get("id"), id))).getSingle(); + } + + @Override + public Lock find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + + @Override + public void delete(Lock item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Lock.class); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/NotificationDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/NotificationDao.java new file mode 100644 index 000000000..7b4249e99 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/NotificationDao.java @@ -0,0 +1,13 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.NotificationCriteria; +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.Notification; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public interface NotificationDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(NotificationCriteria criteria); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/NotificationDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/NotificationDaoImpl.java new file mode 100644 index 000000000..6c09bcbe9 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/NotificationDaoImpl.java @@ -0,0 +1,60 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.NotificationCriteria; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.Notification; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Service("NotificationDao") +public class NotificationDaoImpl extends DatabaseAccess implements NotificationDao { + @Autowired + public NotificationDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(NotificationCriteria criteria) { + QueryableList query = this.getDatabaseService().getQueryable(Notification.class); + if (criteria.getIsActive() != null) + query.where((builder, root) -> builder.equal(root.get("isActive"), criteria.getIsActive())); + if (criteria.getNotifyState() != null) + query.where(((builder, root) -> builder.equal(root.get("notifyState"), criteria.getNotifyState()))); + return query; + } + + @Override + public Notification createOrUpdate(Notification item) { + return this.getDatabaseService().createOrUpdate(item, Notification.class); + } + + @Override + public CompletableFuture createOrUpdateAsync(Notification item) { + return CompletableFuture.supplyAsync(() -> this.getDatabaseService().createOrUpdate(item, Notification.class)); + } + + @Override + public Notification find(UUID id) { + return this.getDatabaseService().getQueryable(Notification.class).where(((builder, root) -> builder.equal(root.get("id"), id))).getSingle(); + } + + @Override + public Notification find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + + @Override + public void delete(Notification item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Notification.class); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/OrganisationDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/OrganisationDao.java new file mode 100644 index 000000000..e16614a5a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/OrganisationDao.java @@ -0,0 +1,16 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.dao.criteria.OrganisationCriteria; +import eu.eudat.old.data.entities.Organisation; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public interface OrganisationDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(OrganisationCriteria criteria); + QueryableList getAuthenticated(QueryableList query, UserInfo principal); + +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/OrganisationDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/OrganisationDaoImpl.java new file mode 100644 index 000000000..7a2825922 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/OrganisationDaoImpl.java @@ -0,0 +1,84 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.OrganisationCriteria; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.Organisation; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.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; + +@Component("organisationDao") +public class OrganisationDaoImpl extends DatabaseAccess implements OrganisationDao { + + @Autowired + public OrganisationDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(OrganisationCriteria criteria) { + QueryableList query = this.getDatabaseService().getQueryable(Organisation.class); + if (criteria.getLabelLike() != null && criteria.getLike() != null) { + query.where((builder, root) -> builder.or(builder.equal(root.get("reference"), criteria.getLike()), builder.like(builder.upper(root.get("label")), "%" + criteria.getLabelLike().toUpperCase() + "%"))); + } else { + 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())); + } + } + + if (criteria.isActive()) { + query.where((builder, root) -> builder.notEqual(root.join("dmps").get("status"), DMP.DMPStatus.DELETED.getValue())).distinct(); + } + + return query; + } + + @Override + public Organisation createOrUpdate(Organisation item) { + return this.getDatabaseService().createOrUpdate(item, Organisation.class); + } + + @Override + public Organisation find(UUID id) { + return this.getDatabaseService().getQueryable(Organisation.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public void delete(Organisation item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Organisation.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(Organisation item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + public QueryableList getAuthenticated(QueryableList query, UserInfo principal) { + query.where((builder, root) -> builder.equal(root.join("dmps").join("users").get("user"), principal)); + return query; + } + + @Override + public Organisation find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ProjectDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ProjectDao.java new file mode 100644 index 000000000..659bd7e7d --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ProjectDao.java @@ -0,0 +1,16 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.dao.criteria.ProjectCriteria; +import eu.eudat.old.data.entities.Project; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public interface ProjectDao extends DatabaseAccessLayer { + + QueryableList getWithCritetia(ProjectCriteria criteria); + + QueryableList getAuthenticated(QueryableList query, UserInfo principal); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ProjectDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ProjectDaoImpl.java new file mode 100644 index 000000000..eb70f5d31 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ProjectDaoImpl.java @@ -0,0 +1,73 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.ProjectCriteria; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.Project; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.stereotype.Service; + +import javax.persistence.criteria.JoinType; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Service("projectDao") +public class ProjectDaoImpl extends DatabaseAccess implements ProjectDao { + + public ProjectDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCritetia(ProjectCriteria criteria) { + QueryableList query = getDatabaseService().getQueryable(Project.class); + if (criteria.getLike() != null && !criteria.getLike().isEmpty()) + query.where((builder, root) -> + builder.or(builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"), + builder.or(builder.like(builder.upper(root.get("description")), "%" + criteria.getLike().toUpperCase() + "%")))); + if (criteria.getReference() != null) + query.where((builder, root) -> builder.like(root.get("reference"), "%" + criteria.getReference() + "%")); + if (criteria.getExactReference() != null) + query.where((builder, root) -> builder.like(root.get("reference"), criteria.getExactReference())); + if (criteria.getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThanOrEqualTo(root.get("startdate"), criteria.getPeriodStart())); + query.where((builder, root) -> builder.notEqual(root.get("status"), Project.Status.DELETED.getValue())); + return query; + } + + public QueryableList getAuthenticated(QueryableList query, UserInfo principal) { + query.where((builder, root) -> builder.or(builder.equal(root.get("creationUser"), principal), builder.equal(root.join("dmps", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), principal.getId()))).distinct(); + return query; + } + + @Override + public Project createOrUpdate(Project item) { + return this.getDatabaseService().createOrUpdate(item, Project.class); + } + + @Override + public CompletableFuture createOrUpdateAsync(Project item) { + return null; + } + + @Override + public Project find(UUID id) { + return this.getDatabaseService().getQueryable(Project.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public Project find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } + + @Override + public void delete(Project item) { + throw new UnsupportedOperationException(); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Project.class); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/RegistryDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/RegistryDao.java new file mode 100644 index 000000000..049c3828b --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/RegistryDao.java @@ -0,0 +1,14 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.RegistryCriteria; +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.Registry; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public interface RegistryDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(RegistryCriteria criteria); + +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/RegistryDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/RegistryDaoImpl.java new file mode 100644 index 000000000..e90968681 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/RegistryDaoImpl.java @@ -0,0 +1,66 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.RegistryCriteria; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.Registry; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("registryDao") +public class RegistryDaoImpl extends DatabaseAccess implements RegistryDao { + + @Autowired + public RegistryDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(RegistryCriteria criteria) { + QueryableList query = this.getDatabaseService().getQueryable(Registry.class); + if (criteria.getLike() != null) + if (criteria.getLike() != null) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("reference")), "%" + criteria.getLike().toUpperCase() + "%"), + builder.equal(builder.upper(root.get("label")), criteria.getLike().toUpperCase()))); + if (criteria.getCreationUserId() != null) + query.where((builder, root) -> builder.equal(root.get("creationUser").get("id"), criteria.getCreationUserId())); + return query; + } + + @Override + public Registry createOrUpdate(Registry item) { + return this.getDatabaseService().createOrUpdate(item, Registry.class); + } + + @Override + public Registry find(UUID id) { + return this.getDatabaseService().getQueryable(Registry.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public void delete(Registry item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Registry.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(Registry item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public Registry find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ResearcherDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ResearcherDao.java new file mode 100644 index 000000000..33ce09f3a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ResearcherDao.java @@ -0,0 +1,14 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.dao.criteria.ResearcherCriteria; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.entities.Researcher; + +import java.util.UUID; + +public interface ResearcherDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(ResearcherCriteria criteria); + +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ResearcherDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ResearcherDaoImpl.java new file mode 100644 index 000000000..54686966e --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ResearcherDaoImpl.java @@ -0,0 +1,67 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.criteria.ResearcherCriteria; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.Researcher; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("researcherDao") +public class ResearcherDaoImpl extends DatabaseAccess implements ResearcherDao { + + @Autowired + public ResearcherDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(ResearcherCriteria criteria) { + QueryableList query = asQueryable(); + if (criteria.getLike() != null && !criteria.getLike().isEmpty()) + query.where((builder, root) ->builder.or(builder.like(builder.lower(root.get("reference")), "%" + criteria.getLike().toLowerCase() + "%"))); + if (criteria.getName() != null && !criteria.getName().isEmpty()) + query.where((builder, root) ->builder.or(builder.like(builder.lower(root.get("label")), "%" + criteria.getName().toLowerCase() + "%"))); + if (criteria.getReference() != null && !criteria.getReference().isEmpty()) + query.where((builder, root) ->builder.or(builder.like(root.get("reference"), criteria.getReference()))); + if (criteria.getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThanOrEqualTo(root.get("created"), criteria.getPeriodStart())); + return query; + } + + @Override + public Researcher createOrUpdate(Researcher item) { + return this.getDatabaseService().createOrUpdate(item, Researcher.class); + } + + @Override + public Researcher find(UUID id) { + return this.getDatabaseService().getQueryable(Researcher.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public void delete(Researcher item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Researcher.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(Researcher item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public Researcher find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ServiceDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ServiceDao.java new file mode 100644 index 000000000..34cdede19 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ServiceDao.java @@ -0,0 +1,14 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.dao.criteria.ServiceCriteria; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.entities.Service; + +import java.util.UUID; + +public interface ServiceDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(ServiceCriteria criteria); + +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ServiceDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ServiceDaoImpl.java new file mode 100644 index 000000000..6ab22f138 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/ServiceDaoImpl.java @@ -0,0 +1,65 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.ServiceCriteria; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.Service; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("serviceDao") +public class ServiceDaoImpl extends DatabaseAccess implements ServiceDao { + + @Autowired + public ServiceDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(ServiceCriteria criteria) { + QueryableList query = this.getDatabaseService().getQueryable(Service.class); + if (criteria.getLike() != null) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("reference")), "%" + criteria.getLike().toUpperCase() + "%"), + builder.equal(builder.upper(root.get("label")), criteria.getLike().toUpperCase()))); + if (criteria.getCreationUserId() != null) + query.where((builder, root) -> builder.equal(root.get("creationUser").get("id"), criteria.getCreationUserId())); + return query; + } + + @Override + public Service createOrUpdate(Service item) { + return this.getDatabaseService().createOrUpdate(item, Service.class); + } + + @Override + public Service find(UUID id) { + return this.getDatabaseService().getQueryable(Service.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public void delete(Service item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Service.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(Service item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public Service find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDatasetProfileDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDatasetProfileDao.java new file mode 100644 index 000000000..e04be4909 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDatasetProfileDao.java @@ -0,0 +1,12 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.UserDatasetProfile; + +import java.util.UUID; + +/** + * Created by ikalyvas on 2/8/2018. + */ +public interface UserDatasetProfileDao extends DatabaseAccessLayer { +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDatasetProfileDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDatasetProfileDaoImpl.java new file mode 100644 index 000000000..32ce2f856 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDatasetProfileDaoImpl.java @@ -0,0 +1,52 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.entities.UserDatasetProfile; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("userDatasetProfileDao") +public class UserDatasetProfileDaoImpl extends DatabaseAccess implements UserDatasetProfileDao { + + @Autowired + public UserDatasetProfileDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public UserDatasetProfile createOrUpdate(UserDatasetProfile item) { + return this.getDatabaseService().createOrUpdate(item, UserDatasetProfile.class); + } + + @Override + public UserDatasetProfile find(UUID id) { + return this.getDatabaseService().getQueryable(UserDatasetProfile.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault(); + } + + @Override + public void delete(UserDatasetProfile item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(UserDatasetProfile.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(UserDatasetProfile item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public UserDatasetProfile find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDmpDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDmpDao.java new file mode 100644 index 000000000..774a4d208 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDmpDao.java @@ -0,0 +1,12 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.UserDMP; + +import java.util.UUID; + +/** + * Created by ikalyvas on 2/8/2018. + */ +public interface UserDmpDao extends DatabaseAccessLayer { +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDmpDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDmpDaoImpl.java new file mode 100644 index 000000000..8768f8720 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserDmpDaoImpl.java @@ -0,0 +1,55 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.UserDMP; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * Created by ikalyvas on 2/8/2018. + */ +@Component("userDmpDao") +public class UserDmpDaoImpl extends DatabaseAccess implements UserDmpDao { + + @Autowired + public UserDmpDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public UserDMP createOrUpdate(UserDMP item) { + return this.getDatabaseService().createOrUpdate(item, UserDMP.class); + } + + @Override + public UserDMP find(UUID id) { + return this.getDatabaseService().getQueryable(UserDMP.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault(); + } + + @Override + public void delete(UserDMP item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(UserDMP.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(UserDMP item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public UserDMP find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserInfoDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserInfoDao.java new file mode 100644 index 000000000..d9933bead --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserInfoDao.java @@ -0,0 +1,15 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.UserInfoCriteria; +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public interface UserInfoDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(UserInfoCriteria criteria); + + QueryableList getAuthenticated(QueryableList users, UUID principalId); +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserInfoDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserInfoDaoImpl.java new file mode 100644 index 000000000..98fde51bc --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserInfoDaoImpl.java @@ -0,0 +1,81 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.criteria.UserInfoCriteria; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.UserInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Component("userInfoDao") +public class UserInfoDaoImpl extends DatabaseAccess implements UserInfoDao { + + @Autowired + public UserInfoDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public QueryableList getWithCriteria(UserInfoCriteria criteria) { + QueryableList users = this.getDatabaseService().getQueryable(UserInfo.class); + users.where(((builder, root) -> builder.equal(root.get("userStatus"), 0))); + if (criteria.getAppRoles() != null && !criteria.getAppRoles().isEmpty()) + users.where((builder, root) -> root.join("userRoles").get("role").in(criteria.getAppRoles())); + if (criteria.getLike() != null) + users.where((builder, root) -> builder.or(builder.like(builder.upper(root.get("name")), "%" + criteria.getLike().toUpperCase() + "%"), builder.like(root.get("email"), "%" + criteria.getLike() + "%"))); + if (criteria.getEmail() != null) + users.where((builder, root) -> builder.equal(root.get("email"), criteria.getEmail())); + if (criteria.getCollaboratorLike() != null) + users.where((builder, root) -> builder.or(builder.like(builder.upper(root.get("name")), "%" + criteria.getCollaboratorLike().toUpperCase() + "%"), builder.like(root.get("email"), "%" + criteria.getCollaboratorLike() + "%"))); + return users; + } + + @Override + public QueryableList getAuthenticated(QueryableList users, UUID principalId) { + users.initSubQuery(UUID.class).where((builder, root) -> + builder.and(root.join("dmps").get("id").in( + users.subQuery((builder1, root1) -> builder1.equal(root1.get("id"), principalId), + Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmps:id")))), + builder.notEqual(root.get("id"), principalId))); + return users; + } + + @Override + public UserInfo createOrUpdate(UserInfo item) { + return this.getDatabaseService().createOrUpdate(item, UserInfo.class); + } + + @Override + public UserInfo find(UUID id) { + return this.getDatabaseService().getQueryable(UserInfo.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle(); + } + + @Override + public void delete(UserInfo item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(UserInfo.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(UserInfo item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public UserInfo find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} \ No newline at end of file diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserRoleDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserRoleDao.java new file mode 100644 index 000000000..74094fb46 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserRoleDao.java @@ -0,0 +1,18 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.dao.criteria.UserRoleCriteria; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.entities.UserRole; +import eu.eudat.old.queryable.QueryableList; + +import java.util.List; +import java.util.UUID; + + +public interface UserRoleDao extends DatabaseAccessLayer { + + QueryableList getWithCriteria(UserRoleCriteria criteria); + + List getUserRoles(UserInfo userInfo); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserRoleDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserRoleDaoImpl.java new file mode 100644 index 000000000..689df9198 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/UserRoleDaoImpl.java @@ -0,0 +1,71 @@ +package eu.eudat.old.data.dao.entities; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.criteria.UserRoleCriteria; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.entities.UserRole; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + + +@Component("userRoleDao") +public class UserRoleDaoImpl extends DatabaseAccess implements UserRoleDao { + + @Autowired + public UserRoleDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public UserRole createOrUpdate(UserRole item) { + return this.getDatabaseService().createOrUpdate(item, UserRole.class); + } + + @Override + public UserRole find(UUID id) { + return this.getDatabaseService().getQueryable(UserRole.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault(); + } + + @Override + public List getUserRoles(UserInfo userInfo) { + return this.getDatabaseService().getQueryable(UserRole.class).where((builder, root) -> builder.equal(root.get("userInfo"), userInfo)).toList(); + } + + @Override + public void delete(UserRole item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList getWithCriteria(UserRoleCriteria criteria) { + QueryableList query = this.getDatabaseService().getQueryable(UserRole.class); + if (criteria.getLike() != null) + query.where((builder, root) -> builder.equal(root.get("userInfo").get("name"), criteria.getLike())); + if (criteria.getAppRoles() != null && !criteria.getAppRoles().isEmpty()) + query.where((builder, root) -> root.get("role").in(criteria.getAppRoles())); + return query; + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(UserRole.class); + } + + @Async + @Override + public CompletableFuture createOrUpdateAsync(UserRole item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public UserRole find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/CredentialDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/CredentialDao.java new file mode 100644 index 000000000..f34feb03d --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/CredentialDao.java @@ -0,0 +1,12 @@ +package eu.eudat.old.data.dao.entities.security; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.Credential; + +import java.util.UUID; + + +public interface CredentialDao extends DatabaseAccessLayer { + + Credential getLoggedInCredentials(String username, String secret, Integer provider); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/CredentialDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/CredentialDaoImpl.java new file mode 100644 index 000000000..1c8796381 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/CredentialDaoImpl.java @@ -0,0 +1,61 @@ +package eu.eudat.old.data.dao.entities.security; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.entities.Credential; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + + +@Component("credentialDao") +public class CredentialDaoImpl extends DatabaseAccess implements CredentialDao { + + @Autowired + public CredentialDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public Credential createOrUpdate(Credential item) { + return this.getDatabaseService().createOrUpdate(item, Credential.class); + } + + @Override + public Credential find(UUID id) { + return this.getDatabaseService().getQueryable(Credential.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault(); + } + + @Override + public Credential getLoggedInCredentials(String username, String secret, Integer provider) { + return this.getDatabaseService().getQueryable(Credential.class).where(((builder, root) -> + builder.and( + builder.equal(root.get("publicValue"), username), + builder.equal(root.get("secret"), secret), + builder.equal(root.get("provider"), provider) + ))).getSingleOrDefault(); + } + + @Override + public void delete(Credential item) { + this.getDatabaseService().delete(item); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(Credential.class); + } + + @Override + public CompletableFuture createOrUpdateAsync(Credential item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public Credential find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/UserTokenDao.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/UserTokenDao.java new file mode 100644 index 000000000..3bcfa95e5 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/UserTokenDao.java @@ -0,0 +1,16 @@ +package eu.eudat.old.data.dao.entities.security; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.UserToken; + +import java.util.UUID; + + +public interface UserTokenDao extends DatabaseAccessLayer { + + UserToken createOrUpdate(UserToken item); + + UserToken find(UUID id); + + void delete(UserToken token); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/UserTokenDaoImpl.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/UserTokenDaoImpl.java new file mode 100644 index 000000000..7fbbde5c9 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/dao/entities/security/UserTokenDaoImpl.java @@ -0,0 +1,51 @@ +package eu.eudat.old.data.dao.entities.security; + +import eu.eudat.old.data.dao.DatabaseAccess; +import eu.eudat.old.data.dao.databaselayer.service.DatabaseService; +import eu.eudat.old.data.entities.UserToken; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + + +@Component("userTokenDao") +public class UserTokenDaoImpl extends DatabaseAccess implements UserTokenDao { + + @Autowired + public UserTokenDaoImpl(DatabaseService databaseService) { + super(databaseService); + } + + @Override + public UserToken createOrUpdate(UserToken item) { + return this.getDatabaseService().createOrUpdate(item, UserToken.class); + } + + @Override + public UserToken find(UUID id) { + return this.getDatabaseService().getQueryable(UserToken.class).where((builder, root) -> builder.equal(root.get("token"), id)).getSingleOrDefault(); + } + + @Override + public void delete(UserToken userToken) { + this.getDatabaseService().delete(userToken); + } + + @Override + public QueryableList asQueryable() { + return this.getDatabaseService().getQueryable(UserToken.class); + } + + @Override + public CompletableFuture createOrUpdateAsync(UserToken item) { + return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item)); + } + + @Override + public UserToken find(UUID id, String hint) { + throw new UnsupportedOperationException(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Content.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Content.java new file mode 100644 index 000000000..2589140da --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Content.java @@ -0,0 +1,155 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.List; +import java.util.UUID; + +/** + * Created by ikalyvas on 3/15/2018. + */ +@Entity +@Table(name = "\"Content\"") +public class Content implements DataEntity { //IGNORE ME + + public enum ParentType { + GRANT(0); + + private int value; + + private ParentType(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + public static ParentType fromInteger(int value) { + switch (value) { + case 0: + return GRANT; + default: + throw new RuntimeException("Unsupported Content Parent Type Status"); + } + } + } + + public enum LocationType { + EXTERNAL(0), INTERNAL(1); + + private Integer value; + + private LocationType(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + public static LocationType fromInteger(int value) { + switch (value) { + case 0: + return EXTERNAL; + case 1: + return INTERNAL; + default: + throw new RuntimeException("Unsupported Content Location Type"); + } + } + } + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"Id\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Filename\"", nullable = false) + private String label; + + @Column(name = "\"Extension\"", nullable = false) + private String extension; + + @Column(name = "\"ParentType\"", nullable = false) + private Integer parentType; + + @Column(name = "\"Uri\"", nullable = false) + private String uri; + + @Column(name = "\"LocationType\"", nullable = false) + private Integer locationType; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public Integer getParentType() { + return parentType; + } + + public void setParentType(Integer parentType) { + this.parentType = parentType; + } + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + + public Integer getLocationType() { + return locationType; + } + + public void setLocationType(Integer locationType) { + this.locationType = locationType; + } + + @Override + public void update(Content entity) { + this.extension = entity.getExtension(); + this.label = entity.getLabel(); + this.locationType = entity.getLocationType(); + this.parentType = entity.getParentType(); + this.uri = entity.getUri(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Content buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Credential.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Credential.java new file mode 100644 index 000000000..448912d47 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Credential.java @@ -0,0 +1,168 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.UUID; + + +@Entity +@Table(name = "\"Credential\"") +@NamedEntityGraphs({ + @NamedEntityGraph( + name = "credentialUserInfo", + attributeNodes = {@NamedAttributeNode("userInfo")}) +}) +public class Credential implements DataEntity { + + @Id + @Column(name = "\"Id\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @ManyToOne + @JoinColumn(name = "\"UserId\"", nullable = false) + private UserInfo userInfo; + + @Column(name = "\"Status\"", nullable = false) + private Integer status; + + @Column(name = "\"Provider\"", nullable = false) + private Integer provider; + @Column(name = "\"Public\"", nullable = false) + private String publicValue; + @Column(name = "\"Email\"") + private String email; + @Column(name = "\"Secret\"", nullable = false) + private String secret; + + @Column(name = "\"CreationTime\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date creationTime; + + @Column(name = "\"LastUpdateTime\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date lastUpdateTime; + + @Column(name = "\"ExternalId\"", nullable = false) + private String externalId; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UserInfo getUserInfo() { + return userInfo; + } + + public void setUserInfo(UserInfo userInfo) { + this.userInfo = userInfo; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public Integer getProvider() { + return provider; + } + + public void setProvider(Integer provider) { + this.provider = provider; + } + + public String getPublicValue() { + return publicValue; + } + + public void setPublicValue(String publicValue) { + this.publicValue = publicValue; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getSecret() { + return secret; + } + + public void setSecret(String secret) { + this.secret = secret; + } + + public Date getCreationTime() { + return creationTime; + } + + public void setCreationTime(Date creationTime) { + this.creationTime = creationTime; + } + + public Date getLastUpdateTime() { + return lastUpdateTime; + } + + public void setLastUpdateTime(Date lastUpdateTime) { + this.lastUpdateTime = lastUpdateTime; + } + + public String getExternalId() { + return externalId; + } + + public void setExternalId(String externalId) { + this.externalId = externalId; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Credential that = (Credential) o; + + return provider.intValue() == that.provider.intValue(); + } + + @Override + public int hashCode() { + return provider.intValue(); + } + + @Override + public void update(Credential entity) { + this.status = entity.status; + this.publicValue = entity.getPublicValue(); + this.email = entity.getEmail(); + this.secret = entity.getSecret(); + this.lastUpdateTime = new Date(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Credential buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMP.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMP.java new file mode 100644 index 000000000..3b5de6046 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMP.java @@ -0,0 +1,399 @@ +package eu.eudat.old.data.entities; + + +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.*; +import java.util.stream.Collectors; + + +@Entity +@Table(name = "\"DMP\"") +@NamedEntityGraphs({ + @NamedEntityGraph( + name = "dataManagementPlanListingModel", + attributeNodes = { + @NamedAttributeNode("grant"), @NamedAttributeNode("creator"), @NamedAttributeNode("profile")}/*,*/ + /*subgraphs = { + @NamedSubgraph(name = "users", attributeNodes = {@NamedAttributeNode("user")}), + }*/ + ), + @NamedEntityGraph( + name = "fullyDetailed", + attributeNodes = { + @NamedAttributeNode("grant"), @NamedAttributeNode("profile"), + @NamedAttributeNode(value = "users", subgraph = "users"), @NamedAttributeNode("organisations"), @NamedAttributeNode("researchers") + }, + subgraphs = { + @NamedSubgraph(name = "users", attributeNodes = {@NamedAttributeNode("user")}) + } + ), + @NamedEntityGraph( + name = "dmpRecentActivity", + attributeNodes = { + @NamedAttributeNode("users"), @NamedAttributeNode("creator")}), + @NamedEntityGraph( + name = "recentDmpModel", + attributeNodes = {@NamedAttributeNode("organisations"), @NamedAttributeNode("researchers"), @NamedAttributeNode("associatedDmps"), + @NamedAttributeNode("grant"), @NamedAttributeNode(value = "users", subgraph = "users"), @NamedAttributeNode("creator"), @NamedAttributeNode("profile"), @NamedAttributeNode(value = "dataset", subgraph = "dataset")}, + subgraphs = { + @NamedSubgraph(name = "users", attributeNodes = {@NamedAttributeNode("user")}), + @NamedSubgraph(name = "dataset", attributeNodes = {@NamedAttributeNode("id"), @NamedAttributeNode("label")}) + } + ), + @NamedEntityGraph( + name = "versionListingModel", + attributeNodes = {@NamedAttributeNode("id"), @NamedAttributeNode("groupId"), @NamedAttributeNode("version")} + ) + +}) +public class DMP implements DataEntity { + + public enum DMPStatus { + ACTIVE((short) 0), FINALISED((short) 1),DELETED((short) 99); + + private short value; + + private DMPStatus(short value) { + this.value = value; + } + + public short getValue() { + return value; + } + + public static DMPStatus fromInteger(short value) { + switch (value) { + case 0: + return ACTIVE; + case 1: + return FINALISED; + case 99: + return DELETED; + default: + throw new RuntimeException("Unsupported DMP Status"); + } + } + } + + public static Set getHints() { + return hints; + } + + private static final Set hints = new HashSet<>(Arrays.asList("dataManagementPlanListingModel", "fullyDetailed")); + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"GroupId\"", columnDefinition = "BINARY(16)") + private UUID groupId; + + @Column(name = "\"Label\"") + private String label; + + @Column(name = "\"Version\"") + private Integer version; + + @OneToMany(mappedBy = "dmp", fetch = FetchType.LAZY) + private Set dataset; + + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"Grant\"") + private Grant grant; + + + /*@Column(name = "\"AssociatedDmps\"", columnDefinition = "xml", nullable = true) + private String associatedDmps;*/ + @OneToMany(fetch = FetchType.LAZY, mappedBy = "dmp") + private Set associatedDmps; + + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"Profile\"") + private DMPProfile profile; + + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"Creator\"") + private UserInfo creator; + + + @OneToMany(fetch = FetchType.LAZY) + @JoinTable(name = "\"DMPOrganisation\"", + joinColumns = {@JoinColumn(name = "\"DMP\"", referencedColumnName = "\"ID\"")}, + inverseJoinColumns = {@JoinColumn(name = "\"Organisation\"", referencedColumnName = "\"ID\"")} + ) + private Set organisations; + + + @OneToMany(fetch = FetchType.LAZY) + @JoinTable(name = "\"DMPResearcher\"", + joinColumns = {@JoinColumn(name = "\"DMP\"", referencedColumnName = "\"ID\"")}, + inverseJoinColumns = {@JoinColumn(name = "\"Researcher\"", referencedColumnName = "\"ID\"")} + ) + private Set researchers; + + + @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 users; + + + @Column(name = "\"Status\"", nullable = false) + private Short status; + + @Column(name = "\"Properties\"") + private String properties; + + @Column(name = "\"DmpProperties\"") + private String dmpProperties; + + @Column(name = "\"Created\"") + @Convert(converter = DateToUTCConverter.class) + private Date created = null; + + @Column(name = "\"Modified\"") + @Convert(converter = DateToUTCConverter.class) + private Date modified = new Date(); + + @Column(name = "\"Description\"") + private String description; + + @Column(name= "\"FinalizedAt\"") + @Convert(converter = DateToUTCConverter.class) + private Date finalizedAt; + + @Column(name = "\"isPublic\"", nullable = false) + private boolean isPublic; + + @Column(name= "\"PublishedAt\"") + @Convert(converter = DateToUTCConverter.class) + private Date publishedAt; + + @OneToMany(mappedBy = "entityId", fetch = FetchType.LAZY) + private Set dois; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"Project\"") + private Project project; + + @Column(name = "\"extraProperties\"") + private String extraProperties; + + + 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 getUsers() { + return users; + } + public void setUsers(Set users) { + this.users = users; + } + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public UUID getGroupId() { + return groupId; + } + public void setGroupId(UUID groupId) { + this.groupId = groupId; + } + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public Integer getVersion() { + return version; + } + public void setVersion(Integer version) { + this.version = version; + } + + public Grant getGrant() { + return grant; + } + public void setGrant(Grant grant) { + this.grant = grant; + } + + public Set getAssociatedDmps() { + return associatedDmps; + } + public void setAssociatedDmps(Set associatedDmps) { + this.associatedDmps = associatedDmps; + } + + public DMPProfile getProfile() { + return profile; + } + public void setProfile(DMPProfile profile) { + this.profile = profile; + } + + public Set getDataset() { + return dataset; + } + public void setDataset(Set dataset) { + this.dataset = dataset; + } + + public Set getOrganisations() { + return organisations; + } + public void setOrganisations(Set organisations) { + this.organisations = organisations; + } + + public Set getResearchers() { + return researchers; + } + public void setResearchers(Set researchers) { + this.researchers = researchers; + } + + public String getProperties() { + return properties; + } + public void setProperties(String properties) { + this.properties = properties; + } + + public String getDmpProperties() { + return dmpProperties; + } + public void setDmpProperties(String dmpProperties) { + this.dmpProperties = dmpProperties; + } + + public Date getFinalizedAt() { + return finalizedAt; + } + public void setFinalizedAt(Date finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public boolean isPublic() { + return isPublic; + } + public void setPublic(boolean aPublic) { + isPublic = aPublic; + } + + public Date getPublishedAt() { + return publishedAt; + } + public void setPublishedAt(Date publishedAt) { + this.publishedAt = publishedAt; + } + + public Set getDois() { + return dois; + } + public void setDois(Set dois) { + this.dois = dois; + } + + public Project getProject() { + return project; + } + public void setProject(Project project) { + this.project = project; + } + + public String getExtraProperties() { + return extraProperties; + } + + public void setExtraProperties(String extraProperties) { + this.extraProperties = extraProperties; + } + + @Override + public void update(DMP entity) { + this.associatedDmps = entity.associatedDmps; + this.label = entity.getLabel(); + this.profile = entity.getProfile(); + this.status = entity.getStatus(); + this.created = entity.created; + this.properties = entity.getProperties(); + this.grant = entity.getGrant(); + this.description = entity.getDescription(); + this.researchers = entity.getResearchers(); + this.organisations = entity.getOrganisations(); + this.dmpProperties = entity.getDmpProperties(); + this.isPublic = entity.isPublic; + this.project = entity.getProject(); + this.setModified(new Date()); + if (entity.getStatus().equals(DMPStatus.FINALISED.getValue())) this.setFinalizedAt(new Date()); + if (entity.isPublic) this.setPublishedAt(new Date()); + if (entity.getUsers() != null) this.users = entity.getUsers(); + this.dois = entity.getDois(); + this.extraProperties = entity.getExtraProperties(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public DMP buildFromTuple(List tuple, List fields, String base) { + this.id = tuple.get(0).get(base.isEmpty() ? "id" : base + "." + "id", UUID.class); + this.dataset = tuple.stream().map(x -> new Dataset().buildFromTuple(tuple, fields ,base.isEmpty() ? "dataset" : base + "." + "dataset")).collect(Collectors.toSet()); + this.creator = tuple.stream().map(x -> new UserInfo().buildFromTuple(tuple, fields , base.isEmpty() ? "creator" : base + "." + "creator")).collect(Collectors.toList()).get(0); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPDatasetProfile.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPDatasetProfile.java new file mode 100644 index 000000000..830701ef9 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPDatasetProfile.java @@ -0,0 +1,76 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.List; +import java.util.UUID; + +@Entity +@Table(name = "\"DMPDatasetProfile\"") +public class DMPDatasetProfile implements DataEntity { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @ManyToOne + @JoinColumn(name = "\"dmp\"") + private DMP dmp; + + @ManyToOne + @JoinColumn(name = "\"datasetprofile\"") + private DescriptionTemplate datasetprofile; + + @Column(name = "\"data\"") + private String data; + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public DMP getDmp() { + return dmp; + } + public void setDmp(DMP dmp) { + this.dmp = dmp; + } + + public DescriptionTemplate getDatasetprofile() { + return datasetprofile; + } + public void setDatasetprofile(DescriptionTemplate datasetprofile) { + this.datasetprofile = datasetprofile; + } + + public String getData() { + return data; + } + public void setData(String data) { + this.data = data; + } + + @Override + public void update(DMPDatasetProfile entity) { + this.dmp = entity.getDmp(); + this.datasetprofile = entity.getDatasetprofile(); + this.data = entity.getData(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public DMPDatasetProfile buildFromTuple(List tuple, List fields, String base) { + this.id = UUID.fromString((String) tuple.get(0).get(base.isEmpty() ? base + "." + "id" : "id")); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPOrganisation.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPOrganisation.java new file mode 100644 index 000000000..55718c0e1 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPOrganisation.java @@ -0,0 +1,63 @@ +package eu.eudat.old.data.entities; + + +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.UUID; + + +@Entity +@Table(name = "\"DMPOrganisation\"") +public class DMPOrganisation { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"DMP\"") + private UUID dmp; + + @Column(name = "\"Organisation\"") + private UUID organisation; + + @Column(name = "\"Role\"") + private Integer role; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getDmp() { + return dmp; + } + + public void setDmp(UUID dmp) { + this.dmp = dmp; + } + + public UUID getOrganisation() { + return organisation; + } + + public void setOrganisation(UUID organisation) { + this.organisation = organisation; + } + + public Integer getRole() { + return role; + } + + public void setRole(Integer role) { + this.role = role; + } + + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPProfile.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPProfile.java new file mode 100644 index 000000000..ffe72c8e0 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPProfile.java @@ -0,0 +1,153 @@ +package eu.eudat.old.data.entities; + + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.Set; +import java.util.UUID; + + +@Entity +@Table(name = "\"DMPProfile\"") +public class DMPProfile implements DataEntity { + + 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") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "profile") + private Set dmps; + + + @Column(name = "\"Label\"") + private String label; + + @Column(name = "\"Definition\"", columnDefinition = "xml") + private String definition; + + + @Column(name = "\"Status\"", nullable = false) + private int status; + + + @Column(name = "\"Created\"") + @Convert(converter = DateToUTCConverter.class) + private Date created = null; + + @Column(name = "\"Modified\"") + @Convert(converter = DateToUTCConverter.class) + private Date modified = new Date(); + + public int getStatus() { + return status; + } + + public void setStatus(int 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 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 getDmps() { + return dmps; + } + + public void setDmps(Set dmps) { + this.dmps = dmps; + } + + @Override + public void update(DMPProfile entity) { + this.modified = new Date(); + this.definition = entity.getDefinition(); + this.label = entity.getLabel(); + this.status= entity.getStatus(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public DMPProfile buildFromTuple(List tuple,List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPResearcher.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPResearcher.java new file mode 100644 index 000000000..7c945cf58 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DMPResearcher.java @@ -0,0 +1,65 @@ +package eu.eudat.old.data.entities; + + +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.UUID; + + +@Entity +@Table(name = "\"DMPResearcher\"") +public class DMPResearcher { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Type(type = "org.hibernate.type.PostgresUUIDType") + @Column(name = "\"DMP\"") + private UUID dmp; + + @Type(type = "org.hibernate.type.PostgresUUIDType") + @Column(name = "\"Researcher\"") + private UUID researcher; + + @Column(name = "\"Role\"") + private Integer role; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getDmp() { + return dmp; + } + + public void setDmp(UUID dmp) { + this.dmp = dmp; + } + + public UUID getResearcher() { + return researcher; + } + + public void setResearcher(UUID researcher) { + this.researcher = researcher; + } + + public Integer getRole() { + return role; + } + + public void setRole(Integer role) { + this.role = role; + } + + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DataRepository.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DataRepository.java new file mode 100644 index 000000000..3aa5fe17e --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DataRepository.java @@ -0,0 +1,151 @@ +package eu.eudat.old.data.entities; + + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +@Entity +@Table(name = "\"DataRepository\"") +public class DataRepository implements Serializable, DataEntity { + + @Id + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Label\"") + private String label; + + @Column(name = "\"Abbreviation\"") + private String abbreviation; + + @Column(name = "\"Reference\"") + private String reference; + + @Column(name = "\"Uri\"") + private String uri; + + @Column(name = "\"Definition\"", columnDefinition = "xml") + private String definition; + + @OneToMany(mappedBy = "dataRepository", cascade = CascadeType.ALL, orphanRemoval = true) + private Set datasetDataRepositories; + + @Column(name = "\"Status\"", nullable = false) + private Short status; + + @Column(name = "\"Created\"", nullable = false) + private Date created = null; + + @Column(name = "\"Modified\"", nullable = false) + private Date modified = new Date(); + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"CreationUser\"") + private UserInfo creationUser; + + + 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 String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getAbbreviation() { + return abbreviation; + } + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + + public String getDefinition() { + return definition; + } + public void setDefinition(String definition) { + this.definition = definition; + } + + public Set getDatasetDataRepositories() { + return datasetDataRepositories; + } + public void setDatasetDataRepositories(Set datasetDataRepositories) { + this.datasetDataRepositories = datasetDataRepositories; + } + + public UserInfo getCreationUser() { + return creationUser; + } + public void setCreationUser(UserInfo creationUser) { + this.creationUser = creationUser; + } + + @Override + public void update(DataRepository entity) { + this.label = entity.getLabel(); + this.abbreviation = entity.getAbbreviation(); + this.uri = entity.getUri(); + + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public DataRepository buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Dataset.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Dataset.java new file mode 100644 index 000000000..eece28e52 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Dataset.java @@ -0,0 +1,357 @@ +package eu.eudat.old.data.entities; + + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.*; +import java.util.stream.Collectors; + +@Entity +@Table(name = "\"Dataset\"") +@NamedEntityGraphs({ + @NamedEntityGraph( + name = "datasetListingModel", + attributeNodes = {/*@NamedAttributeNode("services"), @NamedAttributeNode(value = "datasetDataRepositories", subgraph = "datasetDataRepositories"), + @NamedAttributeNode(value = "datasetExternalDatasets", subgraph = "datasetExternalDatasets"), @NamedAttributeNode("registries"),*/ + @NamedAttributeNode(value = "dmp", subgraph = "dmp"), @NamedAttributeNode(value = "profile", subgraph = "profile"), @NamedAttributeNode("creator")}, + subgraphs = { + @NamedSubgraph(name = "dmp", attributeNodes = {@NamedAttributeNode("creator"), @NamedAttributeNode("users"), @NamedAttributeNode("grant"), @NamedAttributeNode("organisations")}), + @NamedSubgraph(name = "datasetDataRepositories", attributeNodes = {@NamedAttributeNode("dataRepository")}), + @NamedSubgraph(name = "datasetExternalDatasets", attributeNodes = {@NamedAttributeNode("externalDataset")}), + @NamedSubgraph(name = "profile", attributeNodes = {@NamedAttributeNode("label")}) + }), + + @NamedEntityGraph( + name = "datasetWizardModel", + attributeNodes = {@NamedAttributeNode("services"), @NamedAttributeNode("datasetDataRepositories"), @NamedAttributeNode("datasetExternalDatasets"), @NamedAttributeNode("registries"), + @NamedAttributeNode("dmp"), @NamedAttributeNode("profile"), @NamedAttributeNode("creator")}), + @NamedEntityGraph( + name = "datasetRecentActivity", + attributeNodes = {@NamedAttributeNode(value = "dmp", subgraph = "dmp")}, + subgraphs = @NamedSubgraph(name = "dmp", attributeNodes = {@NamedAttributeNode("users")})), + @NamedEntityGraph( + name = "datasetDataRepositories", + attributeNodes = {@NamedAttributeNode(value = "dmp", subgraph = "dmp"), @NamedAttributeNode("creator")}, + subgraphs = @NamedSubgraph(name = "dmp", attributeNodes = {@NamedAttributeNode("creator"), @NamedAttributeNode("users")})), + @NamedEntityGraph( + name = "recentDatasetModel", + attributeNodes = {@NamedAttributeNode("services"), @NamedAttributeNode(value = "datasetDataRepositories", subgraph = "datasetDataRepositories"), + @NamedAttributeNode(value = "datasetExternalDatasets", subgraph = "datasetExternalDatasets"), @NamedAttributeNode("registries"), + @NamedAttributeNode(value = "dmp", subgraph = "dmp"), @NamedAttributeNode("profile"), @NamedAttributeNode("creator")}, + subgraphs = { + @NamedSubgraph(name = "dmp", attributeNodes = {@NamedAttributeNode("creator"), @NamedAttributeNode("users"), @NamedAttributeNode("grant"), @NamedAttributeNode("organisations")}), + @NamedSubgraph(name = "datasetDataRepositories", attributeNodes = {@NamedAttributeNode("dataRepository")}), + @NamedSubgraph(name = "datasetExternalDatasets", attributeNodes = {@NamedAttributeNode("externalDataset")}) + }) +}) +public class Dataset implements DataEntity { + + public static Set getHints() { + return hints; + } + + private static final Set hints = new HashSet<>(Arrays.asList("datasetListingModel")); + + public enum Status { + SAVED((short) 0), FINALISED((short) 1), CANCELED((short) 2), 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 FINALISED; + case 2: + return CANCELED; + case 99: + return DELETED; + default: + throw new RuntimeException("Unsupported Dataset Status"); + } + } + } + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Label\"", nullable = false) + private String label; + + @ManyToOne(fetch = FetchType.LAZY) +// @Cascade(value=org.hibernate.annotations.CascadeType.ALL) + @JoinColumn(name = "\"DMP\"", nullable = false) + private DMP dmp; + + @Column(name = "\"DmpSectionIndex\"") + private Integer dmpSectionIndex; + + @Column(name = "\"Uri\"") + private String uri; + + @Column(name = "\"Properties\"", columnDefinition = "xml") + private String properties; + + @ManyToOne(fetch = FetchType.LAZY) + //@Cascade(value=org.hibernate.annotations.CascadeType.ALL) + @JoinColumn(name = "\"Profile\"") + private DescriptionTemplate profile; + + @Column(name = "\"Reference\"", columnDefinition = "xml") + private String reference; + + @OneToMany(fetch = FetchType.LAZY) + @JoinTable(name = "\"DatasetRegistry\"", + joinColumns = {@JoinColumn(name = "\"Dataset\"", referencedColumnName = "\"ID\"")}, + inverseJoinColumns = {@JoinColumn(name = "\"Registry\"", referencedColumnName = "\"ID\"")} + ) + private Set registries; + + @OneToMany(mappedBy = "dataset", cascade = CascadeType.ALL, orphanRemoval = true) + private Set datasetDataRepositories; + + @OneToMany(mappedBy = "dataset", cascade = CascadeType.ALL, orphanRemoval = true) + private Set services; + + @OneToMany(mappedBy = "dataset", cascade = CascadeType.ALL, orphanRemoval = true) + private Set datasetExternalDatasets; + + @Column(name = "\"Status\"", nullable = false) + private Short status; + + + @Column(name = "\"Created\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date created = null; + + @Column(name = "\"Modified\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date modified = new Date(); + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"Creator\"") + private UserInfo creator; + + @Column(name = "\"Description\"") + private String description; + + @Column(name= "\"FinalizedAt\"") + @Convert(converter = DateToUTCConverter.class) + private Date finalizedAt; + + + 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 getRegistries() { + return registries; + } + public void setRegistries(Set registries) { + this.registries = registries; + } + + public Set getServices() { + return services; + } + public void setServices(Set services) { + this.services = services; + } + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + + public DMP getDmp() { + return dmp; + } + public void setDmp(DMP dmp) { + this.dmp = dmp; + } + + public Integer getDmpSectionIndex() { + return dmpSectionIndex; + } + public void setDmpSectionIndex(Integer dmpSectionIndex) { + this.dmpSectionIndex = dmpSectionIndex; + } + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + + + public String getProperties() { + return properties; + } + public void setProperties(String properties) { + this.properties = properties; + } + + + public DescriptionTemplate getProfile() { + return profile; + } + public void setProfile(DescriptionTemplate profile) { + this.profile = profile; + } + + + public Set getDatasetDataRepositories() { + return datasetDataRepositories; + } + public void setDatasetDataRepositories(Set datasetDataRepositories) { + this.datasetDataRepositories = datasetDataRepositories; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public Set getDatasetExternalDatasets() { + return datasetExternalDatasets; + } + public void setDatasetExternalDatasets(Set datasetExternalDatasets) { + this.datasetExternalDatasets = datasetExternalDatasets; + } + + public Date getFinalizedAt() { + return finalizedAt; + } + public void setFinalizedAt(Date finalizedAt) { + this.finalizedAt = finalizedAt; + } + + @Override + public void update(Dataset entity) { + this.setUri(entity.getUri()); + this.setDescription(entity.getDescription()); + this.setLabel(entity.getLabel()); + this.setProperties(entity.getProperties()); + + if (entity.getDatasetDataRepositories() == null || entity.getDatasetDataRepositories().size() < 1) { + if (this.getDatasetDataRepositories() != null) this.getDatasetDataRepositories().removeAll(this.getDatasetDataRepositories()); + } else { + if (this.getDatasetDataRepositories() != null) { + this.getDatasetDataRepositories().removeAll(this.getDatasetDataRepositories()); + } else { + this.setDatasetDataRepositories(new HashSet<>()); + } + this.getDatasetDataRepositories().addAll(entity.getDatasetDataRepositories().stream().peek(item -> item.setDataset(this)).collect(Collectors.toList())); + } + + if (entity.getDatasetExternalDatasets() == null || entity.getDatasetExternalDatasets().size() < 1) { + if (this.getDatasetExternalDatasets() != null) this.getDatasetExternalDatasets().removeAll(this.getDatasetExternalDatasets()); + } else { + if (this.getDatasetExternalDatasets() != null) { + this.getDatasetExternalDatasets().removeAll(this.getDatasetExternalDatasets()); + } else { + this.setDatasetExternalDatasets(new HashSet<>()); + } + this.getDatasetExternalDatasets().addAll(entity.getDatasetExternalDatasets().stream().peek(item -> item.setDataset(this)).collect(Collectors.toList())); + } + + if (entity.getServices() == null || entity.getServices().size() < 1) { + if (this.getServices() != null) this.getServices().removeAll(this.getServices()); + } else { + if (this.getServices() != null) { + this.getServices().removeAll(this.getServices()); + } else { + this.setServices(new HashSet<>()); + } + this.getServices().addAll(entity.getServices().stream().peek(item -> item.setDataset(this)).collect(Collectors.toList())); + } + + this.setRegistries(entity.getRegistries()); + + this.setDmp(entity.getDmp()); + this.setDmpSectionIndex(entity.getDmpSectionIndex()); + this.setStatus(entity.getStatus()); + this.setProfile(entity.getProfile()); + this.setModified(new Date()); + if (entity.getStatus().equals(Status.FINALISED.getValue())) this.setFinalizedAt(new Date()); + if (entity.getCreator() != null) this.creator = entity.getCreator(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Dataset buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetDataRepository.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetDataRepository.java new file mode 100644 index 000000000..ef6040786 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetDataRepository.java @@ -0,0 +1,97 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.List; +import java.util.UUID; + +/** + * Created by ikalyvas on 5/22/2018. + */ + +@Entity +@Table(name = "\"DatasetDataRepository\"") +public class DatasetDataRepository implements DataEntity { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @ManyToOne + @JoinColumn(name = "\"Dataset\"", nullable = false) + private Dataset dataset; + + @ManyToOne + @JoinColumn(name = "\"DataRepository\"", nullable = false) + private DataRepository dataRepository; + + @Column(name = "\"Role\"") + private Integer role; + + @Column(name = "\"Data\"") + private String data; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public Dataset getDataset() { + return dataset; + } + + public void setDataset(Dataset dataset) { + this.dataset = dataset; + } + + public DataRepository getDataRepository() { + return dataRepository; + } + + public void setDataRepository(DataRepository dataRepository) { + this.dataRepository = dataRepository; + } + + public Integer getRole() { + return role; + } + + public void setRole(Integer role) { + this.role = role; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + @Override + public void update(DatasetDataRepository entity) { + this.dataset = entity.getDataset(); + this.dataRepository = entity.getDataRepository(); + this.role = entity.getRole(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public DatasetDataRepository buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetExternalDataset.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetExternalDataset.java new file mode 100644 index 000000000..194d65644 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetExternalDataset.java @@ -0,0 +1,95 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.List; +import java.util.UUID; + + +@Entity +@Table(name = "\"DatasetExternalDataset\"") +public class DatasetExternalDataset implements DataEntity { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"Id\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @ManyToOne + @JoinColumn(name = "\"Dataset\"", nullable = false) + private Dataset dataset; + + @ManyToOne + @JoinColumn(name = "\"ExternalDataset\"", nullable = false) + private ExternalDataset externalDataset; + + @Column(name = "\"Role\"") + private Integer role; + + @Column(name = "\"Data\"") + private String data; + + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public Dataset getDataset() { + return dataset; + } + + public void setDataset(Dataset dataset) { + this.dataset = dataset; + } + + public ExternalDataset getExternalDataset() { + return externalDataset; + } + + public void setExternalDataset(ExternalDataset externalDataset) { + this.externalDataset = externalDataset; + } + + public Integer getRole() { + return role; + } + + public void setRole(Integer role) { + this.role = role; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + @Override + public void update(DatasetExternalDataset entity) { + this.dataset = entity.getDataset(); + this.externalDataset = entity.getExternalDataset(); + this.role = entity.getRole(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public DatasetExternalDataset buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetProfileRuleset.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetProfileRuleset.java new file mode 100644 index 000000000..e5965203e --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetProfileRuleset.java @@ -0,0 +1,56 @@ +package eu.eudat.old.data.entities; + + +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.UUID; + + +@Entity +@Table(name = "\"DatasetProfileRuleset\"") +public class DatasetProfileRuleset { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + + @Column(name = "\"Label\"") + private String label; + + @Column(name = "\"Definition\"", columnDefinition = "xml", nullable = false) + private String definition; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getDefinition() { +// return XML.toJSONObject(definition).toString(); //return definition as json + return definition; + } + + public void setDefinition(String definition) { +// this.definition = XML.toString(definition); //if definition is in json + this.definition = definition; + } + + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetProfileViewstyle.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetProfileViewstyle.java new file mode 100644 index 000000000..170bb8405 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetProfileViewstyle.java @@ -0,0 +1,56 @@ +package eu.eudat.old.data.entities; + + +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.UUID; + + +@Entity +@Table(name = "\"DatasetProfileViewstyle\"") +public class DatasetProfileViewstyle { + + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + + @Column(name = "\"Label\"") + private String label; + + @Column(name = "\"Definition\"", columnDefinition = "xml", nullable = false) + private String definition; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getDefinition() { +// return XML.toJSONObject(definition).toString(); //return definition as json + return definition; + } + + public void setDefinition(String definition) { +// this.definition = XML.toString(definition); //if definition is in json + this.definition = definition; + } + + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetRegistry.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetRegistry.java new file mode 100644 index 000000000..b5f4512d9 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetRegistry.java @@ -0,0 +1,76 @@ +package eu.eudat.old.data.entities; + + +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.UUID; + + +@Entity +@Table(name = "\"DatasetRegistry\"") +public class DatasetRegistry { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + + @Type(type = "org.hibernate.type.PostgresUUIDType") //DEPWARN dependency to Hibernate and PostgreSQL + @Column(name = "\"Dataset\"", nullable = false) + private UUID dataset; + + @Type(type = "org.hibernate.type.PostgresUUIDType") //DEPWARN dependency to Hibernate and PostgreSQL + @Column(name = "\"Registry\"", nullable = false) + private UUID registry; + + @Column(name = "\"Role\"") + private Integer role; + + @Column(name = "\"Data\"") + private String data; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getDataset() { + return dataset; + } + + public void setDataset(UUID dataset) { + this.dataset = dataset; + } + + public UUID getRegistry() { + return registry; + } + + public void setRegistry(UUID registry) { + this.registry = registry; + } + + public Integer getRole() { + return role; + } + + public void setRole(Integer role) { + this.role = role; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetService.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetService.java new file mode 100644 index 000000000..62ee187da --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DatasetService.java @@ -0,0 +1,96 @@ +package eu.eudat.old.data.entities; + + +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.List; +import java.util.UUID; + + +@Entity +@Table(name = "\"DatasetService\"") +public class DatasetService implements DataEntity { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + + @ManyToOne + @JoinColumn(name = "\"Dataset\"", nullable = false) + private Dataset dataset; + + @ManyToOne + @JoinColumn(name = "\"Service\"", nullable = false) + private Service service; + + @Column(name = "\"Role\"") + private Integer role; + + @Column(name = "\"Data\"") + private String data; + + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public Dataset getDataset() { + return dataset; + } + + public void setDataset(Dataset dataset) { + this.dataset = dataset; + } + + public Service getService() { + return service; + } + + public void setService(Service service) { + this.service = service; + } + + public Integer getRole() { + return role; + } + + public void setRole(Integer role) { + this.role = role; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + @Override + public void update(DatasetService entity) { + this.dataset = entity.getDataset(); + this.service = entity.getService(); + this.role = entity.getRole(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public DatasetService buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if(fields.contains(currentBase + "id")) this.id = UUID.fromString((String) tuple.get(0).get(currentBase + "id")); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DescriptionTemplate.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DescriptionTemplate.java new file mode 100644 index 000000000..f894f4508 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DescriptionTemplate.java @@ -0,0 +1,197 @@ +package eu.eudat.old.data.entities; + + +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.Set; +import java.util.UUID; + + +@Entity +@Table(name = "\"DescriptionTemplate\"") +public class DescriptionTemplate implements DataEntity{ + + 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 + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Label\"", nullable = false) + private String label; + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "profile") + private Set dataset; + + @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; + + @Column(name = "\"Modified\"") + @Convert(converter = DateToUTCConverter.class) + private Date modified = new Date(); + + @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; + + @OneToMany(fetch = FetchType.LAZY) + private Set dmps; + + @Column(name = "\"Language\"", nullable = false) + private String language; + + @OneToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "\"Type\"", nullable = false) + private DescriptionTemplateType type; + + @OneToMany(mappedBy = "descriptionTemplate", fetch = FetchType.LAZY) + private Set users; + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "datasetprofile") + private Set associatedDmps; + + 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 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 getDataset() { + return dataset; + } + public void setDataset(Set 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; } + + public String getLanguage() { + return language; + } + public void setLanguage(String language) { + this.language = language; + } + + public DescriptionTemplateType getType() { + return type; + } + public void setType(DescriptionTemplateType type) { + this.type = type; + } + + public Set getUsers() { + return users; + } + public void setUsers(Set users) { + this.users = users; + } + + @Override + public String toString() { + return "DatasetProfileListingModel [id=" + id + ", label=" + label + ", dataset=" + dataset + ", definition=" + definition + ", version=" + version + ", language=" + language + ", type=" + type +"]"; + } + + @Override + public void update(DescriptionTemplate entity) { + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public DescriptionTemplate buildFromTuple(List tuple, List fields, String base) { + this.id = UUID.fromString((String) tuple.get(0).get(base.isEmpty() ? base + "." + "id" : "id")); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DescriptionTemplateType.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DescriptionTemplateType.java new file mode 100644 index 000000000..e266860b4 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/DescriptionTemplateType.java @@ -0,0 +1,89 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.List; +import java.util.UUID; + +@Entity +@Table(name = "\"DescriptionTemplateType\"") +public class DescriptionTemplateType implements DataEntity { + + 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 Description Template Type Status"); + } + } + } + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Name\"", nullable = false) + private String name; + + @Column(name = "\"Status\"", nullable = false) + private Short status; + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public Short getStatus() { + return status; + } + public void setStatus(Short status) { + this.status = status; + } + + @Override + public void update(DescriptionTemplateType entity) { + this.name = entity.name; + this.status = entity.status; + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public DescriptionTemplateType buildFromTuple(List tuple, List fields, String base) { + this.id = UUID.fromString((String) tuple.get(0).get(!base.isEmpty() ? base + "." + "id" : "id")); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/EmailConfirmation.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/EmailConfirmation.java new file mode 100644 index 000000000..9e5b7710b --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/EmailConfirmation.java @@ -0,0 +1,102 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Entity +@Table(name = "\"EmailConfirmation\"") +public class EmailConfirmation implements DataEntity { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false) + private UUID id; + + @Column(name = "\"email\"", nullable = false) + private String email; + + @Column(name = "\"isConfirmed\"", nullable = false) + private boolean isConfirmed; + + @Column(name = "\"token\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID token; + + @Column(name = "\"userId\"", nullable = false) + private UUID userId; + + @Column(name = "\"data\"") + private String data; + + @Column(name = "\"expiresAt\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date expiresAt; + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + public boolean getIsConfirmed() { + return isConfirmed; + } + public void setIsConfirmed(boolean confirmed) { + isConfirmed = confirmed; + } + + public UUID getToken() { + return token; + } + public void setToken(UUID token) { + this.token = token; + } + + public UUID getUserId() { + return userId; + } + public void setUserId(UUID userId) { + this.userId = userId; + } + + public Date getExpiresAt() { + return expiresAt; + } + public void setExpiresAt(Date expiresAt) { + this.expiresAt = expiresAt; + } + + public String getData() { + return data; + } + public void setData(String data) { + this.data = data; + } + @Override + public void update(EmailConfirmation entity) { + } + + @Override + public UUID getKeys() { + return null; + } + + @Override + public EmailConfirmation buildFromTuple(List tuple, List fields, String base) { + return null; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/EntityDoi.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/EntityDoi.java new file mode 100644 index 000000000..a92c6c6e5 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/EntityDoi.java @@ -0,0 +1,120 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Entity +@Table(name = "\"EntityDoi\"") +public class EntityDoi implements DataEntity { + public enum EntityType { + DMP + } + + @Id + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Enumerated(EnumType.STRING) + @Column(name = "\"EntityType\"", nullable = false) + private EntityType entityType; + + @Column(name = "\"RepositoryId\"", nullable = false) + private String repositoryId; + + @Column(name = "\"Doi\"", nullable = false) + private String doi; + + @Column(name = "\"CreatedAt\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date createdAt; + + @Column(name = "\"UpdatedAt\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date updatedAt; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"EntityId\"", nullable = false) + private DMP entityId; + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public EntityType getEntityType() { + return entityType; + } + public void setEntityType(EntityType entityType) { + this.entityType = entityType; + } + + public String getRepositoryId() { + return repositoryId; + } + public void setRepositoryId(String repositoryId) { + this.repositoryId = repositoryId; + } + + public String getDoi() { + return doi; + } + public void setDoi(String doi) { + this.doi = doi; + } + + public Date getCreatedAt() { + return createdAt; + } + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public Date getUpdatedAt() { + return updatedAt; + } + public void setUpdatedAt(Date updatedAt) { + this.updatedAt = updatedAt; + } + + public DMP getEntityId() { + return entityId; + } + public void setEntityId(DMP entityId) { + this.entityId = entityId; + } + + @Override + public void update(EntityDoi doi) { + this.entityType = doi.getEntityType(); + this.repositoryId = doi.getRepositoryId(); + this.doi = doi.getDoi(); + this.createdAt = doi.getCreatedAt(); + this.updatedAt = doi.getUpdatedAt(); + this.entityId = doi.getEntityId(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public EntityDoi buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + if (fields.contains(currentBase + "entityId")) + this.entityId = tuple.stream().map(x -> new DMP().buildFromTuple(Arrays.asList(x), fields , base.isEmpty() ? "entityId" : base + "." + "entityId")).collect(Collectors.toList()).get(0); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/ExternalDataset.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/ExternalDataset.java new file mode 100644 index 000000000..9e82e962a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/ExternalDataset.java @@ -0,0 +1,122 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.Set; +import java.util.UUID; + + +@Entity +@Table(name = "\"ExternalDataset\"") +public class ExternalDataset implements DataEntity { + + @Id + @Column(name = "\"Id\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Label\"", nullable = false) + private String label; + + @Column(name = "\"Abbreviation\"", nullable = false) + private String abbreviation; + + @Column(name = "\"Reference\"", nullable = false) + private String reference; + + @Column(name = "\"Created\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date created; + + @Column(name = "\"Modified\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date modified; + + @OneToMany(mappedBy = "externalDataset", cascade = CascadeType.ALL, orphanRemoval = true) + private Set datasets; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"CreationUser\"", nullable = true) + private UserInfo creationUser; + + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getAbbreviation() { + return abbreviation; + } + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + 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 getDatasets() { + return datasets; + } + public void setDatasets(Set datasets) { + this.datasets = datasets; + } + + public UserInfo getCreationUser() { + return creationUser; + } + public void setCreationUser(UserInfo creationUser) { + this.creationUser = creationUser; + } + + @Override + public void update(ExternalDataset entity) { + this.label = entity.getLabel(); + this.abbreviation = entity.getAbbreviation(); + this.modified = new Date(); + this.creationUser = entity.getCreationUser(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public ExternalDataset buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/FileUpload.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/FileUpload.java new file mode 100644 index 000000000..ccd3f20e0 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/FileUpload.java @@ -0,0 +1,128 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Entity +@Table(name = "\"FileUpload\"") +public class FileUpload implements DataEntity { + public enum EntityType { + DATASET, DMP + } + + @Id + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Name\"", nullable = false) + private String name; + + @Column(name = "\"FileType\"", nullable = false) + private String fileType; + + @Column(name = "\"EntityId\"", nullable = false) + private UUID entityId; + + @Enumerated(EnumType.STRING) + @Column(name = "\"EntityType\"", nullable = false) + private EntityType entityType; + + @Column(name = "\"CreatedAt\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date createdAt; + + @Column(name = "\"IsDeleted\"", nullable = false) + private Boolean isDeleted; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"Creator\"") + private UserInfo creator; + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getFileType() { + return fileType; + } + public void setFileType(String fileType) { + this.fileType = fileType; + } + + public UUID getEntityId() { + return entityId; + } + public void setEntityId(UUID entityId) { + this.entityId = entityId; + } + + public EntityType getEntityType() { + return entityType; + } + public void setEntityType(EntityType entityType) { + this.entityType = entityType; + } + + public Date getCreatedAt() { + return createdAt; + } + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public Boolean getIsDeleted() { + return isDeleted; + } + public void setIsDeleted(Boolean isDeleted) { + this.isDeleted = isDeleted; + } + + public UserInfo getCreator() { + return creator; + } + public void setCreator(UserInfo creator) { + this.creator = creator; + } + + @Override + public void update(FileUpload file) { + this.name = file.getName(); + this.fileType = file.getFileType(); + this.entityId = file.getEntityId(); + this.entityType = file.getEntityType(); + this.createdAt = file.getCreatedAt(); + this.isDeleted = file.getIsDeleted(); + this.creator = file.getCreator(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public FileUpload buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + this.creator = tuple.stream().map(x -> new UserInfo().buildFromTuple(tuple, fields , base.isEmpty() ? "creator" : base + "." + "creator")).collect(Collectors.toList()).get(0); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Funder.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Funder.java new file mode 100644 index 000000000..f4d1079c0 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Funder.java @@ -0,0 +1,183 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Entity +@Table(name = "\"Funder\"") +public class Funder implements DataEntity { + + public enum Status { + ACTIVE((short) 1), INACTIVE((short) 0), DELETED((short) 99); + + private short value; + + Status(short value) { + this.value = value; + } + + public short getValue() { + return value; + } + + public static Status fromInteger(int value) { + switch (value) { + case 0: + return INACTIVE; + case 1: + return ACTIVE; + case 99: + return DELETED; + default: + throw new RuntimeException("Unsupported Funder Status"); + } + } + } + + public enum FunderType { + EXTERNAL(0), INTERNAL(1); + + private Integer value; + + FunderType(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + public static FunderType fromInteger(int value) { + switch (value) { + case 0: + return EXTERNAL; + case 1: + return INTERNAL; + default: + throw new RuntimeException("Unsupported Grant Type"); + } + } + } + + @Id + //@GeneratedValue + //@GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Label\"") + private String label; + + @Column(name = "\"Reference\"", columnDefinition = "xml") + private String reference; + + @Column(name = "\"Definition\"", columnDefinition = "xml") + private String definition; + + @Column(name = "\"Status\"", nullable = false) + private Short status; + + @Column(name = "\"Created\"") + private Date created = null; + + @Column(name = "\"Modified\"") + private Date modified = new Date(); + + @Column(name = "\"Type\"") + private Integer type; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"CreationUser\"", nullable = true) + private UserInfo creationUser; + + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public String getDefinition() { + return definition; + } + public void setDefinition(String definition) { + this.definition = definition; + } + + 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 Integer getType() { + return type; + } + public void setType(Integer type) { + this.type = type; + } + + public UserInfo getCreationUser() { + return creationUser; + } + public void setCreationUser(UserInfo creationUser) { + this.creationUser = creationUser; + } + + @Override + public void update(Funder entity) { + this.label = entity.getLabel(); + this.reference = entity.getReference(); + this.definition = entity.getDefinition(); + this.status = entity.getStatus(); + this.created = entity.getCreated(); + this.modified = new Date(); + this.type = entity.getType(); + this.creationUser = entity.getCreationUser(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Funder buildFromTuple(List tuple, List fields, String base) { + return null; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Grant.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Grant.java new file mode 100644 index 000000000..eeb925f40 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Grant.java @@ -0,0 +1,299 @@ +package eu.eudat.old.data.entities; + + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.*; +import java.util.stream.Collectors; + + +@Entity +@Table(name = "\"Grant\"") +@NamedEntityGraphs({ + @NamedEntityGraph( + name = "grantRecentActivity", + attributeNodes = {@NamedAttributeNode(value = "dmps", subgraph = "dmps")}, + subgraphs = @NamedSubgraph(name = "dmps", attributeNodes = {@NamedAttributeNode("users")}) + ), + @NamedEntityGraph( + name = "grantListingItem", + attributeNodes = {@NamedAttributeNode(value = "dmps", subgraph = "dmps"), @NamedAttributeNode(value = "content")}, + subgraphs = @NamedSubgraph(name = "dmps", attributeNodes = {@NamedAttributeNode("creator"), @NamedAttributeNode("grant"), @NamedAttributeNode("users")}) + ) +}) +public class Grant implements DataEntity { + + public enum Status { + ACTIVE((short) 1), INACTIVE((short) 0), 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 INACTIVE; + case 1: + return ACTIVE; + case 99: + return DELETED; + default: + throw new RuntimeException("Unsupported Grant Status"); + } + } + } + + public enum GrantType { + EXTERNAL(0), INTERNAL(1); + + private Integer value; + + private GrantType(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + public static GrantType fromInteger(int value) { + switch (value) { + case 0: + return EXTERNAL; + case 1: + return INTERNAL; + default: + throw new RuntimeException("Unsupported Grant Type"); + } + } + } + + @Id + //@GeneratedValue + //@GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + + @OneToMany(mappedBy = "grant") + private Set dmps; + + @Column(name = "\"Label\"") + private String label; + + @Column(name = "\"Abbreviation\"") + private String abbreviation; + + @Column(name = "\"Reference\"", columnDefinition = "xml", nullable = true) + private String reference; + + @Column(name = "\"Uri\"") + private String uri; + + @Column(name = "\"Definition\"", columnDefinition = "xml") + private String definition; + + @Column(name = "\"StartDate\"", nullable = true) + @Convert(converter = DateToUTCConverter.class) + private Date startdate = null; + + @Column(name = "\"EndDate\"", nullable = true) + @Convert(converter = DateToUTCConverter.class) + private Date enddate = null; + + @Column(name = "\"Status\"", nullable = false) + private Short status; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"CreationUser\"", nullable = true) + private UserInfo creationUser; + + @Column(name = "\"Created\"") + private Date created = null; + + @Column(name = "\"Modified\"") + private Date modified = new Date(); + + @Column(name = "\"Description\"") + private String description; + + @Column(name = "\"Type\"") + private Integer type; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"Content\"") + private Content content; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"Funder\"") + private Funder funder; + + public Grant() { + } + + public Grant(Grant grant) { + this.id = grant.getId(); + } + + 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 Date getStartdate() { + return startdate; + } + public void setStartdate(Date startdate) { + this.startdate = startdate; + } + + public Date getEnddate() { + return enddate; + } + public void setEnddate(Date enddate) { + this.enddate = enddate; + } + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getAbbreviation() { + return abbreviation; + } + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + + public String getDefinition() { + return definition; + } + public void setDefinition(String definition) { + this.definition = definition; + } + + public Set getDmps() { + return dmps; + } + public void setDmps(Set dmps) { + this.dmps = dmps; + } + + public UserInfo getCreationUser() { + return creationUser; + } + public void setCreationUser(UserInfo creationUser) { + this.creationUser = creationUser; + } + + public Integer getType() { + return type; + } + public void setType(Integer type) { + this.type = type; + } + + public Content getContent() { + return content; + } + public void setContent(Content content) { + this.content = content; + } + + public Funder getFunder() { + return funder; + } + public void setFunder(Funder funder) { + this.funder = funder; + } + + @Override + public void update(Grant entity) { + this.description = entity.getDescription(); + this.label = entity.getLabel(); + this.abbreviation = entity.getAbbreviation(); + this.created = entity.getCreated(); + this.definition = entity.getDefinition(); + this.dmps = entity.getDmps(); + this.startdate = entity.getStartdate(); + this.enddate = entity.getEnddate(); + this.modified = new Date(); + this.uri = entity.getUri(); + this.funder = entity.getFunder(); + if (entity.getContent() != null) this.content = entity.getContent(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Grant buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + if (fields.contains(currentBase + "dmps")) + this.dmps = tuple.stream().map(x -> new DMP().buildFromTuple(Arrays.asList(x), fields, currentBase + "dmps")).collect(Collectors.toSet()); + if (fields.contains(currentBase + "creationUser")) + this.creationUser = tuple.stream().map(x -> new UserInfo().buildFromTuple(Arrays.asList(x), fields, currentBase + "creationUser")).collect(Collectors.toList()).get(0); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Invitation.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Invitation.java new file mode 100644 index 000000000..d09b9d800 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Invitation.java @@ -0,0 +1,115 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.List; +import java.util.UUID; + + +@Entity +@Table(name = "\"Invitation\"") +public class Invitation implements DataEntity { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"Id\"", updatable = false, nullable = false) + private UUID id; + + @Column(name = "\"InvitationEmail\"", nullable = false) + private String invitationEmail; + + @OneToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "\"CreationUser\"", nullable = false) + private UserInfo user; + + @OneToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "\"Dmp\"", nullable = false) + private DMP dmp; + + @Column(name = "\"Token\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID token; + + @Column(name = "\"AcceptedInvitation\"", nullable = false) + private boolean acceptedInvitation; + + @Column(name = "\"Properties\"", columnDefinition = "xml") + private String properties; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getInvitationEmail() { + return invitationEmail; + } + + public void setInvitationEmail(String invitationEmail) { + this.invitationEmail = invitationEmail; + } + + public UserInfo getUser() { + return user; + } + + public void setUser(UserInfo user) { + this.user = user; + } + + public DMP getDmp() { + return dmp; + } + + public void setDmp(DMP dmp) { + this.dmp = dmp; + } + + public UUID getToken() { + return token; + } + + public void setToken(UUID token) { + this.token = token; + } + + public String getProperties() { + return properties; + } + + public void setProperties(String properties) { + this.properties = properties; + } + + public boolean getAcceptedInvitation() { + return acceptedInvitation; + } + + public void setAcceptedInvitation(boolean acceptedInvitation) { + this.acceptedInvitation = acceptedInvitation; + } + + @Override + public void update(Invitation entity) { + + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Invitation buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Lock.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Lock.java new file mode 100644 index 000000000..bf3e265b0 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Lock.java @@ -0,0 +1,95 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Entity +@Table(name = "\"Lock\"") +public class Lock implements DataEntity { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Target\"", nullable = false) + private UUID target; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "\"LockedBy\"", nullable = false) + private UserInfo lockedBy; + + @Column(name = "\"LockedAt\"") + @Convert(converter = DateToUTCConverter.class) + private Date lockedAt = new Date(); + + @Column(name = "\"TouchedAt\"") + @Convert(converter = DateToUTCConverter.class) + private Date touchedAt = null; + + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getTarget() { + return target; + } + + public void setTarget(UUID target) { + this.target = target; + } + + public UserInfo getLockedBy() { + return lockedBy; + } + + public void setLockedBy(UserInfo lockedBy) { + this.lockedBy = lockedBy; + } + + public Date getLockedAt() { + return lockedAt; + } + + public void setLockedAt(Date lockedAt) { + this.lockedAt = lockedAt; + } + + public Date getTouchedAt() { + return touchedAt; + } + + public void setTouchedAt(Date touchedAt) { + this.touchedAt = touchedAt; + } + + @Override + public void update(Lock entity) { + this.touchedAt = entity.touchedAt; + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Lock buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Notification.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Notification.java new file mode 100644 index 000000000..3259f1f26 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Notification.java @@ -0,0 +1,175 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.enumeration.notification.ActiveStatus; +import eu.eudat.old.data.enumeration.notification.NotifyState; +import eu.eudat.old.data.enumeration.notification.ContactType; +import eu.eudat.old.data.enumeration.notification.NotificationType; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Entity +@Table(name = "\"Notification\"") +public class Notification implements DataEntity { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "\"UserId\"") + private UserInfo userId; + + @Enumerated + @Column(name = "\"IsActive\"", nullable = false) + private ActiveStatus isActive; + + @Enumerated + @Column(name = "\"Type\"", nullable = false) + private NotificationType type; + + @Enumerated + @Column(name = "\"ContactTypeHint\"") + private ContactType contactTypeHint; + + @Column(name = "\"ContactHint\"") + private String contactHint; + + @Column(name = "\"Data\"") + private String data; + + @Enumerated + @Column(name = "\"NotifyState\"") + private NotifyState notifyState; + + @Column(name = "\"NotifiedAt\"") + private Date notifiedAt; + + @Column(name = "\"RetryCount\"") + private Integer retryCount; + + @Column(name = "\"CreatedAt\"") + private Date createdAt; + + @Column(name = "\"UpdatedAt\"") + private Date updatedAt; + + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UserInfo getUserId() { + return userId; + } + + public void setUserId(UserInfo userId) { + this.userId = userId; + } + + public ActiveStatus getIsActive() { + return isActive; + } + + public void setIsActive(ActiveStatus isActive) { + this.isActive = isActive; + } + + public NotificationType getType() { + return type; + } + + public void setType(NotificationType type) { + this.type = type; + } + + public ContactType getContactTypeHint() { + return contactTypeHint; + } + + public void setContactTypeHint(ContactType contactTypeHint) { + this.contactTypeHint = contactTypeHint; + } + + public String getContactHint() { + return contactHint; + } + + public void setContactHint(String contactHint) { + this.contactHint = contactHint; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public NotifyState getNotifyState() { + return notifyState; + } + + public void setNotifyState(NotifyState notifyState) { + this.notifyState = notifyState; + } + + public Date getNotifiedAt() { + return notifiedAt; + } + + public void setNotifiedAt(Date notifiedAt) { + this.notifiedAt = notifiedAt; + } + + public Integer getRetryCount() { + return retryCount; + } + + public void setRetryCount(Integer retryCount) { + this.retryCount = retryCount; + } + + public Date getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public Date getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Date updatedAt) { + this.updatedAt = updatedAt; + } + + @Override + public void update(Notification entity) { + } + + @Override + public UUID getKeys() { + return null; + } + + @Override + public Notification buildFromTuple(List tuple, List fields, String base) { + return null; + } + + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Organisation.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Organisation.java new file mode 100644 index 000000000..f210508de --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Organisation.java @@ -0,0 +1,152 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; +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 { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Label\"") + private String label; + + @Column(name = "\"Abbreviation\"") + private String abbreviation; + + @Column(name = "\"Reference\"", columnDefinition = "xml") + private String reference; + + @Column(name = "\"Uri\"") + private String uri; + + @Column(name = "\"Definition\"", columnDefinition = "xml") + private String definition; + + @OneToMany(fetch = FetchType.LAZY) + @JoinTable(name = "\"DMPOrganisation\"", + joinColumns = {@JoinColumn(name = "\"Organisation\"", referencedColumnName = "\"ID\"")}, + inverseJoinColumns = {@JoinColumn(name = "\"DMP\"", referencedColumnName = "\"ID\"")} + ) + private Set dmps; + + @Column(name = "\"Status\"", nullable = false) + private Short status; + + @Column(name = "\"Created\"") + @Convert(converter = DateToUTCConverter.class) + private Date created = null; + + @Column(name = "\"Modified\"") + @Convert(converter = DateToUTCConverter.class) + private Date modified = new Date(); + + + 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 String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getAbbreviation() { + return abbreviation; + } + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + + public String getDefinition() { + return definition; + } + public void setDefinition(String definition) { + this.definition = definition; + } + + public Set getDmps() { + return dmps; + } + public void setDmps(Set dmps) { + this.dmps = dmps; + } + + @Override + public void update(Organisation entity) { + + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Organisation buildFromTuple(List tuple,List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Project.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Project.java new file mode 100644 index 000000000..5a233d833 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Project.java @@ -0,0 +1,289 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.*; +import java.util.stream.Collectors; + +@Entity +@Table(name = "\"Project\"") +public class Project implements DataEntity { + + public enum Status { + ACTIVE((short) 1), INACTIVE((short) 0), DELETED((short) 99); + + private short value; + + Status(short value) { + this.value = value; + } + + public short getValue() { + return value; + } + + public static Status fromInteger(int value) { + switch (value) { + case 0: + return INACTIVE; + case 1: + return ACTIVE; + case 99: + return DELETED; + default: + throw new RuntimeException("Unsupported Project Status"); + } + } + } + + public enum ProjectType { + EXTERNAL(0), INTERNAL(1); + + private Integer value; + + ProjectType(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + public static ProjectType fromInteger(int value) { + switch (value) { + case 0: + return EXTERNAL; + case 1: + return INTERNAL; + default: + throw new RuntimeException("Unsupported Project Type"); + } + } + } + + @Id + //@GeneratedValue + //@GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @OneToMany(mappedBy = "project") + private Set dmps; + + @Column(name = "\"Label\"") + private String label; + + @Column(name = "\"Abbreviation\"") + private String abbreviation; + + @Column(name = "\"Reference\"", columnDefinition = "xml", nullable = true) + private String reference; + + @Column(name = "\"Uri\"") + private String uri; + + @Column(name = "\"Definition\"", columnDefinition = "xml") + private String definition; + + @Column(name = "\"StartDate\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date startdate = null; + + @Column(name = "\"EndDate\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date enddate = null; + + @Column(name = "\"Status\"", nullable = false) + private Short status; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"CreationUser\"", nullable = true) + private UserInfo creationUser; + + @Column(name = "\"Created\"") + private Date created = null; + + @Column(name = "\"Modified\"") + private Date modified = new Date(); + + @Column(name = "\"Description\"") + private String description; + + @Column(name = "\"Type\"") + private Integer type; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"Content\"") + private Content content; + + public Project() { + } + + public Project(Project project) {this.id = project.getId();} + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public Set getDmps() { + return dmps; + } + public void setDmps(Set dmps) { + this.dmps = dmps; + } + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getAbbreviation() { + return abbreviation; + } + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + + public String getDefinition() { + return definition; + } + public void setDefinition(String definition) { + this.definition = definition; + } + + public Date getStartdate() { + return startdate; + } + public void setStartdate(Date startdate) { + this.startdate = startdate; + } + + public Date getEnddate() { + return enddate; + } + public void setEnddate(Date enddate) { + this.enddate = enddate; + } + + public Short getStatus() { + return status; + } + public void setStatus(Short status) { + this.status = status; + } + + public UserInfo getCreationUser() { + return creationUser; + } + public void setCreationUser(UserInfo creationUser) { + this.creationUser = creationUser; + } + + 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 String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + + public Integer getType() { + return type; + } + public void setType(Integer type) { + this.type = type; + } + + public Content getContent() { + return content; + } + public void setContent(Content content) { + this.content = content; + } + + @Override + public void update(Project entity) { + this.description = entity.getDescription(); + this.label = entity.getLabel(); + this.abbreviation = entity.getAbbreviation(); + this.created = entity.getCreated(); + this.definition = entity.getDefinition(); + this.dmps = entity.getDmps(); + this.startdate = entity.getStartdate(); + this.enddate = entity.getEnddate(); + this.modified = new Date(); + this.uri = entity.getUri(); + if (entity.getContent() != null) this.content = entity.getContent(); + } + + public Project projectFromGrant(Grant grant) { + Project project = new Project(); + project.setDescription(grant.getDescription()); + project.setLabel(grant.getLabel()); + project.setAbbreviation(grant.getAbbreviation()); + project.setCreated(new Date()); + project.setDefinition(grant.getDefinition()); + project.setDmps(grant.getDmps()); + project.setStartdate(grant.getStartdate()); + project.setEnddate(grant.getEnddate()); + project.setModified(new Date()); + project.setUri(grant.getUri()); + project.setContent(grant.getContent()); + project.setReference(grant.getReference()); + project.setStatus(grant.getStatus()); + + return project; + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Project buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + if (fields.contains(currentBase + "dmps")) + this.dmps = tuple.stream().map(x -> new DMP().buildFromTuple(Arrays.asList(x), fields, currentBase + "dmps")).collect(Collectors.toSet()); + if (fields.contains(currentBase + "creationUser")) + this.creationUser = tuple.stream().map(x -> new UserInfo().buildFromTuple(Arrays.asList(x), fields, currentBase + "creationUser")).collect(Collectors.toList()).get(0); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Registry.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Registry.java new file mode 100644 index 000000000..d20581a1a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Registry.java @@ -0,0 +1,157 @@ +package eu.eudat.old.data.entities; + + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.Set; +import java.util.UUID; + + +@Entity +@Table(name = "\"Registry\"") +public class Registry implements DataEntity { + + @Id + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Label\"") + private String label; + + @Column(name = "\"Abbreviation\"") + private String abbreviation; + + @Column(name = "\"Reference\"", nullable = true) + private String reference; + + @Column(name = "\"Uri\"") + private String uri; + + @Column(name = "\"Definition\"", columnDefinition = "xml") + private String definition; + + @OneToMany(fetch = FetchType.LAZY) + @JoinTable(name = "\"DatasetRegistry\"", + joinColumns = {@JoinColumn(name = "\"Registry\"", referencedColumnName = "\"ID\"")}, + inverseJoinColumns = {@JoinColumn(name = "\"Dataset\"", referencedColumnName = "\"ID\"")} + ) + private Set datasets; + + @Column(name = "\"Status\"", nullable = false) + private Short status; + + @Column(name = "\"Created\"") + @Convert(converter = DateToUTCConverter.class) + private Date created = null; + + @Column(name = "\"Modified\"") + @Convert(converter = DateToUTCConverter.class) + private Date modified = new Date(); + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"CreationUser\"", nullable = true) + private UserInfo creationUser; + + + 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 String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getAbbreviation() { + return abbreviation; + } + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + + public String getDefinition() { + return definition; + } + public void setDefinition(String definition) { + this.definition = definition; + } + + public Set getDatasets() { + return datasets; + } + public void setDatasets(Set datasets) { + this.datasets = datasets; + } + + public UserInfo getCreationUser() { + return creationUser; + } + public void setCreationUser(UserInfo creationUser) { + this.creationUser = creationUser; + } + + @Override + public void update(Registry entity) { + this.label = entity.getLabel(); + this.abbreviation = entity.getAbbreviation(); + this.uri = entity.getUri(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Registry buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Researcher.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Researcher.java new file mode 100644 index 000000000..bb922d4b2 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Researcher.java @@ -0,0 +1,159 @@ +package eu.eudat.old.data.entities; + + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.Set; +import java.util.UUID; + + +@Entity +@Table(name = "\"Researcher\"") +public class Researcher implements DataEntity { + + @Id + /*@GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2")*/ + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Label\"", nullable = false, length = 250) + private String label; + + @Column(name = "\"Uri\"") + private String uri; + + @Column(name = "\"PrimaryEmail\"") + private String primaryEmail; + + @Column(name = "\"Definition\"", columnDefinition = "xml") + private String definition; + + @Column(name = "\"Reference\"", columnDefinition = "xml") + private String reference; + + + @OneToMany(fetch = FetchType.LAZY) + @JoinTable(name = "\"DMPResearcher\"", + joinColumns = {@JoinColumn(name = "\"Researcher\"", referencedColumnName = "\"ID\"")}, + inverseJoinColumns = {@JoinColumn(name = "\"DMP\"", referencedColumnName = "\"ID\"")} + ) + private Set dMPs; + + + @Column(name = "\"Status\"", nullable = false) + private Short status; + + + @Column(name = "\"Created\"") + @Convert(converter = DateToUTCConverter.class) + private Date created = null; + + @Column(name = "\"Modified\"") + @Convert(converter = DateToUTCConverter.class) + private Date modified = new Date(); + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"CreationUser\"", nullable = true) + private UserInfo creationUser; + + 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 String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getPrimaryEmail() { + return primaryEmail; + } + public void setPrimaryEmail(String primaryEmail) { + this.primaryEmail = primaryEmail; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + + public String getDefinition() { + return definition; + } + public void setDefinition(String definition) { + this.definition = definition; + } + + public Set getdMPs() { + return dMPs; + } + public void setdMPs(Set dMPs) { + this.dMPs = dMPs; + } + + public UserInfo getCreationUser() { + return creationUser; + } + public void setCreationUser(UserInfo creationUser) { + this.creationUser = creationUser; + } + + @Override + public void update(Researcher entity) { + + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Researcher buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Service.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Service.java new file mode 100644 index 000000000..aa748734c --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/Service.java @@ -0,0 +1,152 @@ +package eu.eudat.old.data.entities; + + +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.Set; +import java.util.UUID; + + +@Entity +@Table(name = "\"Service\"") +public class Service implements DataEntity { + + @Id + @Column(name = "\"ID\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Label\"") + private String label; + + @Column(name = "\"Abbreviation\"") + private String abbreviation; + + @Column(name = "\"Reference\"", nullable = true) + private String reference; + + @Column(name = "\"Uri\"") + private String uri; + + @Column(name = "\"Definition\"", columnDefinition = "xml") + private String definition; + + @OneToMany(mappedBy = "service", cascade = CascadeType.ALL, orphanRemoval = true) + private Set services; + + @Column(name = "\"Status\"", nullable = false) + private Short status; + + @Column(name = "\"Created\"") + @Convert(converter = DateToUTCConverter.class) + private Date created = null; + + @Column(name = "\"Modified\"") + @Convert(converter = DateToUTCConverter.class) + private Date modified = new Date(); + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"CreationUser\"", nullable = true) + private UserInfo creationUser; + + + 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 String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getAbbreviation() { + return abbreviation; + } + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getReference() { + return reference; + } + public void setReference(String reference) { + this.reference = reference; + } + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + + public String getDefinition() { + return definition; + } + public void setDefinition(String definition) { + this.definition = definition; + } + + public Set getServices() { + return services; + } + public void setServices(Set services) { + this.services = services; + } + + public UserInfo getCreationUser() { + return creationUser; + } + public void setCreationUser(UserInfo creationUser) { + this.creationUser = creationUser; + } + + @Override + public void update(Service entity) { + this.label = entity.getLabel(); + this.abbreviation = entity.getAbbreviation(); + this.uri = entity.getUri(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public Service buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = UUID.fromString((String) tuple.get(0).get(currentBase + "id")); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserDMP.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserDMP.java new file mode 100644 index 000000000..37b49b1e2 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserDMP.java @@ -0,0 +1,115 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; + +@Entity +@Table(name = "\"UserDMP\"") +public class UserDMP implements DataEntity { + + public enum UserDMPRoles { + OWNER(0), USER(1); + + private Integer value; + + private UserDMPRoles(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + public static List getAllValues() { + List list = new LinkedList<>(); + for (Enum en : UserDMP.UserDMPRoles.values()) { + list.add(((UserDMPRoles) en).value); + } + return list; + } + + public static UserDMPRoles fromInteger(Integer value) { + switch (value) { + case 0: + return OWNER; + case 1: + return USER; + default: + throw new RuntimeException("Unsupported User Dmp Role Message Code"); + } + } + } + + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "usr") + private UserInfo user; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "dmp") + private DMP dmp; + + @Column(name = "role") + private Integer role; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UserInfo getUser() { + return user; + } + + public void setUser(UserInfo user) { + this.user = user; + } + + public DMP getDmp() { + return dmp; + } + + public void setDmp(DMP dmp) { + this.dmp = dmp; + } + + public Integer getRole() { + return role; + } + + public void setRole(Integer role) { + this.role = role; + } + + @Override + public void update(UserDMP entity) { + this.role = entity.getRole(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public UserDMP buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserDatasetProfile.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserDatasetProfile.java new file mode 100644 index 000000000..2cde1f89a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserDatasetProfile.java @@ -0,0 +1,79 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.List; +import java.util.UUID; + +@Entity +@Table(name = "\"UserDatasetProfile\"") +public class UserDatasetProfile implements DataEntity { + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "usr") + private UserInfo user; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "\"descriptionTemplate\"") + private DescriptionTemplate descriptionTemplate; + + @Column(name = "role") + private Integer role; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UserInfo getUser() { + return user; + } + + public void setUser(UserInfo user) { + this.user = user; + } + + public DescriptionTemplate getDatasetProfile() { + return descriptionTemplate; + } + + public void setDatasetProfile(DescriptionTemplate descriptionTemplate) { + this.descriptionTemplate = descriptionTemplate; + } + + public Integer getRole() { + return role; + } + + public void setRole(Integer role) { + this.role = role; + } + + @Override + public void update(UserDatasetProfile entity) { + this.role = entity.getRole(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public UserDatasetProfile buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserInfo.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserInfo.java new file mode 100644 index 000000000..d64a018f0 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserInfo.java @@ -0,0 +1,221 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.*; + + +@Entity +@Table(name = "\"UserInfo\"") +@NamedEntityGraphs({ + @NamedEntityGraph( + name = "userInfo", + attributeNodes = {@NamedAttributeNode("userRoles"), @NamedAttributeNode("credentials"), @NamedAttributeNode("additionalinfo")}), +}) +public class UserInfo implements DataEntity { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + + @Column(name = "email") + private String email = null; + + @Column(name = "authorization_level", nullable = false) + private Short authorization_level; //0 admin, 1 user + + @Column(name = "usertype", nullable = false) + private Short usertype; // 0 internal, 1 external + + @Column(name = "userstatus", nullable = false) + private Short userStatus; // 0 active, 1 inactive + + @Column(name = "verified_email", nullable = true) + private Boolean verified_email = null; + + @Column(name = "name", nullable = true) + private String name = null; + + + @Column(name = "created", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date created = null; + + + @Column(name = "lastloggedin", nullable = true) + @Convert(converter = DateToUTCConverter.class) + private Date lastloggedin = null; + + + @Column(name = "additionalinfo") + private String additionalinfo; + + @OneToMany(fetch = FetchType.LAZY) + @JoinTable(name = "\"UserDMP\"", + joinColumns = {@JoinColumn(name = "usr", referencedColumnName = "id")}, + inverseJoinColumns = {@JoinColumn(name = "dmp", referencedColumnName = "\"ID\"")} + ) + private Set dmps; + + @OneToMany(mappedBy = "userInfo", fetch = FetchType.LAZY) + private Set credentials = new HashSet<>(); + + @OneToMany(mappedBy = "userInfo", fetch = FetchType.LAZY) + private Set userRoles = new HashSet<>(); + + @OneToMany(mappedBy = "lockedBy", fetch = FetchType.LAZY) + private Set locks = new HashSet<>(); + + @OneToMany(mappedBy = "userId", fetch = FetchType.LAZY) + private Set notifications = new HashSet<>(); + + public Set getDmps() { + return dmps; + } + + public void setDmps(Set dmps) { + this.dmps = dmps; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getLastloggedin() { + return lastloggedin; + } + + public void setLastloggedin(Date lastloggedin) { + this.lastloggedin = lastloggedin; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Short getAuthorization_level() { + return authorization_level; + } + + public void setAuthorization_level(Short authorization_level) { + this.authorization_level = authorization_level; + } + + public Short getUsertype() { + return usertype; + } + + public void setUsertype(Short usertype) { + this.usertype = usertype; + } + + public Boolean getVerified_email() { + return verified_email; + } + + public void setVerified_email(Boolean verified_email) { + this.verified_email = verified_email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAdditionalinfo() { + return additionalinfo; + } + + public void setAdditionalinfo(String additionalinfo) { + this.additionalinfo = additionalinfo; + } + + public Set getCredentials() { + return credentials; + } + + public void setCredentials(Set credentials) { + this.credentials = credentials; + } + + public Set getUserRoles() { + return userRoles; + } + + public void setUserRoles(Set userRoles) { + this.userRoles = userRoles; + } + + public Set getLocks() { + return locks; + } + + public void setLocks(Set locks) { + this.locks = locks; + } + + public Set getNotifications() { + return notifications; + } + + public void setNotifications(Set notifications) { + this.notifications = notifications; + } + + public Short getUserStatus() { + return userStatus; + } + + public void setUserStatus(Short userStatus) { + this.userStatus = userStatus; + } + + @Override + public void update(UserInfo entity) { + this.name = entity.getName(); + this.email = entity.getEmail(); + this.additionalinfo = entity.getAdditionalinfo(); + this.lastloggedin = entity.getLastloggedin(); + this.userRoles = entity.getUserRoles(); + this.userStatus = entity.getUserStatus(); + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public UserInfo buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserRole.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserRole.java new file mode 100644 index 000000000..94b23234b --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserRole.java @@ -0,0 +1,69 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.List; +import java.util.UUID; + + +@Entity +@Table(name = "\"UserRole\"") +public class UserRole implements DataEntity { + + @Id + @GeneratedValue + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Column(name = "\"Id\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + @Column(name = "\"Role\"", nullable = false) + private int role; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "\"UserId\"", nullable = false) + private UserInfo userInfo; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public int getRole() { + return role; + } + + public void setRole(int role) { + this.role = role; + } + + public UserInfo getUserInfo() { + return userInfo; + } + + public void setUserInfo(UserInfo userInfo) { + this.userInfo = userInfo; + } + + @Override + public void update(UserRole entity) { + + } + + @Override + public UUID getKeys() { + return this.id; + } + + @Override + public UserRole buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserToken.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserToken.java new file mode 100644 index 000000000..ca5758a4d --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/UserToken.java @@ -0,0 +1,82 @@ +package eu.eudat.old.data.entities; + +import eu.eudat.old.data.entities.helpers.EntityBinder; +import eu.eudat.old.data.converters.DateToUTCConverter; +import eu.eudat.old.queryable.queryableentity.DataEntity; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; +import java.util.UUID; + + +@Entity +@Table(name = "\"UserToken\"") +public class UserToken implements DataEntity { + + @Id + @Column(name = "\"Token\"", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID token; + + @OneToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "\"UserId\"", nullable = false) + private UserInfo user; + + @Column(name = "\"IssuedAt\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date issuedAt = null; + + + @Column(name = "\"ExpiresAt\"", nullable = false) + @Convert(converter = DateToUTCConverter.class) + private Date expiresAt = null; + + public UUID getToken() { + return token; + } + + public void setToken(UUID token) { + this.token = token; + } + + public UserInfo getUser() { + return user; + } + + public void setUser(UserInfo user) { + this.user = user; + } + + public Date getIssuedAt() { + return issuedAt; + } + + public void setIssuedAt(Date issuedAt) { + this.issuedAt = issuedAt; + } + + public Date getExpiresAt() { + return expiresAt; + } + + public void setExpiresAt(Date expiresAt) { + this.expiresAt = expiresAt; + } + + @Override + public void update(UserToken entity) { + + } + + @Override + public UUID getKeys() { + return this.token; + } + + @Override + public UserToken buildFromTuple(List tuple, List fields, String base) { + String currentBase = base.isEmpty() ? "" : base + "."; + if (fields.contains(currentBase + "token")) this.token = EntityBinder.fromTuple(tuple, currentBase + "token"); + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/helpers/EntityBinder.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/helpers/EntityBinder.java new file mode 100644 index 000000000..d480defdf --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/entities/helpers/EntityBinder.java @@ -0,0 +1,14 @@ +package eu.eudat.old.data.entities.helpers; + +import javax.persistence.Tuple; +import java.util.List; + +public class EntityBinder { + public static T fromTuple(List tuple, String path) { + try { + return (T) tuple.get(0).get(path); + }catch (IllegalArgumentException illegalArgument){ + return null; + } + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/ActiveStatus.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/ActiveStatus.java new file mode 100644 index 000000000..3910fc777 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/ActiveStatus.java @@ -0,0 +1,27 @@ +package eu.eudat.old.data.enumeration.notification; + +public enum ActiveStatus { + ACTIVE(0), + INACTIVE(1); + + private int status; + + ActiveStatus(int status) { + this.status = status; + } + + public int getStatus() { + return status; + } + + public ActiveStatus fromInteger(int status) { + switch (status) { + case 0: + return ACTIVE; + case 1: + return INACTIVE; + default: + throw new RuntimeException("Unsupported Active Status"); + } + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/ContactType.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/ContactType.java new file mode 100644 index 000000000..3a5f0afbc --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/ContactType.java @@ -0,0 +1,24 @@ +package eu.eudat.old.data.enumeration.notification; + +public enum ContactType { + EMAIL(0); + + private int type; + + ContactType(int type) { + this.type = type; + } + + public int getType() { + return type; + } + + public ContactType fromInteger(int type) { + switch (type) { + case 0: + return EMAIL; + default: + throw new RuntimeException("Unsupported Contact Type"); + } + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/NotificationType.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/NotificationType.java new file mode 100644 index 000000000..b4912ae18 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/NotificationType.java @@ -0,0 +1,39 @@ +package eu.eudat.old.data.enumeration.notification; + +public enum NotificationType { + DMP_MODIFIED(0), + DATASET_MODIFIED(1), + DMP_PUBLISH(2), + DMP_FINALISED(3), + DMP_MODIFIED_FINALISED(4), + DATASET_MODIFIED_FINALISED(5); + + private int type; + + NotificationType(int type) { + this.type = type; + } + + public int getType() { + return type; + } + + public NotificationType fromInteger(int type) { + switch (type) { + case 0: + return DMP_MODIFIED; + case 1: + return DATASET_MODIFIED; + case 2: + return DMP_PUBLISH; + case 3: + return DMP_FINALISED; + case 4: + return DMP_MODIFIED_FINALISED; + case 5: + return DATASET_MODIFIED_FINALISED; + default: + throw new RuntimeException("Unsupported Notification Type"); + } + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/NotifyState.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/NotifyState.java new file mode 100644 index 000000000..823f1d4d2 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/enumeration/notification/NotifyState.java @@ -0,0 +1,36 @@ +package eu.eudat.old.data.enumeration.notification; + +public enum NotifyState { + PENDING(0), + PROCESSING(1), + SENDING(2), + SUCCEEDED(3), + ERROR(4); + + private int state; + + NotifyState(int state) { + this.state = state; + } + + public int getState() { + return state; + } + + public NotifyState fromInteger(int state) { + switch (state) { + case 0: + return PENDING; + case 1: + return PROCESSING; + case 2: + return SENDING; + case 3: + return SUCCEEDED; + case 4: + return ERROR; + default: + throw new RuntimeException("Unsupported Notify State"); + } + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/PaginationService.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/PaginationService.java new file mode 100644 index 000000000..1271ef25b --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/PaginationService.java @@ -0,0 +1,61 @@ +package eu.eudat.old.data.query; + +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.data.query.definition.helpers.Ordering; +import eu.eudat.old.data.query.definition.helpers.ColumnOrderings; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.queryableentity.DataEntity; + +import java.util.Arrays; +import java.util.Collection; + +/** + * Created by ikalyvas on 3/21/2018. + */ +public class PaginationService { + public static QueryableList applyPaging(QueryableList items, TableQuery tableRequest) { + if (tableRequest.getOrderings() != null) applyOrder(items, tableRequest); + if (tableRequest.getLength() != null) items.take(tableRequest.getLength()); + if (tableRequest.getOffset() != null) items.skip(tableRequest.getOffset()); + if (tableRequest.getSelection() != null && tableRequest.getSelection().getFields() != null && tableRequest.getSelection().getFields().length > 0) + items.withFields(Arrays.asList(tableRequest.getSelection().getFields())); + return items; + } + public static void applyOrder(QueryableList items, TableQuery tableRequest) { + applyOrder(items, tableRequest.getOrderings()); + } + + + public static void applyOrder(QueryableList items, ColumnOrderings columnOrderings) { + for (Ordering ordering : columnOrderings.getFieldOrderings()) { + if (ordering.getOrderByType() == Ordering.OrderByType.ASC) + applyAscOrder(items, ordering); + if (ordering.getOrderByType() == Ordering.OrderByType.DESC) { + applyDescOrder(items, ordering); + } + } + return; + } + + private static void applyAscOrder(QueryableList items, Ordering ordering) { + if (ordering.getColumnType() == Ordering.ColumnType.COUNT) { + items.orderBy((builder, root) -> builder.asc(builder.size(root.get(ordering.getFieldName())))); + } else if (ordering.getColumnType() == Ordering.ColumnType.JOIN_COLUMN) { + String[] fields = ordering.getFieldName().split(":"); + items.orderBy((builder, root) -> builder.asc(root.get(fields[0]).get(fields[1]))); + } else { + items.orderBy((builder, root) -> builder.asc(root.get(ordering.getFieldName()))); + } + } + + private static void applyDescOrder(QueryableList items, Ordering ordering) { + if (ordering.getColumnType() == Ordering.ColumnType.COUNT) { + items.orderBy((builder, root) -> builder.desc(builder.size(root.get(ordering.getFieldName())))); + } else if (ordering.getColumnType() == Ordering.ColumnType.JOIN_COLUMN) { + String[] fields = ordering.getFieldName().split(":"); + items.orderBy((builder, root) -> builder.desc(root.get(fields[0]).get(fields[1]))); + } else { + items.orderBy((builder, root) -> builder.desc(root.get(ordering.getFieldName()))); + } + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/Collector.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/Collector.java new file mode 100644 index 000000000..64b1fcf6a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/Collector.java @@ -0,0 +1,14 @@ +package eu.eudat.old.data.query.definition; + +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.queryableentity.DataEntity; + +/** + * Created by ikalyvas on 3/21/2018. + */ +public interface Collector { + QueryableList collect() throws Exception; + + QueryableList collect(QueryableList repo) throws Exception; + +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/CriteriaQuery.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/CriteriaQuery.java new file mode 100644 index 000000000..29c52ddc9 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/CriteriaQuery.java @@ -0,0 +1,13 @@ +package eu.eudat.old.data.query.definition; + +import eu.eudat.old.data.dao.criteria.Criteria; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.queryableentity.DataEntity; + +/** + * Created by ikalyvas on 3/21/2018. + */ +public interface CriteriaQuery, T extends DataEntity> extends Collector { + + QueryableList applyCriteria(); +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/Query.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/Query.java new file mode 100644 index 000000000..b2da497d6 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/Query.java @@ -0,0 +1,74 @@ +package eu.eudat.old.data.query.definition; + +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.criteria.Criteria; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import io.swagger.annotations.ApiModelProperty; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class Query, T extends DataEntity> implements CriteriaQuery { + private static final Logger logger = LoggerFactory.getLogger(Query.class); + private C criteria; + @ApiModelProperty(value = "query", name = "query", dataType = "String", hidden = true) + private QueryableList query; + + public static class QueryBuilder, T extends DataEntity, Q extends Query> { + private C criteria; + private QueryableList query; + private Class tClass; + + public QueryBuilder(Class tClass) { + this.tClass = tClass; + } + + public QueryBuilder criteria(C criteria) { + this.criteria = criteria; + return this; + } + + public QueryBuilder query(QueryableList query) { + this.query = query; + return this; + } + + public Q build() { + try { + Q q = tClass.newInstance(); + q.setCriteria(criteria); + q.setQuery(query); + return q; + } catch (InstantiationException | IllegalAccessException e) { + logger.error (e.getMessage(), e); + } + return null; + } + } + + public QueryableList getQuery() { + return query; + } + + public void setQuery(QueryableList query) { + this.query = query; + } + + public C getCriteria() { + return criteria; + } + + public void setCriteria(C criteria) { + this.criteria = criteria; + } + + @Override + public QueryableList collect() { + return this.applyCriteria(); + } + + @Override + public QueryableList collect(QueryableList repo) { + this.query = repo; + return this.applyCriteria(); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/TableCriteriaQuery.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/TableCriteriaQuery.java new file mode 100644 index 000000000..9699a4f88 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/TableCriteriaQuery.java @@ -0,0 +1,12 @@ +package eu.eudat.old.data.query.definition; + +import eu.eudat.old.data.dao.criteria.Criteria; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.queryableentity.DataEntity; + +/** + * Created by ikalyvas on 3/21/2018. + */ +public interface TableCriteriaQuery, T extends DataEntity> extends CriteriaQuery { + QueryableList applyPaging(QueryableList items) ; +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/TableQuery.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/TableQuery.java new file mode 100644 index 000000000..21ba99f35 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/TableQuery.java @@ -0,0 +1,62 @@ +package eu.eudat.old.data.query.definition; + + +import eu.eudat.old.data.dao.criteria.Criteria; +import eu.eudat.old.data.query.definition.helpers.ColumnOrderings; +import eu.eudat.old.data.query.definition.helpers.SelectionFields; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import io.swagger.annotations.ApiModelProperty; + + +public abstract class TableQuery, T extends DataEntity, K> extends Query implements TableCriteriaQuery { + private ColumnOrderings orderings; + @ApiModelProperty(hidden = true) + private SelectionFields selection; + @ApiModelProperty(value = "length", name = "length", dataType = "Integer", example = "2") + private Integer length; + @ApiModelProperty(value = "offset", name = "offset", dataType = "Integer", example = "0") + private Integer offset; + + public Integer getLength() { + return length; + } + + public void setLength(Integer length) { + this.length = length; + } + + public Integer getOffset() { + return offset; + } + + public void setOffset(Integer offset) { + this.offset = offset; + } + + public ColumnOrderings getOrderings() { + return orderings; + } + + public void setOrderings(ColumnOrderings orderings) { + this.orderings = orderings; + } + + public SelectionFields getSelection() { + return selection; + } + + public void setSelection(SelectionFields selection) { + this.selection = selection; + } + + @Override + public QueryableList collect() { + return this.applyPaging(super.collect()); + } + + @Override + public QueryableList collect(QueryableList repo) { + return this.applyPaging(super.collect(repo)); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/helpers/ColumnOrderings.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/helpers/ColumnOrderings.java new file mode 100644 index 000000000..d5dde86c0 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/helpers/ColumnOrderings.java @@ -0,0 +1,46 @@ +package eu.eudat.old.data.query.definition.helpers; + +import io.swagger.annotations.ApiModelProperty; + +import java.util.LinkedList; +import java.util.List; + + +public class ColumnOrderings { + + @ApiModelProperty(value = "fields", name = "fields", dataType = "List", example = "[]") + private List fields; + + public List getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } + + public List getFieldOrderings() { + List orderings = new LinkedList<>(); + for (String field : fields) { + orderings.add(this.orderingFromString(field)); + } + return orderings; + } + + private Ordering orderingFromString(String field) { + Ordering ordering = new Ordering(field); + if (ordering.getFieldName().contains("+")) + ordering.fieldName(ordering.getFieldName().replace("+", "")).orderByType(Ordering.OrderByType.ASC); + else if (ordering.getFieldName().startsWith("-")) + ordering.fieldName(ordering.getFieldName().replace("-", "")).orderByType(Ordering.OrderByType.DESC); + if (ordering.getFieldName().contains("|count|")) + ordering.fieldName(ordering.getFieldName().replace("|count|", "")).columnType(Ordering.ColumnType.COUNT); + else if (ordering.getFieldName().contains("|join|")) + ordering.fieldName(ordering.getFieldName().replace("|join|", "")).columnType(Ordering.ColumnType.JOIN_COLUMN); + else if (ordering.getFieldName().equals("asc")) + ordering.fieldName("label").orderByType(Ordering.OrderByType.ASC); + else if (ordering.getFieldName().equals("desc")) + ordering.fieldName("label").orderByType(Ordering.OrderByType.DESC); + return ordering; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/helpers/Ordering.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/helpers/Ordering.java new file mode 100644 index 000000000..5ba39993c --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/helpers/Ordering.java @@ -0,0 +1,59 @@ +package eu.eudat.old.data.query.definition.helpers; + + +public class Ordering { + public enum OrderByType { + ASC, DESC + } + + public enum ColumnType { + COUNT, COLUMN, JOIN_COLUMN + } + + private String fieldName; + private OrderByType orderByType; + private ColumnType columnType; + + public Ordering(String fieldName) { + this.fieldName = fieldName; + } + + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public OrderByType getOrderByType() { + return orderByType; + } + + public void setOrderByType(OrderByType orderByType) { + this.orderByType = orderByType; + } + + public Ordering fieldName(String fieldName) { + this.fieldName = fieldName; + return this; + } + + public Ordering orderByType(OrderByType orderByType) { + this.orderByType = orderByType; + return this; + } + + public ColumnType getColumnType() { + return columnType; + } + + public void setColumnType(ColumnType columnType) { + this.columnType = columnType; + } + + public Ordering columnType(ColumnType columnType) { + this.columnType = columnType; + return this; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/helpers/SelectionFields.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/helpers/SelectionFields.java new file mode 100644 index 000000000..ea3828771 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/definition/helpers/SelectionFields.java @@ -0,0 +1,18 @@ +package eu.eudat.old.data.query.definition.helpers; + + +import io.swagger.annotations.ApiModelProperty; + +public class SelectionFields { + + @ApiModelProperty(value = "fields", name = "fields", dataType = "String[]", example = "[]") + private String[] fields; + + public String[] getFields() { + return fields; + } + + public void setFields(String[] fields) { + this.fields = fields; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/dmpblueprint/DataManagementPlanBlueprintTableRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/dmpblueprint/DataManagementPlanBlueprintTableRequest.java new file mode 100644 index 000000000..7cab09a5d --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/dmpblueprint/DataManagementPlanBlueprintTableRequest.java @@ -0,0 +1,27 @@ +package eu.eudat.old.data.query.items.dmpblueprint; + +import eu.eudat.old.data.entities.DMPProfile; +import eu.eudat.old.data.query.PaginationService; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.criteria.DataManagementPlanBlueprintCriteria; + +import java.util.UUID; + +public class DataManagementPlanBlueprintTableRequest extends TableQuery { + + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) + query.where((builder, root) -> builder.like(root.get("label"), "%" + this.getCriteria().getLike() + "%")); + if (this.getCriteria().getStatus() != null) + query.where((builder, root) -> builder.equal(root.get("status"), this.getCriteria().getStatus())); + return query; + } + + @Override + public QueryableList applyPaging(QueryableList items) { + return PaginationService.applyPaging(items, this); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/dataset/DatasetWizardAutocompleteRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/dataset/DatasetWizardAutocompleteRequest.java new file mode 100644 index 000000000..f3aad8ada --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/dataset/DatasetWizardAutocompleteRequest.java @@ -0,0 +1,17 @@ +package eu.eudat.old.data.query.items.item.dataset; + +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.query.definition.Query; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.criteria.DatasetWizardUserDmpCriteria; + +public class DatasetWizardAutocompleteRequest extends Query { + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery().where((builder, root) -> builder.or(builder.equal(root.get("creator"), this.getCriteria().getUserInfo()), builder.isMember(this.getCriteria().getUserInfo(), root.get("users")))); + if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) { + query.where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%")); + } + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/datasetprofile/DatasetProfileAutocompleteRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/datasetprofile/DatasetProfileAutocompleteRequest.java new file mode 100644 index 000000000..cbc9e9eef --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/datasetprofile/DatasetProfileAutocompleteRequest.java @@ -0,0 +1,24 @@ +package eu.eudat.old.data.query.items.item.datasetprofile; + +import eu.eudat.old.data.dao.criteria.DatasetProfileCriteria; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.data.query.PaginationService; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public class DatasetProfileAutocompleteRequest extends TableQuery { + @Override + public QueryableList applyCriteria() { + QueryableList 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 applyPaging(QueryableList items) { + return PaginationService.applyPaging(items, this); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/datasetprofile/DatasetProfileWizardAutocompleteRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/datasetprofile/DatasetProfileWizardAutocompleteRequest.java new file mode 100644 index 000000000..28ac3a271 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/datasetprofile/DatasetProfileWizardAutocompleteRequest.java @@ -0,0 +1,13 @@ +package eu.eudat.old.data.query.items.item.datasetprofile; + +import eu.eudat.old.data.dao.criteria.DatasetProfileWizardCriteria; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.data.query.definition.Query; +import eu.eudat.old.queryable.QueryableList; + +public class DatasetProfileWizardAutocompleteRequest extends Query { + @Override + public QueryableList applyCriteria() { + return null; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/dmp/DataManagementPlanCriteriaRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/dmp/DataManagementPlanCriteriaRequest.java new file mode 100644 index 000000000..f28974b67 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/dmp/DataManagementPlanCriteriaRequest.java @@ -0,0 +1,33 @@ +package eu.eudat.old.data.query.items.item.dmp; + +import eu.eudat.old.data.dao.criteria.DataManagementPlanCriteria; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.query.definition.Query; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; + +import java.util.Arrays; + +public class DataManagementPlanCriteriaRequest extends Query { + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), + builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%"))); + if (this.getCriteria().getPeriodEnd() != null) + query.where((builder, root) -> builder.lessThan(root.get("created"), this.getCriteria().getPeriodEnd())); + if (this.getCriteria().getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThan(root.get("created"), this.getCriteria().getPeriodStart())); + if (this.getCriteria().getGrants() != null && !this.getCriteria().getGrants().isEmpty()) + query.where(((builder, root) -> root.get("grant").in(this.getCriteria().getGrants()))); + if (!this.getCriteria().getAllVersions()) + query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("version"), query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("groupId"), nestedRoot.get("groupId")), Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "version")), String.class))); + if (this.getCriteria().getGroupIds() != null && !this.getCriteria().getGroupIds().isEmpty()) + query.where((builder, root) -> root.get("groupId").in(this.getCriteria().getGroupIds())); + query.where((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue())); + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/dmpprofile/DataManagementPlanProfileCriteriaRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/dmpprofile/DataManagementPlanProfileCriteriaRequest.java new file mode 100644 index 000000000..5922c24e1 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/dmpprofile/DataManagementPlanProfileCriteriaRequest.java @@ -0,0 +1,19 @@ +package eu.eudat.old.data.query.items.item.dmpprofile; + +import eu.eudat.old.data.dao.criteria.DataManagementPlanProfileCriteria; +import eu.eudat.old.data.entities.DMPProfile; +import eu.eudat.old.data.query.definition.Query; +import eu.eudat.old.queryable.QueryableList; + +/** + * Created by ikalyvas on 3/21/2018. + */ +public class DataManagementPlanProfileCriteriaRequest extends Query { + @Override + public QueryableList applyCriteria() { + QueryableList 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; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/funder/FunderCriteriaRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/funder/FunderCriteriaRequest.java new file mode 100644 index 000000000..5a66acba3 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/funder/FunderCriteriaRequest.java @@ -0,0 +1,17 @@ +package eu.eudat.old.data.query.items.item.funder; + +import eu.eudat.old.data.dao.criteria.FunderCriteria; +import eu.eudat.old.data.entities.Funder; +import eu.eudat.old.data.query.definition.Query; +import eu.eudat.old.queryable.QueryableList; + +public class FunderCriteriaRequest extends Query { + @Override + public QueryableList applyCriteria() { + QueryableList 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() + "%")); + query.where((builder, root) -> builder.notEqual(root.get("status"), Funder.Status.DELETED.getValue())); + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/grant/GrantCriteriaRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/grant/GrantCriteriaRequest.java new file mode 100644 index 000000000..179e995f5 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/grant/GrantCriteriaRequest.java @@ -0,0 +1,38 @@ +package eu.eudat.old.data.query.items.item.grant; + +import eu.eudat.old.data.dao.criteria.GrantCriteria; +import eu.eudat.old.data.entities.Grant; +import eu.eudat.old.data.query.definition.Query; +import eu.eudat.old.queryable.QueryableList; + +public class GrantCriteriaRequest extends Query { + private Integer length; + + public Integer getLength() { + return length; + } + + public void setLength(Integer length) { + this.length = length; + } + + private GrantCriteriaRequest() { + } + + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), + builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%"))); + if (this.getCriteria().getPeriodEnd() != null) + query.where((builder, root) -> builder.lessThan(root.get("enddate"), this.getCriteria().getPeriodEnd())); + if (this.getCriteria().getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThan(root.get("startdate"), this.getCriteria().getPeriodStart())); + if (this.getCriteria().getReference() != null) + query.where((builder, root) -> builder.equal(root.get("reference"), this.getCriteria().getReference())); + query.where((builder, root) -> builder.notEqual(root.get("status"), Grant.Status.DELETED.getValue())); + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/lock/LockCriteriaRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/lock/LockCriteriaRequest.java new file mode 100644 index 000000000..f240c44c8 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/lock/LockCriteriaRequest.java @@ -0,0 +1,20 @@ +package eu.eudat.old.data.query.items.item.lock; + +import eu.eudat.old.data.dao.criteria.LockCriteria; +import eu.eudat.old.data.entities.Lock; +import eu.eudat.old.data.query.definition.Query; +import eu.eudat.old.queryable.QueryableList; + +public class LockCriteriaRequest extends Query { + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + if (this.getCriteria().getTouchedAt() != null) + query.where((builder, root) -> builder.equal(root.get("touchedAt"), this.getCriteria().getTouchedAt())); + if (this.getCriteria().getLockedBy() != null) + query.where(((builder, root) -> builder.equal(root.get("lockedBy"), this.getCriteria().getLockedBy()))); + if (this.getCriteria().getTarget() != null) + query.where(((builder, root) -> builder.equal(root.get("target"), this.getCriteria().getTarget()))); + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/project/ProjectCriteriaRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/project/ProjectCriteriaRequest.java new file mode 100644 index 000000000..f5fa19184 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/project/ProjectCriteriaRequest.java @@ -0,0 +1,17 @@ +package eu.eudat.old.data.query.items.item.project; + +import eu.eudat.old.data.dao.criteria.ProjectCriteria; +import eu.eudat.old.data.entities.Project; +import eu.eudat.old.data.query.definition.Query; +import eu.eudat.old.queryable.QueryableList; + +public class ProjectCriteriaRequest extends Query { + @Override + public QueryableList applyCriteria() { + QueryableList 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() + "%")); + query.where((builder, root) -> builder.notEqual(root.get("status"), Project.Status.DELETED.getValue())); + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/researcher/ResearcherCriteriaRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/researcher/ResearcherCriteriaRequest.java new file mode 100644 index 000000000..518f40e6a --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/researcher/ResearcherCriteriaRequest.java @@ -0,0 +1,21 @@ +package eu.eudat.old.data.query.items.item.researcher; + +import eu.eudat.old.data.dao.criteria.ResearcherCriteria; +import eu.eudat.old.data.entities.Researcher; +import eu.eudat.old.data.query.definition.Query; +import eu.eudat.old.queryable.QueryableList; + +/** + * Created by ikalyvas on 3/6/2018. + */ +public class ResearcherCriteriaRequest extends Query { + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + if (this.getCriteria().getLike() != null) + query.where((builder, root) -> builder.equal(root.get("reference"), this.getCriteria().getLike())); + if (this.getCriteria().getName() != null) + query.where((builder, root) -> builder.equal(root.get("label"), this.getCriteria().getName())); + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/userinfo/UserInfoRequestItem.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/userinfo/UserInfoRequestItem.java new file mode 100644 index 000000000..d4fae1aca --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/item/userinfo/UserInfoRequestItem.java @@ -0,0 +1,20 @@ +package eu.eudat.old.data.query.items.item.userinfo; + +import eu.eudat.old.data.dao.criteria.UserInfoCriteria; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.query.definition.Query; +import eu.eudat.old.queryable.QueryableList; + +public class UserInfoRequestItem extends Query { + @Override + public QueryableList applyCriteria() { + QueryableList users = this.getQuery(); + if (this.getCriteria().getAppRoles() != null && !this.getCriteria().getAppRoles().isEmpty()) + users.where((builder, root) -> root.join("userRoles").get("role").in(this.getCriteria().getAppRoles())); + if (this.getCriteria().getLike() != null) + users.where((builder, root) -> builder.or(builder.like(builder.upper(root.get("name")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), builder.like(root.get("email"), "%" + this.getCriteria().getLike() + "%"))); + if (this.getCriteria().getEmail() != null) + users.where((builder, root) -> builder.equal(root.get("email"), this.getCriteria().getEmail())); + return users; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dataset/DatasetPublicTableRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dataset/DatasetPublicTableRequest.java new file mode 100644 index 000000000..38047f813 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dataset/DatasetPublicTableRequest.java @@ -0,0 +1,56 @@ +package eu.eudat.old.data.query.items.table.dataset; + +import eu.eudat.old.data.dao.criteria.DatasetPublicCriteria; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; +import eu.eudat.old.types.grant.GrantStateType; + +import java.util.Arrays; +import java.util.Date; +import java.util.UUID; + +/** + * Created by ikalyvas on 10/2/2018. + */ +public class DatasetPublicTableRequest extends TableQuery { + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + query.where((builder, root) -> builder.equal(root.get("dmp").get("isPublic"), true)); + query.where((builder, root) -> builder.equal(root.get("status"), Dataset.Status.FINALISED.getValue())); + query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), + query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("dmp").get("groupId"), nestedRoot.get("dmp").get("groupId")), + Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:version")), String.class))); + if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), + builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%"))); + if (this.getCriteria().getGrants() != null && !this.getCriteria().getGrants().isEmpty()) + query.where(((builder, root) -> root.get("dmp").get("grant").get("id").in(this.getCriteria().getGrants()))); + if (this.getCriteria().getGrantStatus() != null) { + if (this.getCriteria().getGrantStatus().getValue().equals(GrantStateType.FINISHED.getValue())) + query.where((builder, root) -> builder.lessThan(root.get("dmp").get("grant").get("enddate"), new Date())); + if (this.getCriteria().getGrantStatus().getValue().equals(GrantStateType.ONGOING.getValue())) + query.where((builder, root) -> + builder.or(builder.greaterThan(root.get("dmp").get("grant").get("enddate"), new Date()) + , builder.isNull(root.get("dmp").get("grant").get("enddate")))); + } + if (this.getCriteria().getDmpIds() != null && !this.getCriteria().getDmpIds().isEmpty()) { + query.where(((builder, root) -> root.get("dmp").get("id").in(this.getCriteria().getDmpIds()))); + } + if (this.getCriteria().getDatasetProfile() != null && !this.getCriteria().getDatasetProfile().isEmpty()) query + .where(((builder, root) -> root.get("profile").get("id").in(this.getCriteria().getDatasetProfile()))); + if (this.getCriteria().getDmpOrganisations() != null && !this.getCriteria().getDmpOrganisations().isEmpty()) query + .where(((builder, root) -> root.join("dmp").join("organisations").get("reference").in(this.getCriteria().getDmpOrganisations()))); + query.where((builder, root) -> builder.notEqual(root.get("status"), Dataset.Status.DELETED.getValue())); + return query; + } + + @Override + public QueryableList applyPaging(QueryableList items) { + return null; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dataset/DatasetTableRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dataset/DatasetTableRequest.java new file mode 100644 index 000000000..d898c71f6 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dataset/DatasetTableRequest.java @@ -0,0 +1,39 @@ +package eu.eudat.old.data.query.items.table.dataset; + +import eu.eudat.old.data.dao.criteria.DatasetCriteria; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; + +import java.util.Arrays; +import java.util.UUID; + +public class DatasetTableRequest extends TableQuery { + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), + builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%"))); + if (this.getCriteria().getStatus() != null) + query.where((builder, root) -> builder.equal(root.get("status"), this.getCriteria().getStatus())); + if (this.getCriteria().getPeriodEnd() != null) + query.where((builder, root) -> builder.lessThan(root.get("created"), this.getCriteria().getPeriodEnd())); + if (this.getCriteria().getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThan(root.get("created"), this.getCriteria().getPeriodStart())); + if (!this.getCriteria().getAllVersions()) + query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("dmp").get("groupId"), nestedRoot.get("dmp").get("groupId")), Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:version")), String.class))); + if (this.getCriteria().getDmpIds() != null && !this.getCriteria().getDmpIds().isEmpty()) + query.where((builder, root) -> root.get("dmp").get("id").in(this.getCriteria().getDmpIds())); + query.where((builder, root) -> builder.equal(root.get("status"), Dataset.Status.FINALISED)); + return query; + } + + @Override + public QueryableList applyPaging(QueryableList items) { + return null; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/datasetprofile/DatasetProfileTableRequestItem.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/datasetprofile/DatasetProfileTableRequestItem.java new file mode 100644 index 000000000..09f159159 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/datasetprofile/DatasetProfileTableRequestItem.java @@ -0,0 +1,23 @@ +package eu.eudat.old.data.query.items.table.datasetprofile; + +import eu.eudat.old.data.dao.criteria.DatasetProfileCriteria; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public class DatasetProfileTableRequestItem extends TableQuery { + @Override + public QueryableList applyCriteria() { + QueryableList 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 applyPaging(QueryableList items) { + return null; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dmp/DataManagementPlanTableRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dmp/DataManagementPlanTableRequest.java new file mode 100644 index 000000000..634b10ba7 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dmp/DataManagementPlanTableRequest.java @@ -0,0 +1,40 @@ +package eu.eudat.old.data.query.items.table.dmp; + +import eu.eudat.old.data.query.PaginationService; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; +import eu.eudat.old.data.dao.criteria.DataManagementPlanCriteria; +import eu.eudat.old.data.entities.DMP; + +import java.util.Arrays; +import java.util.UUID; + +public class DataManagementPlanTableRequest extends TableQuery { + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), + builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%"))); + if (this.getCriteria().getPeriodEnd() != null) + query.where((builder, root) -> builder.lessThan(root.get("created"), this.getCriteria().getPeriodEnd())); + if (this.getCriteria().getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThan(root.get("created"), this.getCriteria().getPeriodStart())); + if (this.getCriteria().getGrants() != null && !this.getCriteria().getGrants().isEmpty()) + query.where(((builder, root) -> root.get("grant").in(this.getCriteria().getGrants()))); + if (!this.getCriteria().getAllVersions()) + query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("version"), query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("groupId"), nestedRoot.get("groupId")), Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "version")), String.class))); + if (this.getCriteria().getGroupIds() != null && !this.getCriteria().getGroupIds().isEmpty()) + query.where((builder, root) -> root.get("groupId").in(this.getCriteria().getGroupIds())); + query.where((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue())); + return query; + } + + @Override + public QueryableList applyPaging(QueryableList items) { + return PaginationService.applyPaging(items, this); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dmp/DataManagmentPlanPublicTableRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dmp/DataManagmentPlanPublicTableRequest.java new file mode 100644 index 000000000..a1da241ab --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dmp/DataManagmentPlanPublicTableRequest.java @@ -0,0 +1,54 @@ +package eu.eudat.old.data.query.items.table.dmp; + +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.query.PaginationService; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; +import eu.eudat.old.types.grant.GrantStateType; +import eu.eudat.old.data.dao.criteria.DataManagementPlanPublicCriteria; + +import java.util.Arrays; +import java.util.Date; +import java.util.UUID; + +public class DataManagmentPlanPublicTableRequest extends TableQuery { + + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + query.where((builder, root) -> builder.equal(root.get("isPublic"), true)); + if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), + builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%"))); + if (this.getCriteria().getGrants() != null && !this.getCriteria().getGrants().isEmpty()) + query.where(((builder, root) -> root.get("grant").get("id").in(this.getCriteria().getGrants()))); + if (this.getCriteria().getGrantStatus() != null) { + if (this.getCriteria().getGrantStatus().getValue().equals(GrantStateType.FINISHED.getValue())) + query.where((builder, root) -> builder.lessThan(root.get("grant").get("enddate"), new Date())); + if (this.getCriteria().getGrantStatus().getValue().equals(GrantStateType.ONGOING.getValue())) + query.where((builder, root) -> + builder.or(builder.greaterThan(root.get("grant").get("enddate"), new Date()) + , builder.isNull(root.get("grant").get("enddate")))); + } + if (this.getCriteria().datasetProfile != null && !this.getCriteria().datasetProfile.isEmpty()) + query.where((builder, root) -> root.join("associatedDmps").get("id").in(this.getCriteria().datasetProfile)); + if (this.getCriteria().getDmpOrganisations() != null && !this.getCriteria().getDmpOrganisations().isEmpty()) + query.where(((builder, root) -> root.join("organisations").get("reference").in(this.getCriteria().getDmpOrganisations()))); + if (!this.getCriteria().getAllVersions()) { + query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("version"), + query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.and(builder1.equal(externalRoot.get("groupId"), + nestedRoot.get("groupId")), builder1.equal(nestedRoot.get("isPublic"), true)), Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "version")), String.class))); + } + if (this.getCriteria().getGroupIds() != null && !this.getCriteria().getGroupIds().isEmpty()) { + query.where((builder, root) -> root.get("groupId").in(this.getCriteria().getGroupIds())); + } + return query; + } + + @Override + public QueryableList applyPaging(QueryableList items) { + return PaginationService.applyPaging(items, this); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dmpprofile/DataManagementPlanProfileTableRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dmpprofile/DataManagementPlanProfileTableRequest.java new file mode 100644 index 000000000..97649563e --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/dmpprofile/DataManagementPlanProfileTableRequest.java @@ -0,0 +1,28 @@ +package eu.eudat.old.data.query.items.table.dmpprofile; + +import eu.eudat.old.data.entities.DMPProfile; +import eu.eudat.old.data.query.PaginationService; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.criteria.DataManagementPlanProfileCriteria; + +import java.util.UUID; + +/** + * Created by ikalyvas on 3/21/2018. + */ +public class DataManagementPlanProfileTableRequest extends TableQuery { + + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) + query.where((builder, root) -> builder.like(root.get("label"), "%" + this.getCriteria().getLike() + "%")); + return query; + } + + @Override + public QueryableList applyPaging(QueryableList items) { + return PaginationService.applyPaging(items, this); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/externaldataset/ExternalDatasetTableRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/externaldataset/ExternalDatasetTableRequest.java new file mode 100644 index 000000000..325d752b3 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/externaldataset/ExternalDatasetTableRequest.java @@ -0,0 +1,23 @@ +package eu.eudat.old.data.query.items.table.externaldataset; + +import eu.eudat.old.data.dao.criteria.ExternalDatasetCriteria; +import eu.eudat.old.data.entities.ExternalDataset; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public class ExternalDatasetTableRequest extends TableQuery { + @Override + public QueryableList applyCriteria() { + QueryableList 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 applyPaging(QueryableList items) { + return null; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/grant/GrantTableRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/grant/GrantTableRequest.java new file mode 100644 index 000000000..040e60f45 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/grant/GrantTableRequest.java @@ -0,0 +1,32 @@ +package eu.eudat.old.data.query.items.table.grant; + +import eu.eudat.old.data.dao.criteria.GrantCriteria; +import eu.eudat.old.data.entities.Grant; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public class GrantTableRequest extends TableQuery { + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) + query.where((builder, root) -> builder.or( + builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), + builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%"))); + if (this.getCriteria().getPeriodEnd() != null) + query.where((builder, root) -> builder.lessThan(root.get("enddate"), this.getCriteria().getPeriodEnd())); + if (this.getCriteria().getPeriodStart() != null) + query.where((builder, root) -> builder.greaterThan(root.get("startdate"), this.getCriteria().getPeriodStart())); + if (this.getCriteria().getReference() != null) + query.where((builder, root) -> builder.equal(root.get("reference"), this.getCriteria().getReference())); + query.where((builder, root) -> builder.notEqual(root.get("status"), Grant.Status.DELETED.getValue())); + return query; + } + + @Override + public QueryableList applyPaging(QueryableList items) { + return null; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/lock/LockTableRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/lock/LockTableRequest.java new file mode 100644 index 000000000..18f78a809 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/lock/LockTableRequest.java @@ -0,0 +1,28 @@ +package eu.eudat.old.data.query.items.table.lock; + +import eu.eudat.old.data.dao.criteria.LockCriteria; +import eu.eudat.old.data.entities.Lock; +import eu.eudat.old.data.query.PaginationService; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public class LockTableRequest extends TableQuery { + @Override + public QueryableList applyCriteria() { + QueryableList query = this.getQuery(); + if (this.getCriteria().getTouchedAt() != null) + query.where((builder, root) -> builder.equal(root.get("touchedAt"), this.getCriteria().getTouchedAt())); + if (this.getCriteria().getLockedBy() != null) + query.where(((builder, root) -> builder.equal(root.get("lockedBy"), this.getCriteria().getLockedBy()))); + if (this.getCriteria().getTarget() != null) + query.where(((builder, root) -> builder.equal(root.get("target"), this.getCriteria().getTarget()))); + return query; + } + + @Override + public QueryableList applyPaging(QueryableList items) { + return PaginationService.applyPaging(items, this); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/organisations/OrganisationsTableRequest.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/organisations/OrganisationsTableRequest.java new file mode 100644 index 000000000..c427051b5 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/organisations/OrganisationsTableRequest.java @@ -0,0 +1,25 @@ +package eu.eudat.old.data.query.items.table.organisations; + +import eu.eudat.old.data.dao.criteria.OrganisationCriteria; +import eu.eudat.old.data.entities.Organisation; +import eu.eudat.old.data.query.PaginationService; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + +public class OrganisationsTableRequest extends TableQuery { + @Override + public QueryableList applyCriteria() { + QueryableList 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 applyPaging(QueryableList items) { + return PaginationService.applyPaging(items, this); + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/userinfo/UserInfoTableRequestItem.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/userinfo/UserInfoTableRequestItem.java new file mode 100644 index 000000000..76f090d4e --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/data/query/items/table/userinfo/UserInfoTableRequestItem.java @@ -0,0 +1,29 @@ +package eu.eudat.old.data.query.items.table.userinfo; + +import eu.eudat.old.data.dao.criteria.UserInfoCriteria; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.queryable.QueryableList; + +import java.util.UUID; + + +public class UserInfoTableRequestItem extends TableQuery { + + @Override + public QueryableList applyCriteria() { + QueryableList users = this.getQuery(); + if (this.getCriteria().getAppRoles() != null && !this.getCriteria().getAppRoles().isEmpty()) + users.where((builder, root) -> root.join("userRoles").get("role").in(this.getCriteria().getAppRoles())); + if (this.getCriteria().getLike() != null) + users.where((builder, root) -> builder.or(builder.like(builder.upper(root.get("name")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), builder.like(root.get("email"), "%" + this.getCriteria().getLike() + "%"))); + if (this.getCriteria().getEmail() != null) + users.where((builder, root) -> builder.equal(root.get("email"), this.getCriteria().getEmail())); + return users; + } + + @Override + public QueryableList applyPaging(QueryableList items) { + return null; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/DMPQuery.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/DMPQuery.java new file mode 100644 index 000000000..55199bc77 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/DMPQuery.java @@ -0,0 +1,143 @@ +package eu.eudat.old.query; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.data.entities.Grant; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; + +import javax.persistence.criteria.Subquery; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +public class DMPQuery extends Query { + private UUID id; + private UUID groupId; + private String label; + private int version; + private GrantQuery grantQuery; + private UserQuery userQuery; + private DatasetQuery datasetQuery; + private List statuses; + private Date created; + private Date modified; + + public DMPQuery(DatabaseAccessLayer databaseAccessLayer) { + super(databaseAccessLayer); + } + + public DMPQuery(DatabaseAccessLayer databaseAccessLayer, List selectionFields) { + super(databaseAccessLayer, selectionFields); + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getGroupId() { + return groupId; + } + + public void setGroupId(UUID groupId) { + this.groupId = groupId; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public int getVersion() { + return version; + } + + public void setVersion(int version) { + this.version = version; + } + + public GrantQuery getGrantQuery() { + return grantQuery; + } + + public void setGrantQuery(GrantQuery grantQuery) { + this.grantQuery = grantQuery; + } + + public List getStatuses() { + return statuses; + } + + public void setStatuses(List statuses) { + statuses = statuses; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getModified() { + return modified; + } + + public void setModified(Date modified) { + this.modified = modified; + } + + public UserQuery getUserQuery() { + return userQuery; + } + + public void setUserQuery(UserQuery userQuery) { + this.userQuery = userQuery; + } + + public DatasetQuery getDatasetQuery() { + return datasetQuery; + } + + public void setDatasetQuery(DatasetQuery datasetQuery) { + this.datasetQuery = datasetQuery; + } + + public QueryableList getQuery() { + QueryableList query = this.databaseAccessLayer.asQueryable(); + if (this.id != null) { + query.where((builder, root) -> builder.equal(root.get("id"), this.id)); + } + if (this.grantQuery != null) { + Subquery grantQuery = this.grantQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id"))); + query.where((builder, root) -> root.get("grant").get("id").in(grantQuery)); + } + if (this.getStatuses() != null && !this.getStatuses().isEmpty()) { + query.where((builder, root) -> root.get("status").in(this.getStatuses())); + } + if (this.userQuery != null) { + Subquery userInfoSubQuery = this.userQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id"))); + query.where((builder, root) -> root.get("creator").get("id").in(userInfoSubQuery)); + } + if(this.datasetQuery != null){ + Subquery datasetSubQuery = this.datasetQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:id"))); + query.where((builder, root) -> root.get("id").in(datasetSubQuery )); + } + if (!this.getSelectionFields().isEmpty() && this.getSelectionFields() != null) { + query.withFields(this.getSelectionFields()); + } + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/DatasetProfileQuery.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/DatasetProfileQuery.java new file mode 100644 index 000000000..51ddc7bee --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/DatasetProfileQuery.java @@ -0,0 +1,14 @@ +package eu.eudat.old.query; + +public class DatasetProfileQuery { + + private UserQuery userQuery; + + public UserQuery getUserQuery() { + return userQuery; + } + + public void setUserQuery(UserQuery userQuery) { + this.userQuery = userQuery; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/DatasetQuery.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/DatasetQuery.java new file mode 100644 index 000000000..26edb0c0f --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/DatasetQuery.java @@ -0,0 +1,65 @@ +package eu.eudat.old.query; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; +import eu.eudat.old.data.entities.DMP; + +import javax.persistence.criteria.Subquery; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +public class DatasetQuery extends Query { + + private UUID id; + private String label; + private DMPQuery dmpQuery; + + public DatasetQuery(DatabaseAccessLayer databaseAccessLayer) { + super(databaseAccessLayer); + } + + public DatasetQuery(DatabaseAccessLayer databaseAccessLayer, List selectionFields) { + super(databaseAccessLayer, selectionFields); + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public DMPQuery getDmpQuery() { + return dmpQuery; + } + + public void setDmpQuery(DMPQuery dmpQuery) { + this.dmpQuery = dmpQuery; + } + + @Override + public QueryableList getQuery() { + QueryableList query = this.databaseAccessLayer.asQueryable(); + if (this.id != null) { + query.where((builder, root) -> builder.equal(root.get("id"), this.id)); + } + if (this.dmpQuery != null) { + Subquery dmpSubQuery = this.dmpQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id"))); + query.where((builder, root) -> root.get("dmp").get("id").in(dmpSubQuery)); + } + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/GrantQuery.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/GrantQuery.java new file mode 100644 index 000000000..e10bc0fb0 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/GrantQuery.java @@ -0,0 +1,108 @@ +package eu.eudat.old.query; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.Grant; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; +import eu.eudat.old.data.entities.UserInfo; + +import javax.persistence.criteria.Subquery; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +public class GrantQuery extends Query { + + private UUID id; + private List ids; + private String label; + private List statuses; + private Date created; + private Date modified; + private UserQuery userQuery; + + public GrantQuery(DatabaseAccessLayer databaseAccessLayer) { + super(databaseAccessLayer); + } + + public GrantQuery(DatabaseAccessLayer databaseAccessLayer, List selectionFields) { + super(databaseAccessLayer, selectionFields); + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public List getIds() { + return ids; + } + + public void setIds(List ids) { + this.ids = ids; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public List getStatuses() { + return statuses; + } + + public void setStatuses(List statuses) { + statuses = statuses; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getModified() { + return modified; + } + + public void setModified(Date modified) { + this.modified = modified; + } + + public UserQuery getUserQuery() { + return userQuery; + } + + public void setUserQuery(UserQuery userQuery) { + this.userQuery = userQuery; + } + + @Override + public QueryableList getQuery() { + QueryableList query = this.databaseAccessLayer.asQueryable(); + if (this.id != null) + query.where((builder, root) -> builder.equal(root.get("id"), this.id)); + if (this.ids != null && !this.ids.isEmpty()) + query.where((builder, root) -> root.get("id").in(this.ids)); + if (this.getStatuses() != null && !this.getStatuses().isEmpty()) + query.where((builder, root) -> root.get("status").in(this.getStatuses())); + if (this.userQuery != null) { + Subquery userInfoSubQuery = this.userQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id"))); + query.where((builder, root) -> root.get("creationUser").get("id").in(userInfoSubQuery)); + } + if (!this.getSelectionFields().isEmpty() && this.getSelectionFields() != null) { + query.withFields(this.getSelectionFields()); + } + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/LockQuery.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/LockQuery.java new file mode 100644 index 000000000..a43795fa5 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/LockQuery.java @@ -0,0 +1,78 @@ +package eu.eudat.old.query; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.Lock; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; + +import javax.persistence.criteria.Subquery; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +public class LockQuery extends Query { + + private UUID id; + private UUID target; + private UserQuery userQuery; + private Date touchedAt; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getTarget() { + return target; + } + + public void setTarget(UUID target) { + this.target = target; + } + + public UserQuery getUserQuery() { + return userQuery; + } + + public void setUserQuery(UserQuery userQuery) { + this.userQuery = userQuery; + } + + public Date getTouchedAt() { + return touchedAt; + } + + public void setTouchedAt(Date touchedAt) { + this.touchedAt = touchedAt; + } + + public LockQuery(DatabaseAccessLayer databaseAccessLayer, List selectionFields) { + super(databaseAccessLayer, selectionFields); + } + + public LockQuery(DatabaseAccessLayer databaseAccessLayer) { + super(databaseAccessLayer); + } + + @Override + public QueryableList getQuery() { + QueryableList query = this.databaseAccessLayer.asQueryable(); + if (this.id != null) { + query.where((builder, root) -> builder.equal(root.get("id"), this.id)); + } + if (this.target != null) { + query.where(((builder, root) -> builder.equal(root.get("target"), this.target))); + } + if (this.userQuery != null) { + Subquery userSubQuery = this.userQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id"))); + query.where((builder, root) -> root.get("lockedBy").get("id").in(userSubQuery)); + } + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/Query.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/Query.java new file mode 100644 index 000000000..81bd53f79 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/Query.java @@ -0,0 +1,29 @@ +package eu.eudat.old.query; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.queryableentity.DataEntity; + +import java.util.LinkedList; +import java.util.List; + +public abstract class Query { + protected DatabaseAccessLayer databaseAccessLayer; + + private List selectionFields = new LinkedList<>(); + + public Query(DatabaseAccessLayer databaseAccessLayer, List selectionFields) { + this.databaseAccessLayer = databaseAccessLayer; + this.selectionFields = selectionFields; + } + + public Query(DatabaseAccessLayer databaseAccessLayer) { + this.databaseAccessLayer = databaseAccessLayer; + } + + public abstract QueryableList getQuery(); + + protected List getSelectionFields() { + return selectionFields; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/UserQuery.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/UserQuery.java new file mode 100644 index 000000000..c5eb29127 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/query/UserQuery.java @@ -0,0 +1,37 @@ +package eu.eudat.old.query; + +import eu.eudat.old.data.dao.DatabaseAccessLayer; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.queryable.QueryableList; + +import java.util.List; +import java.util.UUID; + +public class UserQuery extends Query { + + private UUID id; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UserQuery(DatabaseAccessLayer databaseAccessLayer) { + super(databaseAccessLayer); + } + + public UserQuery(DatabaseAccessLayer databaseAccessLayer, List selectionFields) { + super(databaseAccessLayer, selectionFields); + } + + @Override + public QueryableList getQuery() { + QueryableList query = this.databaseAccessLayer.asQueryable(); + if (this.id != null) + query.where((builder, root) -> builder.equal(root.get("id"), this.id)); + return query; + } +} diff --git a/dmp-migration-tool/data/src/main/java/eu/eudat/old/types/grant/GrantStateType.java b/dmp-migration-tool/data/src/main/java/eu/eudat/old/types/grant/GrantStateType.java new file mode 100644 index 000000000..416365bc8 --- /dev/null +++ b/dmp-migration-tool/data/src/main/java/eu/eudat/old/types/grant/GrantStateType.java @@ -0,0 +1,29 @@ +package eu.eudat.old.types.grant; + +/** + * Created by ikalyvas on 8/24/2018. + */ +public enum GrantStateType { + ONGOING(0), FINISHED(1); + + private Integer value; + + private GrantStateType(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + public static GrantStateType fromInteger(Integer value) { + switch (value) { + case 0: + return ONGOING; + case 1: + return FINISHED; + default: + throw new RuntimeException("Unsupported Grant State Type"); + } + } +} diff --git a/dmp-migration-tool/elastic/pom.xml b/dmp-migration-tool/elastic/pom.xml new file mode 100644 index 000000000..a78208200 --- /dev/null +++ b/dmp-migration-tool/elastic/pom.xml @@ -0,0 +1,14 @@ + + + + dmp-backend + eu.eudat + 1.0.0-SNAPSHOT + + 4.0.0 + + elastic + + \ No newline at end of file diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/Criteria.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/Criteria.java new file mode 100644 index 000000000..fe0c2f64d --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/Criteria.java @@ -0,0 +1,7 @@ +package eu.eudat.old.elastic.criteria; + +/** + * Created by ikalyvas on 7/5/2018. + */ +public abstract class Criteria { +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/DatasetCriteria.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/DatasetCriteria.java new file mode 100644 index 000000000..44e9fee7f --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/DatasetCriteria.java @@ -0,0 +1,156 @@ +package eu.eudat.old.elastic.criteria; + +import eu.eudat.old.elastic.entities.Tag; + +import java.util.List; +import java.util.UUID; + +/** + * Created by ikalyvas on 7/5/2018. + */ +public class DatasetCriteria extends Criteria { + private String like; + private List datasetTemplates; + private Short status; + private List dmps; + private List groupIds; + private List grants; + private List collaborators; + private Boolean allowAllVersions; + private List organiztions; + private Boolean hasTags; + private List tags; + private boolean isPublic; + private Short grantStatus; + private int offset; + private int size; + private List sortCriteria; + + public String getLike() { + return like; + } + + public void setLike(String like) { + this.like = like; + } + + public List getDatasetTemplates() { + return datasetTemplates; + } + + public void setDatasetTemplates(List datasetTemplates) { + this.datasetTemplates = datasetTemplates; + } + + public Short getStatus() { + return status; + } + + public void setStatus(Short status) { + this.status = status; + } + + public List getDmps() { + return dmps; + } + + public void setDmps(List dmps) { + this.dmps = dmps; + } + + public List getGroupIds() { + return groupIds; + } + + public void setGroupIds(List groupIds) { + this.groupIds = groupIds; + } + + public List getGrants() { + return grants; + } + + public void setGrants(List grants) { + this.grants = grants; + } + + public List getCollaborators() { + return collaborators; + } + + public void setCollaborators(List collaborators) { + this.collaborators = collaborators; + } + + public Boolean getAllowAllVersions() { + return allowAllVersions; + } + + public void setAllowAllVersions(Boolean allowAllVersions) { + this.allowAllVersions = allowAllVersions; + } + + public List getOrganiztions() { + return organiztions; + } + + public void setOrganiztions(List organiztions) { + this.organiztions = organiztions; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public boolean isPublic() { + return isPublic; + } + + public void setPublic(boolean aPublic) { + isPublic = aPublic; + } + + public Short getGrantStatus() { + return grantStatus; + } + + public void setGrantStatus(Short grantStatus) { + this.grantStatus = grantStatus; + } + + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public List getSortCriteria() { + return sortCriteria; + } + + public void setSortCriteria(List sortCriteria) { + this.sortCriteria = sortCriteria; + } + + public Boolean getHasTags() { + return hasTags; + } + + public void setHasTags(Boolean hasTags) { + this.hasTags = hasTags; + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/DmpCriteria.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/DmpCriteria.java new file mode 100644 index 000000000..46629654f --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/DmpCriteria.java @@ -0,0 +1,134 @@ +package eu.eudat.old.elastic.criteria; + +import java.util.List; +import java.util.UUID; + +public class DmpCriteria extends Criteria { + private String like; + private Short status; + private List templates; + private List grants; + private List collaborators; + private List roles; + private List organizations; + private boolean isPublic; + private List groupIds; + private boolean allowAllVersions; + private Short grantStatus; + private int offset; + private Integer size; + private List sortCriteria; + + + public String getLike() { + return like; + } + + public void setLike(String like) { + this.like = like; + } + + public Short getStatus() { + return status; + } + + public void setStatus(Short status) { + this.status = status; + } + + public List getTemplates() { + return templates; + } + + public void setTemplates(List templates) { + this.templates = templates; + } + + public List getGrants() { + return grants; + } + + public void setGrants(List grants) { + this.grants = grants; + } + + public List getCollaborators() { + return collaborators; + } + + public void setCollaborators(List collaborators) { + this.collaborators = collaborators; + } + + public List getRoles() { + return roles; + } + + public void setRoles(List roles) { + this.roles = roles; + } + + public List getOrganizations() { + return organizations; + } + + public void setOrganizations(List organizations) { + this.organizations = organizations; + } + + public boolean isPublic() { + return isPublic; + } + + public void setPublic(boolean aPublic) { + isPublic = aPublic; + } + + public List getGroupIds() { + return groupIds; + } + + public void setGroupIds(List groupIds) { + this.groupIds = groupIds; + } + + public boolean isAllowAllVersions() { + return allowAllVersions; + } + + public void setAllowAllVersions(boolean allowAllVersions) { + this.allowAllVersions = allowAllVersions; + } + + public Short getGrantStatus() { + return grantStatus; + } + + public void setGrantStatus(Short grantStatus) { + this.grantStatus = grantStatus; + } + + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public Integer getSize() { + return size; + } + + public void setSize(Integer size) { + this.size = size; + } + + public List getSortCriteria() { + return sortCriteria; + } + + public void setSortCriteria(List sortCriteria) { + this.sortCriteria = sortCriteria; + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/SortCriteria.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/SortCriteria.java new file mode 100644 index 000000000..3a6e36346 --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/SortCriteria.java @@ -0,0 +1,39 @@ +package eu.eudat.old.elastic.criteria; + +public class SortCriteria { + public enum OrderByType { + ASC, DESC + } + + public enum ColumnType { + COUNT, COLUMN, JOIN_COLUMN + } + + private String fieldName; + private OrderByType orderByType; + private ColumnType columnType; + + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public OrderByType getOrderByType() { + return orderByType; + } + + public void setOrderByType(OrderByType orderByType) { + this.orderByType = orderByType; + } + + public ColumnType getColumnType() { + return columnType; + } + + public void setColumnType(ColumnType columnType) { + this.columnType = columnType; + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/TagCriteria.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/TagCriteria.java new file mode 100644 index 000000000..637b26720 --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/criteria/TagCriteria.java @@ -0,0 +1,7 @@ +package eu.eudat.old.elastic.criteria; + +/** + * Created by ikalyvas on 7/5/2018. + */ +public class TagCriteria extends Criteria { +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Collaborator.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Collaborator.java new file mode 100644 index 000000000..b0aab3755 --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Collaborator.java @@ -0,0 +1,54 @@ +package eu.eudat.old.elastic.entities; + +import org.elasticsearch.common.xcontent.XContentBuilder; + +import java.io.IOException; +import java.util.Map; + +public class Collaborator implements ElasticEntity { + private String id; + private String name; + private int role; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getRole() { + return role; + } + + public void setRole(int role) { + this.role = role; + } + + @Override + public XContentBuilder toElasticEntity(XContentBuilder builder) throws IOException { + builder.startObject(); + builder.field("id", this.id); + builder.field("name", this.name); + builder.field("role", this.role); + builder.endObject(); + return builder; + } + + @Override + public Collaborator fromElasticEntity(Map fields) { + this.id = (String) fields.get("id"); + this.name = (String) fields.get("name"); + this.role = (int) fields.get("role"); + return this; + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Dataset.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Dataset.java new file mode 100644 index 000000000..dd6294232 --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Dataset.java @@ -0,0 +1,334 @@ +package eu.eudat.old.elastic.entities; + +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.time.Instant; +import java.util.*; +import java.util.stream.Collectors; + +/** + * Created by ikalyvas on 7/5/2018. + */ +public class Dataset implements ElasticEntity { + private static final Logger logger = LoggerFactory.getLogger(Dataset.class); + + public enum Status { + SAVED((short) 0), FINALISED((short) 1), CANCELED((short) 2), 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 FINALISED; + case 2: + return CANCELED; + case 99: + return DELETED; + default: + throw new RuntimeException("Unsupported Dataset Status"); + } + } + } + + private String id; + private List tags = new LinkedList<>(); + private String label; + private String description; + private UUID template; + private Short status; + private UUID dmp; + private UUID group; + private UUID grant; + private List collaborators; + private Boolean lastVersion; + private Boolean lastPublicVersion; + private List organizations; + private Boolean isPublic; + private Short grantStatus; + private String formData; + private Date created; + private Date modified; + private Date finalizedAt; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public UUID getTemplate() { + return template; + } + + public void setTemplate(UUID template) { + this.template = template; + } + + public Short getStatus() { + return status; + } + + public void setStatus(Short status) { + this.status = status; + } + + public UUID getDmp() { + return dmp; + } + + public void setDmp(UUID dmp) { + this.dmp = dmp; + } + + public UUID getGroup() { + return group; + } + + public void setGroup(UUID group) { + this.group = group; + } + + public UUID getGrant() { + return grant; + } + + public void setGrant(UUID grant) { + this.grant = grant; + } + + public List getCollaborators() { + return collaborators; + } + + public void setCollaborators(List collaborators) { + this.collaborators = collaborators; + } + + public Boolean getLastVersion() { + return lastVersion; + } + + public void setLastVersion(Boolean lastVersion) { + this.lastVersion = lastVersion; + } + + public Boolean getLastPublicVersion() { + return lastPublicVersion; + } + + public void setLastPublicVersion(Boolean lastPublicVersion) { + this.lastPublicVersion = lastPublicVersion; + } + + public List getOrganizations() { + return organizations; + } + + public void setOrganizations(List organizations) { + this.organizations = organizations; + } + + public Boolean getPublic() { + return isPublic; + } + + public void setPublic(Boolean aPublic) { + isPublic = aPublic; + } + + public Short getGrantStatus() { + return grantStatus; + } + + public void setGrantStatus(Short grantStatus) { + this.grantStatus = grantStatus; + } + + public String getFormData() { + return formData; + } + + public void setFormData(String formData) { + this.formData = formData; + } + + 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 Date getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Date finalizedAt) { + this.finalizedAt = finalizedAt; + } + + @Override + public XContentBuilder toElasticEntity(XContentBuilder builder) throws IOException { + builder.startObject(); + builder.field("id", this.id); + builder.field("label", this.label); + builder.field("description", this.description); + builder.field("template", this.template.toString()); + builder.field("status", this.status.toString()); + builder.field("dmp", this.dmp.toString()); + builder.field("created", this.created); + builder.field("modified", this.modified); + builder.field("finalizedAt", this.finalizedAt); + if (this.group != null) { + builder.field("group", this.group.toString()); + } + if (this.grant != null) { + builder.field("grant", this.grant.toString()); + } + if (collaborators != null) { + builder.startArray("collaborators"); + this.collaborators.forEach(x -> { + try { + x.toElasticEntity(builder); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + + }); + builder.endArray(); + } + builder.field("lastVersion", this.lastVersion.toString()); + builder.field("lastPublicVersion", this.lastPublicVersion.toString()); + if (organizations != null) { + builder.startArray("organizations"); + this.organizations.forEach(x -> { + try { + x.toElasticEntity(builder); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + + }); + builder.endArray(); + } + if (this.tags != null) { + builder.startArray("tags"); + this.tags.forEach(x -> { + try { + x.toElasticEntity(builder); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + }); + builder.endArray(); + } + if (this.isPublic != null) { + builder.field("public", this.isPublic.toString()); + } + if (this.grantStatus != null) { + builder.field("grantStatus", this.grantStatus.toString()); + } + builder.field("formData", this.formData); + builder.endObject(); + return builder; + } + + @Override + public Dataset fromElasticEntity(Map fields) { + if (fields != null) { + if (fields.size() == 1) { + if (fields.containsKey("id")) { + this.id = (String) fields.get("id"); + } else if (fields.containsKey("tags")) { + this.tags = ((List) fields.get("tags")).stream().map(hashMap -> new Tag().fromElasticEntity(hashMap)).collect(Collectors.toList()); + } + }else if (fields.size() > 1) { + this.id = (String) fields.get("id"); + if (fields.get("tags") != null) { + this.tags = ((List) fields.get("tags")).stream().map(hashMap -> new Tag().fromElasticEntity(hashMap)).collect(Collectors.toList()); + } + this.label = (String) fields.get("label"); + this.description = (String) fields.get("description"); + this.template = UUID.fromString((String) fields.get("template")); + this.status = Short.valueOf((String) fields.get("status")); + this.dmp = UUID.fromString((String) fields.get("dmp")); + this.group = UUID.fromString((String) fields.get("group")); + if (fields.get("grant") != null) { + this.grant = UUID.fromString((String) fields.get("grant")); + } + if (fields.get("created") != null) + this.created = Date.from(Instant.parse((String) fields.get("created"))); + if (fields.get("modified") != null) + this.modified = Date.from(Instant.parse((String) fields.get("modified"))); + if (fields.get("finalizedAt") != null) + this.finalizedAt = Date.from(Instant.parse((String) fields.get("finalizedAt"))); + if (fields.get("collaborators") != null) { + this.collaborators = ((List) fields.get("collaborators")).stream().map(hashMap -> new Collaborator().fromElasticEntity(hashMap)).collect(Collectors.toList()); + } + this.lastVersion = Boolean.parseBoolean((String) fields.get("lastVersion")); + this.lastPublicVersion = Boolean.parseBoolean((String) fields.get("lastPublicVersion")); + if (fields.get("organizations") != null) { + this.organizations = ((List) fields.get("organizations")).stream().map(hashMap -> new Organization().fromElasticEntity(hashMap)).collect(Collectors.toList()); + } + if (fields.get("public") != null) { + this.isPublic = Boolean.valueOf((String) fields.get("public")); + } + if (fields.get("grantStatus") != null) { + this.grantStatus = Short.valueOf((String) fields.get("grantStatus")); + } + this.formData = (String) fields.get("formData"); + } + } + return this; + } + +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/DatasetTempalate.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/DatasetTempalate.java new file mode 100644 index 000000000..f760e695b --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/DatasetTempalate.java @@ -0,0 +1,68 @@ +package eu.eudat.old.elastic.entities; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.elasticsearch.common.xcontent.XContentBuilder; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class DatasetTempalate implements ElasticEntity { + private UUID id; + private String name; + private Map data; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map getData() { + return data; + } + + public void setData(Map data) { + this.data = data; + } + + @Override + public XContentBuilder toElasticEntity(XContentBuilder builder) throws IOException { + builder.startObject(); + builder.field("id", this.id.toString()); + builder.field("name", this.name); + if(this.data != null) { + builder.field("data", new ObjectMapper().writeValueAsString(this.data)); + } + else{ + builder.field("data", ""); + } + builder.endObject(); + return builder; + } + + @Override + public DatasetTempalate fromElasticEntity(Map fields) { + this.id = UUID.fromString((String) fields.get("id")); + this.name = (String) fields.get("name"); + try { + this.data = new ObjectMapper().readValue((String) fields.get("data"), new TypeReference>() {}); + } + catch (Exception e){ + this.data = new HashMap<>(); + } + return this; + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Dmp.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Dmp.java new file mode 100644 index 000000000..1df5abc81 --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Dmp.java @@ -0,0 +1,382 @@ +package eu.eudat.old.elastic.entities; + +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.time.Instant; +import java.util.*; +import java.util.stream.Collectors; + +public class Dmp implements ElasticEntity { + private static final Logger logger = LoggerFactory.getLogger(Dmp.class); + + public enum DMPStatus { + ACTIVE((short) 0), FINALISED((short) 1),DELETED((short) 99); + + private short value; + + private DMPStatus(short value) { + this.value = value; + } + + public short getValue() { + return value; + } + + public static DMPStatus fromInteger(short value) { + switch (value) { + case 0: + return ACTIVE; + case 1: + return FINALISED; + case 99: + return DELETED; + default: + throw new RuntimeException("Unsupported DMP Status"); + } + } + } + + private UUID id; + private String label; + private String description; + private UUID groupId; + private Short status; + private List templates; + private List collaborators; + private List organizations; + private Boolean lastVersion; + private Boolean lastPublicVersion; + private Boolean isPublic; + private List datasets; + private UUID grant; + private Short grantStatus; + private Date created; + private Date modified; + private Date finalizedAt; + private Date publishedAt; + private List dois; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public UUID getGroupId() { + return groupId; + } + + public void setGroupId(UUID groupId) { + this.groupId = groupId; + } + + public Short getStatus() { + return status; + } + + public void setStatus(Short status) { + this.status = status; + } + + public List getTemplates() { + return templates; + } + + public void setTemplates(List templates) { + this.templates = templates; + } + + public List getCollaborators() { + return collaborators; + } + + public void setCollaborators(List collaborators) { + this.collaborators = collaborators; + } + + public List getOrganizations() { + return organizations; + } + + public void setOrganizations(List organizations) { + this.organizations = organizations; + } + + public Boolean getLastVersion() { + return lastVersion; + } + + public void setLastVersion(Boolean lastVersion) { + this.lastVersion = lastVersion; + } + + public Boolean getLastPublicVersion() { + return lastPublicVersion; + } + + public void setLastPublicVersion(Boolean lastPublicVersion) { + this.lastPublicVersion = lastPublicVersion; + } + + public Boolean getPublic() { + return isPublic; + } + + public void setPublic(Boolean aPublic) { + isPublic = aPublic; + } + + public List getDatasets() { + return datasets; + } + + public void setDatasets(List datasets) { + this.datasets = datasets; + } + + public UUID getGrant() { + return grant; + } + + public void setGrant(UUID grant) { + this.grant = grant; + } + + public Short getGrantStatus() { + return grantStatus; + } + + public void setGrantStatus(Short grantStatus) { + this.grantStatus = grantStatus; + } + + 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 Date getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Date finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public Date getPublishedAt() { + return publishedAt; + } + + public void setPublishedAt(Date publishedAt) { + this.publishedAt = publishedAt; + } + + public List getDois() { + return dois; + } + + public void setDois(List dois) { + this.dois = dois; + } + + @Override + public XContentBuilder toElasticEntity(XContentBuilder builder) throws IOException { + builder.startObject(); + if (this.id != null) { + builder.field(MapKey.ID.getName(), this.id.toString()); + } + builder.field(MapKey.LABEL.getName(), this.label); + builder.field(MapKey.DESCRIPTION.getName(), this.description); + if (this.groupId != null) { + builder.field(MapKey.GROUPID.getName(), this.groupId.toString()); + } + builder.field(MapKey.STATUS.getName(), this.status); + if (this.templates != null && !this.templates.isEmpty()) { + builder.startArray(MapKey.TEMPLATES.getName()); + this.templates.forEach(template -> { + try { + template.toElasticEntity(builder); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + }); + builder.endArray(); + } + if (this.collaborators != null && !this.collaborators.isEmpty()) { + builder.startArray(MapKey.COLLABORATORS.getName()); + this.collaborators.forEach(collaborator -> { + try { + collaborator.toElasticEntity(builder); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + }); + builder.endArray(); + } + if (this.organizations != null && !this.organizations.isEmpty()) { + builder.startArray(MapKey.ORGANIZATIONS.getName()); + this.organizations.forEach(organization -> { + try { + organization.toElasticEntity(builder); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + }); + builder.endArray(); + } + builder.field(MapKey.LASTVERSION.getName(), this.lastVersion); + builder.field(MapKey.LASTPUBLICVERSION.getName(), this.lastPublicVersion); + builder.field(MapKey.ISPUBLIC.getName(), this.isPublic); + if (datasets != null && !this.datasets.isEmpty()) { + builder.startArray(MapKey.DATASETS.getName()); + this.datasets.forEach(dataset -> { + try { + if (dataset != null) { + dataset.toElasticEntity(builder); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }); + builder.endArray(); + } + if (this.grant != null) { + builder.field(MapKey.GRANT.getName(), this.grant.toString()); + } + builder.field(MapKey.GRANTSTATUS.getName(), this.grantStatus); + builder.field(MapKey.CREATED.getName(), this.created); + builder.field(MapKey.MODIFIED.getName(), this.modified); + builder.field(MapKey.FINALIZEDAT.getName(), this.finalizedAt); + builder.field(MapKey.PUBLISHEDAT.getName(), this.publishedAt); + if (this.dois != null && !this.dois.isEmpty()) { + builder.startArray(MapKey.DOIS.getName()); + this.dois.forEach(doi -> { + try { + doi.toElasticEntity(builder); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + }); + builder.endArray(); + } + builder.endObject(); + return builder; + } + + @Override + public Dmp fromElasticEntity(Map fields) { + if (fields == null || fields.isEmpty()) { + return null; + } + this.id = UUID.fromString((String) fields.get(MapKey.ID.getName())); + if (fields.size() > 1) { + this.label = (String) fields.get(MapKey.LABEL.getName()); + this.description = (String) fields.get(MapKey.DESCRIPTION.getName()); + if (fields.get(MapKey.GROUPID.getName()) != null) { + this.groupId = UUID.fromString((String) fields.get(MapKey.GROUPID.getName())); + } + this.status = Short.valueOf(fields.get(MapKey.STATUS.getName()).toString()); + if (fields.get(MapKey.TEMPLATES.getName()) != null) { + this.templates = ((List>) fields.get(MapKey.TEMPLATES.getName())).stream().map(hashMap -> new DatasetTempalate().fromElasticEntity(hashMap)).collect(Collectors.toList()); + } + if (fields.get(MapKey.COLLABORATORS.getName()) != null) { + this.collaborators = ((List>) fields.get(MapKey.COLLABORATORS.getName())).stream().map(map -> new Collaborator().fromElasticEntity(map)).collect(Collectors.toList()); + } + if (fields.get(MapKey.ORGANIZATIONS.getName()) != null) { + this.organizations = ((List>) fields.get(MapKey.ORGANIZATIONS.getName())).stream().map(map -> new Organization().fromElasticEntity(map)).collect(Collectors.toList()); + } + this.lastVersion = (Boolean) fields.get(MapKey.LASTVERSION.getName()); + this.lastPublicVersion = (Boolean) fields.get(MapKey.LASTPUBLICVERSION.getName()); + this.isPublic = (Boolean) fields.get(MapKey.ISPUBLIC.getName()); + if (fields.get(MapKey.DATASETS.getName()) != null) { + this.datasets = ((List>) fields.get(MapKey.DATASETS.getName())).stream().map(map -> new Dataset().fromElasticEntity(map)).collect(Collectors.toList()); + } + if (fields.containsKey(MapKey.GRANT.getName()) && fields.get(MapKey.GRANT.getName()) != null) { + this.grant = UUID.fromString((String) fields.get(MapKey.GRANT.getName())); + } + if (fields.get(MapKey.GRANTSTATUS.getName()) != null) { + this.grantStatus = Short.valueOf(fields.get(MapKey.GRANTSTATUS.getName()).toString()); + } + if (fields.containsKey(MapKey.CREATED.getName())) { + this.created = Date.from(Instant.parse(fields.get(MapKey.CREATED.getName()).toString())); + } + if (fields.containsKey(MapKey.MODIFIED.getName())) { + this.modified = Date.from(Instant.parse(fields.get(MapKey.MODIFIED.getName()).toString())); + } + if (fields.get(MapKey.FINALIZEDAT.getName()) != null) { + this.finalizedAt = Date.from(Instant.parse(fields.get(MapKey.FINALIZEDAT.getName()).toString())); + } + if (fields.get(MapKey.PUBLISHEDAT.getName()) != null) { + this.publishedAt = Date.from(Instant.parse(fields.get(MapKey.PUBLISHEDAT.getName()).toString())); + } + if (fields.get(MapKey.DOIS.getName()) != null) { + this.dois = ((List>) fields.get(MapKey.DOIS.getName())).stream().map(map -> new Doi().fromElasticEntity(map)).collect(Collectors.toList()); + } + } + return this; + } + + public enum MapKey { + ID ("id"), + LABEL ("label"), + DESCRIPTION ("description"), + GROUPID ("groupId"), + STATUS ("status"), + TEMPLATES ("templates"), + COLLABORATORS ("collaborators"), + ORGANIZATIONS ("organizations"), + LASTVERSION ("lastVersion"), + LASTPUBLICVERSION ("lastPublicVersion"), + ISPUBLIC ("isPublic"), + DATASETS ("datasets"), + GRANT ("grant"), + GRANTSTATUS ("grantStatus"), + CREATED ("created"), + MODIFIED ("modified"), + FINALIZEDAT ("finalizedAt"), + PUBLISHEDAT ("publishedAt"), + DOIS ("dois"); + + private final String name; + + private MapKey(String name) { + this.name = name; + } + + public String getName() { + return name; + } + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Doi.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Doi.java new file mode 100644 index 000000000..e38a38d97 --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Doi.java @@ -0,0 +1,65 @@ +package eu.eudat.old.elastic.entities; + +import org.elasticsearch.common.xcontent.XContentBuilder; + +import java.io.IOException; +import java.util.Map; +import java.util.UUID; + +public class Doi implements ElasticEntity{ + private UUID id; + private String repositoryId; + private String doi; + private UUID dmp; + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public String getRepositoryId() { + return repositoryId; + } + public void setRepositoryId(String repositoryId) { + this.repositoryId = repositoryId; + } + + public String getDoi() { + return doi; + } + public void setDoi(String doi) { + this.doi = doi; + } + + public UUID getDmp() { + return dmp; + } + public void setDmp(UUID dmp) { + this.dmp = dmp; + } + + @Override + public XContentBuilder toElasticEntity(XContentBuilder builder) throws IOException { + builder.startObject(); + builder.field("id", this.id.toString()); + builder.field("repositoryId", this.repositoryId); + builder.field("doi", this.doi); + builder.field("dmp", this.dmp.toString()); + builder.endObject(); + return builder; + } + + @Override + public Doi fromElasticEntity(Map fields) { + if (fields == null || fields.isEmpty()) { + return null; + } + this.id = UUID.fromString((String) fields.get("id")); + this.repositoryId = (String) fields.get("repositoryId"); + this.doi = (String) fields.get("doi"); + this.dmp = UUID.fromString((String) fields.get("dmp")); + return this; + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/ElasticEntity.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/ElasticEntity.java new file mode 100644 index 000000000..a0efd6253 --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/ElasticEntity.java @@ -0,0 +1,15 @@ +package eu.eudat.old.elastic.entities; + +import org.elasticsearch.common.document.DocumentField; +import org.elasticsearch.common.xcontent.XContentBuilder; + +import java.io.IOException; +import java.util.Map; + +/** + * Created by ikalyvas on 7/5/2018. + */ +public interface ElasticEntity { + XContentBuilder toElasticEntity(XContentBuilder builder) throws IOException; + T fromElasticEntity(Map fields); +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Organization.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Organization.java new file mode 100644 index 000000000..bd7870caf --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Organization.java @@ -0,0 +1,43 @@ +package eu.eudat.old.elastic.entities; + +import org.elasticsearch.common.xcontent.XContentBuilder; + +import java.io.IOException; +import java.util.Map; + +public class Organization implements ElasticEntity { + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public XContentBuilder toElasticEntity(XContentBuilder builder) throws IOException { + builder.startObject(); + builder.field("id", this.id); + builder.field("name", this.name); + builder.endObject(); + return builder; + } + + @Override + public Organization fromElasticEntity(Map fields) { + this.id = (String) fields.get("id"); + this.name = (String) fields.get("name"); + return this; + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Tag.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Tag.java new file mode 100644 index 000000000..bd62cbc47 --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/entities/Tag.java @@ -0,0 +1,55 @@ +package eu.eudat.old.elastic.entities; + +import org.elasticsearch.common.xcontent.XContentBuilder; + +import java.io.IOException; +import java.util.Map; + +/** + * Created by ikalyvas on 7/5/2018. + */ +public class Tag implements ElasticEntity { + + private String id; + private String name; + + public Tag() { + } + + public Tag(String id, String name) { + this.id = id; + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public XContentBuilder toElasticEntity(XContentBuilder builder) throws IOException { + builder.startObject(); + builder.field("id", this.id); + builder.field("name", this.name); + builder.endObject(); + return builder; + } + + @Override + public Tag fromElasticEntity(Map fields) { + this.id = (String) fields.get("id"); + this.name = (String) fields.get("name"); + return this; + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/DatasetRepository.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/DatasetRepository.java new file mode 100644 index 000000000..25c6e6cd1 --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/DatasetRepository.java @@ -0,0 +1,344 @@ +package eu.eudat.old.elastic.repository; + +import eu.eudat.old.elastic.criteria.DatasetCriteria; +import eu.eudat.old.elastic.entities.Dataset; +import eu.eudat.old.elastic.entities.Dmp; +import eu.eudat.old.elastic.entities.Tag; +import org.apache.lucene.search.join.ScoreMode; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.client.indices.GetIndexRequest; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.common.xcontent.XContentFactory; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.InnerHitBuilder; +import org.elasticsearch.index.query.NestedQueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.search.SearchHits; +import org.elasticsearch.search.aggregations.AggregationBuilders; +import org.elasticsearch.search.aggregations.bucket.filter.FiltersAggregationBuilder; +import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilters; +import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder; +import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.elasticsearch.search.fetch.subphase.FetchSourceContext; +import org.elasticsearch.search.sort.SortBuilder; +import org.elasticsearch.search.sort.SortBuilders; +import org.elasticsearch.search.sort.SortOrder; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Service("datasetRepository") +public class DatasetRepository extends ElasticRepository { + + private final DmpRepository dmpRepository; + private final Environment environment; + + public DatasetRepository(RestHighLevelClient client, DmpRepository dmpRepository, Environment environment) { + super(client); + this.dmpRepository = dmpRepository; + this.environment = environment; + } + + @Override + public Dataset createOrUpdate(Dataset entity) throws IOException { + if (this.getClient() != null) { + XContentBuilder builder = XContentFactory.jsonBuilder(); + Dmp dmp = this.dmpRepository.findDocument(entity.getDmp().toString()); + if (dmp != null) { + boolean found = false; + if (dmp.getDatasets() != null && !dmp.getDatasets().isEmpty()) { + for (int i = 0; i < dmp.getDatasets().size(); i++) { + if (dmp.getDatasets().get(i).getId().equals(entity.getId())) { + dmp.getDatasets().set(i, entity); + found = true; + break; + } + } + } + if (!found) { + if (dmp.getDatasets() == null) { + dmp.setDatasets(new ArrayList<>()); + } + dmp.getDatasets().add(entity); + } + IndexRequest request = new IndexRequest(this.environment.getProperty("elasticsearch.index")).id(dmp.getId().toString()).source(dmp.toElasticEntity(builder));//new IndexRequest("datasets", "doc", entity.getId()).source(entity.toElasticEntity(builder)); + this.getClient().index(request, RequestOptions.DEFAULT); + } + return entity; + } + return null; + } + + @Override + public Dataset findDocument(String id) throws IOException { + if (this.getClient() != null) { + SearchRequest searchRequest = new SearchRequest(this.environment.getProperty("elasticsearch.index")); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + BoolQueryBuilder boolQuery = QueryBuilders.boolQuery().should(QueryBuilders.termQuery("datasets.id.keyword", id)); + NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery( "datasets", boolQuery, ScoreMode.Avg).innerHit(new InnerHitBuilder()); + searchSourceBuilder.query(nestedQueryBuilder); + searchRequest.source(searchSourceBuilder); + SearchResponse response = this.getClient().search(searchRequest, RequestOptions.DEFAULT); + return ((Stream)Arrays.stream(response.getHits().getHits()) + .map(hit -> hit.getInnerHits().values()).flatMap(Collection::stream) + .map(SearchHits::getHits).flatMap(Arrays::stream) + .map(x -> new Dataset().fromElasticEntity(this.transformFromString(x.getSourceAsString(), Map.class)))).findFirst().orElse(null); +// GetRequest request = new GetRequest("datasets", id); +// GetResponse response = this.getClient().get(request, RequestOptions.DEFAULT); +// return new Dataset().fromElasticEntity(response.getSourceAsMap()); + } + return null; + } + + @Override + public List query(DatasetCriteria criteria) throws IOException { + if (this.getClient() != null) { + SearchRequest searchRequest = new SearchRequest(this.environment.getProperty("elasticsearch.index")); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + + /*CountRequest countRequest = new CountRequest("dmps").routing("datasets").routing("id"); + countRequest.query(QueryBuilders.boolQuery().mustNot(QueryBuilders.termsQuery("datasets.status.keyword", Stream.of(Dataset.Status.DELETED.getValue(), Dataset.Status.CANCELED.getValue()).collect(Collectors.toList())))); + CountResponse countResponse = getClient().count(countRequest, RequestOptions.DEFAULT); + Long count = countResponse.getCount();*/ + + SearchRequest countRequest = new SearchRequest(this.environment.getProperty("elasticsearch.index")); + NestedAggregationBuilder nestedAggregationBuilder = AggregationBuilders.nested("by_dataset", "datasets"); + FiltersAggregationBuilder filtersAggregationBuilder = AggregationBuilders.filters("dataset_query", QueryBuilders.boolQuery().mustNot(QueryBuilders.termsQuery("datasets.status.keyword", Stream.of(Dataset.Status.DELETED.getValue(), Dataset.Status.CANCELED.getValue()).collect(Collectors.toList())))); + nestedAggregationBuilder.subAggregation(filtersAggregationBuilder); + SearchSourceBuilder countSourceBuilder = new SearchSourceBuilder(); + countSourceBuilder.aggregation(nestedAggregationBuilder); + countRequest.source(countSourceBuilder); + SearchResponse countResponse = getClient().search(countRequest, RequestOptions.DEFAULT); + Long count = ((ParsedFilters)((ParsedNested)countResponse.getAggregations().asMap().get("by_dataset")).getAggregations().get("dataset_query")).getBuckets().get(0).getDocCount(); + + + searchSourceBuilder.size(count.intValue()); + + List sortBuilders = new ArrayList<>(); + BoolQueryBuilder boolQuery = createBoolQuery(criteria); + + + if (criteria.getSortCriteria() != null && !criteria.getSortCriteria().isEmpty()) { + criteria.getSortCriteria().forEach(sortCriteria -> { + switch(sortCriteria.getColumnType()) { + case COLUMN: + sortBuilders.add(SortBuilders.fieldSort("datasets." + sortCriteria.getFieldName()).order(SortOrder.fromString(sortCriteria.getOrderByType().name()))); + break; + case JOIN_COLUMN: + List fields = Arrays.asList(sortCriteria.getFieldName().split(":")); + fields.stream().filter(name -> !name.startsWith("dmp")).forEach(field -> { + sortBuilders.add(SortBuilders.fieldSort(field).order(SortOrder.fromString(sortCriteria.getOrderByType().name()))); + }); + break; + } + }); + + } + + NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("datasets", boolQuery, ScoreMode.Avg).innerHit(new InnerHitBuilder().setFetchSourceContext(new FetchSourceContext(true, new String[]{"datasets.tags"}, null)).setSize(this.environment.getProperty("elasticsearch.innerHitsSize", Integer.class))); + searchSourceBuilder.query(nestedQueryBuilder)/*.from(criteria.getOffset())*/.fetchSource("datasets.tags", null); + /*if (criteria.getSize() > 0) { + searchSourceBuilder.size(criteria.getSize()); + }*/ + sortBuilders.forEach(searchSourceBuilder::sort); + searchRequest.source(searchSourceBuilder); + SearchResponse response = this.getClient().search(searchRequest, RequestOptions.DEFAULT); + return ((Stream)Arrays.stream(response.getHits().getHits()) + .map(hit -> hit.getInnerHits().values()).flatMap(Collection::stream) + .map(SearchHits::getHits).flatMap(Arrays::stream) + .map(x -> new Dataset().fromElasticEntity(this.transformFromString(x.getSourceAsString(), Map.class)))).collect(Collectors.toList()); + } + return null; + } + + public List queryIds(DatasetCriteria criteria) throws IOException { + if (this.getClient() != null) { + SearchRequest searchRequest = new SearchRequest(this.environment.getProperty("elasticsearch.index")); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + + /*CountRequest countRequest = new CountRequest("dmps").routing("datasets").routing("id"); + countRequest.query(QueryBuilders.boolQuery().mustNot(QueryBuilders.termsQuery("datasets.status.keyword", Stream.of(Dataset.Status.DELETED.getValue(), Dataset.Status.CANCELED.getValue()).collect(Collectors.toList())))); + CountResponse countResponse = getClient().count(countRequest, RequestOptions.DEFAULT); + Long count = countResponse.getCount();*/ + + SearchRequest countRequest = new SearchRequest(this.environment.getProperty("elasticsearch.index")); + NestedAggregationBuilder nestedAggregationBuilder = AggregationBuilders.nested("by_dataset", "datasets"); + FiltersAggregationBuilder filtersAggregationBuilder = AggregationBuilders.filters("dataset_query", QueryBuilders.boolQuery().mustNot(QueryBuilders.termsQuery("datasets.status.keyword", Stream.of(Dataset.Status.DELETED.getValue(), Dataset.Status.CANCELED.getValue()).collect(Collectors.toList())))); + nestedAggregationBuilder.subAggregation(filtersAggregationBuilder); + SearchSourceBuilder countSourceBuilder = new SearchSourceBuilder(); + countSourceBuilder.aggregation(nestedAggregationBuilder); + countRequest.source(countSourceBuilder); + SearchResponse countResponse = getClient().search(countRequest, RequestOptions.DEFAULT); + Long count = ((ParsedFilters)((ParsedNested)countResponse.getAggregations().asMap().get("by_dataset")).getAggregations().get("dataset_query")).getBuckets().get(0).getDocCount(); + + + searchSourceBuilder.size(count.intValue()); + + List sortBuilders = new ArrayList<>(); + BoolQueryBuilder boolQuery = createBoolQuery(criteria); + + + if (criteria.getSortCriteria() != null && !criteria.getSortCriteria().isEmpty()) { + criteria.getSortCriteria().forEach(sortCriteria -> { + switch(sortCriteria.getColumnType()) { + case COLUMN: + sortBuilders.add(SortBuilders.fieldSort("datasets." + sortCriteria.getFieldName()).order(SortOrder.fromString(sortCriteria.getOrderByType().name()))); + break; + case JOIN_COLUMN: + List fields = Arrays.asList(sortCriteria.getFieldName().split(":")); + fields.stream().filter(name -> !name.startsWith("dmp")).forEach(field -> { + sortBuilders.add(SortBuilders.fieldSort(field).order(SortOrder.fromString(sortCriteria.getOrderByType().name()))); + }); + break; + } + }); + + } + + NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("datasets", boolQuery, ScoreMode.None).innerHit(new InnerHitBuilder().setFetchSourceContext(new FetchSourceContext(true, new String[]{"datasets.id"}, null)).setSize(this.environment.getProperty("elasticsearch.innerHitsSize", Integer.class))); + searchSourceBuilder.query(nestedQueryBuilder)/*.from(criteria.getOffset()).size(criteria.getSize())*/.fetchSource("datasets.id", null); + sortBuilders.forEach(searchSourceBuilder::sort); + searchRequest.source(searchSourceBuilder); + SearchResponse response = this.getClient().search(searchRequest, RequestOptions.DEFAULT); + return ((Stream)Arrays.stream(response.getHits().getHits()) + .map(hit -> hit.getInnerHits().values()).flatMap(Collection::stream) + .map(SearchHits::getHits).flatMap(Arrays::stream) + .map(x -> new Dataset().fromElasticEntity(this.transformFromString(x.getSourceAsString(), Map.class)))).collect(Collectors.toList()); + } + return null; + } + + @Override + public Long count(DatasetCriteria criteria) throws IOException { + if (this.getClient() != null) { + //CountRequest countRequest = new CountRequest(this.environment.getProperty("elasticsearch.index")); + + SearchRequest countRequest = new SearchRequest(this.environment.getProperty("elasticsearch.index")); + BoolQueryBuilder boolQuery = createBoolQuery(criteria); + NestedAggregationBuilder nestedAggregationBuilder = AggregationBuilders.nested("by_dataset", "datasets"); + FiltersAggregationBuilder filtersAggregationBuilder = AggregationBuilders.filters("dataset_query", boolQuery); + nestedAggregationBuilder.subAggregation(filtersAggregationBuilder); + SearchSourceBuilder countSourceBuilder = new SearchSourceBuilder(); + countSourceBuilder.aggregation(nestedAggregationBuilder); + countRequest.source(countSourceBuilder); + SearchResponse countResponse = getClient().search(countRequest, RequestOptions.DEFAULT); + return ((ParsedFilters)((ParsedNested)countResponse.getAggregations().asMap().get("by_dataset")).getAggregations().get("dataset_query")).getBuckets().get(0).getDocCount(); + + + + /*NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("datasets", boolQuery, ScoreMode.None).innerHit(new InnerHitBuilder()); + countRequest.query(nestedQueryBuilder); + CountResponse response = this.getClient().count(countRequest, RequestOptions.DEFAULT); + return response.getCount();*/ + } + return null; + } + + private BoolQueryBuilder createBoolQuery(DatasetCriteria criteria) { + BoolQueryBuilder boolQuery = QueryBuilders.boolQuery().mustNot(QueryBuilders.termsQuery("datasets.status", Stream.of(Dataset.Status.DELETED.getValue(), Dataset.Status.CANCELED.getValue()).collect(Collectors.toList()))); + if (criteria.isPublic()) { + boolQuery = boolQuery.should(QueryBuilders.termQuery("datasets.public", "true")); + boolQuery = boolQuery.should(QueryBuilders.termQuery("datasets.status", Dataset.Status.FINALISED.getValue())); + boolQuery = boolQuery.should(QueryBuilders.termQuery("datasets.lastPublicVersion", "true")); + } + if (criteria.getLike() != null && !criteria.getLike().isEmpty()) { + boolQuery = boolQuery.should(QueryBuilders.queryStringQuery(criteria.getLike()).allowLeadingWildcard(true).fields(Stream.of(new Object[][]{ + {"datasets.label", 1.0f}, + {"datasets.description", 1.0f}, + {"datasets.formData", 1.0f} + }).collect(Collectors.toMap(data -> (String) data[0], data -> (Float) data[1])))); + } + + if (criteria.getDatasetTemplates() != null && criteria.getDatasetTemplates().size() > 0) { + criteria.setDatasetTemplates(criteria.getDatasetTemplates().stream().filter(Objects::nonNull).collect(Collectors.toList())); + boolQuery = boolQuery.should(QueryBuilders.termsQuery("datasets.template", criteria.getDatasetTemplates().stream().map(UUID::toString).collect(Collectors.toList()))); + } + + if (criteria.getStatus() != null) { + boolQuery = boolQuery.should(QueryBuilders.termQuery("datasets.status", criteria.getStatus().toString())); + } + + if (criteria.getDmps() != null && criteria.getDmps().size() > 0) { + criteria.setDmps(criteria.getDmps().stream().filter(Objects::nonNull).collect(Collectors.toList())); + boolQuery = boolQuery.should(QueryBuilders.termsQuery("datasets.dmp", criteria.getDmps().stream().map(UUID::toString).collect(Collectors.toList()))); + } + + if (criteria.getGroupIds() != null && criteria.getGroupIds().size() > 0) { + criteria.setGroupIds(criteria.getGroupIds().stream().filter(Objects::nonNull).collect(Collectors.toList())); + boolQuery = boolQuery.should(QueryBuilders.termsQuery("datasets.group", criteria.getGroupIds().stream().map(UUID::toString).collect(Collectors.toList()))); + } + + if (criteria.getGrants() != null && criteria.getGrants().size() > 0) { + criteria.setGrants(criteria.getGrants().stream().filter(Objects::nonNull).collect(Collectors.toList())); + boolQuery = boolQuery.should(QueryBuilders.termsQuery("datasets.grant", criteria.getGrants().stream().map(UUID::toString).collect(Collectors.toList()))); + } + + if (criteria.getGrantStatus() != null) { + boolQuery = boolQuery.should(QueryBuilders.termQuery("datasets.grantStatus", criteria.getGrantStatus().toString())); + } + + if (criteria.getCollaborators() != null && criteria.getCollaborators().size() > 0) { + criteria.setCollaborators(criteria.getCollaborators().stream().filter(Objects::nonNull).collect(Collectors.toList())); + boolQuery = boolQuery.should(QueryBuilders.termsQuery("datasets.collaborators.id.keyword", criteria.getCollaborators().stream().map(UUID::toString).collect(Collectors.toList()))); + } + + if (!criteria.isPublic()) { + if (criteria.getAllowAllVersions() != null && !criteria.getAllowAllVersions()) { + boolQuery = boolQuery.should(QueryBuilders.termQuery("datasets.lastVersion", "true")); + } + } + + if (criteria.getOrganiztions() != null && criteria.getOrganiztions().size() > 0) { + criteria.setOrganiztions(criteria.getOrganiztions().stream().filter(Objects::nonNull).collect(Collectors.toList())); + boolQuery = boolQuery.should(QueryBuilders.termsQuery("datasets.organizations.id", criteria.getOrganiztions())); + } + + if (criteria.getTags() != null && criteria.getTags().size() > 0) { + criteria.setTags(criteria.getTags().stream().filter(Objects::nonNull).collect(Collectors.toList())); + boolQuery = boolQuery.should(QueryBuilders.termsQuery("datasets.tags.name", criteria.getTags().stream().map(Tag::getName).collect(Collectors.toList()))); + } + + if (criteria.getHasTags() != null) { + boolQuery = criteria.getHasTags() == true ? boolQuery.should(QueryBuilders.existsQuery("datasets.tags.id")) : boolQuery.mustNot(QueryBuilders.existsQuery("datasets.tags.id")); + } + + if (boolQuery.should().isEmpty() && boolQuery.mustNot().isEmpty()) { + boolQuery.should(QueryBuilders.matchAllQuery()); + } else { + boolQuery.minimumShouldMatch(boolQuery.should().size()); + } + + + + return boolQuery; + } + + @Override + public boolean exists() throws IOException { + if (this.getClient() != null) { + GetIndexRequest request = new GetIndexRequest(this.environment.getProperty("elasticsearch.index")); +// request.indices("datasets"); + return this.getClient().indices().exists(request, RequestOptions.DEFAULT); + } + return false; + } + + @Override + public void clear() throws IOException { + //DON'T + /* if (exists()) { + DeleteByQueryRequest delete = new DeleteByQueryRequest("datasets"); + delete.setQuery(QueryBuilders.matchAllQuery()); + this.getClient().deleteByQuery(delete, RequestOptions.DEFAULT); + }*/ + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/DmpRepository.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/DmpRepository.java new file mode 100644 index 000000000..aa7e7dba4 --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/DmpRepository.java @@ -0,0 +1,232 @@ +package eu.eudat.old.elastic.repository; + +import eu.eudat.old.elastic.criteria.DmpCriteria; +import eu.eudat.old.elastic.entities.Dmp; +import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; +import org.elasticsearch.action.get.GetRequest; +import org.elasticsearch.action.get.GetResponse; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.client.core.CountRequest; +import org.elasticsearch.client.core.CountResponse; +import org.elasticsearch.client.indices.CreateIndexRequest; +import org.elasticsearch.client.indices.GetIndexRequest; +import org.elasticsearch.client.indices.PutMappingRequest; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.common.xcontent.XContentFactory; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.index.reindex.DeleteByQueryRequest; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.elasticsearch.search.sort.SortBuilder; +import org.elasticsearch.search.sort.SortBuilders; +import org.elasticsearch.search.sort.SortOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Service("dmpRepository") +public class DmpRepository extends ElasticRepository { + private static final Logger logger = LoggerFactory.getLogger(DmpRepository.class); + + private final Environment environment; + + @Autowired + public DmpRepository(RestHighLevelClient client, Environment environment) { + super(client); + this.environment = environment; + } + + private void generateMapping() throws IOException { + if (this.getClient() != null) { + XContentBuilder builder = XContentFactory.jsonBuilder(); + builder.startObject(); + builder.startObject("properties"); + builder.startObject("datasets"); + builder.field("type", "nested"); + builder.endObject(); + builder.endObject(); + builder.endObject(); + PutMappingRequest putMappingRequest = new PutMappingRequest(this.environment.getProperty("elasticsearch.index")); + putMappingRequest.source(builder); + this.getClient().indices().putMapping(putMappingRequest, RequestOptions.DEFAULT); + } + } + + @Override + public Dmp createOrUpdate(Dmp entity) throws IOException { + if (this.getClient() != null) { + XContentBuilder builder = XContentFactory.jsonBuilder(); + IndexRequest request = new IndexRequest(this.environment.getProperty("elasticsearch.index")).id(entity.getId().toString()).source(entity.toElasticEntity(builder)); + IndexResponse response = this.getClient().index(request, RequestOptions.DEFAULT); + return entity; + } + return null; + } + + @Override + public Dmp findDocument(String id) throws IOException { + if (this.getClient() != null) { + GetRequest request = new GetRequest(this.environment.getProperty("elasticsearch.index"), id); + GetResponse response = this.getClient().get(request, RequestOptions.DEFAULT); + return new Dmp().fromElasticEntity(response.getSourceAsMap()); + } + return null; + } + + @Override + public List query(DmpCriteria criteria) throws IOException { + if (this.getClient() != null) { + SearchRequest searchRequest = new SearchRequest(this.environment.getProperty("elasticsearch.index")); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + + CountRequest countRequest = new CountRequest(this.environment.getProperty("elasticsearch.index")); + countRequest.query(QueryBuilders.boolQuery().mustNot(QueryBuilders.termsQuery(Dmp.MapKey.STATUS.getName(), Collections.singletonList(Dmp.DMPStatus.DELETED.getValue())))); + CountResponse countResponse = getClient().count(countRequest, RequestOptions.DEFAULT); + Long count = countResponse.getCount(); + + searchSourceBuilder.size(count.intValue()); + + List sortBuilders = new ArrayList<>(); + BoolQueryBuilder boolQuery = createBoolQuery(criteria); + + if (criteria.getSortCriteria() != null && !criteria.getSortCriteria().isEmpty()) { + criteria.getSortCriteria().forEach(sortCriteria -> { + switch(sortCriteria.getColumnType()) { + case COLUMN: + sortBuilders.add(SortBuilders.fieldSort(sortCriteria.getFieldName()).order(SortOrder.fromString(sortCriteria.getOrderByType().name()))); + break; + case JOIN_COLUMN: + List fields = Arrays.asList(sortCriteria.getFieldName().split(":")); + fields.forEach(field -> { + sortBuilders.add(SortBuilders.fieldSort(sortCriteria.getFieldName()).order(SortOrder.fromString(sortCriteria.getOrderByType().name()))); + }); + break; + } + }); + + } + searchSourceBuilder.query(boolQuery).from(criteria.getOffset()).fetchSource("id", null); + if (criteria.getSize() != null && criteria.getSize() > 0) { + searchSourceBuilder.size(criteria.getSize()); + } + sortBuilders.forEach(searchSourceBuilder::sort); + searchRequest.source(searchSourceBuilder); + SearchResponse response = this.getClient().search(searchRequest, RequestOptions.DEFAULT); + return Arrays.stream(response.getHits().getHits()).map(x -> new Dmp().fromElasticEntity((Map) this.transformFromString(x.getSourceAsString(), Map.class))).collect(Collectors.toList()); + } + return null; + } + + @Override + public Long count(DmpCriteria criteria) throws IOException { + if (this.getClient() != null) { + CountRequest countRequest = new CountRequest(this.environment.getProperty("elasticsearch.index")); + + BoolQueryBuilder boolQuery = createBoolQuery(criteria); + + countRequest.query(boolQuery); + CountResponse response = this.getClient().count(countRequest, RequestOptions.DEFAULT); + return response.getCount(); + } + return null; + } + + private BoolQueryBuilder createBoolQuery(DmpCriteria criteria) { + BoolQueryBuilder boolQuery = QueryBuilders.boolQuery().mustNot(QueryBuilders.termsQuery(Dmp.MapKey.STATUS.getName(), Collections.singletonList(Dmp.DMPStatus.DELETED.getValue()))); + if (criteria.isPublic()) { + boolQuery = boolQuery.should(QueryBuilders.termQuery(Dmp.MapKey.ISPUBLIC.getName(), true)); + boolQuery = boolQuery.should(QueryBuilders.termQuery(Dmp.MapKey.STATUS.getName(), Dmp.DMPStatus.FINALISED.getValue())); + } + if (criteria.getLike() != null && !criteria.getLike().isEmpty()) { + boolQuery = boolQuery.should(QueryBuilders.queryStringQuery(criteria.getLike()).fields(Stream.of(new Object[][]{ + {Dmp.MapKey.LABEL.getName(), 1.0f}, + {Dmp.MapKey.DESCRIPTION.getName(), 1.0f} + }).collect(Collectors.toMap(data -> (String) data[0], data -> (Float) data[1])))); + } + + if (criteria.getTemplates() != null && criteria.getTemplates().size() > 0) { + boolQuery = boolQuery.should(QueryBuilders.termsQuery(Dmp.MapKey.TEMPLATES.getName() + ".id.keyword", criteria.getTemplates().stream().map(UUID::toString).collect(Collectors.toList()))); + } + + if (criteria.getStatus() != null) { + boolQuery = boolQuery.should(QueryBuilders.termQuery(Dmp.MapKey.STATUS.getName(), criteria.getStatus().intValue())); + } + + if (criteria.getGroupIds() != null && criteria.getGroupIds().size() > 0) { + boolQuery = boolQuery.should(QueryBuilders.termsQuery(Dmp.MapKey.GROUPID.getName(), criteria.getGroupIds().stream().map(UUID::toString).collect(Collectors.toList()))); + } + + if (criteria.getGrants() != null && criteria.getGrants().size() > 0) { + boolQuery = boolQuery.should(QueryBuilders.termsQuery(Dmp.MapKey.GRANT.getName() + ".keyword", criteria.getGrants().stream().map(UUID::toString).collect(Collectors.toList()))); + } + + if (criteria.getCollaborators() != null && criteria.getCollaborators().size() > 0) { + boolQuery = boolQuery.should(QueryBuilders.termsQuery(Dmp.MapKey.COLLABORATORS.getName() + ".id.keyword", criteria.getCollaborators().stream().filter(Objects::nonNull).map(UUID::toString).collect(Collectors.toList()))); + } + + if (!criteria.isAllowAllVersions()) { + boolQuery = boolQuery.should(QueryBuilders.termQuery(criteria.isPublic() ? Dmp.MapKey.LASTPUBLICVERSION.getName() : Dmp.MapKey.LASTVERSION.getName(), true)); + } + + if (criteria.getOrganizations() != null && criteria.getOrganizations().size() > 0) { + boolQuery = boolQuery.should(QueryBuilders.termsQuery(Dmp.MapKey.ORGANIZATIONS.getName() + ".id.keyword", criteria.getOrganizations().stream().map(UUID::toString).collect(Collectors.toList()))); + } + + if (criteria.getGrantStatus() != null) { + boolQuery = boolQuery.should(QueryBuilders.termQuery(Dmp.MapKey.GRANTSTATUS.getName(), criteria.getGrantStatus())); + } + + if (boolQuery.should().isEmpty() && boolQuery.mustNot().isEmpty()) { + boolQuery = boolQuery.should(QueryBuilders.matchAllQuery()); + } else { + boolQuery.minimumShouldMatch(boolQuery.should().size()); + } + return boolQuery; + } + + public boolean createIndex() { + try { + if (!this.exists()) { + CreateIndexRequest createIndexRequest = new CreateIndexRequest(this.environment.getProperty("elasticsearch.index")); + this.getClient().indices().create(createIndexRequest, RequestOptions.DEFAULT); + this.generateMapping(); + } + return true; + } catch (Exception e) { + logger.error(e.getMessage(), e); + return false; + } + } + + @Override + public boolean exists() throws IOException { + if (this.getClient() != null) { + GetIndexRequest request = new GetIndexRequest(this.environment.getProperty("elasticsearch.index")); + return this.getClient().indices().exists(request, RequestOptions.DEFAULT); + } + return false; + } + + @Override + public void clear() throws IOException { + if (exists()) { + DeleteByQueryRequest delete = new DeleteByQueryRequest(this.environment.getProperty("elasticsearch.index")); + delete.setQuery(QueryBuilders.matchAllQuery()); + this.getClient().deleteByQuery(delete, RequestOptions.DEFAULT); + DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(this.environment.getProperty("elasticsearch.index")); + this.getClient().indices().delete(deleteIndexRequest, RequestOptions.DEFAULT); + } + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/ElasticRepository.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/ElasticRepository.java new file mode 100644 index 000000000..1b69037ac --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/ElasticRepository.java @@ -0,0 +1,46 @@ +package eu.eudat.old.elastic.repository; + +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.elastic.criteria.Criteria; +import eu.eudat.old.elastic.entities.ElasticEntity; +import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.RestHighLevelClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +/** + * Created by ikalyvas on 7/5/2018. + */ +public abstract class ElasticRepository implements Repository { + private static final Logger logger = LoggerFactory.getLogger(ElasticRepository.class); + private RestHighLevelClient client; + + public RestHighLevelClient getClient() { + return client; + } + + public ElasticRepository(RestHighLevelClient client) { + try { + if (client.ping(RequestOptions.DEFAULT)) { + this.client = client; + } + } catch (IOException e) { + logger.warn("Unable to connect to Elastic Services"); + logger.error(e.getMessage(), e); + this.client = null; + } + } + + public T transformFromString(String value, Class tClass) { + ObjectMapper mapper = new ObjectMapper(); + T item = null; + try { + item = mapper.readValue(value, tClass); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + return item; + } +} diff --git a/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/Repository.java b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/Repository.java new file mode 100644 index 000000000..ce79105a7 --- /dev/null +++ b/dmp-migration-tool/elastic/src/main/java/eu/eudat/old/elastic/repository/Repository.java @@ -0,0 +1,26 @@ +package eu.eudat.old.elastic.repository; + +import eu.eudat.old.elastic.entities.ElasticEntity; +import eu.eudat.old.elastic.criteria.Criteria; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.ExecutionException; + +/** + * Created by ikalyvas on 7/5/2018. + */ +public interface Repository { + + ET createOrUpdate(ET entity) throws IOException; + + ET findDocument(String id) throws IOException; + + List query(C criteria) throws ExecutionException, InterruptedException, IOException; + + Long count(C criteria) throws ExecutionException, InterruptedException, IOException; + + boolean exists() throws IOException; + + void clear() throws IOException; +} diff --git a/dmp-migration-tool/package-lock.json b/dmp-migration-tool/package-lock.json new file mode 100644 index 000000000..48e341a09 --- /dev/null +++ b/dmp-migration-tool/package-lock.json @@ -0,0 +1,3 @@ +{ + "lockfileVersion": 1 +} diff --git a/dmp-migration-tool/pom.xml b/dmp-migration-tool/pom.xml new file mode 100644 index 000000000..56aad0165 --- /dev/null +++ b/dmp-migration-tool/pom.xml @@ -0,0 +1,363 @@ + + + 4.0.0 + eu.eudat + dmp-backend + 1.0.0-SNAPSHOT + pom + + + org.springframework.boot + spring-boot-starter-parent + 2.5.2 + + + + queryable + web + data + elastic + + + + 1.19.0 + 1.19.0 + 0.2.0 + 1.8 + + 0.0.1-SNAPSHOT + 5.3.8 + + 5.3.10.RELEASE + + + + + 5.5.3.Final + + 1.9 + 4.11 + 1.2.17 + 2.15.0 + 1.7.15 + + 1.2.3 + + + + + + + + org.json + json + 20160810 + + + org.springframework + spring-context-support + ${org.springframework.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + org.elasticsearch + elasticsearch + 7.7.0 + + + org.apache.httpcomponents + httpclient + + + org.apache.httpcomponents + httpcore + + + org.apache.httpcomponents + httpcore-nio + + + + + + org.apache.httpcomponents + httpclient + 4.5.12 + + + + org.apache.httpcomponents + httpcore-nio + 4.4.13 + + + + org.apache.httpcomponents + httpcore + 4.4.13 + + + + org.elasticsearch.client + elasticsearch-rest-high-level-client + 7.6.0 + + + org.hibernate + hibernate-core + ${hibernate.version} + + + + org.hibernate + hibernate-c3p0 + ${hibernate.version} + + + + + com.google.api-client + google-api-client + 1.23.0 + + + + com.jayway.jsonpath + json-path + 2.4.0 + + + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + 2.12.3 + + + + + + com.fasterxml.jackson.core + jackson-core + 2.12.3 + + + + com.fasterxml.jackson.core + jackson-databind + 2.12.3 + + + + + + + + + + org.apache.commons + commons-lang3 + 3.5 + + + + org.apache.poi + poi-ooxml + 4.1.1 + + + + org.apache.poi + poi + 4.1.1 + + + + + org.apache.xmlgraphics + fop + 2.3 + + + + org.jsoup + jsoup + 1.14.3 + + + + fr.opensagres.xdocreport + org.apache.poi.xwpf.converter.pdf + 1.0.6 + + + + fr.opensagres.xdocreport + org.apache.poi.xwpf.converter.core + 1.0.6 + + + + fr.opensagres.xdocreport + fr.opensagres.xdocreport.itext.extension + 2.0.1 + + + + commons-io + commons-io + 2.1 + + + + + + org.elasticsearch.client + transport + 7.6.0 + + + + + + + javax.xml.bind + jaxb-api + 2.3.1 + + + + + org.glassfish.jaxb + jaxb-core + 2.3.0 + + + + + org.glassfish.jaxb + jaxb-runtime + 2.3.1 + + + + + + javax.annotation + javax.annotation-api + 1.3.1 + + + + + javax.validation + validation-api + 2.0.1.Final + + + + + + io.prometheus + simpleclient + 0.11.0 + + + + io.prometheus + simpleclient_hotspot + 0.11.0 + + + + io.prometheus + simpleclient_httpserver + 0.11.0 + + + + io.prometheus + simpleclient_pushgateway + 0.11.0 + + + + + io.micrometer + micrometer-registry-prometheus + 1.7.1 + + + org.springframework.boot + spring-boot-starter-actuator + + + + io.micrometer + micrometer-core + + + + + + + + devel + + true + + + jar + + + + intellij-properties-launcher + + + + org.springframework.boot + spring-boot-loader + 2.5.2 + + + + + + production + + jar + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + + profile + production + + + + + + \ No newline at end of file diff --git a/dmp-migration-tool/queryable/pom.xml b/dmp-migration-tool/queryable/pom.xml new file mode 100644 index 000000000..7460a7129 --- /dev/null +++ b/dmp-migration-tool/queryable/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + dmp-backend + queryable + 1.0-SNAPSHOT + jar + + + eu.eudat + dmp-backend + 1.0.0-SNAPSHOT + + \ No newline at end of file diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/QueryableList.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/QueryableList.java new file mode 100644 index 000000000..cfb53581d --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/QueryableList.java @@ -0,0 +1,76 @@ +package eu.eudat.old.queryable; + +import eu.eudat.old.queryable.jpa.predicates.*; +import eu.eudat.old.queryable.types.SelectionField; +import eu.eudat.old.queryable.queryableentity.DataEntity; + +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.Subquery; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +public interface QueryableList { + QueryableList where(SinglePredicate predicate); + + List select(SelectPredicate predicate); + + CompletableFuture> selectAsync(SelectPredicate predicate); + + List toList(); + + void update(EntitySelectPredicate selectPredicate, V value); + + QueryableList withFields(List fields); + + List toListWithFields(); + + CompletableFuture> toListAsync(); + + T getSingle(); + + CompletableFuture getSingleAsync(); + + T getSingleOrDefault(); + + CompletableFuture getSingleOrDefaultAsync(); + + QueryableList skip(Integer offset); + + QueryableList take(Integer length); + + QueryableList distinct(); + + QueryableList orderBy(OrderByPredicate predicate); + + QueryableList groupBy(GroupByPredicate predicate); + + QueryableList withHint(String hint); + + Long count(); + + QueryableList where(NestedQuerySinglePredicate predicate); + + CompletableFuture countAsync(); + + Subquery query(List fields); + + Subquery subQuery(SinglePredicate predicate, List fields); + + Subquery subQuery(NestedQuerySinglePredicate predicate, List fields); + + Subquery subQueryCount(NestedQuerySinglePredicate predicate, List fields); + + Subquery subQueryCount(SinglePredicate predicate, List fields); + + QueryableList initSubQuery(Class uClass); + + Subquery subQueryMax(SinglePredicate predicate, List fields, Class uClass); + + Subquery subQueryMax(NestedQuerySinglePredicate predicate, List fields, Class uClass); + + Join getJoin(String field, JoinType type); + + +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/collector/Collector.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/collector/Collector.java new file mode 100644 index 000000000..9628e7e25 --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/collector/Collector.java @@ -0,0 +1,34 @@ +package eu.eudat.old.queryable.collector; + +import javax.persistence.Tuple; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class Collector { + + public List buildFromTuple(List results, Map> groupedResults, List fields, String key) { + return results.stream().map(tuple -> { + Map parsedResult = new HashMap<>(); + tuple.getElements().forEach(tupleElement -> parsedResult.put(tupleElement.getAlias(), tuple.get(tupleElement.getAlias()))); + return parsedResult; + }).collect(Collectors.toList());/*groupedResults.keySet().stream() + .map(x -> buildOne(groupedResults.get(x), fields, key)) + .collect(Collectors.toList());*/ + } + + private Map buildOne(List tuples, List fields, String key) { + Map tupleValues = new LinkedHashMap(); + List projectionFields = fields.stream() + .map(x -> x.split("\\.")) + .collect(Collectors.groupingBy(x -> x[0])) + .values() + .stream() + .map(field -> new ProjectionField(field.stream().map(x -> String.join(".", x)).collect(Collectors.toList()), null)) + .collect(Collectors.toList()); + projectionFields.forEach(x -> x.collect(tupleValues, tuples)); + return tupleValues; + } +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/collector/ProjectionField.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/collector/ProjectionField.java new file mode 100644 index 000000000..f165424e6 --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/collector/ProjectionField.java @@ -0,0 +1,107 @@ +package eu.eudat.old.queryable.collector; + +import com.google.common.collect.Lists; + +import javax.persistence.Tuple; +import java.util.*; +import java.util.stream.Collectors; + +public class ProjectionField { + private String key; + private List fields; + private ProjectionField parent; + + public ProjectionField(List field, ProjectionField parent) { + this.parse(field); + this.parent = parent; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public List getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } + + private void parse(List fields) { + String[] fieldsArr = fields.get(0).split("\\."); + this.key = fieldsArr[0]; + this.fields = fields.stream() + .map(x -> x.replace(x.contains(".") ? this.key + "." : this.key, "")) + .filter(x -> !x.isEmpty()) + .map(x -> x.split("\\.")) + .collect(Collectors.groupingBy(x -> x[0])) + .values() + .stream() + .map(field -> new ProjectionField(field.stream().map(x -> String.join(".", x)).collect(Collectors.toList()), this)) + .collect(Collectors.toList()); + } + + public Map collect(Map map, List tuples) { + if (fields != null && !fields.isEmpty()) { + this.collect(map, this.fields, tuples); + } else { + map.put(key, this.createObject(tuples, this.generatePath())); + } + return map; + } + + public Map collect(Map map, List projectionGroup, List tuples) { + map.put(key, this.createObject(tuples, projectionGroup)); + return map; + } + + private String generatePath() { + List list = new LinkedList<>(); + ProjectionField current = this; + list.add(current.key); + while (current.parent != null) { + list.add(current.parent.key); + current = current.parent; + } + return String.join(".", Lists.reverse(list)); + } + + private Object createObject(List tuples, String field) { + List values = tuples.stream() + .map(x -> x.get(field)) + .distinct() + .collect(Collectors.toList()); + + if (values.size() > 1) { + return values.stream().map(x -> { + Map map = new LinkedHashMap(); + map.put(field, x); + return map; + }).collect(Collectors.toList()); + } else if (values.size() == 1) { + return values.get(0); + } else return null; + } + + private Object createObject(List tuples, List group) { + Collection values = tuples.stream() + .map(x -> getValuesFrom(tuples, x, group)) + .collect(Collectors.toMap(x -> x.get("id"), x -> x, (x, y) -> x)).values(); + return values; + } + + private Map getValuesFrom(List tuples, Tuple tuple, List group) { + Map map = new LinkedHashMap(); + group.forEach(x -> { + if (x.fields != null && !x.fields.isEmpty()) + map.put(x.key, this.createObject(tuples, x.fields)); + else map.put(x.key, tuple.get(x.generatePath())); + }); + return map; + } +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/exceptions/NotSingleResultException.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/exceptions/NotSingleResultException.java new file mode 100644 index 000000000..c7545867b --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/exceptions/NotSingleResultException.java @@ -0,0 +1,20 @@ +package eu.eudat.old.queryable.exceptions; + + +public class NotSingleResultException extends RuntimeException { + public NotSingleResultException() { + super(); + } + + public NotSingleResultException(String message, Throwable cause) { + super(message, cause); + } + + public NotSingleResultException(String message) { + super(message); + } + + public NotSingleResultException(Throwable cause) { + super(cause); + } +} \ No newline at end of file diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java new file mode 100644 index 000000000..7cba452dd --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java @@ -0,0 +1,507 @@ +package eu.eudat.old.queryable.jpa.hibernatequeryablelist; + +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.collector.Collector; +import eu.eudat.old.queryable.exceptions.NotSingleResultException; +import eu.eudat.old.queryable.jpa.predicates.*; +import eu.eudat.old.queryable.types.FieldSelectionType; +import eu.eudat.old.queryable.types.SelectionField; +import eu.eudat.old.queryable.queryableentity.DataEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Async; + +import javax.persistence.EntityManager; +import javax.persistence.Tuple; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.*; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; + +public class QueryableHibernateList implements QueryableList { + private static final Logger logger = LoggerFactory.getLogger(QueryableHibernateList.class); + + private Collector collector = new Collector(); + private EntityManager manager; + private CriteriaQuery query; + private Class tClass; + private Root root; + private Root nestedQueryRoot; + private Subquery subquery; + private List> singlePredicates = new LinkedList<>(); + private List> nestedPredicates = new LinkedList<>(); + private boolean distinct = false; + private List> orderings = new LinkedList<>(); + private List> groupings = new LinkedList<>(); + private List fields = new LinkedList<>(); + private Integer length; + private Integer offset; + private Set hints; + private String hint; + private Map joinsMap = new HashMap<>(); + + public QueryableHibernateList(EntityManager manager, Class tClass) { + this.manager = manager; + this.tClass = tClass; + } + + public QueryableHibernateList setManager(EntityManager manager) { + this.manager = manager; + return this; + } + + public QueryableList withHint(String hint) { + this.hint = hint; + return this; + } + + @Override + public QueryableList withFields(List fields) { + this.fields = fields; + return this; + } + + private QueryableList selectFields() { + List rootFields = fields.stream().map(this::convertFieldToPath).filter(Objects::nonNull).collect(Collectors.toList()); + this.query.select(this.manager.getCriteriaBuilder().tuple(rootFields.toArray(new Selection[rootFields.size()]))); + return this; + } + + private Path convertFieldToPath(String field) { + if (!field.contains(".")) { + Path path = this.root.get(field); + path.alias(field); + return path; + } else { + String[] fields = field.split("\\."); + Path path = this.root.get(fields[0]); + Join join = null; + path.alias(fields[0]); + for (int i = 1; i < fields.length; i++) { + join = join != null ? join.join(fields[i - 1], JoinType.LEFT) : this.getJoin(fields[i - 1], JoinType.LEFT); + path = join.get(fields[i]); + path.alias(String.join(".", Arrays.asList(fields).subList(0, i + 1))); + } + return path; + } + } + + private Join getJoin(String field, String path, Join joined, JoinType type) { + if (this.joinsMap.containsKey(path)) return this.joinsMap.get(path); + Join join = joined.join(path, type); + this.joinsMap.put(path, join); + return join; + } + + public Join getJoin(String field, JoinType type) { + if (this.joinsMap.containsKey(field)) return this.joinsMap.get(field); + Join join = this.root.join(field, type); + this.joinsMap.put(field, join); + return join; + } + + public QueryableHibernateList setEntity(Class type) { + + return this; + } + + public void initiateQueryableList(Class type) { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + this.query = builder.createQuery(type); + } + + @Override + public QueryableList skip(Integer offset) { + this.offset = offset; + return this; + } + + @Override + public QueryableList take(Integer length) { + this.length = length; + return this; + } + + public QueryableList where(SinglePredicate predicate) { + this.singlePredicates.add(predicate); + return this; + } + + public QueryableList where(NestedQuerySinglePredicate predicate) { + this.nestedPredicates.add(predicate); + return this; + } + + public List select(SelectPredicate predicate) { + return this.toList().stream().map(predicate::applySelection).collect(Collectors.toList()); + } + + public CompletableFuture> selectAsync(SelectPredicate predicate) { + return this.toListAsync().thenApplyAsync(items -> items.stream().map(predicate::applySelection).collect(Collectors.toList())); + } + + public QueryableList distinct() { + this.distinct = true; + return this; + } + + public QueryableList orderBy(OrderByPredicate predicate) { + this.orderings.add(predicate); + return this; + } + + public QueryableList groupBy(GroupByPredicate predicate) { + this.groupings.add(predicate); + return this; + } + + public Long count() { + CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Long.class); + this.root = criteriaQuery.from(tClass); + if (distinct) criteriaQuery.select(criteriaBuilder.countDistinct(this.root.get("id"))); + else criteriaQuery.select(criteriaBuilder.count(this.root)); + criteriaQuery.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.groupings.isEmpty()) criteriaQuery.groupBy(this.generateGroupPredicates(this.groupings, this.root)); + //if (distinct) criteriaQuery.distinct(true); + + //GK: Group By special case. When group by is used, since it will result in a list of how many elements have the grouped field common + // then it will instead return the number of the distinct values of the grouped field + if (this.groupings.isEmpty()) { + return this.manager.createQuery(criteriaQuery).getSingleResult(); + } else { + return (long) this.manager.createQuery(criteriaQuery).getResultList().size(); + } + } + + @Async + public CompletableFuture countAsync() { + CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Long.class); + this.root = criteriaQuery.from(tClass); + if (distinct) criteriaQuery.select(criteriaBuilder.countDistinct(this.root.get("id"))); + else criteriaQuery.select(criteriaBuilder.count(this.root)); + criteriaQuery.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.groupings.isEmpty()) criteriaQuery.groupBy(this.generateGroupPredicates(this.groupings, this.root)); + //if (distinct) criteriaQuery.distinct(true); + return CompletableFuture.supplyAsync(() -> { + if (this.groupings.isEmpty()) { + return this.manager.createQuery(criteriaQuery).getSingleResult(); + } else { + return (long) this.manager.createQuery(criteriaQuery).getResultList().size(); + } + }); + } + + + private Predicate[] generateWherePredicates(List> singlePredicates, Root root, List> nestedPredicates, Root nestedQueryRoot) { + List predicates = new LinkedList<>(); + predicates.addAll(Arrays.asList(this.generateSingleWherePredicates(singlePredicates, root))); + predicates.addAll(Arrays.asList(this.generateNestedWherePredicates(nestedPredicates, root, nestedQueryRoot))); + return predicates.toArray(new Predicate[predicates.size()]); + } + + private Predicate[] generateSingleWherePredicates(List> singlePredicates, Root root) { + List predicates = new LinkedList<>(); + for (SinglePredicate singlePredicate : singlePredicates) { + predicates.add(singlePredicate.applyPredicate(this.manager.getCriteriaBuilder(), root)); + } + return predicates.toArray(new Predicate[predicates.size()]); + } + + private Predicate[] generateNestedWherePredicates(List> nestedPredicates, Root root, Root nestedQueryRoot) { + List predicates = new LinkedList<>(); + for (NestedQuerySinglePredicate singlePredicate : nestedPredicates) { + predicates.add(singlePredicate.applyPredicate(this.manager.getCriteriaBuilder(), root, nestedQueryRoot)); + } + return predicates.toArray(new Predicate[predicates.size()]); + } + + private Order[] generateOrderPredicates(List> orderByPredicates, Root root) { + List predicates = new LinkedList<>(); + for (OrderByPredicate orderPredicate : orderByPredicates) { + predicates.add(orderPredicate.applyPredicate(this.manager.getCriteriaBuilder(), root)); + } + return predicates.toArray(new Order[predicates.size()]); + } + + private Expression[] generateGroupPredicates(List> groupByPredicates, Root root) { + List predicates = new LinkedList<>(); + for (GroupByPredicate groupPredicate : groupByPredicates) { + predicates.add(groupPredicate.applyPredicate(this.manager.getCriteriaBuilder(), root)); + } + return predicates.toArray(new Expression[predicates.size()]); + } + + public List toList() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.orderings.isEmpty()) this.query.orderBy(this.generateOrderPredicates(this.orderings, this.root)); + if (!this.groupings.isEmpty()) this.query.groupBy(this.generateGroupPredicates(this.groupings, this.root)); + if (!this.fields.isEmpty()) this.selectFields(); + if (distinct) this.query.distinct(true); + //if (!this.fields.isEmpty()) this.query.multiselect(this.parseFields(this.fields)); + ObjectMapper mapper = new ObjectMapper(); + if (!this.fields.isEmpty()) return this.toListWithFields().stream().map(m -> mapper.convertValue(m, this.tClass)).collect(Collectors.toList()); + return this.toListWithOutFields(); + } + + public List toListWithFields() { + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.offset != null) typedQuery.setFirstResult(this.offset); + if (this.length != null) typedQuery.setMaxResults(this.length); + List results = typedQuery.getResultList(); + Map> groupedResults = results.stream() + .collect(Collectors.groupingBy(x -> x.get("id"))); + return this.collector.buildFromTuple(results, groupedResults, this.fields, "id"); + } + + private List toListWithOutFields() { + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.offset != null) typedQuery.setFirstResult(this.offset); + if (this.length != null) typedQuery.setMaxResults(this.length); + if (this.hint != null) { + List ids = typedQuery.getResultList().stream().map(item -> item.getKeys()).collect(Collectors.toList()); + if (ids != null && !ids.isEmpty()) typedQuery = queryWithHint(ids); + } + return typedQuery.getResultList(); + } + + @Async + public CompletableFuture> toListAsync() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.orderings.isEmpty()) this.query.orderBy(this.generateOrderPredicates(this.orderings, this.root)); + if (!this.groupings.isEmpty()) this.query.groupBy(this.generateGroupPredicates(this.groupings, this.root)); + if (!this.fields.isEmpty()) this.selectFields(); + if (distinct) this.query.distinct(true); + if (!this.fields.isEmpty()) return this.toListAsyncWithFields(); + else return this.toListAsyncWithOutFields(); + } + + @Async + private CompletableFuture> toListAsyncWithFields() { + List results = this.manager.createQuery(query).getResultList(); + Map> groupedResults = results.stream() + .collect(Collectors.groupingBy(x -> x.get("id"))); + return CompletableFuture.supplyAsync(() -> results.stream().map(x -> { + try { + return (T) this.tClass.newInstance().buildFromTuple(groupedResults.get(x.get("id")), this.fields, ""); + } catch (InstantiationException | IllegalAccessException e) { + logger.error(e.getMessage(), e); + } + return null; + }).collect(Collectors.toList())); + } + + @Async + private CompletableFuture> toListAsyncWithOutFields() { + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.offset != null) typedQuery.setFirstResult(this.offset); + if (this.length != null) typedQuery.setMaxResults(this.length); + return CompletableFuture.supplyAsync(() -> { + if (this.hint != null) { + List ids = typedQuery.getResultList().stream().map(item -> item.getKeys()).collect(Collectors.toList()); + if (ids != null && !ids.isEmpty()) return queryWithHint(ids).getResultList(); + } + return typedQuery.getResultList(); + }); + } + + public T getSingle() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.fields.isEmpty()) this.selectFields(); + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.hint != null) + typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); + return typedQuery.getSingleResult(); + } + + @Async + public CompletableFuture getSingleAsync() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.fields.isEmpty()) this.selectFields(); + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.hint != null) + typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); + return CompletableFuture.supplyAsync(() -> typedQuery.getSingleResult()); + } + + public T getSingleOrDefault() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.fields.isEmpty()) this.selectFields(); + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.hint != null) + typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); + List results = typedQuery.getResultList(); + if (results.size() == 0) return null; + if (results.size() == 1) return results.get(0); + else throw new NotSingleResultException("Query returned more than one items"); + } + + @Async + public CompletableFuture getSingleOrDefaultAsync() { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + if (!this.fields.isEmpty()) this.query = builder.createTupleQuery(); + else this.query = builder.createQuery(this.tClass); + this.root = this.query.from(this.tClass); + this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (!this.fields.isEmpty()) this.selectFields(); + TypedQuery typedQuery = this.manager.createQuery(this.query); + if (this.hint != null) + typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); + return CompletableFuture.supplyAsync(() -> typedQuery.getResultList()).thenApply(list -> { + if (list.size() == 0) return null; + if (list.size() == 1) return list.get(0); + else throw new NotSingleResultException("Query returned more than one items"); + }); + } + + private TypedQuery queryWithHint(List ids) { + CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(tClass); + Root criteriaRoot = criteriaQuery.from(this.tClass); + criteriaQuery.where(criteriaRoot.get("id").in(ids)); + if (!this.orderings.isEmpty()) + criteriaQuery.orderBy(this.generateOrderPredicates(this.orderings, criteriaRoot)); + + if (!this.groupings.isEmpty()) criteriaQuery.groupBy(this.generateGroupPredicates(this.groupings, this.root)); + + TypedQuery typedQuery = this.manager.createQuery(criteriaQuery); + typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); + return typedQuery; + } + + @Override + public Subquery subQuery(SinglePredicate predicate, List fields) { + Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(this.tClass); + this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); + if (fields.get(0).getType() == FieldSelectionType.FIELD) + subquery.select(this.nestedQueryRoot.get(fields.get(0).getField())); + else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { + subquery.select(this.nestedQueryRoot.join(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1])); + } + return subquery; + } + + @Override + public Subquery subQuery(NestedQuerySinglePredicate predicate, List fields) { + Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(this.tClass); + this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); + if (fields.get(0).getType() == FieldSelectionType.FIELD) + subquery.select(this.nestedQueryRoot.get(fields.get(0).getField())); + else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { + subquery.select(this.nestedQueryRoot.get(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1])); + } + return subquery; + } + + @Override + public Subquery subQueryCount(SinglePredicate predicate, List fields) { + Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(Long.class); + this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); + subquery.select(this.manager.getCriteriaBuilder().count(this.nestedQueryRoot.get(fields.get(0).getField()))); + return subquery; + } + + @Override + public Subquery subQueryCount(NestedQuerySinglePredicate predicate, List fields) { + Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(Long.class); + this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); + subquery.select(this.manager.getCriteriaBuilder().count(this.nestedQueryRoot.get(fields.get(0).getField()))); + return subquery; + } + + @Override + public Subquery subQueryMax(SinglePredicate predicate, List fields, Class uClass) { + Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass); + this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); + if (fields.get(0).getType() == FieldSelectionType.FIELD) + subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField()))); + else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { + subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1]))); + } + return subquery; + } + + @Override + public Subquery subQueryMax(NestedQuerySinglePredicate predicate, List fields, Class uClass) { + //Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass); + //this.nestedQueryRoot = subquery.from(this.tClass); + subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); + if (fields.get(0).getType() == FieldSelectionType.FIELD) + subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField()))); + else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { + subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1]))); + } + return subquery; + } + + public QueryableList initSubQuery(Class uClass) { + this.subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass); + this.nestedQueryRoot = subquery.from(this.tClass); + return this; + } + + @Override + public Subquery query(List fields) { + CriteriaBuilder builder = this.manager.getCriteriaBuilder(); + Subquery query = builder.createQuery().subquery(this.tClass); + this.root = query.from(this.tClass); + query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + if (fields.get(0).getType() == FieldSelectionType.FIELD) + query.select(this.root.get(fields.get(0).getField())); + else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { + query.select(this.root.get(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1])); + } + if (distinct) query.distinct(true); + return query; + } + + @Override + public void update(EntitySelectPredicate selectPredicate, V value) { + CriteriaBuilder builder = this.manager + .getCriteriaBuilder(); + CriteriaUpdate update = builder + .createCriteriaUpdate(tClass); + this.root = update.from(tClass); + update.set(selectPredicate.applyPredicate(root), value) + .where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); + this.manager + .createQuery(update) + .executeUpdate(); + } + + private Path[] parseFields(List selectedFields) { + List paths = new ArrayList<>(); + selectedFields.forEach(s -> paths.add(root.get(s))); + + return paths.toArray(new Path[0]); + } +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/EntitySelectPredicate.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/EntitySelectPredicate.java new file mode 100644 index 000000000..09a881d13 --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/EntitySelectPredicate.java @@ -0,0 +1,13 @@ +package eu.eudat.old.queryable.jpa.predicates; + +import javax.persistence.criteria.Path; +import javax.persistence.criteria.Root; +import java.util.function.Predicate; + +/** + * Created by ikalyvas on 10/10/2018. + */ +public interface EntitySelectPredicate { + Path applyPredicate(Root root); + +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/GroupByPredicate.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/GroupByPredicate.java new file mode 100644 index 000000000..62680247e --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/GroupByPredicate.java @@ -0,0 +1,10 @@ +package eu.eudat.old.queryable.jpa.predicates; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Root; + +public interface GroupByPredicate { + Expression applyPredicate(CriteriaBuilder builder, Root root); + +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/NestedQuerySinglePredicate.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/NestedQuerySinglePredicate.java new file mode 100644 index 000000000..1326c8288 --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/NestedQuerySinglePredicate.java @@ -0,0 +1,13 @@ +package eu.eudat.old.queryable.jpa.predicates; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +/** + * Created by ikalyvas on 2/7/2018. + */ +public interface NestedQuerySinglePredicate { + Predicate applyPredicate(CriteriaBuilder builder, Root root, Root nestedQueryRoot); + +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/OrderByPredicate.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/OrderByPredicate.java new file mode 100644 index 000000000..642376a33 --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/OrderByPredicate.java @@ -0,0 +1,10 @@ +package eu.eudat.old.queryable.jpa.predicates; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Order; +import javax.persistence.criteria.Root; + +public interface OrderByPredicate { + Order applyPredicate(CriteriaBuilder builder, Root root); + +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/QueryablePredicate.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/QueryablePredicate.java new file mode 100644 index 000000000..b50ef404c --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/QueryablePredicate.java @@ -0,0 +1,7 @@ +package eu.eudat.old.queryable.jpa.predicates; + +/** + * Created by ikalyvas on 2/7/2018. + */ +public interface QueryablePredicate { +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/SelectPredicate.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/SelectPredicate.java new file mode 100644 index 000000000..db82a0372 --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/SelectPredicate.java @@ -0,0 +1,5 @@ +package eu.eudat.old.queryable.jpa.predicates; + +public interface SelectPredicate { + R applySelection(T item); +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/SinglePredicate.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/SinglePredicate.java new file mode 100644 index 000000000..1c2dac730 --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/jpa/predicates/SinglePredicate.java @@ -0,0 +1,9 @@ +package eu.eudat.old.queryable.jpa.predicates; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +public interface SinglePredicate { + Predicate applyPredicate(CriteriaBuilder builder, Root root); +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/queryableentity/DataEntity.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/queryableentity/DataEntity.java new file mode 100644 index 000000000..2b680c1ee --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/queryableentity/DataEntity.java @@ -0,0 +1,12 @@ +package eu.eudat.old.queryable.queryableentity; + +import javax.persistence.Tuple; +import java.util.List; + +public interface DataEntity { + void update(T entity); + + K getKeys(); + + T buildFromTuple(List tuple, List fields, String base); +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/types/FieldSelectionType.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/types/FieldSelectionType.java new file mode 100644 index 000000000..7933ada47 --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/types/FieldSelectionType.java @@ -0,0 +1,8 @@ +package eu.eudat.old.queryable.types; + +/** + * Created by ikalyvas on 2/7/2018. + */ +public enum FieldSelectionType { + FIELD, COMPOSITE_FIELD, COUNT, MAX +} diff --git a/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/types/SelectionField.java b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/types/SelectionField.java new file mode 100644 index 000000000..a68c8e15b --- /dev/null +++ b/dmp-migration-tool/queryable/src/main/java/eu/eudat/old/queryable/types/SelectionField.java @@ -0,0 +1,34 @@ +package eu.eudat.old.queryable.types; + +/** + * Created by ikalyvas on 2/7/2018. + */ +public class SelectionField { + private FieldSelectionType type = FieldSelectionType.FIELD; + private String field; + + public SelectionField(String field) { + this.field = field; + } + + public SelectionField(FieldSelectionType type, String field) { + this.type = type; + this.field = field; + } + + public FieldSelectionType getType() { + return type; + } + + public void setType(FieldSelectionType type) { + this.type = type; + } + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } +} diff --git a/dmp-migration-tool/web/pom.xml b/dmp-migration-tool/web/pom.xml new file mode 100644 index 000000000..7d44a4e48 --- /dev/null +++ b/dmp-migration-tool/web/pom.xml @@ -0,0 +1,276 @@ + + + 4.0.0 + + dmp-backend + web + 1.0-SNAPSHOT + ${packaging.type} + + + eu.eudat + dmp-backend + 1.0.0-SNAPSHOT + + + + + eu.eudat + data + 1.0-SNAPSHOT + + + dmp-backend + queryable + 1.0-SNAPSHOT + + + eu.eudat + elastic + 1.0.0-SNAPSHOT + + + gr.cite.opendmp + repositorydepositbase + 1.0.4 + + + + eu.eudat + core + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-mail + + + org.springframework.boot + spring-boot-starter-webflux + + + + + + + com.fasterxml.jackson.core + jackson-annotations + 2.12.3 + + + + + + + + + + + com.github.ben-manes.caffeine + caffeine + 2.9.0 + + + + + + + org.junit.jupiter + junit-jupiter-api + 5.7.2 + test + + + + org.postgresql + postgresql + 42.2.22 + + + + io.springfox + springfox-swagger-ui + 3.0.0 + + + io.springfox + springfox-swagger2 + 3.0.0 + + + io.springfox + springfox-boot-starter + 3.0.0 + + + + + org.springframework.social + spring-social-facebook + 2.0.3.RELEASE + + + + + org.springframework.social + spring-social-linkedin + 1.0.2.RELEASE + + + + + org.springframework.social + spring-social-twitter + 1.1.2.RELEASE + + + org.springframework.boot + spring-boot-starter-tomcat + + + + org.opensaml + opensaml-core + ${opensaml.version} + compile + + + org.opensaml + opensaml-saml-api + ${opensaml.version} + compile + + + org.opensaml + opensaml-saml-impl + ${opensaml.version} + compile + + + org.opensaml + opensaml-soap-api + ${opensaml.version} + compile + + + org.opensaml + opensaml-xmlsec-api + ${opensaml.version} + + + org.opensaml + opensaml-security-api + ${opensaml.version} + + + org.opensaml + opensaml-security-impl + ${opensaml.version} + + + org.opensaml + opensaml-profile-api + ${opensaml.version} + + + org.opensaml + xmltooling + 1.4.4 + + + jakarta.xml.soap + jakarta.xml.soap-api + 3.0.0 + + + com.sun.xml.messaging.saaj + saaj-impl + 3.0.0-M2 + + + + + ${project.artifactId}-${project.version} + + + src/main/ui-resources + + node_modules/** + + + + src/main/resources + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + true + eu.eudat.old.EuDatApplication + dependency-jars/ + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.5.1 + + + copy-dependencies + package + + copy-dependencies + + + + ${project.build.directory}/dependency-jars/ + + + + + + + + + + eu.eudat.old.EuDatApplication + 4.0.1 + + \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/EuDatApplication.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/EuDatApplication.java new file mode 100644 index 000000000..1461ef55b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/EuDatApplication.java @@ -0,0 +1,24 @@ +package eu.eudat.old; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.scheduling.annotation.EnableAsync; + +@SpringBootApplication(scanBasePackages = {"eu.eudat", "eu.eudat.depositinterface"}) +@EnableAsync +public class EuDatApplication extends SpringBootServletInitializer { + private static final Logger logger = LoggerFactory.getLogger(EuDatApplication.class); + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(EuDatApplication.class); + } + + public static void main(String[] args) { + SpringApplication.run(EuDatApplication.class, args); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/cache/ExternalUrlsKeyGenerator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/cache/ExternalUrlsKeyGenerator.java new file mode 100644 index 000000000..d8582355f --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/cache/ExternalUrlsKeyGenerator.java @@ -0,0 +1,22 @@ +package eu.eudat.old.cache; + +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import org.springframework.cache.interceptor.KeyGenerator; + +import java.lang.reflect.Method; + +public class ExternalUrlsKeyGenerator implements KeyGenerator { + @Override + public Object generate(Object o, Method method, Object... params) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append(o.getClass().getSimpleName()).append("_"); + stringBuffer.append(method.getName()).append("_"); + for (Object param: params) { + if (param instanceof ExternalUrlCriteria) { + ExternalUrlCriteria externalUrlCriteria = (ExternalUrlCriteria) param; + stringBuffer.append(externalUrlCriteria); + } + } + return stringBuffer.toString(); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/cache/ResponsesCache.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/cache/ResponsesCache.java new file mode 100644 index 000000000..942e16635 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/cache/ResponsesCache.java @@ -0,0 +1,60 @@ +package eu.eudat.old.cache; + + +import com.github.benmanes.caffeine.cache.Caffeine; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.caffeine.CaffeineCache; +import org.springframework.cache.interceptor.KeyGenerator; +import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + + +@Component +@EnableCaching +public class ResponsesCache { + private static final Logger logger = LoggerFactory.getLogger(ResponsesCache.class); + + public static long HOW_MANY = 30; + public static TimeUnit TIME_UNIT = TimeUnit.MINUTES; + + + @Bean + public CacheManager cacheManager() { + logger.info("Loading ResponsesCache..."); + SimpleCacheManager simpleCacheManager = new SimpleCacheManager(); + List caches = new ArrayList(); + caches.add(new CaffeineCache("repositories", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("pubrepos", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("journals", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("taxonomies", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("publications", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("grants", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("projects", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("funders", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("organisations", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("registries", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("services", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("tags", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("researchers", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("externalDatasets", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("currencies", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + caches.add(new CaffeineCache("licenses", Caffeine.newBuilder().expireAfterAccess(HOW_MANY, TIME_UNIT).build())); + simpleCacheManager.setCaches(caches); + logger.info("OK"); + return simpleCacheManager; + } + + @Bean(name = "externalUrlsKeyGenerator") + private KeyGenerator externalUrlsKeyGenerator() { + return new ExternalUrlsKeyGenerator(); + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/DevelDatabaseConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/DevelDatabaseConfiguration.java new file mode 100644 index 000000000..667db5843 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/DevelDatabaseConfiguration.java @@ -0,0 +1,74 @@ +package eu.eudat.old.configurations; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.context.annotation.*; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import java.util.Properties; + +@Configuration +@EnableTransactionManagement +@Profile("devel") +@ComponentScan(basePackages = {"eu.eudat.data.entities"}) +public class DevelDatabaseConfiguration { + + @Autowired + private Environment env; + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[]{"eu.eudat.data.entities"}); + JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + return em; + } + + @Bean + @Primary + @ConfigurationProperties(prefix = "spring.datasource") + public DataSource dataSource() { + return DataSourceBuilder + .create() + .username(env.getProperty("database.username")) + .password(env.getProperty("database.password")) + .url(env.getProperty("database.url")) + .driverClassName(env.getProperty("database.driver-class-name")) + .build(); + } + + @Bean + public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { + JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(emf); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + private Properties additionalProperties() { + Properties properties = new Properties(); + properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL92Dialect"); + properties.setProperty("hibernate.show_sql", "true"); + properties.setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false"); + return properties; + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/ElasticSearchConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/ElasticSearchConfiguration.java new file mode 100644 index 000000000..66bc1606d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/ElasticSearchConfiguration.java @@ -0,0 +1,108 @@ +package eu.eudat.old.configurations; + +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; +import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; +import org.apache.http.nio.reactor.IOReactorException; +import org.apache.http.nio.reactor.IOReactorExceptionHandler; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.SSLContexts; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestHighLevelClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +import javax.net.ssl.SSLContext; +import java.io.IOException; + +/** + * Created by ikalyvas on 7/5/2018. + */ +@Configuration +public class ElasticSearchConfiguration { + private static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfiguration.class); + + private Environment environment; + + @Autowired + public ElasticSearchConfiguration(Environment environment) { + this.environment = environment; + } + + @Bean(destroyMethod = "close") + public RestHighLevelClient client() throws Exception { + final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(AuthScope.ANY, + new UsernamePasswordCredentials(this.environment.getProperty("elasticsearch.username"), this.environment.getProperty("elasticsearch.password"))); + + try { + DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); + ioReactor.setExceptionHandler(new IOReactorExceptionHandler() { + @Override + public boolean handle(IOException e) { + logger.warn("System may be unstable: IOReactor encountered a checked exception : " + e.getMessage(), e); + return true; // Return true to note this exception as handled, it will not be re-thrown + } + + @Override + public boolean handle(RuntimeException e) { + logger.warn("System may be unstable: IOReactor encountered a runtime exception : " + e.getMessage(), e); + return true; // Return true to note this exception as handled, it will not be re-thrown + } + }); + + RestHighLevelClient client; + if(this.environment.getProperty("elasticsearch.usingssl", Boolean.class)){ + +// Path caCertificatePath = Paths.get(this.environment.getProperty("elasticsearch.certPath")); +// CertificateFactory factory = +// CertificateFactory.getInstance("X.509"); +// Certificate trustedCa; +// try (InputStream is = Files.newInputStream(caCertificatePath)) { +// trustedCa = factory.generateCertificate(is); +// } +// KeyStore trustStore = KeyStore.getInstance("pkcs12"); +// trustStore.load(null, null); +// trustStore.setCertificateEntry("ca", trustedCa); +// +// TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); +// tmf.init(trustStore); +// +// SSLContext sslContext = SSLContext.getInstance("TLS"); +// sslContext.init(null, tmf.getTrustManagers(), null); + + SSLContextBuilder sslBuilder = SSLContexts.custom() + .loadTrustMaterial(null, (x509Certificates, s) -> true); + final SSLContext sslContext = sslBuilder.build(); + client = new RestHighLevelClient( + RestClient.builder( + new HttpHost(this.environment.getProperty("elasticsearch.host"), + Integer.parseInt(this.environment.getProperty("elasticsearch.port")), "https")) + .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder + .setDefaultCredentialsProvider(credentialsProvider).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext)) + .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectTimeout(5000).setSocketTimeout(120000)) + ); + } + else { + client = new RestHighLevelClient( + RestClient.builder( + new HttpHost(this.environment.getProperty("elasticsearch.host"), + Integer.parseInt(this.environment.getProperty("elasticsearch.port")), "http")) + .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder + .setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(new PoolingNHttpClientConnectionManager(ioReactor)))); + } + return client; + }catch (IOReactorException ex) { + throw new RuntimeException(ex); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/ExecutorServiceConfig.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/ExecutorServiceConfig.java new file mode 100644 index 000000000..8af9f3c56 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/ExecutorServiceConfig.java @@ -0,0 +1,28 @@ +package eu.eudat.old.configurations; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.TaskExecutor; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Created by ikalyvas on 9/26/2018. + */ +@Configuration +public class ExecutorServiceConfig { + + @Bean + public Executor asyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(2); + executor.setMaxPoolSize(2); + executor.setQueueCapacity(500); + executor.setThreadNamePrefix("Rules-"); + executor.initialize(); + return executor; + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/JacksonConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/JacksonConfiguration.java new file mode 100644 index 000000000..18bb043ca --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/JacksonConfiguration.java @@ -0,0 +1,28 @@ +package eu.eudat.old.configurations; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.Module; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import eu.eudat.old.criteria.serialzier.CriteriaSerializer; +import eu.eudat.old.criteria.entities.Criteria; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; + +@Configuration +public class JacksonConfiguration { + @Bean + public ObjectMapper buildObjectMapper() { + + ArrayList modules = new ArrayList<>(); + SimpleModule criteriaSerializerModule = new SimpleModule(); + criteriaSerializerModule.addDeserializer(Criteria.class, new CriteriaSerializer()); + modules.add(criteriaSerializerModule); + + return new ObjectMapper() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .registerModules(modules); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/ProductionDatabaseConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/ProductionDatabaseConfiguration.java new file mode 100644 index 000000000..b7a5783bc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/ProductionDatabaseConfiguration.java @@ -0,0 +1,76 @@ +package eu.eudat.old.configurations; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import java.util.Properties; + +/** + * Created by ikalyvas on 2/9/2018. + */ +@Configuration +@EnableTransactionManagement +@Profile({ "production", "staging", "docker" }) +@ComponentScan(basePackages = {"eu.eudat.data.entities"}) +public class ProductionDatabaseConfiguration { + + @Autowired + private Environment env; + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[]{"eu.eudat.data.entities"}); + JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(env.getProperty("database.driver-class-name")); + dataSource.setUrl(env.getProperty("database.url")); + dataSource.setUsername(env.getProperty("database.username")); + dataSource.setPassword(env.getProperty("database.password")); + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { + JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(emf); + + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + private Properties additionalProperties() { + Properties properties = new Properties(); + properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL92Dialect"); + properties.setProperty("hibernate.show_sql", "true"); + properties.setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false"); + return properties; + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/WebMVCConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/WebMVCConfiguration.java new file mode 100644 index 000000000..5538091d5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/WebMVCConfiguration.java @@ -0,0 +1,43 @@ +package eu.eudat.old.configurations; + +import eu.eudat.old.logic.handlers.PrincipalArgumentResolver; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import java.util.List; + +@EnableAsync +@Configuration +@EnableScheduling +public class WebMVCConfiguration extends WebMvcConfigurerAdapter { + + private ApiContext apiContext; + + private AuthenticationService verifiedUserAuthenticationService; + private AuthenticationService nonVerifiedUserAuthenticationService; + + @Autowired + public WebMVCConfiguration(ApiContext apiContext, AuthenticationService verifiedUserAuthenticationService, AuthenticationService nonVerifiedUserAuthenticationService) { + this.apiContext = apiContext; + this.verifiedUserAuthenticationService = verifiedUserAuthenticationService; + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + } + + @Autowired + @Override + public void addArgumentResolvers(List argumentResolvers) { + argumentResolvers.add(new PrincipalArgumentResolver(verifiedUserAuthenticationService, nonVerifiedUserAuthenticationService)); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { +// registry.addInterceptor(new RequestInterceptor(this.apiContext.getHelpersService().getLoggerService())); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/DynamicFunderConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/DynamicFunderConfiguration.java new file mode 100644 index 000000000..b6beaaf3d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/DynamicFunderConfiguration.java @@ -0,0 +1,12 @@ +package eu.eudat.old.configurations.dynamicfunder; + +import eu.eudat.old.models.data.dynamicfields.DynamicField; +import eu.eudat.old.configurations.dynamicfunder.entities.Configuration; + +import java.util.List; + +public interface DynamicFunderConfiguration { + Configuration getConfiguration(); + + List getFields(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/DynamicFunderConfigurationDevelImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/DynamicFunderConfigurationDevelImpl.java new file mode 100644 index 000000000..17e965499 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/DynamicFunderConfigurationDevelImpl.java @@ -0,0 +1,85 @@ +package eu.eudat.old.configurations.dynamicfunder; + +import eu.eudat.old.configurations.dynamicfunder.entities.Property; +import eu.eudat.old.configurations.dynamicfunder.entities.Configuration; +import eu.eudat.old.models.data.dynamicfields.Dependency; +import eu.eudat.old.models.data.dynamicfields.DynamicField; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.LinkedList; +import java.util.List; + +@Service("dynamicFunderConfiguration") +@Profile("devel") +public class DynamicFunderConfigurationDevelImpl implements DynamicFunderConfiguration { + private static final Logger logger = LoggerFactory.getLogger(DynamicFunderConfigurationDevelImpl.class); + + private Configuration configuration; + private List fields; + private Environment environment; + + public DynamicFunderConfigurationDevelImpl(Environment environment) { + this.environment = environment; + } + + @Override + public Configuration getConfiguration() { + if (this.configuration != null) return this.configuration; + String fileUrl = this.environment.getProperty("configuration.dynamicFunderUrl"); + logger.info("Loaded also config file: " + fileUrl); + String current = null; + InputStream is = null; + try { + current = new java.io.File(".").getCanonicalPath(); + + JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + is = new URL("file:///"+ current + "/web/src/main/resources/FunderConfiguration.xml").openStream(); + this.configuration = (Configuration) jaxbUnmarshaller.unmarshal(is); + } catch (Exception ex) { + logger.error("Cannot find in folder" + current, ex); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + fileUrl, e); + } + } + return this.configuration; + } + + @Override + public List getFields() { + if (this.fields != null) return this.fields; + Configuration configuration = this.getConfiguration(); + List fields = new LinkedList<>(); + List properties = configuration.getConfigurationProperties(); + properties.stream().forEach(item -> { + DynamicField dynamicField = new DynamicField(); + dynamicField.setId(item.getId()); + dynamicField.setName(item.getName()); + dynamicField.setQueryProperty(item.getQueryProperty()); + dynamicField.setRequired(item.getRequired()); + List dependencies = new LinkedList<>(); + item.getDependencies().stream().forEach(dependency -> { + Dependency modelDependency = new Dependency(); + modelDependency.setId(dependency.getId()); + modelDependency.setQueryProperty(dependency.getQueryProperty()); + dependencies.add(modelDependency); + }); + dynamicField.setDependencies(dependencies); + fields.add(dynamicField); + }); + this.fields = fields; + return fields; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/DynamicFunderConfigurationProdImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/DynamicFunderConfigurationProdImpl.java new file mode 100644 index 000000000..31c4f3b23 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/DynamicFunderConfigurationProdImpl.java @@ -0,0 +1,86 @@ +package eu.eudat.old.configurations.dynamicfunder; + +import eu.eudat.old.configurations.dynamicfunder.entities.Property; +import eu.eudat.old.models.data.dynamicfields.Dependency; +import eu.eudat.old.models.data.dynamicfields.DynamicField; +import eu.eudat.old.configurations.dynamicfunder.entities.Configuration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Paths; +import java.util.LinkedList; +import java.util.List; + +@Service("dynamicFunderConfiguration") +@Profile({ "production", "staging", "docker" }) +public class DynamicFunderConfigurationProdImpl implements DynamicFunderConfiguration { + private static final Logger logger = LoggerFactory.getLogger(DynamicFunderConfigurationProdImpl.class); + + private Configuration configuration; + private List fields; + private Environment environment; + + public DynamicFunderConfigurationProdImpl(Environment environment) { + this.environment = environment; + } + + @Override + public Configuration getConfiguration() { + if (this.configuration != null) return this.configuration; + String fileUrl = this.environment.getProperty("configuration.dynamicFunderUrl"); + logger.info("Loaded also config file: " + fileUrl); + String current = null; + InputStream is = null; + try { + current = new java.io.File(".").getCanonicalPath(); + + JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + is = new URL(Paths.get(fileUrl).toUri().toURL().toString()).openStream(); + this.configuration = (Configuration) jaxbUnmarshaller.unmarshal(is); + } catch (Exception ex) { + logger.error("Cannot find in folder" + current, ex); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + fileUrl, e); + } + } + return this.configuration; + } + + @Override + public List getFields() { + if (this.fields != null) return this.fields; + Configuration configuration = this.getConfiguration(); + List fields = new LinkedList<>(); + List properties = configuration.getConfigurationProperties(); + properties.stream().forEach(item -> { + DynamicField dynamicField = new DynamicField(); + dynamicField.setId(item.getId()); + dynamicField.setName(item.getName()); + dynamicField.setQueryProperty(item.getQueryProperty()); + dynamicField.setRequired(item.getRequired()); + List dependencies = new LinkedList<>(); + item.getDependencies().stream().forEach(dependency -> { + Dependency modelDependency = new Dependency(); + modelDependency.setId(dependency.getId()); + modelDependency.setQueryProperty(dependency.getQueryProperty()); + dependencies.add(modelDependency); + }); + dynamicField.setDependencies(dependencies); + fields.add(dynamicField); + }); + this.fields = fields; + return fields; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Configuration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Configuration.java new file mode 100644 index 000000000..b71d7b734 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Configuration.java @@ -0,0 +1,31 @@ +package eu.eudat.old.configurations.dynamicfunder.entities; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement +public class Configuration { + private List configurationProperties; + private MainProperty mainExternalField; + + public MainProperty getMainExternalField() { + return mainExternalField; + } + + @XmlElement(name = "mainExternalField") + public void setMainExternalField(MainProperty mainExternalField) { + this.mainExternalField = mainExternalField; + } + + public List getConfigurationProperties() { + return configurationProperties; + } + + @XmlElementWrapper + @XmlElement(name = "property") + public void setConfigurationProperties(List configurationProperties) { + this.configurationProperties = configurationProperties; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Dependency.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Dependency.java new file mode 100644 index 000000000..92b257b0a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Dependency.java @@ -0,0 +1,26 @@ +package eu.eudat.old.configurations.dynamicfunder.entities; + +import javax.xml.bind.annotation.XmlElement; + +public class Dependency { + private String id; + private String queryProperty; + + public String getId() { + return id; + } + + public String getQueryProperty() { + return queryProperty; + } + + @XmlElement(name = "id") + public void setId(String id) { + this.id = id; + } + + @XmlElement(name = "queryProperty") + public void setQueryProperty(String queryProperty) { + this.queryProperty = queryProperty; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Language.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Language.java new file mode 100644 index 000000000..71532e90a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Language.java @@ -0,0 +1,26 @@ +package eu.eudat.old.configurations.dynamicfunder.entities; + +import javax.xml.bind.annotation.XmlElement; + +public class Language { + private String key; + private String languageKey; + + public String getKey() { + return key; + } + + @XmlElement(name = "key") + public void setKey(String key) { + this.key = key; + } + + public String getLanguageKey() { + return languageKey; + } + + @XmlElement(name = "languageKey") + public void setLanguageKey(String languageKey) { + this.languageKey = languageKey; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/MainProperty.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/MainProperty.java new file mode 100644 index 000000000..9a0d53f08 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/MainProperty.java @@ -0,0 +1,103 @@ +package eu.eudat.old.configurations.dynamicfunder.entities; + +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class MainProperty { + private String id; + private String name; + private String queryProperty; + private String externalFieldId; + private List urlConfig; + private String externalFieldLabel; + private List dependencies; + private Boolean required; + private List language; + + + public String getId() { + return id; + } + + @XmlElement(name = "id") + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + @XmlElement(name = "name") + public void setName(String name) { + this.name = name; + } + + public String getExternalFieldId() { + return externalFieldId; + } + + @XmlElement(name = "externalFieldId") + public void setExternalFieldId(String externalFieldId) { + this.externalFieldId = externalFieldId; + } + + public String getExternalFieldLabel() { + return externalFieldLabel; + } + + @XmlElement(name = "externalFieldLabel") + public void setExternalFieldLabel(String externalFieldLabel) { + this.externalFieldLabel = externalFieldLabel; + } + + public List getDependencies() { + return dependencies; + } + + @XmlElementWrapper + @XmlElement(name = "dependency") + public void setDependencies(List dependencies) { + this.dependencies = dependencies; + } + + public Boolean getRequired() { + return required; + } + + @XmlElement(name = "required") + public void setRequired(Boolean required) { + this.required = required; + } + + public String getQueryProperty() { + return queryProperty; + } + + @XmlElement(name = "queryProperty") + public void setQueryProperty(String queryProperty) { + this.queryProperty = queryProperty; + } + + public List getUrlConfig() { + return urlConfig; + } + + @XmlElement(name = "urlConfig") + public void setUrlConfig(List urlConfig) { + this.urlConfig = urlConfig; + } + + public List getLanguage() { + return language; + } + + @XmlElementWrapper + @XmlElement(name = "languageProperty") + public void setLanguage(List language) { + this.language = language; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Property.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Property.java new file mode 100644 index 000000000..c6bd25f71 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicfunder/entities/Property.java @@ -0,0 +1,91 @@ +package eu.eudat.old.configurations.dynamicfunder.entities; + + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class Property { + private String id; + private String name; + private String sourceUrl; + private String queryProperty; + private String externalFieldId; + private String externalFieldLabel; + private List dependencies; + private Boolean required; + + + public String getId() { + return id; + } + + @XmlElement(name = "id") + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + @XmlElement(name = "name") + public void setName(String name) { + this.name = name; + } + + public String getSourceUrl() { + return sourceUrl; + } + + @XmlElement(name = "sourceUrl") + public void setSourceUrl(String sourceUrl) { + this.sourceUrl = sourceUrl; + } + + public String getExternalFieldId() { + return externalFieldId; + } + + @XmlElement(name = "externalFieldId") + public void setExternalFieldId(String externalFieldId) { + this.externalFieldId = externalFieldId; + } + + public String getExternalFieldLabel() { + return externalFieldLabel; + } + + @XmlElement(name = "externalFieldLabel") + public void setExternalFieldLabel(String externalFieldLabel) { + this.externalFieldLabel = externalFieldLabel; + } + + public List getDependencies() { + return dependencies; + } + + @XmlElementWrapper + @XmlElement(name = "dependency") + public void setDependencies(List dependencies) { + this.dependencies = dependencies; + } + + public Boolean getRequired() { + return required; + } + + @XmlElement(name = "required") + public void setRequired(Boolean required) { + this.required = required; + } + + public String getQueryProperty() { + return queryProperty; + } + + @XmlElement(name = "queryProperty") + public void setQueryProperty(String queryProperty) { + this.queryProperty = queryProperty; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/DynamicGrantConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/DynamicGrantConfiguration.java new file mode 100644 index 000000000..7532c789a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/DynamicGrantConfiguration.java @@ -0,0 +1,15 @@ +package eu.eudat.old.configurations.dynamicgrant; + +import eu.eudat.old.configurations.dynamicgrant.entities.Configuration; +import eu.eudat.old.models.data.dynamicfields.DynamicField; + +import java.util.List; + +/** + * Created by ikalyvas on 3/23/2018. + */ +public interface DynamicGrantConfiguration { + Configuration getConfiguration(); + + List getFields(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/DynamicGrantConfigurationDevelImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/DynamicGrantConfigurationDevelImpl.java new file mode 100644 index 000000000..9fe095555 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/DynamicGrantConfigurationDevelImpl.java @@ -0,0 +1,93 @@ +package eu.eudat.old.configurations.dynamicgrant; + +import eu.eudat.old.configurations.dynamicgrant.entities.Configuration; +import eu.eudat.old.configurations.dynamicgrant.entities.Property; +import eu.eudat.old.models.data.dynamicfields.Dependency; +import eu.eudat.old.models.data.dynamicfields.DynamicField; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.LinkedList; +import java.util.List; + +/** + * Created by ikalyvas on 5/4/2018. + */ + +@Service("dynamicGrantConfiguration") +@Profile("devel") +public class DynamicGrantConfigurationDevelImpl implements DynamicGrantConfiguration { + private static final Logger logger = LoggerFactory.getLogger(DynamicGrantConfigurationDevelImpl.class); + + private Configuration configuration; + + private List fields; + + private Environment environment; + + @Autowired + public DynamicGrantConfigurationDevelImpl(Environment environment) { + this.environment = environment; + } + + @Override + public Configuration getConfiguration() { + if (this.configuration != null) return this.configuration; + String fileUrl = this.environment.getProperty("configuration.dynamicGrantUrl"); + logger.info("Loaded also config file: " + fileUrl); + String current = null; + InputStream is = null; + try { + current = new java.io.File(".").getCanonicalPath(); + + JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + is = new URL("file:///"+ current + "/web/src/main/resources/GrantConfiguration.xml").openStream(); + this.configuration = (Configuration) jaxbUnmarshaller.unmarshal(is); + } catch (Exception ex) { + logger.error("Cannot find in folder" + current, ex); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + fileUrl, e); + } + } + return this.configuration; + } + + @Override + public List getFields() { + if (this.fields != null) return this.fields; + Configuration configuration = this.getConfiguration(); + List fields = new LinkedList<>(); + List properties = configuration.getConfigurationProperties(); + properties.stream().forEach(item -> { + DynamicField dynamicField = new DynamicField(); + dynamicField.setId(item.getId()); + dynamicField.setName(item.getName()); + dynamicField.setQueryProperty(item.getQueryProperty()); + dynamicField.setRequired(item.getRequired()); + List dependencies = new LinkedList<>(); + item.getDependencies().stream().forEach(dependency -> { + Dependency modelDependency = new Dependency(); + modelDependency.setId(dependency.getId()); + modelDependency.setQueryProperty(dependency.getQueryProperty()); + dependencies.add(modelDependency); + }); + dynamicField.setDependencies(dependencies); + fields.add(dynamicField); + }); + this.fields = fields; + return fields; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/DynamicGrantConfigurationProdImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/DynamicGrantConfigurationProdImpl.java new file mode 100644 index 000000000..ee38d1b0b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/DynamicGrantConfigurationProdImpl.java @@ -0,0 +1,93 @@ +package eu.eudat.old.configurations.dynamicgrant; + +import eu.eudat.old.configurations.dynamicgrant.entities.Configuration; +import eu.eudat.old.configurations.dynamicgrant.entities.Property; +import eu.eudat.old.models.data.dynamicfields.Dependency; +import eu.eudat.old.models.data.dynamicfields.DynamicField; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Paths; +import java.util.LinkedList; +import java.util.List; + +/** + * Created by ikalyvas on 3/23/2018. + */ +@Service("dynamicGrantConfiguration") +@Profile({ "production", "staging", "docker" }) +public class DynamicGrantConfigurationProdImpl implements DynamicGrantConfiguration { + private static final Logger logger = LoggerFactory.getLogger(DynamicGrantConfigurationProdImpl.class); + + private Configuration configuration; + + private List fields; + + private Environment environment; + + @Autowired + public DynamicGrantConfigurationProdImpl(Environment environment) { + this.environment = environment; + } + + @Override + public Configuration getConfiguration() { + if (this.configuration != null) return this.configuration; + String fileUrl = this.environment.getProperty("configuration.dynamicGrantUrl"); + logger.info("Loaded also config file: " + fileUrl); + String current = null; + InputStream is = null; + try { + current = new java.io.File(".").getCanonicalPath(); + + JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + is = new URL(Paths.get(fileUrl).toUri().toURL().toString()).openStream(); + this.configuration = (Configuration) jaxbUnmarshaller.unmarshal(is); + } catch (Exception ex) { + logger.error("Cannot find in folder" + current, ex); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + fileUrl, e); + } + } + return this.configuration; + } + + @Override + public List getFields() { + if (this.fields != null) return this.fields; + Configuration configuration = this.getConfiguration(); + List fields = new LinkedList<>(); + List properties = configuration.getConfigurationProperties(); + properties.stream().forEach(item -> { + DynamicField dynamicField = new DynamicField(); + dynamicField.setId(item.getId()); + dynamicField.setName(item.getName()); + dynamicField.setQueryProperty(item.getQueryProperty()); + dynamicField.setRequired(item.getRequired()); + List dependencies = new LinkedList<>(); + item.getDependencies().stream().forEach(dependency -> { + Dependency modelDependency = new Dependency(); + modelDependency.setId(dependency.getId()); + modelDependency.setQueryProperty(dependency.getQueryProperty()); + dependencies.add(modelDependency); + }); + dynamicField.setDependencies(dependencies); + fields.add(dynamicField); + }); + this.fields = fields; + return fields; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Configuration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Configuration.java new file mode 100644 index 000000000..aad25053b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Configuration.java @@ -0,0 +1,34 @@ +package eu.eudat.old.configurations.dynamicgrant.entities; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +/** + * Created by ikalyvas on 3/23/2018. + */ +@XmlRootElement +public class Configuration { + private List configurationProperties; + private MainProperty mainExternalField; + + public MainProperty getMainExternalField() { + return mainExternalField; + } + + @XmlElement(name = "mainExternalField") + public void setMainExternalField(MainProperty mainExternalField) { + this.mainExternalField = mainExternalField; + } + + public List getConfigurationProperties() { + return configurationProperties; + } + + @XmlElementWrapper + @XmlElement(name = "property") + public void setConfigurationProperties(List configurationProperties) { + this.configurationProperties = configurationProperties; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Dependency.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Dependency.java new file mode 100644 index 000000000..a9f7507d1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Dependency.java @@ -0,0 +1,29 @@ +package eu.eudat.old.configurations.dynamicgrant.entities; + +import javax.xml.bind.annotation.XmlElement; + +/** + * Created by ikalyvas on 3/23/2018. + */ +public class Dependency { + private String id; + private String queryProperty; + + public String getId() { + return id; + } + + public String getQueryProperty() { + return queryProperty; + } + + @XmlElement(name = "id") + public void setId(String id) { + this.id = id; + } + + @XmlElement(name = "queryProperty") + public void setQueryProperty(String queryProperty) { + this.queryProperty = queryProperty; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Language.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Language.java new file mode 100644 index 000000000..67ab06545 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Language.java @@ -0,0 +1,29 @@ +package eu.eudat.old.configurations.dynamicgrant.entities; + +import javax.xml.bind.annotation.XmlElement; + +/** + * Created by ikalyvas on 3/28/2018. + */ +public class Language { + private String key; + private String languageKey; + + public String getKey() { + return key; + } + + @XmlElement(name = "key") + public void setKey(String key) { + this.key = key; + } + + public String getLanguageKey() { + return languageKey; + } + + @XmlElement(name = "languageKey") + public void setLanguageKey(String languageKey) { + this.languageKey = languageKey; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/MainProperty.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/MainProperty.java new file mode 100644 index 000000000..45017e894 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/MainProperty.java @@ -0,0 +1,106 @@ +package eu.eudat.old.configurations.dynamicgrant.entities; + +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +/** + * Created by ikalyvas on 3/28/2018. + */ +public class MainProperty { + private String id; + private String name; + private String queryProperty; + private String externalFieldId; + private List urlConfig; + private String externalFieldLabel; + private List dependencies; + private Boolean required; + private List language; + + + public String getId() { + return id; + } + + @XmlElement(name = "id") + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + @XmlElement(name = "name") + public void setName(String name) { + this.name = name; + } + + public String getExternalFieldId() { + return externalFieldId; + } + + @XmlElement(name = "externalFieldId") + public void setExternalFieldId(String externalFieldId) { + this.externalFieldId = externalFieldId; + } + + public String getExternalFieldLabel() { + return externalFieldLabel; + } + + @XmlElement(name = "externalFieldLabel") + public void setExternalFieldLabel(String externalFieldLabel) { + this.externalFieldLabel = externalFieldLabel; + } + + public List getDependencies() { + return dependencies; + } + + @XmlElementWrapper + @XmlElement(name = "dependency") + public void setDependencies(List dependencies) { + this.dependencies = dependencies; + } + + public Boolean getRequired() { + return required; + } + + @XmlElement(name = "required") + public void setRequired(Boolean required) { + this.required = required; + } + + public String getQueryProperty() { + return queryProperty; + } + + @XmlElement(name = "queryProperty") + public void setQueryProperty(String queryProperty) { + this.queryProperty = queryProperty; + } + + public List getUrlConfig() { + return urlConfig; + } + + @XmlElement(name = "urlConfig") + public void setUrlConfig(List urlConfig) { + this.urlConfig = urlConfig; + } + + public List getLanguage() { + return language; + } + + @XmlElementWrapper + @XmlElement(name = "languageProperty") + public void setLanguage(List language) { + this.language = language; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Property.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Property.java new file mode 100644 index 000000000..4ca19756a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicgrant/entities/Property.java @@ -0,0 +1,93 @@ +package eu.eudat.old.configurations.dynamicgrant.entities; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +/** + * Created by ikalyvas on 3/23/2018. + */ +public class Property { + private String id; + private String name; + private String sourceUrl; + private String queryProperty; + private String externalFieldId; + private String externalFieldLabel; + private List dependencies; + private Boolean required; + + + public String getId() { + return id; + } + + @XmlElement(name = "id") + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + @XmlElement(name = "name") + public void setName(String name) { + this.name = name; + } + + public String getSourceUrl() { + return sourceUrl; + } + + @XmlElement(name = "sourceUrl") + public void setSourceUrl(String sourceUrl) { + this.sourceUrl = sourceUrl; + } + + public String getExternalFieldId() { + return externalFieldId; + } + + @XmlElement(name = "externalFieldId") + public void setExternalFieldId(String externalFieldId) { + this.externalFieldId = externalFieldId; + } + + public String getExternalFieldLabel() { + return externalFieldLabel; + } + + @XmlElement(name = "externalFieldLabel") + public void setExternalFieldLabel(String externalFieldLabel) { + this.externalFieldLabel = externalFieldLabel; + } + + public List getDependencies() { + return dependencies; + } + + @XmlElementWrapper + @XmlElement(name = "dependency") + public void setDependencies(List dependencies) { + this.dependencies = dependencies; + } + + public Boolean getRequired() { + return required; + } + + @XmlElement(name = "required") + public void setRequired(Boolean required) { + this.required = required; + } + + public String getQueryProperty() { + return queryProperty; + } + + @XmlElement(name = "queryProperty") + public void setQueryProperty(String queryProperty) { + this.queryProperty = queryProperty; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/DynamicProjectConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/DynamicProjectConfiguration.java new file mode 100644 index 000000000..54efacf85 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/DynamicProjectConfiguration.java @@ -0,0 +1,12 @@ +package eu.eudat.old.configurations.dynamicproject; + +import eu.eudat.old.models.data.dynamicfields.DynamicField; +import eu.eudat.old.configurations.dynamicproject.entities.Configuration; + +import java.util.List; + +public interface DynamicProjectConfiguration { + Configuration getConfiguration(); + + List getFields(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/DynamicProjectConfigurationDevelImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/DynamicProjectConfigurationDevelImpl.java new file mode 100644 index 000000000..f5c954e97 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/DynamicProjectConfigurationDevelImpl.java @@ -0,0 +1,87 @@ +package eu.eudat.old.configurations.dynamicproject; + +import eu.eudat.old.configurations.dynamicproject.entities.Configuration; +import eu.eudat.old.configurations.dynamicproject.entities.Property; +import eu.eudat.old.models.data.dynamicfields.Dependency; +import eu.eudat.old.models.data.dynamicfields.DynamicField; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.LinkedList; +import java.util.List; + +@Service("dynamicProjectConfiguration") +@Profile("devel") +public class DynamicProjectConfigurationDevelImpl implements DynamicProjectConfiguration{ + private static final Logger logger = LoggerFactory.getLogger(DynamicProjectConfigurationDevelImpl.class); + + private Configuration configuration; + private List fields; + private Environment environment; + + @Autowired + public DynamicProjectConfigurationDevelImpl(Environment environment) { + this.environment = environment; + } + + @Override + public Configuration getConfiguration() { + if (this.configuration != null) return this.configuration; + String fileUrl = this.environment.getProperty("configuration.dynamicProjectUrl"); + logger.info("Loaded also config file: " + fileUrl); + String current = null; + InputStream is = null; + try { + current = new java.io.File(".").getCanonicalPath(); + + JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + is = new URL("file:///"+ current + "/web/src/main/resources/ProjectConfiguration.xml").openStream(); + this.configuration = (Configuration) jaxbUnmarshaller.unmarshal(is); + } catch (Exception ex) { + logger.error("Cannot find in folder" + current, ex); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + fileUrl, e); + } + } + return this.configuration; + } + + @Override + public List getFields() { + if (this.fields != null) return this.fields; + Configuration configuration = this.getConfiguration(); + List fields = new LinkedList<>(); + List properties = configuration.getConfigurationProperties(); + properties.stream().forEach(item -> { + DynamicField dynamicField = new DynamicField(); + dynamicField.setId(item.getId()); + dynamicField.setName(item.getName()); + dynamicField.setQueryProperty(item.getQueryProperty()); + dynamicField.setRequired(item.getRequired()); + List dependencies = new LinkedList<>(); + item.getDependencies().stream().forEach(dependency -> { + Dependency modelDependency = new Dependency(); + modelDependency.setId(dependency.getId()); + modelDependency.setQueryProperty(dependency.getQueryProperty()); + dependencies.add(modelDependency); + }); + dynamicField.setDependencies(dependencies); + fields.add(dynamicField); + }); + this.fields = fields; + return fields; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/DynamicProjectConfigurationProdImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/DynamicProjectConfigurationProdImpl.java new file mode 100644 index 000000000..6909c6358 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/DynamicProjectConfigurationProdImpl.java @@ -0,0 +1,90 @@ +package eu.eudat.old.configurations.dynamicproject; + +import eu.eudat.old.models.data.dynamicfields.DynamicField; +import eu.eudat.old.configurations.dynamicproject.entities.Configuration; +import eu.eudat.old.configurations.dynamicproject.entities.Property; +import eu.eudat.old.models.data.dynamicfields.Dependency; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Paths; +import java.util.LinkedList; +import java.util.List; + +@Service("dynamicProjectConfiguration") +@Profile({ "production", "staging", "docker" }) +public class DynamicProjectConfigurationProdImpl implements DynamicProjectConfiguration{ + private static final Logger logger = LoggerFactory.getLogger(DynamicProjectConfigurationProdImpl.class); + + private Configuration configuration; + + private List fields; + + private Environment environment; + + @Autowired + public DynamicProjectConfigurationProdImpl(Environment environment) { + this.environment = environment; + } + + @Override + public Configuration getConfiguration() { + if (this.configuration != null) return this.configuration; + String fileUrl = this.environment.getProperty("configuration.dynamicProjectUrl"); + logger.info("Loaded also config file: " + fileUrl); + String current = null; + InputStream is = null; + try { + current = new java.io.File(".").getCanonicalPath(); + + JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + is = new URL(Paths.get(fileUrl).toUri().toURL().toString()).openStream(); + this.configuration = (Configuration) jaxbUnmarshaller.unmarshal(is); + } catch (Exception ex) { + logger.error("Cannot find in folder" + current, ex); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + fileUrl, e); + } + } + return this.configuration; + } + + @Override + public List getFields() { + if (this.fields != null) return this.fields; + Configuration configuration = this.getConfiguration(); + List fields = new LinkedList<>(); + List properties = configuration.getConfigurationProperties(); + properties.stream().forEach(item -> { + DynamicField dynamicField = new DynamicField(); + dynamicField.setId(item.getId()); + dynamicField.setName(item.getName()); + dynamicField.setQueryProperty(item.getQueryProperty()); + dynamicField.setRequired(item.getRequired()); + List dependencies = new LinkedList<>(); + item.getDependencies().stream().forEach(dependency -> { + Dependency modelDependency = new Dependency(); + modelDependency.setId(dependency.getId()); + modelDependency.setQueryProperty(dependency.getQueryProperty()); + dependencies.add(modelDependency); + }); + dynamicField.setDependencies(dependencies); + fields.add(dynamicField); + }); + this.fields = fields; + return fields; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Configuration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Configuration.java new file mode 100644 index 000000000..20253dc7a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Configuration.java @@ -0,0 +1,32 @@ +package eu.eudat.old.configurations.dynamicproject.entities; + + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement +public class Configuration { + private List configurationProperties; + private MainProperty mainExternalField; + + public MainProperty getMainExternalField() { + return mainExternalField; + } + + @XmlElement(name = "mainExternalField") + public void setMainExternalField(MainProperty mainExternalField) { + this.mainExternalField = mainExternalField; + } + + public List getConfigurationProperties() { + return configurationProperties; + } + + @XmlElementWrapper + @XmlElement(name = "property") + public void setConfigurationProperties(List configurationProperties) { + this.configurationProperties = configurationProperties; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Dependency.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Dependency.java new file mode 100644 index 000000000..236b7efb8 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Dependency.java @@ -0,0 +1,26 @@ +package eu.eudat.old.configurations.dynamicproject.entities; + +import javax.xml.bind.annotation.XmlElement; + +public class Dependency { + private String id; + private String queryProperty; + + public String getId() { + return id; + } + + public String getQueryProperty() { + return queryProperty; + } + + @XmlElement(name = "id") + public void setId(String id) { + this.id = id; + } + + @XmlElement(name = "queryProperty") + public void setQueryProperty(String queryProperty) { + this.queryProperty = queryProperty; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Language.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Language.java new file mode 100644 index 000000000..ca3e66860 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Language.java @@ -0,0 +1,26 @@ +package eu.eudat.old.configurations.dynamicproject.entities; + +import javax.xml.bind.annotation.XmlElement; + +public class Language { + private String key; + private String languageKey; + + public String getKey() { + return key; + } + + @XmlElement(name = "key") + public void setKey(String key) { + this.key = key; + } + + public String getLanguageKey() { + return languageKey; + } + + @XmlElement(name = "languageKey") + public void setLanguageKey(String languageKey) { + this.languageKey = languageKey; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/MainProperty.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/MainProperty.java new file mode 100644 index 000000000..fdd6e3d30 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/MainProperty.java @@ -0,0 +1,103 @@ +package eu.eudat.old.configurations.dynamicproject.entities; + +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class MainProperty { + private String id; + private String name; + private String queryProperty; + private String externalFieldId; + private List urlConfig; + private String externalFieldLabel; + private List dependencies; + private Boolean required; + private List language; + + + public String getId() { + return id; + } + + @XmlElement(name = "id") + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + @XmlElement(name = "name") + public void setName(String name) { + this.name = name; + } + + public String getExternalFieldId() { + return externalFieldId; + } + + @XmlElement(name = "externalFieldId") + public void setExternalFieldId(String externalFieldId) { + this.externalFieldId = externalFieldId; + } + + public String getExternalFieldLabel() { + return externalFieldLabel; + } + + @XmlElement(name = "externalFieldLabel") + public void setExternalFieldLabel(String externalFieldLabel) { + this.externalFieldLabel = externalFieldLabel; + } + + public List getDependencies() { + return dependencies; + } + + @XmlElementWrapper + @XmlElement(name = "dependency") + public void setDependencies(List dependencies) { + this.dependencies = dependencies; + } + + public Boolean getRequired() { + return required; + } + + @XmlElement(name = "required") + public void setRequired(Boolean required) { + this.required = required; + } + + public String getQueryProperty() { + return queryProperty; + } + + @XmlElement(name = "queryProperty") + public void setQueryProperty(String queryProperty) { + this.queryProperty = queryProperty; + } + + public List getUrlConfig() { + return urlConfig; + } + + @XmlElement(name = "urlConfig") + public void setUrlConfig(List urlConfig) { + this.urlConfig = urlConfig; + } + + public List getLanguage() { + return language; + } + + @XmlElementWrapper + @XmlElement(name = "languageProperty") + public void setLanguage(List language) { + this.language = language; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Property.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Property.java new file mode 100644 index 000000000..5aaf2f09b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/dynamicproject/entities/Property.java @@ -0,0 +1,91 @@ +package eu.eudat.old.configurations.dynamicproject.entities; + + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class Property { + private String id; + private String name; + private String sourceUrl; + private String queryProperty; + private String externalFieldId; + private String externalFieldLabel; + private List dependencies; + private Boolean required; + + + public String getId() { + return id; + } + + @XmlElement(name = "id") + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + @XmlElement(name = "name") + public void setName(String name) { + this.name = name; + } + + public String getSourceUrl() { + return sourceUrl; + } + + @XmlElement(name = "sourceUrl") + public void setSourceUrl(String sourceUrl) { + this.sourceUrl = sourceUrl; + } + + public String getExternalFieldId() { + return externalFieldId; + } + + @XmlElement(name = "externalFieldId") + public void setExternalFieldId(String externalFieldId) { + this.externalFieldId = externalFieldId; + } + + public String getExternalFieldLabel() { + return externalFieldLabel; + } + + @XmlElement(name = "externalFieldLabel") + public void setExternalFieldLabel(String externalFieldLabel) { + this.externalFieldLabel = externalFieldLabel; + } + + public List getDependencies() { + return dependencies; + } + + @XmlElementWrapper + @XmlElement(name = "dependency") + public void setDependencies(List dependencies) { + this.dependencies = dependencies; + } + + public Boolean getRequired() { + return required; + } + + @XmlElement(name = "required") + public void setRequired(Boolean required) { + this.required = required; + } + + public String getQueryProperty() { + return queryProperty; + } + + @XmlElement(name = "queryProperty") + public void setQueryProperty(String queryProperty) { + this.queryProperty = queryProperty; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/typedefinition/DataType.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/typedefinition/DataType.java new file mode 100644 index 000000000..b5be7347e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/typedefinition/DataType.java @@ -0,0 +1,13 @@ +package eu.eudat.old.configurations.typedefinition; + +public enum DataType { + TINY, + SHORT, + INTEGER, + LONG, + DOUBLE, + FLOAT, + DATE, + STRING, + TEXT +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/typedefinition/DatabaseColumnType.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/typedefinition/DatabaseColumnType.java new file mode 100644 index 000000000..ac94f41bc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/typedefinition/DatabaseColumnType.java @@ -0,0 +1,5 @@ +package eu.eudat.old.configurations.typedefinition; + +public interface DatabaseColumnType { + public String getType(DataType dt); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/typedefinition/PostgreSQLDatabaseColumnType.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/typedefinition/PostgreSQLDatabaseColumnType.java new file mode 100644 index 000000000..6df17c522 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/configurations/typedefinition/PostgreSQLDatabaseColumnType.java @@ -0,0 +1,25 @@ +package eu.eudat.old.configurations.typedefinition; + +public class PostgreSQLDatabaseColumnType implements DatabaseColumnType { + + public String getType(DataType dt) { + switch (dt) { + case TINY: + case SHORT: + case INTEGER: + return "integer"; + case LONG: + return "bigint"; + case FLOAT: + case DOUBLE: + return "numeric"; + case DATE: + return "timestamp"; + case STRING: + return "character varying(250)"; + case TEXT: + return "text"; + } + return "character varying(250)"; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/AboutController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/AboutController.java new file mode 100644 index 000000000..baaea333d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/AboutController.java @@ -0,0 +1,39 @@ +package eu.eudat.old.controllers; + +import eu.eudat.data.DmpEntity; +import eu.eudat.old.logic.managers.MaterialManager; +import eu.eudat.old.logic.managers.MetricsManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Objects; +import java.util.stream.Stream; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/material/about/"}) +public class AboutController { + + private Environment environment; + private MaterialManager materialManager; + + @Autowired + public AboutController(Environment environment, MaterialManager materialManager, MetricsManager metricsManager) { + this.environment = environment; + this.materialManager = materialManager; + } + + @RequestMapping(path = "{lang}", method = RequestMethod.GET ) + public ResponseEntity getAbout(@PathVariable(name = "lang") String lang) throws IOException { + try (Stream paths = Files.walk(Paths.get(Objects.requireNonNull(this.environment.getProperty("about.path"))))) { + return this.materialManager.getResponseEntity(lang, paths); + } + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Admin.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Admin.java new file mode 100644 index 000000000..762993ee5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Admin.java @@ -0,0 +1,200 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.data.entities.UserDatasetProfile; +import eu.eudat.old.logic.managers.AdminManager; +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.admin.composite.DatasetProfile; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileListingModel; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem; +import eu.eudat.old.exceptions.datasetprofile.DatasetProfileNewVersionException; +import eu.eudat.old.exceptions.datasetprofile.DatasetProfileWithDatasetsExeption; +import eu.eudat.old.logic.managers.DatasetProfileManager; +import eu.eudat.old.logic.managers.MetricsManager; +import eu.eudat.old.logic.managers.UserManager; +import eu.eudat.old.models.data.user.composite.PagedDatasetProfile; +import eu.eudat.old.types.MetricNames; +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.old.types.Authorities.ADMIN; +import static eu.eudat.old.types.Authorities.DATASET_PROFILE_MANAGER; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/admin/"}) +public class Admin extends BaseController { + + private DatasetProfileManager datasetProfileManager; + private UserManager userManager; + private ConfigLoader configLoader; + private final MetricsManager metricsManager; + + @Autowired + public Admin(ApiContext apiContext, DatasetProfileManager datasetProfileManager, UserManager userManager/*, Logger logger*/, ConfigLoader configLoader, MetricsManager metricsManager) { + super(apiContext); + this.datasetProfileManager = datasetProfileManager; + this.userManager = userManager; + this.configLoader = configLoader; + this.metricsManager = metricsManager; + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/addDmp"}, consumes = "application/json", produces = "application/json") + public ResponseEntity addDmp(@Valid @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN ,DATASET_PROFILE_MANAGER}) Principal principal) throws Exception { + //this.getLoggerService().info(principal, "Admin Added Dataset Profile"); + DatasetProfile shortenProfile = profile.toShort(); + DescriptionTemplate modelDefinition = AdminManager.generateViewStyleDefinition(shortenProfile, getApiContext()); + modelDefinition.setType(getApiContext().getOperationsContext().getDatabaseRepository().getDescriptionTemplateTypeDao().findFromName(profile.getType())); + modelDefinition.setGroupId(UUID.randomUUID()); + modelDefinition.setVersion((short) 0); + + DescriptionTemplate descriptionTemplate = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition); + UserDatasetProfile userDatasetProfile = new UserDatasetProfile(); + userDatasetProfile.setDatasetProfile(descriptionTemplate); + UserInfo userInfo = getApiContext().getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + userDatasetProfile.setUser(userInfo); + userDatasetProfile.setRole(0); + getApiContext().getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile); + datasetProfileManager.storeDatasetProfileUsers(descriptionTemplate, profile); + + metricsManager.increaseValue(MetricNames.DATASET_TEMPLATE, 1, MetricsManager.datasetTemplateStatus.get(descriptionTemplate.getStatus()) ); + return ResponseEntity.status(HttpStatus.OK).body(modelDefinition.getId()); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/addDmp/{id}"}, consumes = "application/json", produces = "application/json") + public ResponseEntity> updateDmp(@PathVariable String id, @RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) throws Exception { + DatasetProfile shortenProfile = profile.toShort(); + DescriptionTemplate modelDefinition = AdminManager.generateViewStyleDefinition(shortenProfile, getApiContext()); + DescriptionTemplate datasetprofile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); + datasetprofile.setDefinition(modelDefinition.getDefinition()); + Short oldStatus = datasetprofile.getStatus(); + datasetprofile.setStatus(modelDefinition.getStatus()); + datasetprofile.setLabel(modelDefinition.getLabel()); + datasetprofile.setDescription(modelDefinition.getDescription()); + datasetprofile.setLanguage(modelDefinition.getLanguage()); + DescriptionTemplate descriptionTemplate = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(datasetprofile); + datasetProfileManager.storeDatasetProfileUsers(descriptionTemplate, profile); + if (descriptionTemplate.getStatus() == 1 && oldStatus == 0) { + metricsManager.increaseValue(MetricNames.DATASET_TEMPLATE, 1, MetricNames.ACTIVE); + } + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().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, DATASET_PROFILE_MANAGER}) Principal principal) throws Exception { + try { + DescriptionTemplate 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().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage())); + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/get/{id}"}, produces = "application/json") + @Transactional + public ResponseEntity> get(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) { + DatasetProfile datasetprofile = this.datasetProfileManager.getDatasetProfile(id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(datasetprofile)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/datasetprofiles/getPaged"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> getPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) throws Exception { + DataTableData datasetProfileTableData = this.datasetProfileManager.getPaged(datasetProfileTableRequestItem, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/preview"}, consumes = "application/json", produces = "application/json") + public ResponseEntity> getPreview(@RequestBody DatasetProfile profile, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) throws Exception { + DescriptionTemplate modelDefinition = AdminManager.generateViewStyleDefinition(profile, getApiContext()); + eu.eudat.old.models.data.user.composite.DatasetProfile datasetProfile = userManager.generateDatasetProfileModel(modelDefinition); + PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile(); + pagedDatasetProfile.buildPagedDatasetProfile(datasetProfile); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(pagedDatasetProfile)); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/datasetprofile/clone/{id}"}, consumes = "application/json", produces = "application/json") + public ResponseEntity> clone(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) { + DatasetProfile datasetprofile = this.datasetProfileManager.getDatasetProfile(id); + datasetprofile.setLabel(datasetprofile.getLabel() + " new "); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(datasetprofile)); + } + + @Transactional + @RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> inactivate(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) { + try { + DescriptionTemplate ret = AdminManager.inactivate(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch (DatasetProfileWithDatasetsExeption exception) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().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, DATASET_PROFILE_MANAGER}) Principal principal) throws IllegalAccessException, IOException, InstantiationException { + if (contentType.equals("application/xml")) { + DescriptionTemplate profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); + eu.eudat.old.models.data.user.composite.DatasetProfile datasetProfile = userManager.generateDatasetProfileModel(profile); + datasetProfile.setStatus(profile.getStatus()); + datasetProfile.setDescription(profile.getDescription()); + datasetProfile.setLanguage(profile.getLanguage()); + datasetProfile.setType(profile.getType().getName()); + return this.datasetProfileManager.getDocument(datasetProfile, profile.getLabel()); + } else { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("NOT AUTHORIZE")); + } + } + + @RequestMapping(method = RequestMethod.POST, value = {"/upload", "/upload/{id}"}) + public ResponseEntity setDatasetProfileXml(@RequestParam("file") MultipartFile file, + @PathVariable(value = "id", required = false) String id, + @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) throws Exception { + eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.DatasetProfile datasetProfileModel = this.datasetProfileManager.createDatasetProfileFromXml(file); + DatasetProfile datasetProfileEntity = datasetProfileModel.toAdminCompositeModel(file.getOriginalFilename()); + DescriptionTemplate modelDefinition; + if (id == null) { + modelDefinition = AdminManager.generateViewStyleDefinition(datasetProfileEntity, getApiContext()); + DescriptionTemplate descriptionTemplate = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition); + UserDatasetProfile userDatasetProfile = new UserDatasetProfile(); + userDatasetProfile.setDatasetProfile(descriptionTemplate); + UserInfo userInfo = getApiContext().getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + userDatasetProfile.setUser(userInfo); + userDatasetProfile.setRole(0); + getApiContext().getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile); + } else { + modelDefinition = datasetProfileManager.createNewVersionDatasetProfile(id, datasetProfileEntity); + } + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>() + .status(ApiMessageCode.SUCCESS_MESSAGE).message("")); + } + + + @RequestMapping(method = RequestMethod.GET, value = {"/getSemantics"}, produces = "application/json") + public ResponseEntity>> getSemantics(@RequestParam(value = "query", required = false) String query, @ClaimedAuthorities(claims = {ADMIN, DATASET_PROFILE_MANAGER}) Principal principal) { + List semantics = this.datasetProfileManager.getSemantics(query); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.SUCCESS_MESSAGE).payload(semantics)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/BaseController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/BaseController.java new file mode 100644 index 000000000..d9abc6ec8 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/BaseController.java @@ -0,0 +1,35 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.models.validators.*; +import eu.eudat.old.logic.services.ApiContext; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; + + +public abstract class BaseController { + + private ApiContext apiContext; + + public ApiContext getApiContext() { + return apiContext; + } + + public BaseController(ApiContext apiContext) { + + this.apiContext = apiContext; + } + + @InitBinder() + protected void initBinder(WebDataBinder binder) { + if (binder.getTarget() != null && DataManagementPlanTableRequestValidator.supportsType((binder.getTarget().getClass()))) + binder.addValidators(this.apiContext.getOperationsContext().getApplicationContext().getBean("dataManagementPlanTableRequestValidator", DataManagementPlanTableRequestValidator.class)); + if (binder.getTarget() != null && GrantTableRequestValidator.supportsType((binder.getTarget().getClass()))) + binder.addValidators(this.apiContext.getOperationsContext().getApplicationContext().getBean("grantTableRequestValidator", GrantTableRequestValidator.class)); + if (binder.getTarget() != null && DatasetProfileValidator.supportsType((binder.getTarget().getClass()))) + binder.addValidators(this.apiContext.getOperationsContext().getApplicationContext().getBean("datasetProfileValidator", DatasetProfileValidator.class)); + if (binder.getTarget() != null && GrantModelValidator.supportsType((binder.getTarget().getClass()))) + binder.addValidators(this.apiContext.getOperationsContext().getApplicationContext().getBean("grantModelValidator", GrantModelValidator.class)); + if (binder.getTarget() != null && DataManagementPlanNewVersionValidator.supportsType((binder.getTarget().getClass()))) + binder.addValidators(this.apiContext.getOperationsContext().getApplicationContext().getBean("dataManagementPlanNewVersionValidator", DataManagementPlanNewVersionValidator.class)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/CommonController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/CommonController.java new file mode 100644 index 000000000..37a159d56 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/CommonController.java @@ -0,0 +1,34 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.CommonsManager; +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.externalurl.ExternalSourcesConfiguration; +import eu.eudat.old.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.*; + +/** + * Created by ikalyvas on 3/28/2018. + */ +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/common"}) +public class CommonController { + + private ConfigLoader configLoader; + + @Autowired + public CommonController(ConfigLoader configLoader) { + this.configLoader = configLoader; + } + + @RequestMapping(method = RequestMethod.GET, value = {"/externalSourcesConfiguration"}, produces = "application/json") + public @ResponseBody + ResponseEntity> getExternalSourcesConfiguration() { + ExternalSourcesConfiguration configuration = CommonsManager.getExternalSourcesConfiguration(configLoader); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(configuration)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/ContactEmail.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/ContactEmail.java new file mode 100644 index 000000000..b8ba24c78 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/ContactEmail.java @@ -0,0 +1,55 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.ContactEmailManager; +import eu.eudat.old.models.data.ContactEmail.ContactEmailModel; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.models.data.ContactEmail.PublicContactEmailModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.transaction.Transactional; + +@RestController +@CrossOrigin +@RequestMapping(value = "api/contactEmail") +public class ContactEmail { + private static final Logger logger = LoggerFactory.getLogger(ContactEmail.class); + + private ContactEmailManager contactEmailManager; + + public ContactEmail(ContactEmailManager contactEmailManager) { + this.contactEmailManager = contactEmailManager; + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity sendContactEmail(@RequestBody ContactEmailModel contactEmailModel, Principal principal) { + try { + this.contactEmailManager.emailValidation(contactEmailModel); + this.contactEmailManager.sendContactEmail(contactEmailModel, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch (Exception ex) { + logger.error(ex.getMessage(), ex); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(ex.getMessage())); + } + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, path = "public", consumes = "application/x-www-form-urlencoded", produces = "application/json") + public @ResponseBody + ResponseEntity sendContactEmailNoAuth(@ModelAttribute PublicContactEmailModel contactEmailModel) { + try { + this.contactEmailManager.sendContactEmailNoAuth(contactEmailModel); + return ResponseEntity.status(HttpStatus.NO_CONTENT).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch (Exception ex) { + logger.error(ex.getMessage(), ex); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(ex.getMessage())); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/CurrencyController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/CurrencyController.java new file mode 100644 index 000000000..dab0fd475 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/CurrencyController.java @@ -0,0 +1,31 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.LocalFetchManager; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.local.LocalFetchModel; +import eu.eudat.old.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 java.util.List; + +@RestController +@CrossOrigin +@RequestMapping(value = "api/currency") +public class CurrencyController { + + private LocalFetchManager localFetchManager; + + @Autowired + public CurrencyController(LocalFetchManager localFetchManager) { + this.localFetchManager = localFetchManager; + } + + @RequestMapping(method = RequestMethod.GET) + public ResponseEntity>> getCurrencies(@RequestParam(value = "query", required = false) String query) throws Exception { + List currencies = localFetchManager.getCurrency(query); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(currencies)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DMPProfileController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DMPProfileController.java new file mode 100644 index 000000000..6b5ad9712 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DMPProfileController.java @@ -0,0 +1,141 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel.DmpBlueprint; +import eu.eudat.old.models.data.helpers.common.AutoCompleteLookupItem; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.data.dao.criteria.RequestItem; +import eu.eudat.old.data.entities.DMPProfile; +import eu.eudat.old.data.query.items.dmpblueprint.DataManagementPlanBlueprintTableRequest; +import eu.eudat.old.data.query.items.table.dmpprofile.DataManagementPlanProfileTableRequest; +import eu.eudat.old.exceptions.dmpblueprint.DmpBlueprintUsedException; +import eu.eudat.old.logic.managers.DataManagementProfileManager; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.helpermodels.Tuple; +import eu.eudat.old.models.data.listingmodels.DataManagementPlanBlueprintListingModel; +import eu.eudat.old.models.data.listingmodels.DataManagementPlanProfileListingModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +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 javax.xml.xpath.XPathExpressionException; +import java.io.IOException; +import java.util.List; + +import static eu.eudat.old.types.Authorities.ADMIN; + +/** + * Created by ikalyvas on 3/21/2018. + */ +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/dmpprofile"}) +public class DMPProfileController extends BaseController { + + private DataManagementProfileManager dataManagementProfileManager; + + @Autowired + public DMPProfileController(ApiContext apiContext, DataManagementProfileManager dataManagementProfileManager) { + super(apiContext); + this.dataManagementProfileManager = dataManagementProfileManager; + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> createOrUpdate(@RequestBody DataManagementPlanProfileListingModel dataManagementPlan, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { + this.dataManagementProfileManager.createOrUpdate(dataManagementPlan, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/blueprint"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> createOrUpdateBlueprint(@RequestBody DataManagementPlanBlueprintListingModel dataManagementPlan, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { + this.dataManagementProfileManager.createOrUpdateBlueprint(dataManagementPlan, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/getSingle/{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity> getSingle(@PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException { + DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel = this.dataManagementProfileManager.getSingle(id, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlanProfileListingModel)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/getSingleBlueprint/{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity> getSingleBlueprint(@PathVariable String id, Principal principal) { + DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel = this.dataManagementProfileManager.getSingleBlueprint(id, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlanBlueprintListingModel)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/getPaged"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getPaged(@Valid @RequestBody DataManagementPlanProfileTableRequest dataManagementPlanProfileTableRequest, Principal principal) throws Exception { + DataTableData dataTable = this.dataManagementProfileManager.getPaged(dataManagementPlanProfileTableRequest, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/getPagedBlueprint"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getPagedBlueprint(@Valid @RequestBody DataManagementPlanBlueprintTableRequest dataManagementPlanBlueprintTableRequest, Principal principal) throws Exception { + DataTableData dataTable = this.dataManagementProfileManager.getPagedBlueprint(dataManagementPlanBlueprintTableRequest, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/clone/{id}"}, consumes = "application/json", produces = "application/json") + public ResponseEntity> clone(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) { + DataManagementPlanBlueprintListingModel dmpBlueprint = this.dataManagementProfileManager.getSingleBlueprint(id, principal); + dmpBlueprint.setLabel(dmpBlueprint.getLabel() + " new "); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(dmpBlueprint)); + } + + @Transactional + @RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> inactivate(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) { + try { + this.dataManagementProfileManager.inactivate(id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch (DmpBlueprintUsedException exception) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.UNSUCCESS_DELETE).message(exception.getMessage())); + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/getXml/{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity getXml( @RequestHeader("Content-Type") String contentType, @PathVariable String id, Principal principal) throws IOException { + if (contentType.equals("application/xml")) { + DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel = this.dataManagementProfileManager.getSingleBlueprint(id, principal); + return this.dataManagementProfileManager.getDocument(dataManagementPlanBlueprintListingModel); + }else { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("NOT AUTHORIZE")); + } + } + + @RequestMapping(method = RequestMethod.POST, value = {"/upload"}) + public ResponseEntity setDatasetProfileXml(@RequestParam("file") MultipartFile file, + @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { + DmpBlueprint dmpBlueprintModel = this.dataManagementProfileManager.createDmpProfileFromXml(file); + DataManagementPlanBlueprintListingModel dmpBlueprint = dmpBlueprintModel.toDmpProfileCompositeModel(file.getOriginalFilename()); + this.dataManagementProfileManager.createOrUpdateBlueprint(dmpBlueprint, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>() + .status(ApiMessageCode.SUCCESS_MESSAGE).message("")); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/search/autocomplete"}) + public ResponseEntity getExternalAutocomplete(@RequestBody RequestItem lookupItem) throws XPathExpressionException { + List> items = this.dataManagementProfileManager.getExternalAutocomplete(lookupItem); + return ResponseEntity.status(HttpStatus.OK).body(items); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DMPs.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DMPs.java new file mode 100644 index 000000000..93978f06d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DMPs.java @@ -0,0 +1,391 @@ +package eu.eudat.old.controllers; + + +import eu.eudat.old.criteria.DMPCriteria; +import eu.eudat.old.data.dao.criteria.RequestItem; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.data.query.items.table.dmp.DataManagementPlanTableRequest; +import eu.eudat.old.exceptions.datamanagementplan.DMPNewVersionException; +import eu.eudat.old.exceptions.security.UnauthorisedException; +import eu.eudat.old.logic.managers.DataManagementPlanManager; +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.logic.utilities.documents.helpers.FileEnvelope; +import eu.eudat.old.logic.utilities.documents.pdf.PDFUtils; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileListingModel; +import eu.eudat.old.models.data.dmp.DataManagementPlanNewVersionModel; +import eu.eudat.old.models.data.helpermodels.Tuple; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.listingmodels.DataManagementPlanListingModel; +import eu.eudat.old.models.data.listingmodels.DataManagementPlanOverviewModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.types.Authorities; +import eu.eudat.old.configurations.dynamicgrant.DynamicGrantConfiguration; +import eu.eudat.old.data.dao.criteria.DynamicFieldsCriteria; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem; +import eu.eudat.old.exceptions.datamanagementplan.DMPWithDatasetsDeleteException; +import eu.eudat.old.models.data.datasetwizard.DatasetsToBeFinalized; +import eu.eudat.old.models.data.dmp.DataManagementPlan; +import eu.eudat.old.models.data.dmp.DataManagementPlanEditorModel; +import eu.eudat.old.models.data.listingmodels.UserInfoListingModel; +import eu.eudat.old.models.data.listingmodels.VersionListingModel; +import eu.eudat.old.query.DMPQuery; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.activation.MimetypesFileTypeMap; +import javax.validation.Valid; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.springframework.http.MediaType.*; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/dmps/"}) +public class DMPs extends BaseController { + private static final Logger logger = LoggerFactory.getLogger(DMPs.class); + + private DynamicGrantConfiguration dynamicGrantConfiguration; + private Environment environment; + private DataManagementPlanManager dataManagementPlanManager; + private ConfigLoader configLoader; + + @Autowired + public DMPs(ApiContext apiContext, DynamicGrantConfiguration dynamicGrantConfiguration, Environment environment, + DataManagementPlanManager dataManagementPlanManager, ConfigLoader configLoader) { + super(apiContext); + this.dynamicGrantConfiguration = dynamicGrantConfiguration; + this.environment = environment; + this.dataManagementPlanManager = dataManagementPlanManager; + this.configLoader = configLoader; + } + + /* + * Data Retrieval + * */ + + @RequestMapping(method = RequestMethod.POST, value = {"/paged"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getPaged(@Valid @RequestBody DataManagementPlanTableRequest dataManagementPlanTableRequest, + @RequestParam String fieldsGroup, + @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + DataTableData dataTable = this.dataManagementPlanManager.getPaged(dataManagementPlanTableRequest, principal, fieldsGroup); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"{id}"}) + public @ResponseBody + ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType, + @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + if (contentType.equals("application/xml") || contentType.equals("application/msword")) { + return this.dataManagementPlanManager.getDocument(id, contentType, principal, this.configLoader); + } else { + DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, principal, false, true); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/plain/{id}"}) + public @ResponseBody + ResponseEntity getSingleNoDatasets(@PathVariable String id, @RequestHeader("Content-Type") String contentType, + @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + + DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, principal, false, false); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); + + } + + @RequestMapping(method = RequestMethod.POST, value = {"/datasetProfilesUsedByDmps/paged"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) { + DataTableData datasetProfileTableData = this.dataManagementPlanManager.getDatasetProfilesUsedByDMP(datasetProfileTableRequestItem, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/overview/{id}"}) + public @ResponseBody + ResponseEntity getOverviewSingle(@PathVariable String id,@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) { + try { + DataManagementPlanOverviewModel dataManagementPlan = this.dataManagementPlanManager.getOverviewSingle(id, principal, false); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); + } catch (Exception e) { + if (e instanceof UnauthorisedException) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE)); + } else { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE)); + } + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/public/{id}"}) + public @ResponseBody + ResponseEntity getSinglePublic(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { +// try { + DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, principal, true, true); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); +// } catch (Exception ex) { +// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage())); +// } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/publicOverview/{id}"}) + public @ResponseBody + ResponseEntity> getOverviewSinglePublic(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { +// try { + DataManagementPlanOverviewModel dataManagementPlan = this.dataManagementPlanManager.getOverviewSingle(id, principal, true); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); +// } catch (Exception ex) { +// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage())); +// } + } + + @RequestMapping(method = RequestMethod.POST, value = {"/dynamic"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>>> getWithCriteria(@RequestBody RequestItem criteriaRequestItem, Principal principal) throws InstantiationException, IllegalAccessException { + List> dataTable = this.dataManagementPlanManager.getDynamicFields(criteriaRequestItem.getCriteria().getId(), this.dynamicGrantConfiguration, criteriaRequestItem.getCriteria()); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/versions/{id}"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getVersions(@PathVariable(value= "id") String groupId, @RequestParam(value= "public") Boolean isPublic, + @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + List versions = this.dataManagementPlanManager.getAllVersions(groupId, principal, isPublic); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(versions)); + } + + /* + * Data Export + * */ + + @RequestMapping(method = RequestMethod.GET, value = {"rda/{id}"}) + public @ResponseBody + ResponseEntity getRDAJsonDocument(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) { + try { + FileEnvelope rdaJsonDocument = this.dataManagementPlanManager.getRDAJsonDocument(id, principal); + + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(rdaJsonDocument.getFile().length()); + responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); + responseHeaders.set("Content-Disposition", "attachment;filename=" + rdaJsonDocument.getFilename()); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + + InputStream resource = new FileInputStream(rdaJsonDocument.getFile()); + byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource); + resource.close(); + Files.deleteIfExists(rdaJsonDocument.getFile().toPath()); + + return new ResponseEntity<>(content, responseHeaders, HttpStatus.OK); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseItem<>().message(e.getMessage()).status(ApiMessageCode.ERROR_MESSAGE)); + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"}) + public @ResponseBody + ResponseEntity getPDFDocument(@PathVariable String id, @RequestHeader("Content-Type") String contentType, + @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException, InterruptedException { + FileEnvelope file = this.dataManagementPlanManager.getWordDocument(id, principal, configLoader); + String name = file.getFilename().substring(0, file.getFilename().length() - 5).replace(" ", "_").replace(",", "_"); + File pdffile = PDFUtils.convertToPDF(file, environment); + InputStream resource = new FileInputStream(pdffile); + logger.info("Mime Type of " + name + " is " + + new MimetypesFileTypeMap().getContentType(file.getFile())); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(pdffile.length()); + responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); + responseHeaders.set("Content-Disposition", "attachment;filename=" + name + ".pdf"); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + + byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource); + resource.close(); + Files.deleteIfExists(file.getFile().toPath()); + Files.deleteIfExists(pdffile.toPath()); + return new ResponseEntity<>(content, responseHeaders, HttpStatus.OK); + } + + /* + * Data Management + * */ + + @Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> createOrUpdate(@RequestBody DataManagementPlanEditorModel dataManagementPlanEditorModel, Principal principal) throws Exception { + DMP dmp = this.dataManagementPlanManager.createOrUpdate(dataManagementPlanEditorModel, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(new DataManagementPlan().fromDataModel(dmp))); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, path = "full", consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> createOrUpdateWithDatasets(@RequestBody DataManagementPlanEditorModel dataManagementPlanEditorModel, Principal principal) throws Exception { + DMP dmp = this.dataManagementPlanManager.createOrUpdateWithDatasets(dataManagementPlanEditorModel, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(dmp.getId())); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/new/{id}"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> newVersion(@PathVariable UUID id, @Valid @RequestBody DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception { + try { + UUID result = this.dataManagementPlanManager.newVersion(id, dataManagementPlan, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(result)); + } catch (DMPNewVersionException exception) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage())); + } + } + + @RequestMapping(method = RequestMethod.POST, value = {"/clone/{id}"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> clone(@PathVariable UUID id, @RequestBody DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception { + UUID cloneId = this.dataManagementPlanManager.clone(id, dataManagementPlan, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).payload(cloneId)); + } + + @RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> delete(@PathVariable UUID id, Principal principal) { + try { + this.dataManagementPlanManager.delete(id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Deleted Datamanagement Plan")); + } catch (DMPWithDatasetsDeleteException | IOException exception) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage())); + } + } + + @RequestMapping(method = RequestMethod.POST, value = {"/upload"}) + public ResponseEntity dmpUpload(@RequestParam("file") MultipartFile[] files, @RequestParam(name = "profiles", required = false)String[] profiles, Principal principal) throws Exception { + if (files[0].getContentType().equals(APPLICATION_JSON.toString())) { + this.dataManagementPlanManager.createFromRDA(files, principal, profiles); + } else if (files[0].getContentType().equals(APPLICATION_ATOM_XML.toString()) || files[0].getContentType().equals(TEXT_XML.toString())) { + this.dataManagementPlanManager.createDmpFromXml(files, principal, profiles); + } else { + return ResponseEntity.badRequest().body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("File format is not supported")); + } + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem() + .status(ApiMessageCode.SUCCESS_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/makepublic/{id}"}) + public ResponseEntity> makePublic(@PathVariable String id, Principal principal) { + try { + this.dataManagementPlanManager.makePublic(UUID.fromString(id), principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made public.")); + } catch (Exception e) { + logger.error(e.getMessage(), e); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to make Data Management Plan public.")); + } + } + + @RequestMapping(method = RequestMethod.POST, value = {"/finalize/{id}"}) + public ResponseEntity> makeFinalize(@PathVariable String id, Principal principal, @RequestBody DatasetsToBeFinalized datasetsToBeFinalized) { + try { + this.dataManagementPlanManager.makeFinalize(UUID.fromString(id), principal, datasetsToBeFinalized); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made finalized.")); + } catch (Exception e) { + logger.error(e.getMessage(), e); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to finalize Data Management Plan.")); + } + } + + @RequestMapping(method = RequestMethod.POST, value = {"/unfinalize/{id}"}) + public ResponseEntity> undoFinalize(@PathVariable String id, Principal principal) { + try { + this.dataManagementPlanManager.undoFinalize(UUID.fromString(id), principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made active.")); + } catch (Exception e) { + logger.error(e.getMessage(), e); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to unfinalize the Data Management Plan.")); + } + } + + + @RequestMapping(method = RequestMethod.POST, value = {"/updateusers/{id}"}) + public ResponseEntity> updateUsers(@PathVariable String id, @RequestBody List users, Principal principal) { + try { + this.dataManagementPlanManager.updateUsers(UUID.fromString(id), users, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Updated Colaborators for Data Datamanagement Plan.")); + } catch (Exception e) { + logger.error(e.getMessage(), e); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to update the users of Data Management Plan.")); + } + } + + /* + * Data Index + * */ + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/index"}) + public @ResponseBody + ResponseEntity> generateIndex(Principal principal) throws Exception { + this.dataManagementPlanManager.generateIndex(principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Generated").payload(null)); + } + + @Transactional + @RequestMapping(method = RequestMethod.DELETE, value = {"/index"}) + public @ResponseBody + ResponseEntity> clearIndex(Principal principal) throws Exception { + this.dataManagementPlanManager.clearIndex(principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Cleared").payload(null)); + } + + /* + * Misc + * */ + + @RequestMapping(method = RequestMethod.POST, value = {"/test"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> test(@RequestBody DMPCriteria criteria, @ClaimedAuthorities(claims = {Authorities.ANONYMOUS}) Principal principal) throws Exception { + DatabaseRepository dbRepo = this.getApiContext().getOperationsContext().getDatabaseRepository(); + + DMPQuery query = criteria.buildQuery(dbRepo); + + List models = query.getQuery().toListWithFields(); + DataTableData dmp = new DataTableData<>(); + dmp.setData(models); + dmp.setTotalCount(query.getQuery().count()); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dmp)); + } + + /*@RequestMapping(method = RequestMethod.POST, value = {"/public/paged"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getPublicPaged(@RequestBody DataManagmentPlanPublicTableRequest dmpTableRequest, + @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal, + @RequestParam String fieldsGroup) throws Exception { + DataTableData dmp = this.dataManagementPlanManager.getPublicPaged(dmpTableRequest, fieldsGroup, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dmp)); + }*/ + /*@Transactional + @RequestMapping(method = RequestMethod.GET, value = {"{id}/unlock"}, produces = "application/json") + public @ResponseBody + ResponseEntity> unlock(@PathVariable(value = "id") UUID id, Principal principal) throws Exception { + this.dataManagementPlanManager.unlock(id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked")); + }*/ +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DashBoardController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DashBoardController.java new file mode 100644 index 000000000..b0d658d6c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DashBoardController.java @@ -0,0 +1,69 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.DashBoardManager; +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.dashboard.recent.RecentActivity; +import eu.eudat.old.models.data.dashboard.recent.model.RecentActivityModel; +import eu.eudat.old.models.data.dashboard.recent.tablerequest.RecentActivityTableRequest; +import eu.eudat.old.models.data.dashboard.searchbar.SearchBarItem; +import eu.eudat.old.models.data.dashboard.statistics.DashBoardStatistics; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.types.Authorities; +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.transaction.Transactional; +import java.io.IOException; +import java.util.List; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api"}) +public class DashBoardController extends BaseController { + + private DashBoardManager dashBoardManager; + @Autowired + public DashBoardController(ApiContext apiContext, DashBoardManager dashBoardManager) { + super(apiContext); + this.dashBoardManager = dashBoardManager; + } + + @RequestMapping(method = RequestMethod.GET, value = {"/dashboard/getStatistics"}, produces = "application/json") + public ResponseEntity> getStatistics() { + DashBoardStatistics statistics = dashBoardManager.getStatistics(); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(statistics)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/dashboard/me/getStatistics"}, produces = "application/json") + public ResponseEntity> getStatistics(Principal principal) throws IOException { + DashBoardStatistics statistics = dashBoardManager.getMeStatistics(principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(statistics)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/dashboard/recentActivity"}, produces = "application/json") + @Transactional + public ResponseEntity>> getNewRecentActivity(@RequestBody RecentActivityTableRequest tableRequest, + @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + List statistics = dashBoardManager.getNewRecentActivity(tableRequest, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(statistics)); + } + + @Deprecated + @RequestMapping(method = RequestMethod.GET, value = {"/user/recentActivity"}, produces = "application/json") + public ResponseEntity> getRecentActivity(@RequestParam(name = "numOfActivities", required = false, defaultValue = "5") Integer numberOfActivities, Principal principal) { + RecentActivity statistics = dashBoardManager.getRecentActivity(principal, numberOfActivities); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(statistics)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/dashboard/search"}, produces = "application/json") + public ResponseEntity>> search(@RequestParam(name = "like") String like, + @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) { + List searchBarItemList = dashBoardManager.searchUserData(like, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(searchBarItemList)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DataRepositories.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DataRepositories.java new file mode 100644 index 000000000..d7b5cfcb9 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DataRepositories.java @@ -0,0 +1,52 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.DataRepositoryManager; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.data.entities.DataRepository; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.datarepository.DataRepositoryModel; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/external/datarepos"}) +public class DataRepositories extends BaseController { + + private DataRepositoryManager dataRepositoryManager; + + @Autowired + public DataRepositories(ApiContext apiContext, DataRepositoryManager dataRepositoryManager) { + super(apiContext); + this.dataRepositoryManager = dataRepositoryManager; + } + + @RequestMapping(method = RequestMethod.GET, produces = "application/json") + public @ResponseBody + ResponseEntity>> listExternalDataRepositories( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal + ) throws HugeResultSet, NoURLFound { + List dataRepositoryModels = this.dataRepositoryManager.getDataRepositories(query, type, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataRepositoryModels)); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> create(@RequestBody DataRepositoryModel dataRepositoryModel, Principal principal) throws Exception { + DataRepository dataRepository = this.dataRepositoryManager.create(dataRepositoryModel, principal); + DataRepositoryModel dataRepositoryModel1 = new DataRepositoryModel().fromDataModel(dataRepository); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(dataRepositoryModel1).status(ApiMessageCode.SUCCESS_MESSAGE)); + } +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DatasetProfileController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DatasetProfileController.java new file mode 100644 index 000000000..2c507e709 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DatasetProfileController.java @@ -0,0 +1,81 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.models.data.externaldataset.ExternalAutocompleteFieldModel; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.data.dao.criteria.RequestItem; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.logic.managers.AdminManager; +import eu.eudat.old.logic.managers.DatasetProfileManager; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.admin.composite.DatasetProfile; +import eu.eudat.old.models.data.components.commons.datafield.AutoCompleteData; +import eu.eudat.old.models.data.helpers.common.AutoCompleteLookupItem; +import eu.eudat.old.models.data.helpers.common.AutoCompleteOptionsLookupItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Field; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import javax.xml.xpath.XPathExpressionException; +import java.util.List; +import java.util.UUID; + +import static eu.eudat.old.types.Authorities.ADMIN; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api"}) +public class DatasetProfileController extends BaseController { + + private DatasetProfileManager datasetProfileManager; + + @Autowired + public DatasetProfileController(ApiContext apiContext, DatasetProfileManager datasetProfileManager) { + super(apiContext); + this.datasetProfileManager = datasetProfileManager; + } + +/* @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/datasetprofile/save/{id}"}, consumes = "application/json", produces = "application/json") + public ResponseEntity updateDataset(@PathVariable String id, @RequestBody PropertiesModel properties) { + eu.eudat.data.entities.Dataset dataset = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao().find(UUID.fromString(id)); + Map values = new HashMap<>(); + properties.toMap(values); + JSONObject jobject = new JSONObject(values); + dataset.setProperties(jobject.toString()); + dataset.setStatus((short) properties.getStatus()); + this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(dataset); //TODO + return ResponseEntity.status(HttpStatus.OK).body(properties); + }*/ + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/datasetprofile/clone/{id}"}, consumes = "application/json", produces = "application/json") + public ResponseEntity> clone(@PathVariable String id, @ClaimedAuthorities(claims = {ADMIN})Principal principal) { + DescriptionTemplate profile = this.datasetProfileManager.clone(id); + DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile); + datasetprofile.setLabel(profile.getLabel() + " new "); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(datasetprofile)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/search/autocomplete"}, consumes = "application/json", produces = "application/json") + public ResponseEntity getDataForAutocomplete(@RequestBody RequestItem lookupItem) throws XPathExpressionException { + DescriptionTemplate descriptionTemplate = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(lookupItem.getCriteria().getProfileID())); + Field modelfield = this.datasetProfileManager.queryForField(descriptionTemplate.getDefinition(), lookupItem.getCriteria().getFieldID()); + AutoCompleteData data = (AutoCompleteData) modelfield.getData(); + List items = this.datasetProfileManager.getAutocomplete(data, lookupItem.getCriteria().getLike()); + return ResponseEntity.status(HttpStatus.OK).body(items); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/search/autocompleteOptions"}, consumes = "application/json", produces = "application/json") + public ResponseEntity getDataForAutocompleteOptions(@RequestBody RequestItem lookupItem) { + AutoCompleteData data = new AutoCompleteData(); + data.setAutoCompleteSingleDataList(lookupItem.getCriteria().getAutoCompleteSingleDataList()); + List items = this.datasetProfileManager.getAutocomplete(data, lookupItem.getCriteria().getLike()); + return ResponseEntity.status(HttpStatus.OK).body(items); + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DatasetProfiles.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DatasetProfiles.java new file mode 100644 index 000000000..baa1ed18f --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DatasetProfiles.java @@ -0,0 +1,54 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.models.data.datasetprofile.DatasetProfileAutocompleteItem; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileListingModel; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileWithPrefillingPropertyModel; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.data.query.items.item.datasetprofile.DatasetProfileAutocompleteRequest; +import eu.eudat.old.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem; +import eu.eudat.old.logic.managers.DatasetProfileManager; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.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 java.util.List; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api"}) +public class DatasetProfiles extends BaseController { + + private DatasetProfileManager datasetProfileManager; + + @Autowired + 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>> get(@RequestBody DatasetProfileAutocompleteRequest datasetProfileAutocompleteRequest) throws InstantiationException, IllegalAccessException { + List datasetProfileAutocompleteItems = this.datasetProfileManager.getWithCriteria(datasetProfileAutocompleteRequest); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileAutocompleteItems)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/datasetprofiles/getAll"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> getAll(@RequestBody DatasetProfileTableRequestItem tableRequestItem) throws InstantiationException, IllegalAccessException { + List datasetProfileTableData = this.datasetProfileManager.getAll(tableRequestItem); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/datasetprofiles/getAllWithPrefilling"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> getAllWithPrefilling(@RequestBody DatasetProfileTableRequestItem tableRequestItem) { + List datasetProfileTableData = this.datasetProfileManager.getAllWithPrefilling(tableRequestItem); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData)); + } +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Datasets.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Datasets.java new file mode 100644 index 000000000..52a35f9e4 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Datasets.java @@ -0,0 +1,348 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.data.query.items.item.datasetprofile.DatasetProfileWizardAutocompleteRequest; +import eu.eudat.old.exceptions.security.UnauthorisedException; +import eu.eudat.old.logic.managers.DatasetManager; +import eu.eudat.old.logic.managers.DatasetWizardManager; +import eu.eudat.old.logic.managers.FileManager; +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.logic.services.forms.VisibilityRuleService; +import eu.eudat.old.logic.utilities.documents.helpers.FileEnvelope; +import eu.eudat.old.logic.utilities.documents.pdf.PDFUtils; +import eu.eudat.old.models.data.dataset.DatasetOverviewModel; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileListingModel; +import eu.eudat.old.models.data.datasetwizard.DataManagentPlanListingModel; +import eu.eudat.old.models.data.dmp.AssociatedProfile; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.listingmodels.DataManagementPlanOverviewModel; +import eu.eudat.old.models.data.listingmodels.DatasetListingModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.user.composite.DatasetProfile; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.data.query.items.item.dataset.DatasetWizardAutocompleteRequest; +import eu.eudat.old.data.query.items.table.dataset.DatasetPublicTableRequest; +import eu.eudat.old.data.query.items.table.dataset.DatasetTableRequest; +import eu.eudat.old.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem; +import eu.eudat.old.exceptions.datasetwizard.DatasetWizardCannotUnlockException; +import eu.eudat.old.logic.managers.UserManager; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.forms.VisibilityRuleServiceImpl; +import eu.eudat.old.models.data.datasetwizard.DatasetWizardModel; +import eu.eudat.old.models.data.user.composite.PagedDatasetProfile; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.types.Authorities; +import org.apache.poi.util.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.persistence.NoResultException; +import javax.transaction.Transactional; +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.Locale; +import java.util.UUID; + +import static eu.eudat.old.types.Authorities.ANONYMOUS; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/datasets/"}) +public class Datasets extends BaseController { + private static final Logger logger = LoggerFactory.getLogger(Datasets.class); + + private Environment environment; + private DatasetManager datasetManager; + private ConfigLoader configLoader; + private UserManager userManager; + private FileManager fileManager; + + @Autowired + public Datasets(ApiContext apiContext, Environment environment, DatasetManager datasetManager, ConfigLoader configLoader, UserManager userManager, + FileManager fileManager) { + super(apiContext); + this.environment = environment; + this.datasetManager = datasetManager; + this.configLoader = configLoader; + this.userManager = userManager; + this.fileManager = fileManager; + } + + /* + * Data Retrieval + * */ + + @RequestMapping(method = RequestMethod.POST, value = {"paged"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getPaged(@RequestBody DatasetTableRequest datasetTableRequest, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + DataTableData dataTable = this.datasetManager.getPaged(datasetTableRequest, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/public/paged"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getPublicPaged(@RequestBody DatasetPublicTableRequest datasetTableRequest, + @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + DataTableData dataTable = this.datasetManager.getPaged(datasetTableRequest, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/overview/{id}"}) + public @ResponseBody + ResponseEntity getOverviewSingle(@PathVariable String id,@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) { + try { + DatasetOverviewModel dataset = this.datasetManager.getOverviewSingle(id, principal, false); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataset)); + } catch (Exception e) { + if (e instanceof UnauthorisedException) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE)); + } else { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE)); + } + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/publicOverview/{id}"}) + public @ResponseBody + ResponseEntity> getOverviewSinglePublic(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { +// try { + DatasetOverviewModel dataset = this.datasetManager.getOverviewSingle(id, principal, true); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataset)); +// } catch (Exception ex) { +// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage())); +// } + } + + @Transactional + @RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException { + try { + VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl(); + if (contentType.equals("application/xml")) { + return this.datasetManager.getDocument(id, visibilityRuleService, contentType, principal); + } else if (contentType.equals("application/msword")) { + FileEnvelope file = datasetManager.getWordDocumentFile(this.configLoader, id, visibilityRuleService, principal); + InputStream resource = new FileInputStream(file.getFile()); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(file.getFile().length()); + responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); + String fileName = file.getFilename().replace(" ", "_").replace(",", "_"); + responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + + byte[] content = IOUtils.toByteArray(resource); + resource.close(); + Files.deleteIfExists(file.getFile().toPath()); + return new ResponseEntity<>(content, + responseHeaders, + HttpStatus.OK); + } else { + DatasetWizardModel dataset = this.datasetManager.getSingle(id, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataset)); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + if (e instanceof UnauthorisedException) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE)); + } else if (e instanceof NoResultException) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE)); + } else { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE)); + } + } + } + + @RequestMapping(method = RequestMethod.POST, value = {"/datasetProfilesUsedByDatasets/paged"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) { + DataTableData datasetProfileTableData = this.datasetManager.getDatasetProfilesUsedByDatasets(datasetProfileTableRequestItem, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/userDmps"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> getUserDmps(@RequestBody DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, Principal principal) throws IllegalAccessException, InstantiationException { + List dataManagementPlans = DatasetWizardManager.getUserDmps(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetWizardAutocompleteRequest, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/getAvailableProfiles"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> getAvailableProfiles(@RequestBody DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, InstantiationException { + List dataManagementPlans = DatasetWizardManager.getAvailableProfiles(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao(), datasetProfileWizardAutocompleteRequest); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans)); + } + + @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().status(ApiMessageCode.NO_MESSAGE).payload(dataset)); + } + catch (Exception ex) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage())); + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/get/{id}"}, produces = "application/json") + public ResponseEntity> getSingle(@PathVariable String id) { + DescriptionTemplate profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); + DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile); + PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile(); + pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(pagedDatasetProfile)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"profile/{id}"}, produces = "application/json") + public @ResponseBody + 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().status(ApiMessageCode.NO_MESSAGE).payload(dataset)); + } + + /* + * Data Export + * */ + + @RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"}) + public @ResponseBody + ResponseEntity getPDFDocument(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException, InterruptedException { + FileEnvelope file = datasetManager.getWordDocumentFile(this.configLoader, id, new VisibilityRuleServiceImpl(), principal); + String fileName = file.getFilename().replace(" ", "_").replace(",", "_"); + if (fileName.endsWith(".docx")){ + fileName = fileName.substring(0, fileName.length() - 5); + } + File pdffile = PDFUtils.convertToPDF(file, environment); + InputStream resource = new FileInputStream(pdffile); + + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(pdffile.length()); + responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); + responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName + ".pdf"); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + + byte[] content = IOUtils.toByteArray(resource); + resource.close(); + Files.deleteIfExists(file.getFile().toPath()); + Files.deleteIfExists(pdffile.toPath()); + return new ResponseEntity<>(content, + responseHeaders, + HttpStatus.OK); + } + + /* + * Data Management + * */ + + @Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> createOrUpdate(@RequestBody DatasetWizardModel profile, Principal principal) throws Exception { + DatasetWizardModel dataset = new DatasetWizardModel().fromDataModel(this.datasetManager.createOrUpdate(profile, principal)); + dataset.setTags(profile.getTags()); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(dataset)); + } + + @Transactional + @RequestMapping(method = RequestMethod.GET, value = {"/makepublic/{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity> makePublic(@PathVariable UUID id, Principal principal, Locale locale) throws Exception { + this.datasetManager.makePublic(this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetDao(), id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message(this.getApiContext().getHelpersService().getMessageSource().getMessage("dataset.public", new Object[]{}, locale))); + } + + @Transactional + @RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity> delete(@PathVariable(value = "id") UUID id, Principal principal) throws Exception { + new DatasetWizardManager().delete(this.getApiContext(), id); + this.fileManager.markAllFilesOfEntityIdAsDeleted(id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted")); + } + + @Transactional + @RequestMapping(method = RequestMethod.GET, value = {"/{id}/unlock"}, produces = "application/json") + public @ResponseBody + ResponseEntity> unlock(@PathVariable(value = "id") UUID id, Principal principal) throws Exception { + try { + new DatasetWizardManager().unlock(this.getApiContext(), id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked")); + } catch (DatasetWizardCannotUnlockException datasetWizardCannotUnlockException) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(datasetWizardCannotUnlockException.getMessage())); + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/{id}/validate"}, produces = "application/json") + public @ResponseBody + ResponseEntity> validate(@PathVariable(value = "id") UUID id, Principal principal) throws Exception { + Dataset dataset = datasetManager.getEntitySingle(id); + String failedField = datasetManager.checkDatasetValidation(dataset); + if (failedField == null) { + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Valid")); + } else { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Field value of " + failedField + " must be filled.")); + } + } + + /* + * Data Import + * */ + + @RequestMapping(method = RequestMethod.POST, value = {"/upload"}) + public ResponseEntity 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) { + logger.error(e.getMessage(), e); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message("Import was unsuccessful.")); + } + } + + /* + * Data Index + * */ + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/index"}) + public @ResponseBody + ResponseEntity> generateIndex(Principal principal) throws Exception { + this.datasetManager.generateIndex(principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Generated").payload(null)); + } + + @Transactional + @RequestMapping(method = RequestMethod.DELETE, value = {"/index"}) + public @ResponseBody + ResponseEntity> clearIndex(Principal principal) throws Exception { + this.datasetManager.clearIndex(principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Cleared").payload(null)); + } + + +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DepositController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DepositController.java new file mode 100644 index 000000000..04031198f --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DepositController.java @@ -0,0 +1,84 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.DepositManager; +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.models.data.doi.DepositRequest; +import eu.eudat.old.models.data.doi.RepositoryConfig; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.doi.DepositCode; +import eu.eudat.old.models.data.doi.Doi; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.types.Authorities; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/deposit/"}) +public class DepositController extends BaseController { + private static final Logger logger = LoggerFactory.getLogger(DepositController.class); + + private DepositManager depositManager; + + @Autowired + public DepositController(ApiContext apiContext, DepositManager depositManager){ + super(apiContext); + this.depositManager = depositManager; + } + + @RequestMapping(method = RequestMethod.GET, value = {"/repos"}) + public @ResponseBody + ResponseEntity>> getAvailableRepos(@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) { + List ids = this.depositManager.getAvailableRepos(); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(ids)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/getAccessToken"}) + public @ResponseBody + ResponseEntity> getAccessToken(@RequestBody DepositCode depositCode, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + String accessToken = this.depositManager.authenticate(depositCode.getRepositoryId(), depositCode.getCode()); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(accessToken)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/createDoi"}) + public @ResponseBody + ResponseEntity> createDoi(@RequestBody DepositRequest depositRequest, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) { + try { + Doi doi = this.depositManager.deposit(depositRequest, principal); + if(doi != null){ + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully created DOI for Data Datamanagement Plan in question.").payload(doi)); + } + else{ + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to create DOI for the Data Management Plan")); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to create DOI for the Data Management Plan: " + e.getMessage())); + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"/logo/{repositoryId}"}) + public @ResponseBody + ResponseEntity> getLogo(@PathVariable("repositoryId") String repositoryId, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) { + try { + String encodedLogo = this.depositManager.getRepositoryLogo(repositoryId); + if(encodedLogo != null){ + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully loaded " + repositoryId + "'s logo.").payload(encodedLogo)); + } + else{ + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(repositoryId + " has no logo").payload(null)); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to load " + repositoryId + "'s logo: " + e.getMessage())); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DescriptionTemplateTypeController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DescriptionTemplateTypeController.java new file mode 100644 index 000000000..a435b43be --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/DescriptionTemplateTypeController.java @@ -0,0 +1,92 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.exceptions.descriptiontemplate.DescriptionTemplatesWithTypeException; +import eu.eudat.old.logic.managers.DescriptionTemplateTypeManager; +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.descriptiontemplatetype.DescriptionTemplateTypeModel; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.types.Authorities; +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.transaction.Transactional; +import java.util.UUID; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/descriptionTemplateType/"}) +public class DescriptionTemplateTypeController extends BaseController { + + private DescriptionTemplateTypeManager descriptionTemplateTypeManager; + + @Autowired + public DescriptionTemplateTypeController(ApiContext apiContext, DescriptionTemplateTypeManager descriptionTemplateTypeManager){ + super(apiContext); + this.descriptionTemplateTypeManager = descriptionTemplateTypeManager; + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"create"}, produces = "application/json") + public @ResponseBody + ResponseEntity> create(@RequestBody DescriptionTemplateTypeModel type, @ClaimedAuthorities(claims = {Authorities.ADMIN}) Principal principal) throws Exception { + try { + this.descriptionTemplateTypeManager.create(type); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); + } + catch(DescriptionTemplatesWithTypeException e){ + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage())); + } + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"update"}, produces = "application/json") + public @ResponseBody + ResponseEntity> update(@RequestBody DescriptionTemplateTypeModel type, @ClaimedAuthorities(claims = {Authorities.ADMIN}) Principal principal) throws Exception { + try { + this.descriptionTemplateTypeManager.update(type); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Updated")); + } + catch(DescriptionTemplatesWithTypeException e){ + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage())); + } + } + + @RequestMapping(method = RequestMethod.GET, value = {"get"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> get(@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + DataTableData dataTable = this.descriptionTemplateTypeManager.get(); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"get/{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity> getSingle(@PathVariable(value = "id") UUID id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + try { + DescriptionTemplateTypeModel typeModel = this.descriptionTemplateTypeManager.getSingle(id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(typeModel)); + } + catch(DescriptionTemplatesWithTypeException e){ + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage())); + } + } + + @Transactional + @RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity> delete(@PathVariable(value = "id") UUID id, @ClaimedAuthorities(claims = {Authorities.ADMIN}) Principal principal) throws Exception { + try{ + this.descriptionTemplateTypeManager.delete(id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted")); + } + catch(DescriptionTemplatesWithTypeException e){ + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.UNSUCCESS_DELETE).message(e.getMessage())); + } + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/EmailConfirmation.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/EmailConfirmation.java new file mode 100644 index 000000000..ee29f4e9b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/EmailConfirmation.java @@ -0,0 +1,59 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.exceptions.emailconfirmation.TokenExpiredException; +import eu.eudat.old.logic.managers.EmailConfirmationManager; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.exceptions.emailconfirmation.HasConfirmedEmailException; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.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.transaction.Transactional; + +@RestController +@CrossOrigin +@RequestMapping(value = "api/emailConfirmation") +public class EmailConfirmation { + + private EmailConfirmationManager emailConfirmationManager; + + @Autowired + public EmailConfirmation(EmailConfirmationManager emailConfirmationManager) { + this.emailConfirmationManager = emailConfirmationManager; + } + + @Transactional + @RequestMapping(method = RequestMethod.GET, value = {"/{emailToken}"}) + public @ResponseBody + ResponseEntity emailConfirmation(@PathVariable(value = "emailToken") String token) { + try { + this.emailConfirmationManager.confirmEmail(token); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch + (HasConfirmedEmailException | TokenExpiredException ex) { + if (ex instanceof TokenExpiredException) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); + } else { + return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem().status(ApiMessageCode.WARN_MESSAGE)); + } + } + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity sendConfirmatioEmail(@RequestBody String email, Principal principal) { + try { + this.emailConfirmationManager.sendConfirmationEmail(email, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch (Exception ex) { + if (ex instanceof HasConfirmedEmailException) { + return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem().status(ApiMessageCode.WARN_MESSAGE)); + } + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/EmailMergeConfirmation.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/EmailMergeConfirmation.java new file mode 100644 index 000000000..89a2ad32c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/EmailMergeConfirmation.java @@ -0,0 +1,60 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.exceptions.emailconfirmation.HasConfirmedEmailException; +import eu.eudat.old.exceptions.emailconfirmation.TokenExpiredException; +import eu.eudat.old.logic.managers.MergeEmailConfirmationManager; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.userinfo.UserMergeRequestModel; +import eu.eudat.old.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.transaction.Transactional; + +@RestController +@CrossOrigin +@RequestMapping(value = "api/emailMergeConfirmation") +public class EmailMergeConfirmation { + + private MergeEmailConfirmationManager emailConfirmationManager; + + @Autowired + public EmailMergeConfirmation(MergeEmailConfirmationManager emailConfirmationManager) { + this.emailConfirmationManager = emailConfirmationManager; + } + + @Transactional + @RequestMapping(method = RequestMethod.GET, value = {"/{emailToken}"}) + public @ResponseBody + ResponseEntity> emailConfirmation(@PathVariable(value = "emailToken") String token) { + try { + String emailToBeMerged = this.emailConfirmationManager.confirmEmail(token); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(emailToBeMerged).status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch + (HasConfirmedEmailException | TokenExpiredException ex) { + if (ex instanceof TokenExpiredException) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); + } else { + return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem().status(ApiMessageCode.WARN_MESSAGE)); + } + } + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity sendConfirmatioEmail(@RequestBody UserMergeRequestModel requestModel, Principal principal) { + try { + this.emailConfirmationManager.sendConfirmationEmail(requestModel.getEmail(), principal, requestModel.getUserId(), requestModel.getProvider()); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch (Exception ex) { + if (ex instanceof HasConfirmedEmailException) { + return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem().status(ApiMessageCode.WARN_MESSAGE)); + } + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/EmailUnlinkConfirmation.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/EmailUnlinkConfirmation.java new file mode 100644 index 000000000..b7501ca01 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/EmailUnlinkConfirmation.java @@ -0,0 +1,57 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.exceptions.emailconfirmation.HasConfirmedEmailException; +import eu.eudat.old.exceptions.emailconfirmation.TokenExpiredException; +import eu.eudat.old.logic.managers.UnlinkEmailConfirmationManager; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.userinfo.UserUnlinkRequestModel; +import eu.eudat.old.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.transaction.Transactional; + +@RestController +@CrossOrigin +@RequestMapping(value = "api/emailUnlinkConfirmation") +public class EmailUnlinkConfirmation { + + private UnlinkEmailConfirmationManager unlinkEmailConfirmationManager; + + @Autowired + public EmailUnlinkConfirmation(UnlinkEmailConfirmationManager unlinkEmailConfirmationManager){ + this.unlinkEmailConfirmationManager = unlinkEmailConfirmationManager; + } + + @Transactional + @RequestMapping(method = RequestMethod.GET, value = {"/{emailToken}"}) + public @ResponseBody + ResponseEntity emailConfirmation(@PathVariable(value = "emailToken") String token) { + try { + this.unlinkEmailConfirmationManager.confirmEmail(token); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch (TokenExpiredException | HasConfirmedEmailException ex) { + if (ex instanceof TokenExpiredException) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); + } + else { + return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem().status(ApiMessageCode.WARN_MESSAGE)); + } + } + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity sendUnlinkConfirmationEmail(@RequestBody UserUnlinkRequestModel requestModel, Principal principal) { + try { + this.unlinkEmailConfirmationManager.sendConfirmationEmail(requestModel.getEmail(), principal, requestModel.getUserId(), requestModel.getProvider()); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch (Exception ex) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message("Could not send unlink email.")); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/ExternalDatasets.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/ExternalDatasets.java new file mode 100644 index 000000000..083257df5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/ExternalDatasets.java @@ -0,0 +1,69 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.data.query.items.table.externaldataset.ExternalDatasetTableRequest; +import eu.eudat.old.logic.managers.ExternalDatasetManager; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.data.entities.ExternalDataset; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.externaldataset.ExternalDatasetListingModel; +import eu.eudat.old.models.data.externaldataset.ExternalDatasetModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.UUID; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api"}) +public class ExternalDatasets extends BaseController { + + private ExternalDatasetManager externalDatasetManager; + + @Autowired + 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>> getPaged(@RequestBody ExternalDatasetTableRequest datasetTableRequest, Principal principal) throws Exception { + DataTableData dataTable = externalDatasetManager.getPaged(datasetTableRequest); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/external/datasets"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> getWithExternal( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal + ) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { + List dataTable = externalDatasetManager.getWithExternal(query, type, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets/getSingle/{id}"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseItem getWithExternal(@PathVariable UUID id, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { + ExternalDatasetListingModel externalDatasetModel = externalDatasetManager.getSingle(id); + return new ResponseItem().payload(externalDatasetModel).status(ApiMessageCode.NO_MESSAGE); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/externaldatasets"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> create(@RequestBody ExternalDatasetModel externalDatasetModel, Principal principal) throws Exception { + ExternalDataset externalDataset = this.externalDatasetManager.create(externalDatasetModel, principal); + ExternalDatasetListingModel externalDatasetListingModel = new ExternalDatasetListingModel().fromDataModel(externalDataset); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(externalDatasetListingModel).status(ApiMessageCode.SUCCESS_MESSAGE)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/FaqController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/FaqController.java new file mode 100644 index 000000000..495554c06 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/FaqController.java @@ -0,0 +1,38 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.MaterialManager; +import eu.eudat.old.logic.managers.MetricsManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Objects; +import java.util.stream.Stream; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/material/faq/"}) +public class FaqController { + + private Environment environment; + private MaterialManager materialManager; + + @Autowired + public FaqController(Environment environment, MaterialManager materialManager, MetricsManager metricsManager) { + this.environment = environment; + this.materialManager = materialManager; + } + + @RequestMapping(path = "{lang}", method = RequestMethod.GET ) + public ResponseEntity getFaq(@PathVariable(name = "lang") String lang) throws IOException { + try (Stream paths = Files.walk(Paths.get(Objects.requireNonNull(this.environment.getProperty("faq.path"))))) { + return this.materialManager.getResponseEntity(lang, paths); + } + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/FileController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/FileController.java new file mode 100644 index 000000000..e235b3d36 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/FileController.java @@ -0,0 +1,181 @@ +package eu.eudat.old.controllers; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.exceptions.security.UnauthorisedException; +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.logic.utilities.documents.helpers.FileEnvelope; +import eu.eudat.old.logic.utilities.json.JsonSearcher; +import eu.eudat.old.models.data.admin.composite.DatasetProfile; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.data.entities.FileUpload; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.logic.managers.DatasetProfileManager; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.HintedModelFactory; +import eu.eudat.old.models.data.datasetwizard.DatasetWizardModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.types.Authorities; +import org.apache.poi.util.IOUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.transaction.Transactional; +import java.io.*; +import java.nio.file.Files; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/file/"}) +public class FileController { + + private DatasetProfileManager datasetProfileManager; + private final Environment environment; + private DatabaseRepository databaseRepository; + + @Autowired + public FileController(DatasetProfileManager datasetProfileManager, Environment environment, ApiContext apiContext) { + this.datasetProfileManager = datasetProfileManager; + this.environment = environment; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/upload"}) + public ResponseEntity> upload( + @RequestParam("file") MultipartFile file, @RequestParam("datasetProfileId") String datasetProfileId, @RequestParam("fieldId") String fieldId, + @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER}) Principal principal) + throws IllegalAccessException, IOException { + String uuid = UUID.randomUUID().toString(); + + DatasetProfile datasetprofile = this.datasetProfileManager.getDatasetProfile(datasetProfileId); + + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + String json = mapper.writeValueAsString(datasetprofile.getSections());; + JsonNode propertiesJson = mapper.readTree(json); + Set fieldNodes = new HashSet<>(); + fieldNodes.addAll(JsonSearcher.findNodes(propertiesJson, "id", fieldId, false)); + +// AtomicReference exceptionMessage = null; + AtomicBoolean acceptedFile = new AtomicBoolean(false); + fieldNodes.forEach(node -> { + JsonNode data = node.get("data"); + if (data != null && !data.toString().equals("\"\"") && !data.toString().equals("null")) { + String stringValue = data.toString().replaceAll("=", ":"); + JSONObject dataObj = new JSONObject(stringValue); + Map dataMap = ((JSONObject) dataObj).toMap(); + if(dataMap.get("maxFileSizeInMB") != null && !dataMap.get("maxFileSizeInMB").toString().equals("\"\"") && !dataMap.get("maxFileSizeInMB").toString().equals("null")) { + if (file.getSize() <= Integer.parseInt(dataMap.get("maxFileSizeInMB").toString())*1048576) { + acceptedFile.set(true); + } +// else { +// exceptionMessage.set("The file is too large. Max file upload is " + dataMap.get("maxFileSizeInMB").toString() + " MB."); +// } + } + + if(acceptedFile.get() && data.get("types") != null && !data.get("types").toString().equals("\"\"") && !data.get("types").toString().equals("null")) { + acceptedFile.set(false); + + JSONArray types = new JSONArray(data.get("types").toString()); + + types.iterator().forEachRemaining(element -> { + Map typesMap = ((JSONObject) element).toMap(); + if(typesMap.get("value") != null && !typesMap.get("value").toString().equals("\"\"") && !typesMap.get("value").toString().equals("null")) { + if(file.getContentType().equals(typesMap.get("value").toString())) { + acceptedFile.set(true); + } + } + }); + } +// if(!acceptedFile.get()) { +// exceptionMessage.set("The file type is not accepted."); +// } + } + }); + + if(!acceptedFile.get()) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("The uploaded file is too large or has an unaccepted type")); + } + + + File convFile = new File(this.environment.getProperty("temp.temp") + uuid); + convFile.createNewFile(); + FileOutputStream fos = new FileOutputStream(convFile); + fos.write(file.getBytes()); + fos.close(); + + + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(uuid) + .status(ApiMessageCode.SUCCESS_MESSAGE).message("")); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/delete-temp"}) + public ResponseEntity> upload(@RequestBody String filename) throws IllegalAccessException, IOException { + File convFile = new File(this.environment.getProperty("temp.temp") + filename); +// Boolean deleted = convFile.delete(); + Boolean deleted = Files.deleteIfExists(convFile.toPath()); + + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(deleted.toString()) + .status(ApiMessageCode.SUCCESS_MESSAGE).message("")); + } + + @Transactional + @RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity download(@PathVariable String id + ,@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal + ) throws IOException { + FileUpload fileUpload = databaseRepository.getFileUploadDao().find(UUID.fromString(id)); + if(fileUpload == null) { + throw new NoSuchElementException("File with id "+id+" not found"); + } + + if(fileUpload.getEntityType().name().equals(FileUpload.EntityType.DATASET.name())) { + Dataset datasetEntity = databaseRepository.getDatasetDao().find(fileUpload.getEntityId(), HintedModelFactory.getHint(DatasetWizardModel.class)); + if (datasetEntity == null) { + throw new NoSuchElementException("No dataset with id " + fileUpload.getEntityId() + " found. This dataset was related to the file with id " + id); + } + if (!datasetEntity.getDmp().isPublic() && datasetEntity.getDmp().getUsers() + .stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()) + .collect(Collectors.toList()).size() == 0) + throw new UnauthorisedException(); + } + + FileEnvelope fileEnvelope = new FileEnvelope(); + fileEnvelope.setFilename(fileUpload.getName()); + File exportFile = new File(this.environment.getProperty("file.storage") + id); + fileEnvelope.setFile(exportFile); + + InputStream resource = new FileInputStream(fileEnvelope.getFile()); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(fileEnvelope.getFile().length()); + responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); + String fileName = fileEnvelope.getFilename().replace(" ", "_").replace(",", "_"); + responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.set("Cache-Control", "no-store"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + + byte[] content = IOUtils.toByteArray(resource); + resource.close(); + return new ResponseEntity<>(content, + responseHeaders, + HttpStatus.OK); + + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Funders.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Funders.java new file mode 100644 index 000000000..5e24514ad --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Funders.java @@ -0,0 +1,35 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.funder.Funder; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.data.query.items.item.funder.FunderCriteriaRequest; +import eu.eudat.old.logic.managers.FunderManager; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/funders/"}) +public class Funders extends BaseController { + private FunderManager funderManager; + + public Funders(ApiContext apiContext, FunderManager funderManager) { + super(apiContext); + this.funderManager = funderManager; + } + + @RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getWithExternal(@RequestBody FunderCriteriaRequest funderCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { + List dataTable = this.funderManager.getCriteriaWithExternal(funderCriteria, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/GlossaryController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/GlossaryController.java new file mode 100644 index 000000000..53caa816d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/GlossaryController.java @@ -0,0 +1,38 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.MaterialManager; +import eu.eudat.old.logic.managers.MetricsManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Objects; +import java.util.stream.Stream; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/material/glossary/"}) +public class GlossaryController { + + private Environment environment; + private MaterialManager materialManager; + + @Autowired + public GlossaryController(Environment environment, MaterialManager materialManager, MetricsManager metricsManager) { + this.environment = environment; + this.materialManager = materialManager; + } + + @RequestMapping(path = "{lang}", method = RequestMethod.GET ) + public ResponseEntity getGlossary(@PathVariable(name = "lang") String lang) throws IOException { + try (Stream paths = Files.walk(Paths.get(Objects.requireNonNull(this.environment.getProperty("glossary.path"))))) { + return this.materialManager.getResponseEntity(lang, paths); + } + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Grants.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Grants.java new file mode 100644 index 000000000..ffa4c40d1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Grants.java @@ -0,0 +1,91 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.data.query.items.item.grant.GrantCriteriaRequest; +import eu.eudat.old.logic.managers.GrantManager; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.models.data.grant.Grant; +import eu.eudat.old.models.data.grant.GrantListingModel; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.data.query.items.table.grant.GrantTableRequest; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +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 static eu.eudat.old.types.Authorities.ANONYMOUS; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/grants/"}) +public class Grants extends BaseController { + private GrantManager grantManager; + + @Autowired + public Grants(ApiContext apiContext, GrantManager grantManager) { + super(apiContext); + this.grantManager = grantManager; + } + + @RequestMapping(method = RequestMethod.POST, value = {"/paged"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getPaged(@Valid @RequestBody GrantTableRequest grantTableRequest, @RequestParam String fieldsGroup, Principal principal) throws Exception { + DataTableData dataTable = this.grantManager.getPaged(grantTableRequest, principal, fieldsGroup); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"public/paged"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getPaged(@Valid @RequestBody GrantTableRequest grantTableRequest) throws Exception { + DataTableData dataTable = this.grantManager.getPublicPaged(grantTableRequest); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity> getSingle(@PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException { + Grant grant = this.grantManager.getSingle(id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(grant).status(ApiMessageCode.NO_MESSAGE)); + } + + /*@Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> addGrant(@Valid @RequestBody eu.eudat.models.data.grant.Grant grant, Principal principal) throws IOException, ParseException { + this.grantManager.createOrUpdate(grant, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); + }*/ + + /*@Transactional + @RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> inactivate(@PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException { + this.grantManager.inactivate(id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + }*/ + + @RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getWithExternal(@RequestBody GrantCriteriaRequest grantCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { + List dataTable = this.grantManager.getCriteriaWithExternal(grantCriteria, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"get"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> get(@RequestBody GrantCriteriaRequest grantCriteria, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { + List dataTable = this.grantManager.getCriteria(grantCriteria); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } + +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/JournalsController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/JournalsController.java new file mode 100644 index 000000000..493c94fd7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/JournalsController.java @@ -0,0 +1,43 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.DataRepositoryManager; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.datarepository.DataRepositoryModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.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 java.util.List; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/external/journals"}) +public class JournalsController extends BaseController { + + private DataRepositoryManager dataRepositoryManager; + + @Autowired + public JournalsController(ApiContext apiContext, DataRepositoryManager dataRepositoryManager) { + super(apiContext); + this.dataRepositoryManager = dataRepositoryManager; + } + + @RequestMapping(method = RequestMethod.GET, produces = "application/json") + public @ResponseBody + ResponseEntity>> listExternalDataRepositories( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal + ) throws HugeResultSet, NoURLFound { + List dataRepositoryModels = this.dataRepositoryManager.getJournals(query, type, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataRepositoryModels)); + } + + +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/LanguageController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/LanguageController.java new file mode 100644 index 000000000..db7dd9173 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/LanguageController.java @@ -0,0 +1,56 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.io.*; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/language/"}) +public class LanguageController { + + private Environment environment; + + @Autowired + public LanguageController(Environment environment) { + this.environment = environment; + } + + @RequestMapping(value = "{lang}", method = RequestMethod.GET) + public ResponseEntity getLanguage(@PathVariable String lang) throws IOException { + + String fileName = this.environment.getProperty("language.path") + lang + ".json"; + InputStream is = new FileInputStream(fileName); + + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(is.available()); + responseHeaders.setContentType(MediaType.APPLICATION_JSON); + responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + + byte[] content = new byte[is.available()]; + is.read(content); + is.close(); + + return new ResponseEntity<>(content, responseHeaders, HttpStatus.OK); + } + + @RequestMapping(value = "update/{lang}", method = RequestMethod.POST) + public @ResponseBody + ResponseEntity> updateLang(@PathVariable String lang, @RequestBody String json) throws Exception { + String fileName = this.environment.getProperty("language.path") + lang + ".json"; + OutputStream os = new FileOutputStream(fileName); + os.write(json.getBytes()); + os.close(); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Updated").payload("Updated")); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Licenses.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Licenses.java new file mode 100644 index 000000000..a9cc93adf --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Licenses.java @@ -0,0 +1,41 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.LicenseManager; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.license.LicenseModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.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 java.util.List; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/external/licenses"}) +public class Licenses extends BaseController { + + private LicenseManager licenseManager; + + @Autowired + public Licenses(ApiContext apiContext, LicenseManager licenseManager) { + super(apiContext); + this.licenseManager = licenseManager; + } + + @RequestMapping(method = RequestMethod.GET, produces = "application/json") + public @ResponseBody + ResponseEntity>> listExternalLicenses( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal + ) throws HugeResultSet, NoURLFound { + List licenseModels = this.licenseManager.getLicenses(query, type); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(licenseModels)); + } +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/LockController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/LockController.java new file mode 100644 index 000000000..224e7ec6c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/LockController.java @@ -0,0 +1,54 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.LockManager; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.lock.Lock; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import java.util.UUID; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/lock/"}) +public class LockController { + + private LockManager lockManager; + + @Autowired + public LockController(LockManager lockManager) { + this.lockManager = lockManager; + } + + @Transactional + @RequestMapping(method = RequestMethod.GET, path = "target/status/{id}") + public @ResponseBody ResponseEntity> getLocked(@PathVariable String id, Principal principal) throws Exception { + boolean locked = this.lockManager.isLocked(id, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("locked").payload(locked)); + } + + @Transactional + @RequestMapping(method = RequestMethod.DELETE, path = "target/unlock/{id}") + public @ResponseBody ResponseEntity> unlock(@PathVariable String id, Principal principal) throws Exception { + this.lockManager.unlock(id, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload("Lock Removed")); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody ResponseEntity> createOrUpdate(@RequestBody Lock lock, Principal principal) throws Exception { + eu.eudat.old.data.entities.Lock result = this.lockManager.createOrUpdate(lock, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(result.getId())); + } + + @RequestMapping(method = RequestMethod.GET, path = "target/{id}") + public @ResponseBody ResponseEntity> getSingle(@PathVariable String id, Principal principal) throws Exception { + Lock lock = this.lockManager.getFromTarget(id, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(lock)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Login.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Login.java new file mode 100644 index 000000000..33aadddde --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Login.java @@ -0,0 +1,178 @@ +package eu.eudat.old.controllers; + + +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.models.ConfigurableProvidersModel; +import eu.eudat.old.logic.security.validators.b2access.B2AccessTokenValidator; +import eu.eudat.old.logic.security.validators.b2access.helpers.B2AccessRequest; +import eu.eudat.old.logic.security.validators.configurableProvider.ConfigurableProviderTokenValidator; +import eu.eudat.old.logic.security.validators.linkedin.LinkedInTokenValidator; +import eu.eudat.old.logic.security.validators.openaire.OpenAIRETokenValidator; +import eu.eudat.old.logic.security.validators.openaire.helpers.OpenAIRERequest; +import eu.eudat.old.logic.security.validators.orcid.helpers.ORCIDRequest; +import eu.eudat.old.logic.security.validators.twitter.TwitterTokenValidator; +import eu.eudat.old.logic.security.validators.zenodo.helpers.ZenodoRequest; +import eu.eudat.old.logic.security.validators.zenodo.helpers.ZenodoResponseToken; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.login.Credentials; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.principal.PrincipalModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.types.MetricNames; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.logic.managers.MetricsManager; +import eu.eudat.old.logic.managers.UserManager; +import eu.eudat.old.logic.security.CustomAuthenticationProvider; +import eu.eudat.old.logic.security.validators.b2access.helpers.B2AccessResponseToken; +import eu.eudat.old.logic.security.validators.configurableProvider.helpers.ConfigurableProviderRequest; +import eu.eudat.old.logic.security.validators.configurableProvider.helpers.ConfigurableProviderResponseToken; +import eu.eudat.old.logic.security.validators.linkedin.helpers.LinkedInRequest; +import eu.eudat.old.logic.security.validators.linkedin.helpers.LinkedInResponseToken; +import eu.eudat.old.logic.security.validators.openaire.helpers.OpenAIREResponseToken; +import eu.eudat.old.logic.security.validators.orcid.ORCIDTokenValidator; +import eu.eudat.old.logic.security.validators.orcid.helpers.ORCIDResponseToken; +import eu.eudat.old.logic.security.validators.zenodo.ZenodoTokenValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.social.oauth1.OAuthToken; +import org.springframework.web.bind.annotation.*; + +import javax.transaction.Transactional; +import java.security.GeneralSecurityException; + + +@RestController +@CrossOrigin +@RequestMapping(value = "api/auth") +public class Login { + private static final Logger logger = LoggerFactory.getLogger(Login.class); + + private CustomAuthenticationProvider customAuthenticationProvider; + private AuthenticationService nonVerifiedUserAuthenticationService; + private TwitterTokenValidator twitterTokenValidator; + private B2AccessTokenValidator b2AccessTokenValidator; + private ORCIDTokenValidator orcidTokenValidator; + private LinkedInTokenValidator linkedInTokenValidator; + private OpenAIRETokenValidator openAIRETokenValidator; + private ConfigurableProviderTokenValidator configurableProviderTokenValidator; + private ZenodoTokenValidator zenodoTokenValidator; + private ConfigLoader configLoader; + private final MetricsManager metricsManager; + +// private Logger logger; + + private UserManager userManager; + + @Autowired + public Login(CustomAuthenticationProvider customAuthenticationProvider, + AuthenticationService nonVerifiedUserAuthenticationService, TwitterTokenValidator twitterTokenValidator, + B2AccessTokenValidator b2AccessTokenValidator, ORCIDTokenValidator orcidTokenValidator, + LinkedInTokenValidator linkedInTokenValidator, OpenAIRETokenValidator openAIRETokenValidator, + ConfigurableProviderTokenValidator configurableProviderTokenValidator, ZenodoTokenValidator zenodoTokenValidator, + ConfigLoader configLoader, UserManager userManager, + MetricsManager metricsManager) { + this.customAuthenticationProvider = customAuthenticationProvider; + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + this.twitterTokenValidator = twitterTokenValidator; + this.b2AccessTokenValidator = b2AccessTokenValidator; + this.orcidTokenValidator = orcidTokenValidator; + this.linkedInTokenValidator = linkedInTokenValidator; + this.openAIRETokenValidator = openAIRETokenValidator; + this.configurableProviderTokenValidator = configurableProviderTokenValidator; + this.zenodoTokenValidator = zenodoTokenValidator; + this.configLoader = configLoader; + this.userManager = userManager; + this.metricsManager = metricsManager; + } + + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/externallogin"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> externallogin(@RequestBody LoginInfo credentials) throws GeneralSecurityException, NullEmailException { + logger.info("Trying To Login With " + credentials.getProvider()); + metricsManager.increaseValue(MetricNames.USERS, 1, MetricNames.LOGGEDIN); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(customAuthenticationProvider.authenticate(credentials)).status(ApiMessageCode.SUCCESS_MESSAGE)); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/nativelogin"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> nativelogin(@RequestBody Credentials credentials) throws NullEmailException { + logger.info(credentials.getUsername() + " Trying To Login"); + metricsManager.increaseValue(MetricNames.USERS, 1, MetricNames.LOGGEDIN); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(userManager.authenticate(this.nonVerifiedUserAuthenticationService, credentials)).status(ApiMessageCode.SUCCESS_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/twitterRequestToken"}, produces = "application/json") + public @ResponseBody + ResponseEntity> twitterRequestToken() { + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(this.twitterTokenValidator.getRequestToken()).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/linkedInRequestToken"}, produces = "application/json", consumes = "application/json") + public @ResponseBody + ResponseEntity> linkedInRequestToken(@RequestBody LinkedInRequest linkedInRequest) { + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(this.linkedInTokenValidator.getAccessToken(linkedInRequest)).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/b2AccessRequestToken"}, produces = "application/json", consumes = "application/json") + public @ResponseBody + ResponseEntity> b2AccessRequestToken(@RequestBody B2AccessRequest b2AccessRequest) { + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(this.b2AccessTokenValidator.getAccessToken(b2AccessRequest)).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/orcidRequestToken"}, produces = "application/json", consumes = "application/json") + public @ResponseBody + ResponseEntity> ORCIDRequestToken(@RequestBody ORCIDRequest orcidRequest) { + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(this.orcidTokenValidator.getAccessToken(orcidRequest)).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/openAireRequestToken"}, produces = "application/json", consumes = "application/json") + public @ResponseBody + ResponseEntity> openAIRERequestToken(@RequestBody OpenAIRERequest openAIRERequest) { + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(this.openAIRETokenValidator.getAccessToken(openAIRERequest)).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/configurableProviderRequestToken"}, produces = "application/json", consumes = "application/json") + public @ResponseBody + ResponseEntity> configurableProviderRequestToken(@RequestBody ConfigurableProviderRequest configurableProviderRequest) { + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(this.configurableProviderTokenValidator.getAccessToken(configurableProviderRequest)).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/zenodoRequestToken"}, produces = "application/json", consumes = "application/json") + public @ResponseBody + ResponseEntity> ZenodoRequestToken(@RequestBody ZenodoRequest zenodoRequest) { + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(this.zenodoTokenValidator.getAccessToken(zenodoRequest)).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/me"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> authMe(Principal principal) throws NullEmailException { + logger.info(principal + " Getting Me"); + Principal principal1 = this.nonVerifiedUserAuthenticationService.Touch(principal.getToken()); + PrincipalModel principalModel = PrincipalModel.fromEntity(principal1); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(principalModel).status(ApiMessageCode.NO_MESSAGE)); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/logout"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> logout(Principal principal) { + this.nonVerifiedUserAuthenticationService.Logout(principal.getToken()); + logger.info(principal + " Logged Out"); + metricsManager.decreaseValue(MetricNames.USERS, 1, MetricNames.LOGGEDIN); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/configurableLogin"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> getConfigurableProviders() { + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(new ConfigurableProvidersModel().fromDataModel(configLoader.getConfigurableProviders())).status(ApiMessageCode.NO_MESSAGE)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/ManagementController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/ManagementController.java new file mode 100644 index 000000000..de3a9b453 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/ManagementController.java @@ -0,0 +1,51 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.types.Authorities; +import eu.eudat.old.logic.managers.DatasetProfileManager; +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.transaction.Transactional; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/management/"}) +public class ManagementController extends BaseController { + + private DatasetProfileManager datasetProfileManager; + + @Autowired + public ManagementController(ApiContext apiContext, DatasetProfileManager datasetProfileManager){ + super(apiContext); + this.datasetProfileManager = datasetProfileManager; + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/addSemantics"}) + public ResponseEntity addSemanticsInDatasetProfiles(@ClaimedAuthorities(claims = {Authorities.ADMIN}) Principal principal) throws Exception { + try { + this.datasetProfileManager.addSemanticsInDatasetProfiles(); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch (Exception exception) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage())); + } + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/addRdaInSemantics"}) + public ResponseEntity addRdaInSemanticsInDatasetProfiles(@ClaimedAuthorities(claims = {Authorities.ADMIN}) Principal principal) throws Exception { + try { + this.datasetProfileManager.addRdaInSemanticsInDatasetProfiles(); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } catch (Exception exception) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage())); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Organisations.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Organisations.java new file mode 100644 index 000000000..8bdeda8f5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Organisations.java @@ -0,0 +1,66 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.data.query.items.table.organisations.OrganisationsTableRequest; +import eu.eudat.old.logic.managers.OrganisationsManager; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.dmp.Organisation; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.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; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api"}) +public class Organisations extends BaseController { + + private OrganisationsManager organisationsManager; + private ApiContext apiContext; + + @Autowired + public Organisations(ApiContext apiContext, OrganisationsManager organisationsManager) { + super(apiContext); + this.organisationsManager = organisationsManager; + } + + @RequestMapping(method = RequestMethod.GET, value = {"/external/organisations"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> listExternalOrganisations( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type + ) throws HugeResultSet, NoURLFound { + List organisations = organisationsManager.getCriteriaWithExternal(query, type); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(organisations).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/general/organisations"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> listGeneralOrganisations(@RequestBody OrganisationsTableRequest organisationsTableRequest, Principal principal) throws Exception { + List organisations = organisationsManager.getWithExternal(organisationsTableRequest, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(organisations).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/internal/organisations"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> getPaged(@Valid @RequestBody OrganisationsTableRequest organisationsTableRequest, Principal principal) throws Exception{ + DataTableData organisationDataTableData = this.organisationsManager.getPagedOrganisations(organisationsTableRequest, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(organisationDataTableData).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/public/organisations"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> getPublicPaged(@Valid @RequestBody OrganisationsTableRequest organisationsTableRequest) throws Exception{ + DataTableData organisationDataTableData = this.organisationsManager.getPublicPagedOrganisations(organisationsTableRequest); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(organisationDataTableData).status(ApiMessageCode.NO_MESSAGE)); + } +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Prefillings.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Prefillings.java new file mode 100644 index 000000000..940e54e2f --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Prefillings.java @@ -0,0 +1,46 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.PrefillingManager; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.prefilling.Prefilling; +import eu.eudat.old.models.data.datasetwizard.DatasetWizardModel; +import eu.eudat.old.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 java.util.List; +import java.util.Map; +import java.util.UUID; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api"}) +public class Prefillings { + + private final PrefillingManager prefillingManager; + + @Autowired + public Prefillings(PrefillingManager prefillingManager) { + this.prefillingManager = prefillingManager; + } + + @RequestMapping(method = RequestMethod.GET, value = {"/prefilling/list"}, produces = "application/json") + public ResponseEntity>> getPrefillingList(@RequestParam String like) { + List prefillingList = prefillingManager.getPrefillings(like); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(prefillingList).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/prefilling/generate/{id}"}, produces = "application/json") + public ResponseEntity> getPrefillingDataset(@PathVariable String id, @RequestParam String configId, @RequestParam UUID profileId) throws Exception { + DatasetWizardModel datasetWizardModel = prefillingManager.getPrefilledDataset(id, configId, profileId); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(datasetWizardModel).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/prefilling/generateUsingData"}, produces = "application/json") + public ResponseEntity> getPrefillingDataset(@RequestBody Map data, @RequestParam String configId, @RequestParam UUID profileId) throws Exception { + DatasetWizardModel datasetWizardModel = prefillingManager.getPrefilledDatasetUsingData(data, configId, profileId); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(datasetWizardModel).status(ApiMessageCode.NO_MESSAGE)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Projects.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Projects.java new file mode 100644 index 000000000..d91f754d9 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Projects.java @@ -0,0 +1,37 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.data.query.items.item.project.ProjectCriteriaRequest; +import eu.eudat.old.logic.managers.ProjectManager; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.project.Project; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/projects/"}) +public class Projects extends BaseController { + private ProjectManager projectManager; + + @Autowired + public Projects(ApiContext apiContext, ProjectManager projectManager) { + super(apiContext); + this.projectManager = projectManager; + } + + @RequestMapping(method = RequestMethod.POST, value = {"/external"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getWithExternal(@RequestBody ProjectCriteriaRequest projectCriteria, Principal principal) throws NoURLFound, InstantiationException, HugeResultSet, IllegalAccessException { + List dataTable = this.projectManager.getCriteriaWithExternal(projectCriteria, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/PubRepositoriesController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/PubRepositoriesController.java new file mode 100644 index 000000000..5ad1ecf74 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/PubRepositoriesController.java @@ -0,0 +1,43 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.DataRepositoryManager; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.datarepository.DataRepositoryModel; +import eu.eudat.old.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 java.util.List; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/external/pubrepos"}) +public class PubRepositoriesController extends BaseController { + + private DataRepositoryManager dataRepositoryManager; + + @Autowired + public PubRepositoriesController(ApiContext apiContext, DataRepositoryManager dataRepositoryManager) { + super(apiContext); + this.dataRepositoryManager = dataRepositoryManager; + } + + @RequestMapping(method = RequestMethod.GET, produces = "application/json") + public @ResponseBody + ResponseEntity>> listExternalDataRepositories( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal + ) throws HugeResultSet, NoURLFound { + List dataRepositoryModels = this.dataRepositoryManager.getPubRepositories(query, type, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataRepositoryModels)); + } + + +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/PublicController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/PublicController.java new file mode 100644 index 000000000..88e079d31 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/PublicController.java @@ -0,0 +1,32 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.data.entities.Project; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/public/projects/"}) +public class PublicController { + + private ApiContext apiContext; + + @GetMapping("all") + public ResponseEntity>> getProjects() { + + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getProjectDao().asQueryable(); + + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(items.toList()).status(ApiMessageCode.NO_MESSAGE)); + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/PublicationsController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/PublicationsController.java new file mode 100644 index 000000000..7574025d3 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/PublicationsController.java @@ -0,0 +1,41 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.logic.managers.PublicationManager; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.publication.PublicationModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.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 java.util.List; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/external/publications"}) +public class PublicationsController extends BaseController { + + private PublicationManager publicationManager; + + @Autowired + public PublicationsController(ApiContext apiContext, PublicationManager publicationManager) { + super(apiContext); + this.publicationManager = publicationManager; + } + + @RequestMapping(method = RequestMethod.GET, produces = "application/json") + public @ResponseBody + ResponseEntity>> listExternalPublications( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal + ) throws HugeResultSet, NoURLFound { + List publicationModels = this.publicationManager.getPublications(query, type); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(publicationModels)); + } +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/QuickWizardController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/QuickWizardController.java new file mode 100644 index 000000000..437d3f5f4 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/QuickWizardController.java @@ -0,0 +1,111 @@ +package eu.eudat.old.controllers; + + +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.quickwizard.DatasetDescriptionQuickWizardModel; +import eu.eudat.old.models.data.quickwizard.QuickWizardModel; +import eu.eudat.old.data.entities.Funder; +import eu.eudat.old.data.entities.Project; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.Grant; +import eu.eudat.old.logic.managers.DatasetManager; +import eu.eudat.old.logic.managers.QuickWizardManager; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.datasetwizard.DatasetWizardModel; +import eu.eudat.old.models.data.dmp.DataManagementPlan; +import eu.eudat.old.models.data.quickwizard.DatasetCreateWizardModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.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.transaction.Transactional; +import javax.validation.Valid; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/quick-wizard/"}) +public class QuickWizardController extends BaseController { + + private QuickWizardManager quickWizardManager; + private DatasetManager datasetManager; + + @Autowired + public QuickWizardController(ApiContext apiContext, QuickWizardManager quickWizardManager, DatasetManager datasetManager) { + super(apiContext); + this.quickWizardManager = quickWizardManager; + this.datasetManager = datasetManager; + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> addQuickWizardModel(@Valid @RequestBody QuickWizardModel quickWizard, Principal principal) throws Exception { + + Funder funderEntity; + //Create Funder + if (quickWizard.getFunder() == null) { + funderEntity = null; + } else if (quickWizard.getFunder().getExistFunder() == null && quickWizard.getFunder().getLabel() == null) { + funderEntity = null; + } else if (quickWizard.getFunder().getExistFunder() == null && quickWizard.getFunder().getLabel() != null) { + funderEntity = this.quickWizardManager.createOrUpdate(quickWizard.getFunder().toDataFunder(), principal); + } else { + funderEntity = quickWizard.getFunder().getExistFunder().toDataModel(); + } + + Grant grantEntity; + //Create Grant + if (quickWizard.getGrant() == null) { + grantEntity = null; + } else if (quickWizard.getGrant().getExistGrant() == null && quickWizard.getGrant().getLabel() == null) { + grantEntity = null; + } else if (quickWizard.getGrant().getExistGrant() == null) { + grantEntity = this.quickWizardManager.createOrUpdate(quickWizard.getGrant().toDataGrant(), principal); + } else { + grantEntity = quickWizard.getGrant().getExistGrant().toDataModel(); + } + + Project projectEntity; + //Create Project + if (quickWizard.getProject().getExistProject() == null + && quickWizard.getProject().getLabel() == null) { + projectEntity = null; + } else if (quickWizard.getProject().getExistProject() == null && quickWizard.getProject().getLabel() != null) { + projectEntity = this.quickWizardManager.createOrUpdate(quickWizard.getProject().toDataProject(), principal); + } else { + projectEntity = quickWizard.getProject().getExistProject().toDataModel(); + } + + //Create Dmp + DataManagementPlan dataManagementPlan = quickWizard.getDmp().toDataDmp(grantEntity, projectEntity, principal); + DMP dmpEntity = this.quickWizardManager.createOrUpdate(dataManagementPlan, funderEntity, principal); + + //Create Datasets + quickWizard.getDmp().setId(dmpEntity.getId()); + for (DatasetDescriptionQuickWizardModel dataset : quickWizard.getDatasets().getDatasetsList()) { + DataManagementPlan dmp = quickWizard.getDmp().toDataDmp(grantEntity, projectEntity, principal); + DescriptionTemplate profile = quickWizard.getDmp().getDatasetProfile(); + DatasetWizardModel datasetWizardModel = dataset.toDataModel(dmp, profile); + this.datasetManager.createOrUpdate(datasetWizardModel, principal); + } + + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/datasetcreate"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> addDatasetWizard(@RequestBody DatasetCreateWizardModel datasetCreateWizardModel, Principal principal) throws Exception{ + for(DatasetDescriptionQuickWizardModel dataset : datasetCreateWizardModel.getDatasets().getDatasetsList()){ + DescriptionTemplate profile = new DescriptionTemplate(); + profile.setId(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getId()); + profile.setLabel(datasetCreateWizardModel.getDmpMeta().getDatasetProfile().getLabel()); + this.datasetManager.createOrUpdate(dataset.toDataModel(datasetCreateWizardModel.getDmpMeta().getDmp(), profile), principal); + } + + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Dataset added!")); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Registries.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Registries.java new file mode 100644 index 000000000..1fd21f395 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Registries.java @@ -0,0 +1,51 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.data.entities.Registry; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.registries.RegistryModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.logic.managers.RegistryManager; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api"}) +public class Registries extends BaseController { + + private RegistryManager registryManager; + + @Autowired + public Registries(ApiContext apiContext, RegistryManager registryManager) { + super(apiContext); + this.registryManager = registryManager; + } + + @RequestMapping(method = RequestMethod.GET, value = {"/external/registries"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> listExternalRegistries(@RequestParam(value = "query", required = false) String query + , @RequestParam(value = "type", required = false) String type, Principal principal) throws HugeResultSet, NoURLFound { + List registryModels = this.registryManager.getRegistries(query, type, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(registryModels).status(ApiMessageCode.NO_MESSAGE)); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/registries"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> create(@RequestBody RegistryModel registryModel, Principal principal) throws Exception { + Registry registry = this.registryManager.create(registryModel, principal); + RegistryModel registryModel1 = new RegistryModel().fromDataModel(registry); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(registryModel1).status(ApiMessageCode.SUCCESS_MESSAGE)); + } +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Researchers.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Researchers.java new file mode 100644 index 000000000..75baabd01 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Researchers.java @@ -0,0 +1,49 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.ResearcherManager; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.dmp.Researcher; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.data.query.items.item.researcher.ResearcherCriteriaRequest; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/researchers"}) + +public class Researchers extends BaseController { + + private ResearcherManager researcherManager; + @Autowired + public Researchers(ApiContext apiContext, ResearcherManager researcherManager) { + super(apiContext); + this.researcherManager = researcherManager; + } + + @RequestMapping(method = RequestMethod.POST, value = {"/getWithExternal"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getWithExternal(@RequestBody ResearcherCriteriaRequest researcherCriteriaRequest, Principal principal) throws HugeResultSet, NoURLFound { + List dataTable = this.researcherManager.getCriteriaWithExternal(researcherCriteriaRequest, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> create(@RequestBody eu.eudat.old.models.data.researcher.Researcher researcher, Principal principal) throws Exception { + this.researcherManager.create(researcher, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE)); + } + +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Saml2MetadataController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Saml2MetadataController.java new file mode 100644 index 000000000..0d02c0be1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Saml2MetadataController.java @@ -0,0 +1,79 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.saml2.Saml2ConfigurableProvider; +import eu.eudat.old.logic.security.validators.configurableProvider.Saml2SSOUtils; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.saml2.AuthnRequestModel; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.nio.charset.StandardCharsets; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/saml2/"}) +public class Saml2MetadataController extends BaseController { + + private final ConfigLoader configLoader; + + @Autowired + public Saml2MetadataController(ApiContext apiContext, ConfigLoader configLoader) { + super(apiContext); + this.configLoader = configLoader; + } + + @RequestMapping(method = RequestMethod.GET, value = {"metadata/{configurableProviderId}"}) + public @ResponseBody + ResponseEntity getMetadata(@PathVariable String configurableProviderId) { + Saml2ConfigurableProvider saml2ConfigurableProvider = (Saml2ConfigurableProvider) this.configLoader.getConfigurableProviders().getProviders().stream() + .filter(prov -> prov.getConfigurableLoginId().equals(configurableProviderId)) + .findFirst().orElse(null); + if (saml2ConfigurableProvider != null) { + try { + String metadataXml = Saml2SSOUtils.getMetadata(saml2ConfigurableProvider); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(metadataXml.length()); + responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); + responseHeaders.set("Content-Disposition", "attachment;filename=" + configurableProviderId + ".xml"); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + return new ResponseEntity<>(metadataXml.getBytes(StandardCharsets.UTF_8), + responseHeaders, + HttpStatus.OK); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to fetch metadata.")); + } + } + else { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to fetch metadata.")); + } + } + @RequestMapping(method = RequestMethod.GET, value = {"authnRequest/{configurableProviderId}"}) + public @ResponseBody + ResponseEntity getAuthnRequest(@PathVariable String configurableProviderId) { + Saml2ConfigurableProvider saml2ConfigurableProvider = (Saml2ConfigurableProvider) this.configLoader.getConfigurableProviders().getProviders().stream() + .filter(prov -> prov.getConfigurableLoginId().equals(configurableProviderId)) + .findFirst().orElse(null); + if (saml2ConfigurableProvider != null) { + try { + AuthnRequestModel authnRequest = Saml2SSOUtils.getAuthnRequest(saml2ConfigurableProvider); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(authnRequest)); + } + catch (Exception e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to create authentication request.")); + } + + } + else { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("Unknown provider.")); + } + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Saml2PostBinding.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Saml2PostBinding.java new file mode 100644 index 000000000..579e6d060 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Saml2PostBinding.java @@ -0,0 +1,52 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.models.data.principal.PrincipalModel; +import eu.eudat.old.logic.security.CustomAuthenticationProvider; +import eu.eudat.old.logic.security.validators.TokenValidatorFactoryImpl; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.login.LoginInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/auth/saml2"}) +public class Saml2PostBinding extends BaseController { + + private CustomAuthenticationProvider customAuthenticationProvider; + + @Autowired + public Saml2PostBinding(ApiContext apiContext, CustomAuthenticationProvider customAuthenticationProvider) { + super(apiContext); + this.customAuthenticationProvider = customAuthenticationProvider; + } + + @RequestMapping(method = RequestMethod.POST, value = {"/postBinding"}, consumes = "application/x-www-form-urlencoded") + public @ResponseBody + ResponseEntity verify(@RequestParam(value = "SAMLResponse") String SAMLResponse, @RequestParam(value = "RelayState") String RelayState) throws GeneralSecurityException { + + Map map = Arrays.stream(RelayState.split("&")).map(s -> s.split("=")).collect(Collectors.toMap(e -> e[0], e -> e[1])); + + LoginInfo loginInfo = new LoginInfo(); + loginInfo.setTicket(SAMLResponse); + loginInfo.setProvider(TokenValidatorFactoryImpl.LoginProvider.CONFIGURABLE.getValue()); + Map providerId = new HashMap<>(); + providerId.put("configurableLoginId", map.get("configurableLoginId")); + loginInfo.setData(providerId); + + PrincipalModel principal = this.customAuthenticationProvider.authenticate(loginInfo); + + return ResponseEntity.status(HttpStatus.FOUND).header(HttpHeaders.LOCATION, "http://localhost:4200/login/external/saml?token=" + principal.getToken().toString()).build(); + + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Services.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Services.java new file mode 100644 index 000000000..0f7b3f16b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Services.java @@ -0,0 +1,52 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.data.entities.Service; +import eu.eudat.old.logic.managers.ServiceManager; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.services.ServiceModel; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api"}) +public class Services extends BaseController { + + private ServiceManager serviceManager; + + @Autowired + public Services(ApiContext apiContext, ServiceManager serviceManager) { + super(apiContext); + this.serviceManager = serviceManager; + } + + @RequestMapping(method = RequestMethod.GET, value = {"/external/services"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> listExternalServices( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal + ) throws HugeResultSet, NoURLFound { + List serviceModels = this.serviceManager.getServices(query, type, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(serviceModels).status(ApiMessageCode.NO_MESSAGE)); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/services"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> create(@RequestBody ServiceModel serviceModel, Principal principal) throws Exception { + Service service = serviceManager.create(serviceModel, principal); + ServiceModel serviceModel1 = new ServiceModel().fromDataModel(service); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(serviceModel1).status(ApiMessageCode.SUCCESS_MESSAGE)); + } +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/TagController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/TagController.java new file mode 100644 index 000000000..acaf616ad --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/TagController.java @@ -0,0 +1,59 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.elastic.criteria.DatasetCriteria; +import eu.eudat.old.elastic.entities.Dataset; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.logic.utilities.helpers.StreamDistinctBy; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.elastic.entities.Tag; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.stream.Collectors; + +/** + * Created by ikalyvas on 7/5/2018. + */ +@RestController +@CrossOrigin +@RequestMapping(value = {"/api"}) +public class TagController extends BaseController { + +// private Repository datasetRepository; + private Environment environment; + + @Autowired + public TagController(ApiContext apiContext, /*Repository tagRepository, */Environment environment) { + super(apiContext); +// this.datasetRepository = tagRepository; + this.environment = environment; + } + + @RequestMapping(method = RequestMethod.GET, value = {"/external/tags"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> listExternalTagModel( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type) throws HugeResultSet, NoURLFound, IOException, ExecutionException, InterruptedException { + //ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + /*List> remoteRepos = this.getApiContext().getOperationsContext().getRemoteFetcher().getTags(externalUrlCriteria, type); + TagExternalSourcesModel researchersExternalSourcesModel = new TagExternalSourcesModel().fromExternalItem(remoteRepos);*/ + if (this.getApiContext().getOperationsContext().getElasticRepository().getDatasetRepository().exists()) { + DatasetCriteria criteria = new DatasetCriteria(); + criteria.setHasTags(true); + List tags = this.getApiContext().getOperationsContext().getElasticRepository().getDatasetRepository().query(criteria).stream().map(Dataset::getTags).flatMap(Collection::stream).filter(StreamDistinctBy.distinctByKey(Tag::getId)).filter(tag -> tag.getName().toLowerCase().startsWith(query.toLowerCase())).collect(Collectors.toList()); + + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(tags).status(ApiMessageCode.NO_MESSAGE)); + } else { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ResponseItem>().status(ApiMessageCode.ERROR_MESSAGE).message("Elastic Services are not available")); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/TaxonomiesController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/TaxonomiesController.java new file mode 100644 index 000000000..1d312e305 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/TaxonomiesController.java @@ -0,0 +1,41 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.taxonomy.TaxonomyModel; +import eu.eudat.old.logic.managers.TaxonomyManager; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.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 java.util.List; + + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/external/taxonomies"}) +public class TaxonomiesController extends BaseController { + + private TaxonomyManager taxonomyManager; + + @Autowired + public TaxonomiesController(ApiContext apiContext, TaxonomyManager taxonomyManager) { + super(apiContext); + this.taxonomyManager = taxonomyManager; + } + + @RequestMapping(method = RequestMethod.GET, produces = "application/json") + public @ResponseBody + ResponseEntity>> listExternalPublications( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal + ) throws HugeResultSet, NoURLFound { + List taxonomyModels = this.taxonomyManager.getTaxonomies(query, type); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(taxonomyModels)); + } +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/TermsOfServiceController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/TermsOfServiceController.java new file mode 100644 index 000000000..7deb7e026 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/TermsOfServiceController.java @@ -0,0 +1,38 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.MaterialManager; +import eu.eudat.old.logic.managers.MetricsManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Objects; +import java.util.stream.Stream; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/material/termsofservice/"}) +public class TermsOfServiceController { + + private Environment environment; + private MaterialManager materialManager; + + @Autowired + public TermsOfServiceController(Environment environment, MaterialManager materialManager, MetricsManager metricsManager) { + this.environment = environment; + this.materialManager = materialManager; + } + + @RequestMapping(path = "{lang}", method = RequestMethod.GET ) + public ResponseEntity getTermsOfService(@PathVariable(name = "lang") String lang) throws IOException { + try (Stream paths = Files.walk(Paths.get(Objects.requireNonNull(this.environment.getProperty("termsofservice.path"))))) { + return this.materialManager.getResponseEntity(lang, paths); + } + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/UserGuideController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/UserGuideController.java new file mode 100644 index 000000000..61e4303e0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/UserGuideController.java @@ -0,0 +1,55 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.userguide.UserGuide; +import eu.eudat.old.logic.managers.MaterialManager; +import eu.eudat.old.logic.managers.MetricsManager; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Objects; +import java.util.stream.Stream; + +import static eu.eudat.old.types.Authorities.ADMIN; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api/userguide/"}) +public class UserGuideController { + + private Environment environment; + private MaterialManager materialManager; + + @Autowired + public UserGuideController(Environment environment, MaterialManager materialManager, MetricsManager metricsManager) { + this.environment = environment; + this.materialManager = materialManager; + } + + @RequestMapping(path = "{lang}", method = RequestMethod.GET ) + public ResponseEntity getUserGuide(@PathVariable(name = "lang") String lang) throws IOException { + try (Stream paths = Files.walk(Paths.get(Objects.requireNonNull(this.environment.getProperty("userguide.path"))))) { + return this.materialManager.getResponseEntity(lang, paths); + } + } + + @RequestMapping(value = "current", method = RequestMethod.POST) + public @ResponseBody + ResponseEntity> updateGuide(@RequestBody UserGuide guide, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { + String fileName = this.environment.getProperty("userguide.path") + guide.getName(); + OutputStream os = new FileOutputStream(fileName); + os.write(guide.getHtml().getBytes()); + os.close(); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Updated").payload("Updated")); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/UserInvitationController.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/UserInvitationController.java new file mode 100644 index 000000000..88349762f --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/UserInvitationController.java @@ -0,0 +1,59 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.data.query.items.item.userinfo.UserInfoRequestItem; +import eu.eudat.old.logic.managers.InvitationsManager; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.invitation.Invitation; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.userinfo.UserInfoInvitationModel; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import javax.xml.bind.JAXBException; +import java.io.IOException; +import java.util.List; +import java.util.UUID; + + +@RequestMapping("api/invite/") +@RestController +@CrossOrigin +public class UserInvitationController extends BaseController { + + private InvitationsManager invitationsManager; + @Autowired + 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> users(@RequestBody Invitation invitation, Principal principal) throws Exception { + this.invitationsManager.inviteUsers(invitation, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Users have beeen invited")); + } + + @Transactional + @RequestMapping(method = RequestMethod.GET, value = {"/exchange/{invitationID}"}, produces = "application/json") + public @ResponseBody + ResponseEntity> exchange(@PathVariable UUID invitationID, Principal principal) throws JAXBException, IOException { + UUID dmpId = invitationsManager.assignUserAcceptedInvitation(invitationID, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).payload(dmpId)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/getUsers"}, consumes = "application/json", produces = "application/json") + public @ResponseBody +// ResponseEntity>> getUsers(Principal principal) throws IllegalAccessException, InstantiationException { + ResponseEntity>> getUsers(Principal principal, @RequestBody UserInfoRequestItem userInfoRequestItem) throws IllegalAccessException, InstantiationException { +// List users = invitationsManager.getUsers(principal); + List users = invitationsManager.getUsersWithCriteria(principal, userInfoRequestItem); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.SUCCESS_MESSAGE).payload(users)); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Users.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Users.java new file mode 100644 index 000000000..6d31803cf --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Users.java @@ -0,0 +1,129 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.doi.DOIRequest; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.userinfo.UserCredential; +import eu.eudat.old.models.data.userinfo.UserListingModel; +import eu.eudat.old.models.data.userinfo.UserProfile; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.data.query.items.table.userinfo.UserInfoTableRequestItem; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.logic.managers.UserManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static eu.eudat.old.types.Authorities.ADMIN; + + +@RestController +@CrossOrigin +@RequestMapping(value = "api/user") +public class Users extends BaseController { + + private UserManager userManager; + @Autowired + 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>> getPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { + DataTableData dataTable = userManager.getPaged(userInfoTableRequestItem); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/updateRoles"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> updateRoles(@Valid @RequestBody UserListingModel userListingModel, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) { + userManager.editRoles(userListingModel); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity> get(@PathVariable String id, Principal principal) throws Exception { + UUID userId = id.equals("me") ? principal.getId() : UUID.fromString(id); + UserProfile user = userManager.getSingle(userId); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(user).status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/{id}/emails"}, produces = "application/json") + public @ResponseBody + ResponseEntity>> getEmails(@PathVariable String id, Principal principal) throws Exception { + UUID userId = id.equals("me") ? principal.getId() : UUID.fromString(id); + List user = userManager.getCredentials(userId); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(user).status(ApiMessageCode.NO_MESSAGE)); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/settings"}, produces = "application/json") + public @ResponseBody + ResponseEntity> saveSettings(@RequestBody Map settings, Principal principal) throws IOException { + userManager.updateSettings(settings, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/getCollaboratorsPaged"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity>> getCollaboratorsPaged(@Valid @RequestBody UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception { + DataTableData dataTable = userManager.getCollaboratorsPaged(userInfoTableRequestItem, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().payload(dataTable).status(ApiMessageCode.NO_MESSAGE)); + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"/registerDOIToken"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> registerDOIToken(@RequestBody DOIRequest doiRequest, Principal principal) throws NullEmailException, IOException { + userManager.registerDOIToken(doiRequest, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); + } + + @Transactional + @RequestMapping(method = RequestMethod.DELETE, value = {"/deleteDOIToken"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> deleteDOIToken(Principal principal) throws NullEmailException, IOException { + userManager.deleteDOIToken(principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"/getCsv"}) + public @ResponseBody + ResponseEntity exportCsv(@ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { + return userManager.exportToCsv(principal); + } + + @RequestMapping(method = RequestMethod.POST, value = {"/find"}, consumes = "application/json", produces = "application/json") + public @ResponseBody + ResponseEntity> find(@Valid @RequestBody String email) throws Exception { + UserProfile userProfile = userManager.getFromEmail(email); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(userProfile).status(ApiMessageCode.NO_MESSAGE)); + } + +} + + + + + + + + + + + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Validation.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Validation.java new file mode 100644 index 000000000..bd9d3bdc2 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/Validation.java @@ -0,0 +1,37 @@ +package eu.eudat.old.controllers; + +import eu.eudat.old.logic.managers.ValidationManager; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.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.*; + +@RestController +@CrossOrigin +@RequestMapping(value = {"/api"}) +public class Validation extends BaseController { + + private ValidationManager validationManager; + + @Autowired + public Validation(ApiContext apiContext, ValidationManager validationManager) { + super(apiContext); + this.validationManager = validationManager; + } + + @RequestMapping(method = RequestMethod.GET, value = {"/external/validation"}, produces = "application/json") + public @ResponseBody + ResponseEntity> validate( + @RequestParam(value = "query", required = false) String query, @RequestParam(value = "type", required = false) String type, Principal principal + ) throws HugeResultSet, NoURLFound { + Boolean isValid = this.validationManager.validateIdentifier(query, type, principal); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().payload(isValid).status(ApiMessageCode.NO_MESSAGE)); + } +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerErrorHandler.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerErrorHandler.java new file mode 100644 index 000000000..ea9751b3d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerErrorHandler.java @@ -0,0 +1,31 @@ +package eu.eudat.old.controllers.controllerhandler; + + +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.types.ApiMessageCode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +import javax.annotation.Priority; + +/** + * Created by ikalyvas on 6/12/2018. + */ +@ControllerAdvice +@Priority(5) +public class ControllerErrorHandler { + private static final Logger logger = LoggerFactory.getLogger(ControllerErrorHandler.class); + + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ResponseBody + public ResponseItem processValidationError(Exception ex) throws Exception { + logger.error(ex.getMessage(), ex); + return new ResponseItem().message(ex.getMessage()).status(ApiMessageCode.DEFAULT_ERROR_MESSAGE); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerUnauthorisedHandler.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerUnauthorisedHandler.java new file mode 100644 index 000000000..477933f92 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerUnauthorisedHandler.java @@ -0,0 +1,34 @@ +package eu.eudat.old.controllers.controllerhandler; + +import eu.eudat.old.exceptions.security.UnauthorisedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +import javax.annotation.Priority; + +/** + * Created by ikalyvas on 6/12/2018. + */ +@ControllerAdvice +@Priority(4) +public class ControllerUnauthorisedHandler { + private static final Logger logger = LoggerFactory.getLogger(ControllerUnauthorisedHandler.class); + + @Autowired + public ControllerUnauthorisedHandler() { + } + + @ExceptionHandler(UnauthorisedException.class) + @ResponseStatus(HttpStatus.UNAUTHORIZED) + @ResponseBody + public void processValidationError(UnauthorisedException ex) { + logger.error(ex.getMessage(), ex); + return; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerUserNullEmailHandler.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerUserNullEmailHandler.java new file mode 100644 index 000000000..669a3b9b1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerUserNullEmailHandler.java @@ -0,0 +1,18 @@ +package eu.eudat.old.controllers.controllerhandler; + +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.types.ApiMessageCode; +import org.springframework.core.annotation.Order; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@ControllerAdvice +@Order(2) +public class ControllerUserNullEmailHandler { + + @ExceptionHandler(NullEmailException.class) + public ResponseEntity nullEmailException(Exception ex) throws Exception { + return ResponseEntity.status(ApiMessageCode.NULL_EMAIL.getValue()).body(""); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerValidatorErrorHandler.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerValidatorErrorHandler.java new file mode 100644 index 000000000..9ad830ec7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/controllerhandler/ControllerValidatorErrorHandler.java @@ -0,0 +1,66 @@ +package eu.eudat.old.controllers.controllerhandler; + +import eu.eudat.old.models.data.helpers.responses.ResponseItem; +import eu.eudat.old.types.ApiMessageCode; +import eu.eudat.old.models.data.errormodels.ValidationErrorContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.validation.BindingResult; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +import java.util.List; +import java.util.Locale; + + +@ControllerAdvice +@Order(3) +public class ControllerValidatorErrorHandler { + + private MessageSource messageSource; + + @Autowired + public ControllerValidatorErrorHandler(MessageSource messageSource) { + this.messageSource = messageSource; + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ResponseBody + public ResponseItem processValidationError(MethodArgumentNotValidException ex) { + BindingResult result = ex.getBindingResult(); + List fieldErrors = result.getFieldErrors(); + + return processFieldErrors(fieldErrors); + } + + private ResponseItem processFieldErrors(List fieldErrors) { + ValidationErrorContext dto = new ValidationErrorContext(); + + for (FieldError fieldError : fieldErrors) { + String localizedErrorMessage = resolveLocalizedErrorMessage(fieldError); + dto.addFieldError(fieldError.getField(), localizedErrorMessage); + } + + return new ResponseItem().status(ApiMessageCode.VALIDATION_MESSAGE).payload(dto); + } + + private String resolveLocalizedErrorMessage(FieldError fieldError) { + Locale currentLocale = LocaleContextHolder.getLocale(); + String localizedErrorMessage = messageSource.getMessage(fieldError, currentLocale); + + if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) { + String[] fieldErrorCodes = fieldError.getCodes(); + localizedErrorMessage = fieldErrorCodes[0]; + } + + return localizedErrorMessage; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/interceptors/RequestInterceptor.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/interceptors/RequestInterceptor.java new file mode 100644 index 000000000..d35e61012 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/controllers/interceptors/RequestInterceptor.java @@ -0,0 +1,32 @@ +package eu.eudat.old.controllers.interceptors; + +import eu.eudat.old.types.WarningLevel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Date; + +/** + * Created by ikalyvas on 3/1/2018. + */ +@Component +public class RequestInterceptor extends HandlerInterceptorAdapter { + private static final Logger logger = LoggerFactory.getLogger(RequestInterceptor.class); + + @Autowired + public RequestInterceptor() { + } + + @Override + public boolean preHandle(HttpServletRequest request, + HttpServletResponse response, Object handler) throws Exception { + String reqUri = request.getRequestURI(); + logger.info("Call to " + reqUri + " method: " + request.getMethod() + " at: " + new Date(), WarningLevel.INFO); + return super.preHandle(request, response, handler); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/DMPCriteria.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/DMPCriteria.java new file mode 100644 index 000000000..8d52726ce --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/DMPCriteria.java @@ -0,0 +1,150 @@ +package eu.eudat.old.criteria; + +import eu.eudat.old.criteria.entities.Criteria; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.criteria.entities.DateCriteria; +import eu.eudat.old.query.DMPQuery; + +import java.util.*; + +public class DMPCriteria { + private Criteria id; + private Criteria groupId; + private Criteria label; + private Criteria version; + private GrantCriteria grant; + private DateCriteria created; + private DateCriteria modified; + private UserCriteria creator; + private DatasetCriteria dataset; + + public Criteria getId() { + return id; + } + + public void setId(Criteria id) { + this.id = id; + } + + public void setId(String id) { + Criteria criteria = new Criteria<>(); + criteria.setAs(id); + this.id = criteria; + } + + public Criteria getGroupId() { + return groupId; + } + + public void setGroupId(Criteria groupId) { + this.groupId = groupId; + } + + public void setGroupId(String groupId) { + Criteria criteria = new Criteria<>(); + criteria.setAs(groupId); + this.groupId = criteria; + } + + public Criteria getLabel() { + return label; + } + + public void setLabel(Criteria label) { + this.label = label; + } + + public void setLabel(String label) { + Criteria criteria = new Criteria<>(); + criteria.setAs(label); + this.label = criteria; + } + + public Criteria getVersion() { + return version; + } + + public void setVersion(Criteria version) { + this.version = version; + } + + public void setVersion(String version) { + Criteria criteria = new Criteria<>(); + criteria.setAs(version); + this.version = criteria; + } + + public GrantCriteria getGrant() { + return grant; + } + + public void setGrant(GrantCriteria grant) { + this.grant = grant; + } + + public DateCriteria getCreated() { + return created; + } + + public void setCreated(DateCriteria created) { + this.created = created; + } + + public void setCreated(String created) { + DateCriteria criteria = new DateCriteria(); + criteria.setAs(created); + this.created = criteria; + } + + public DateCriteria getModified() { + return modified; + } + + public void setModified(DateCriteria modified) { + this.modified = modified; + } + + public void setModified(String modified) { + DateCriteria criteria = new DateCriteria(); + criteria.setAs(modified); + this.modified = criteria; + } + + public UserCriteria getCreator() { + return creator; + } + + public void setCreator(UserCriteria creator) { + this.creator = creator; + } + + public DatasetCriteria getDataset() { + return dataset; + } + + public void setDataset(DatasetCriteria dataset) { + this.dataset = dataset; + } + + protected List buildFields(String path) { + Set fields = new LinkedHashSet<>(); + path = path != null && !path.isEmpty() ? path + "." : ""; + if (this.id != null) fields.add(path + this.id.getAs()); + if (this.label != null) fields.add(path + this.label.getAs()); + if (this.grant != null) fields.addAll(this.grant.buildFields(path + "grant")); + if (this.creator != null) fields.addAll(this.creator.buildFields(path + "creator")); + if (this.dataset != null) fields.addAll(this.dataset.buildFields(path + "dataset")); + if (!fields.contains(path + "id")) fields.add(path + "id"); + return new LinkedList<>(fields); + } + + public DMPQuery buildQuery(DatabaseRepository dao) { + List fields = this.buildFields(""); + DMPQuery dmpQuery = new DMPQuery(dao.getDmpDao(), fields); + if (this.id != null) dmpQuery.setId(this.id.getValue()); + if (this.grant != null) dmpQuery.setGrantQuery(this.grant.buildQuery(dao)); + if (this.creator != null) dmpQuery.setUserQuery(this.creator.buildQuery(dao)); + if (this.dataset != null) dmpQuery.setDatasetQuery(this.dataset.buildQuery(dao)); + return dmpQuery; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/DatasetCriteria.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/DatasetCriteria.java new file mode 100644 index 000000000..a15fa77f4 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/DatasetCriteria.java @@ -0,0 +1,77 @@ +package eu.eudat.old.criteria; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.node.JsonNodeType; +import eu.eudat.old.criteria.entities.Criteria; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.query.DatasetQuery; + +import java.io.IOException; +import java.util.*; + +public class DatasetCriteria { + private Criteria id; + private Criteria label; + private DMPCriteria dmp; + + public Criteria getId() { + return id; + } + + public void setId(JsonNode jsonNode) throws IOException { + if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) { + Criteria criteria = new Criteria<>(); + criteria.setAs(jsonNode.asText()); + this.id = criteria; + } else if (jsonNode.getNodeType().equals(JsonNodeType.OBJECT)) { + ObjectReader reader = new ObjectMapper().readerFor(new TypeReference>() { + }); + this.id = reader.readValue(jsonNode); + } + } + + public Criteria getLabel() { + return label; + } + + public void setLabel(JsonNode jsonNode) throws IOException { + if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) { + Criteria criteria = new Criteria<>(); + criteria.setAs(jsonNode.asText()); + this.label = criteria; + } else if (jsonNode.getNodeType().equals(JsonNodeType.OBJECT)) { + ObjectReader reader = new ObjectMapper().readerFor(new TypeReference>() { + }); + this.label = reader.readValue(jsonNode); + } + } + + public DMPCriteria getDmp() { + return dmp; + } + + public void setDmp(DMPCriteria dmp) { + this.dmp = dmp; + } + + protected List buildFields(String path) { + Set fields = new HashSet<>(); + path = path != null && !path.isEmpty() ? path + "." : ""; + if (this.id != null) fields.add(path + this.id.getAs()); + if (this.label != null) fields.add(path + this.label.getAs()); + if (this.dmp != null) fields.addAll(this.dmp.buildFields(path + "dmp")); + if (!fields.contains(path + "id")) fields.add(path + "id"); + return new LinkedList<>(fields); + } + + public DatasetQuery buildQuery(DatabaseRepository dao) { + List fields = this.buildFields(""); + DatasetQuery datasetQuery = new DatasetQuery(dao.getDatasetDao(), fields); + if (this.id != null) datasetQuery.setId(this.id.getValue()); + if (this.dmp != null) datasetQuery.setDmpQuery(this.dmp.buildQuery(dao)); + return datasetQuery; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/GrantCriteria.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/GrantCriteria.java new file mode 100644 index 000000000..ef63077d3 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/GrantCriteria.java @@ -0,0 +1,110 @@ +package eu.eudat.old.criteria; + +import eu.eudat.old.criteria.entities.Criteria; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.criteria.entities.DateCriteria; +import eu.eudat.old.query.GrantQuery; + +import java.util.*; + +public class GrantCriteria { + private Criteria id; + private List ids; + private Criteria label; + private List statuses; + private DateCriteria created; + private DateCriteria modified; + private UserCriteria creator; + + public Criteria getId() { + return id; + } + + public void setId(Criteria id) { + this.id = id; + } + + public List getIds() { + return ids; + } + + public void setIds(List ids) { + this.ids = ids; + } + + public Criteria getLabel() { + return label; + } + + public void setLabel(Criteria label) { + this.label = label; + } + + public void setLabel(String label) { + Criteria criteria = new Criteria<>(); + criteria.setAs(label); + this.label = criteria; + } + + public List getStatuses() { + return statuses; + } + + public void setStatuses(List statuses) { + this.statuses = statuses; + } + + public DateCriteria getCreated() { + return created; + } + + public void setCreated(DateCriteria created) { + this.created = created; + } + + public void setCreated(String created) { + DateCriteria criteria = new DateCriteria(); + criteria.setAs(created); + this.created = criteria; + } + + public DateCriteria getModified() { + return modified; + } + + public void setModified(DateCriteria modified) { + this.modified = modified; + } + + public void setModified(String modified) { + DateCriteria criteria = new DateCriteria(); + criteria.setAs(modified); + this.modified = criteria; + } + + public UserCriteria getCreator() { + return creator; + } + + public void setCreator(UserCriteria creator) { + this.creator = creator; + } + + protected List buildFields(String path) { + Set fields = new LinkedHashSet<>(); + path = path != null && !path.isEmpty() ? path + "." : ""; + if (this.id != null) fields.add(path + this.id.getAs()); + if (this.label != null) fields.add(path + this.label.getAs()); + if (!fields.contains(path + "id")) fields.add(path + "id"); + if (this.creator != null) fields.addAll(this.creator.buildFields(path + "creationUser")); + return new LinkedList<>(fields); + } + + public GrantQuery buildQuery(DatabaseRepository dao) { + List fields = this.buildFields(""); + GrantQuery query = new GrantQuery(dao.getGrantDao(), fields); + query.setId(this.id.getValue()); + if (this.creator != null) query.setUserQuery(this.creator.buildQuery(dao)); + return query; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/RecentActivityCriteria.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/RecentActivityCriteria.java new file mode 100644 index 000000000..7c57db499 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/RecentActivityCriteria.java @@ -0,0 +1,31 @@ +package eu.eudat.old.criteria; + +public class RecentActivityCriteria { + private String like; + private String order; + private Integer status; + + public String getLike() { + return like; + } + + public void setLike(String like) { + this.like = like; + } + + public String getOrder() { + return order; + } + + public void setOrder(String order) { + this.order = order; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/UserCriteria.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/UserCriteria.java new file mode 100644 index 000000000..c09653047 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/UserCriteria.java @@ -0,0 +1,66 @@ +package eu.eudat.old.criteria; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.node.JsonNodeType; +import eu.eudat.old.criteria.entities.Criteria; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.query.UserQuery; + +import java.io.IOException; +import java.util.*; + +public class UserCriteria { + private Criteria id; + private Criteria email; + + public Criteria getId() { + return id; + } + + public void setId(JsonNode jsonNode) throws IOException { + if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) { + Criteria criteria = new Criteria<>(); + criteria.setAs(jsonNode.asText()); + this.id = criteria; + } else if (jsonNode.getNodeType().equals(JsonNodeType.OBJECT)) { + ObjectReader reader = new ObjectMapper().readerFor(new TypeReference>() { + }); + this.id = reader.readValue(jsonNode); + } + } + + public Criteria getEmail() { + return email; + } + + public void setEmail(JsonNode jsonNode) throws IOException { + if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) { + Criteria criteria = new Criteria<>(); + criteria.setAs(jsonNode.asText()); + this.email = criteria; + } else if (jsonNode.getNodeType().equals(JsonNodeType.OBJECT)) { + ObjectReader reader = new ObjectMapper().readerFor(new TypeReference>() { + }); + this.email = reader.readValue(jsonNode); + } + } + + protected List buildFields(String path) { + Set fields = new LinkedHashSet<>(); + path = path != null && !path.isEmpty() ? path + "." : ""; + if (this.id != null) fields.add(path + this.id.getAs()); + if (this.email != null) fields.add(path + this.email.getAs()); + if (!fields.contains(path + "id")) fields.add(path + "id"); + return new LinkedList<>(fields); + } + + public UserQuery buildQuery(DatabaseRepository dao) { + List fields = this.buildFields(""); + UserQuery query = new UserQuery(dao.getUserInfoDao(), fields); + if (this.id != null) query.setId(this.id.getValue()); + return query; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/entities/Criteria.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/entities/Criteria.java new file mode 100644 index 000000000..5f91d2417 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/entities/Criteria.java @@ -0,0 +1,36 @@ +package eu.eudat.old.criteria.entities; + +enum BaseCriteriaType implements CriteriaType { + EQUALS, + NOT_EQUALS +} + +public class Criteria { + private String as; + private BaseCriteriaType type; + private T value; + + public String getAs() { + return as; + } + + public void setAs(String as) { + this.as = as; + } + + public CriteriaType getType() { + return type; + } + + public void setType(BaseCriteriaType type) { + this.type = type; + } + + public T getValue() { + return value; + } + + public void setValue(T value) { + this.value = value; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/entities/CriteriaType.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/entities/CriteriaType.java new file mode 100644 index 000000000..39ec5f330 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/entities/CriteriaType.java @@ -0,0 +1,4 @@ +package eu.eudat.old.criteria.entities; + +public interface CriteriaType { +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/entities/DateCriteria.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/entities/DateCriteria.java new file mode 100644 index 000000000..58f68b692 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/entities/DateCriteria.java @@ -0,0 +1,32 @@ +package eu.eudat.old.criteria.entities; + +import java.util.Date; + +enum DateCriteriaType implements CriteriaType { + EQUALS, + NOT_EQUALS, + BEFORE, + BETWEEN, + AFTER +} + +public class DateCriteria extends Criteria { + private Date values; + private CriteriaType type; + + public Date getValues() { + return values; + } + + public void setValues(Date values) { + this.values = values; + } + + public CriteriaType getType() { + return type; + } + + public void setType(DateCriteriaType type) { + this.type = type; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/serialzier/CriteriaSerializer.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/serialzier/CriteriaSerializer.java new file mode 100644 index 000000000..9b9ba37fa --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/criteria/serialzier/CriteriaSerializer.java @@ -0,0 +1,41 @@ +package eu.eudat.old.criteria.serialzier; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.deser.ContextualDeserializer; +import com.fasterxml.jackson.databind.node.JsonNodeType; +import eu.eudat.old.criteria.entities.Criteria; + +import java.io.IOException; + +public class CriteriaSerializer extends JsonDeserializer> implements ContextualDeserializer { + + private JavaType valueType; + + @Override + public JsonDeserializer createContextual(DeserializationContext ctxt, BeanProperty property) { + JavaType wrapperType = property.getType(); + JavaType valueType = wrapperType.containedType(0); + CriteriaSerializer deserializer = new CriteriaSerializer(); + deserializer.valueType = valueType; + return deserializer; + } + + @Override + public Criteria deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { + ObjectCodec oc = jp.getCodec(); + JsonNode jsonNode = oc.readTree(jp); + if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) { + Criteria criteria = new Criteria<>(); + criteria.setAs(jsonNode.asText()); + return criteria; + } else if (jsonNode.getNodeType().equals(JsonNodeType.OBJECT)) { + ObjectReader reader = new ObjectMapper().readerFor(new TypeReference>() { + }); + return reader.readValue(jsonNode); + } + return null; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datamanagementplan/DMPNewVersionException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datamanagementplan/DMPNewVersionException.java new file mode 100644 index 000000000..0074420f1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datamanagementplan/DMPNewVersionException.java @@ -0,0 +1,8 @@ +package eu.eudat.old.exceptions.datamanagementplan; + +public class DMPNewVersionException extends RuntimeException { + + public DMPNewVersionException(String message) { + super(message); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datamanagementplan/DMPWithDatasetsDeleteException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datamanagementplan/DMPWithDatasetsDeleteException.java new file mode 100644 index 000000000..6bfacb9a5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datamanagementplan/DMPWithDatasetsDeleteException.java @@ -0,0 +1,22 @@ +package eu.eudat.old.exceptions.datamanagementplan; + +/** + * Created by ikalyvas on 2/5/2018. + */ +public class DMPWithDatasetsDeleteException extends RuntimeException { + public DMPWithDatasetsDeleteException() { + super(); + } + + public DMPWithDatasetsDeleteException(String message, Throwable cause) { + super(message, cause); + } + + public DMPWithDatasetsDeleteException(String message) { + super(message); + } + + public DMPWithDatasetsDeleteException(Throwable cause) { + super(cause); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datasetprofile/DatasetProfileNewVersionException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datasetprofile/DatasetProfileNewVersionException.java new file mode 100644 index 000000000..5a44987a0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datasetprofile/DatasetProfileNewVersionException.java @@ -0,0 +1,9 @@ +package eu.eudat.old.exceptions.datasetprofile; + +public class DatasetProfileNewVersionException extends RuntimeException { + + public DatasetProfileNewVersionException(String message) { + super(message); + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datasetprofile/DatasetProfileWithDatasetsExeption.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datasetprofile/DatasetProfileWithDatasetsExeption.java new file mode 100644 index 000000000..d2c077ecf --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datasetprofile/DatasetProfileWithDatasetsExeption.java @@ -0,0 +1,19 @@ +package eu.eudat.old.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); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datasetwizard/DatasetWizardCannotUnlockException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datasetwizard/DatasetWizardCannotUnlockException.java new file mode 100644 index 000000000..f4d8afe10 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/datasetwizard/DatasetWizardCannotUnlockException.java @@ -0,0 +1,22 @@ +package eu.eudat.old.exceptions.datasetwizard; + +/** + * Created by ikalyvas on 10/12/2018. + */ +public class DatasetWizardCannotUnlockException extends RuntimeException { + public DatasetWizardCannotUnlockException() { + super(); + } + + public DatasetWizardCannotUnlockException(String message, Throwable cause) { + super(message, cause); + } + + public DatasetWizardCannotUnlockException(String message) { + super(message); + } + + public DatasetWizardCannotUnlockException(Throwable cause) { + super(cause); + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/descriptiontemplate/DescriptionTemplatesWithTypeException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/descriptiontemplate/DescriptionTemplatesWithTypeException.java new file mode 100644 index 000000000..04cdd45d2 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/descriptiontemplate/DescriptionTemplatesWithTypeException.java @@ -0,0 +1,9 @@ +package eu.eudat.old.exceptions.descriptiontemplate; + +public class DescriptionTemplatesWithTypeException extends RuntimeException { + + public DescriptionTemplatesWithTypeException(String message) { + super(message); + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/dmpblueprint/DmpBlueprintUsedException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/dmpblueprint/DmpBlueprintUsedException.java new file mode 100644 index 000000000..f36e4bac5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/dmpblueprint/DmpBlueprintUsedException.java @@ -0,0 +1,18 @@ +package eu.eudat.old.exceptions.dmpblueprint; + +public class DmpBlueprintUsedException extends RuntimeException { + public DmpBlueprintUsedException() { + } + + public DmpBlueprintUsedException(String message) { + super(message); + } + + public DmpBlueprintUsedException(String message, Throwable cause) { + super(message, cause); + } + + public DmpBlueprintUsedException(Throwable cause) { + super(cause); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/emailconfirmation/HasConfirmedEmailException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/emailconfirmation/HasConfirmedEmailException.java new file mode 100644 index 000000000..ada270f3d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/emailconfirmation/HasConfirmedEmailException.java @@ -0,0 +1,8 @@ +package eu.eudat.old.exceptions.emailconfirmation; + +public class HasConfirmedEmailException extends Exception { + + public HasConfirmedEmailException(String msg) { + super(msg); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/emailconfirmation/TokenExpiredException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/emailconfirmation/TokenExpiredException.java new file mode 100644 index 000000000..5aa84ec09 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/emailconfirmation/TokenExpiredException.java @@ -0,0 +1,8 @@ +package eu.eudat.old.exceptions.emailconfirmation; + +public class TokenExpiredException extends Exception { + + public TokenExpiredException(String msg) { + super(msg); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/files/TempFileNotFoundException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/files/TempFileNotFoundException.java new file mode 100644 index 000000000..15d979656 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/files/TempFileNotFoundException.java @@ -0,0 +1,22 @@ +package eu.eudat.old.exceptions.files; + +/** + * Created by ikalyvas on 3/16/2018. + */ +public class TempFileNotFoundException extends RuntimeException { + public TempFileNotFoundException() { + super(); + } + + public TempFileNotFoundException(String message, Throwable cause) { + super(message, cause); + } + + public TempFileNotFoundException(String message) { + super(message); + } + + public TempFileNotFoundException(Throwable cause) { + super(cause); + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/grant/GrantWithDMPsDeleteException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/grant/GrantWithDMPsDeleteException.java new file mode 100644 index 000000000..cdbe240fe --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/grant/GrantWithDMPsDeleteException.java @@ -0,0 +1,22 @@ +package eu.eudat.old.exceptions.grant; + +/** + * Created by ikalyvas on 11/30/2018. + */ +public class GrantWithDMPsDeleteException extends RuntimeException { + public GrantWithDMPsDeleteException() { + super(); + } + + public GrantWithDMPsDeleteException(String message, Throwable cause) { + super(message, cause); + } + + public GrantWithDMPsDeleteException(String message) { + super(message); + } + + public GrantWithDMPsDeleteException(Throwable cause) { + super(cause); + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/ExpiredTokenException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/ExpiredTokenException.java new file mode 100644 index 000000000..6aa6bd608 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/ExpiredTokenException.java @@ -0,0 +1,8 @@ +package eu.eudat.old.exceptions.security; + +public class ExpiredTokenException extends Exception { + + public ExpiredTokenException(String message) { + super(message); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/ForbiddenException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/ForbiddenException.java new file mode 100644 index 000000000..d729a94a1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/ForbiddenException.java @@ -0,0 +1,19 @@ +package eu.eudat.old.exceptions.security; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.FORBIDDEN) +public class ForbiddenException extends RuntimeException { + public ForbiddenException() { + super(); + } + + public ForbiddenException(String message) { + super(message); + } + + public ForbiddenException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/NonValidTokenException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/NonValidTokenException.java new file mode 100644 index 000000000..d5735891b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/NonValidTokenException.java @@ -0,0 +1,11 @@ +package eu.eudat.old.exceptions.security; + +public class NonValidTokenException extends Exception { + + private static final long serialVersionUID = -2834659827755141154L; + + public NonValidTokenException(String msg) { + super(msg); + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/NullEmailException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/NullEmailException.java new file mode 100644 index 000000000..1fd48d1aa --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/NullEmailException.java @@ -0,0 +1,8 @@ +package eu.eudat.old.exceptions.security; + +public class NullEmailException extends RuntimeException { + + public NullEmailException() { + super(); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/UnauthorisedException.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/UnauthorisedException.java new file mode 100644 index 000000000..ea062c947 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/exceptions/security/UnauthorisedException.java @@ -0,0 +1,24 @@ +package eu.eudat.old.exceptions.security; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + + +@ResponseStatus(value = HttpStatus.UNAUTHORIZED) +public class UnauthorisedException extends RuntimeException { + public UnauthorisedException() { + super(); + } + + public UnauthorisedException(String message, Throwable cause) { + super(message, cause); + } + + public UnauthorisedException(String message) { + super(message); + } + + public UnauthorisedException(Throwable cause) { + super(cause); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/Builder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/Builder.java new file mode 100644 index 000000000..1ff385959 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/Builder.java @@ -0,0 +1,8 @@ +package eu.eudat.old.logic.builders; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public abstract class Builder { + public abstract T build(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/BuilderFactory.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/BuilderFactory.java new file mode 100644 index 000000000..f25f3b518 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/BuilderFactory.java @@ -0,0 +1,8 @@ +package eu.eudat.old.logic.builders; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public interface BuilderFactory { + T getBuilder(Class tClass); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/BuilderFactoryImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/BuilderFactoryImpl.java new file mode 100644 index 000000000..ea9c8c0a0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/BuilderFactoryImpl.java @@ -0,0 +1,34 @@ +package eu.eudat.old.logic.builders; + +import eu.eudat.old.logic.builders.entity.*; +import eu.eudat.old.logic.builders.model.criteria.ExternalDatasetCriteriaBuilder; +import eu.eudat.old.logic.builders.model.models.*; +import eu.eudat.old.logic.builders.model.criteria.DataRepositoryCriteriaBuilder; +import eu.eudat.old.logic.builders.model.criteria.RegistryCriteriaBuilder; +import org.springframework.stereotype.Service; + + +@Service("builderFactory") +public class BuilderFactoryImpl implements BuilderFactory { + + public T getBuilder(Class tClass) { + if (tClass.equals(CredentialBuilder.class)) return (T) new CredentialBuilder(); + if (tClass.equals(DataRepositoryCriteriaBuilder.class)) return (T) new DataRepositoryCriteriaBuilder(); + if (tClass.equals(DatasetProfileBuilder.class)) return (T) new DatasetProfileBuilder(); + if (tClass.equals(DataTableDataBuilder.class)) return (T) new DataTableDataBuilder<>(); + if (tClass.equals(PrincipalBuilder.class)) return (T) new PrincipalBuilder(); + if (tClass.equals(GrantBuilder.class)) return (T) new GrantBuilder(); + if (tClass.equals(ProjectBuilder.class)) return (T) new ProjectBuilder(); + if (tClass.equals(FunderBuilder.class)) return (T) new FunderBuilder(); + if (tClass.equals(RegistryCriteriaBuilder.class)) return (T) new RegistryCriteriaBuilder(); + if (tClass.equals(UserInfoBuilder.class)) return (T) new UserInfoBuilder(); + if (tClass.equals(UserRoleBuilder.class)) return (T) new UserRoleBuilder(); + if (tClass.equals(UserTokenBuilder.class)) return (T) new UserTokenBuilder(); + if (tClass.equals(ResearcherBuilder.class)) return (T) new ResearcherBuilder(); + if (tClass.equals(ExternalDatasetCriteriaBuilder.class)) return (T) new ExternalDatasetCriteriaBuilder(); + if (tClass.equals(RecentActivityDataBuilder.class)) return (T) new RecentActivityDataBuilder(); + if (tClass.equals(OrganisationBuilder.class)) return (T) new OrganisationBuilder(); + + return null; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/ContentBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/ContentBuilder.java new file mode 100644 index 000000000..fd5fe769d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/ContentBuilder.java @@ -0,0 +1,90 @@ +package eu.eudat.old.logic.builders.entity; + +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.data.entities.Content; + +import java.util.UUID; + +/** + * Created by ikalyvas on 3/16/2018. + */ +public class ContentBuilder extends Builder { + + private UUID id; + + private String label; + + private String extension; + + private Integer parentType; + + private String uri; + + private Integer locationType; + + public UUID getId() { + return id; + } + + public ContentBuilder id(UUID id) { + this.id = id; + return this; + } + + public String getLabel() { + return label; + } + + public ContentBuilder label(String label) { + this.label = label; + return this; + } + + public String getExtension() { + return extension; + } + + public ContentBuilder extension(String extension) { + this.extension = extension; + return this; + } + + public Integer getParentType() { + return parentType; + } + + public ContentBuilder parentType(Integer parentType) { + this.parentType = parentType; + return this; + } + + public String getUri() { + return uri; + } + + public ContentBuilder uri(String uri) { + this.uri = uri; + return this; + } + + public Integer getLocationType() { + return locationType; + } + + public ContentBuilder locationType(Integer locationType) { + this.locationType = locationType; + return this; + } + + @Override + public Content build() { + Content content = new Content(); + content.setExtension(extension); + content.setId(id); + content.setLabel(label); + content.setParentType(parentType); + content.setLocationType(locationType); + content.setUri(uri); + return content; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/CredentialBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/CredentialBuilder.java new file mode 100644 index 000000000..6a6ae46a0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/CredentialBuilder.java @@ -0,0 +1,99 @@ +package eu.eudat.old.logic.builders.entity; + +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.data.entities.Credential; +import eu.eudat.old.data.entities.UserInfo; + +import java.util.Date; +import java.util.UUID; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public class CredentialBuilder extends Builder { + + private UUID id; + + private UserInfo userInfo; + + private Integer status; + + private Integer provider; + + private String publicValue; + + private String secret; + + private Date creationTime; + + private Date lastUpdateTime; + + private String externalId; + + private String email; + + public CredentialBuilder id(UUID id) { + this.id = id; + return this; + } + + public CredentialBuilder userInfo(UserInfo userInfo) { + this.userInfo = userInfo; + return this; + } + + public CredentialBuilder status(Integer status) { + this.status = status; + return this; + } + + public CredentialBuilder provider(Integer provider) { + this.provider = provider; + return this; + } + + public CredentialBuilder publicValue(String publicValue) { + this.publicValue = publicValue; + return this; + } + + public CredentialBuilder secret(String secret) { + this.secret = secret; + return this; + } + + public CredentialBuilder creationTime(Date creationTime) { + this.creationTime = creationTime; + return this; + } + + public CredentialBuilder lastUpdateTime(Date lastUpdateTime) { + this.lastUpdateTime = lastUpdateTime; + return this; + } + + public CredentialBuilder externalId(String externalId) { + this.externalId = externalId; + return this; + } + + public CredentialBuilder email(String email) { + this.email = email; + return this; + } + + public Credential build() { + Credential credential = new Credential(); + credential.setStatus(status); + credential.setLastUpdateTime(lastUpdateTime); + credential.setCreationTime(creationTime); + credential.setProvider(provider); + credential.setSecret(secret); + credential.setPublicValue(publicValue); + credential.setUserInfo(userInfo); + credential.setId(id); + credential.setExternalId(externalId); + credential.setEmail(email); + return credential; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/DatasetProfileBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/DatasetProfileBuilder.java new file mode 100644 index 000000000..1adc0a1cf --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/DatasetProfileBuilder.java @@ -0,0 +1,102 @@ +package eu.eudat.old.logic.builders.entity; + +import eu.eudat.old.data.entities.DescriptionTemplateType; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.data.entities.Dataset; + +import java.util.Date; +import java.util.Set; +import java.util.UUID; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public class DatasetProfileBuilder extends Builder { + + private UUID id; + + private String label; + + private DescriptionTemplateType type; + + private Set dataset; + + private String definition; + + private Short status; + + private Date created; + + private Date modified = new Date(); + + private String description; + + private String language; + + public DatasetProfileBuilder id(UUID id) { + this.id = id; + return this; + } + + public DatasetProfileBuilder label(String label) { + this.label = label; + return this; + } + + public DatasetProfileBuilder type(DescriptionTemplateType type) { + this.type = type; + return this; + } + + public DatasetProfileBuilder dataset(Set dataset) { + this.dataset = dataset; + return this; + } + + public DatasetProfileBuilder definition(String definition) { + this.definition = definition; + return this; + } + + public DatasetProfileBuilder status(Short status) { + this.status = status; + return this; + } + + public DatasetProfileBuilder created(Date created) { + this.created = created; + return this; + } + + public DatasetProfileBuilder modified(Date modified) { + this.modified = modified; + return this; + } + + public DatasetProfileBuilder description(String description) { + this.description = description; + return this; + } + + public DatasetProfileBuilder language(String language) { + this.language = language; + return this; + } + + @Override + public DescriptionTemplate build() { + DescriptionTemplate descriptionTemplate = new DescriptionTemplate(); + descriptionTemplate.setCreated(created); + descriptionTemplate.setStatus(status); + descriptionTemplate.setId(id); + descriptionTemplate.setDataset(dataset); + descriptionTemplate.setDefinition(definition); + descriptionTemplate.setDescription(description); + descriptionTemplate.setModified(modified); + descriptionTemplate.setLabel(label); + descriptionTemplate.setLanguage(language); + descriptionTemplate.setType(type); + return descriptionTemplate; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/UserInfoBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/UserInfoBuilder.java new file mode 100644 index 000000000..1fb3c4ecc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/UserInfoBuilder.java @@ -0,0 +1,128 @@ +package eu.eudat.old.logic.builders.entity; + +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.data.entities.Credential; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.entities.UserRole; + +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public class UserInfoBuilder extends Builder { + + private UUID id; + + private String email = null; + + private Short authorization_level; //0 admin, 1 user + + private Short usertype; // 0 internal, 1 external + + private Boolean verified_email = null; + + private String name = null; + + private Date created = null; + + private Date lastloggedin = null; + + private String additionalinfo; + + private Set dmps; + + private Set credentials = new HashSet<>(); + + private Set userRoles = new HashSet<>(); + + private Short userStatus; + + public UserInfoBuilder id(UUID id) { + this.id = id; + return this; + } + + public UserInfoBuilder email(String email) { + this.email = email; + return this; + } + + public UserInfoBuilder authorization_level(Short authorization_level) { + this.authorization_level = authorization_level; + return this; + } + + public UserInfoBuilder usertype(Short usertype) { + this.usertype = usertype; + return this; + } + + public UserInfoBuilder verified_email(Boolean verified_email) { + this.verified_email = verified_email; + return this; + } + + public UserInfoBuilder name(String name) { + this.name = name; + return this; + } + + public UserInfoBuilder created(Date created) { + this.created = created; + return this; + } + + public UserInfoBuilder lastloggedin(Date lastloggedin) { + this.lastloggedin = lastloggedin; + return this; + } + + public UserInfoBuilder additionalinfo(String additionalinfo) { + this.additionalinfo = additionalinfo; + return this; + } + + public UserInfoBuilder dmps(Set dmps) { + this.dmps = dmps; + return this; + } + + public UserInfoBuilder credentials(Set credentials) { + this.credentials = credentials; + return this; + } + + public UserInfoBuilder userRoles(Set userRoles) { + this.userRoles = userRoles; + return this; + } + + public UserInfoBuilder userStatus(Short userStatus) { + this.userStatus = userStatus; + return this; + } + + @Override + public UserInfo build() { + UserInfo userInfo = new UserInfo(); + userInfo.setId(id); + userInfo.setUsertype(usertype); + userInfo.setAuthorization_level(authorization_level); + userInfo.setLastloggedin(lastloggedin); + userInfo.setCreated(created); + userInfo.setEmail(email); + userInfo.setName(name); + userInfo.setAdditionalinfo(additionalinfo); + userInfo.setUserRoles(userRoles); + userInfo.setCredentials(credentials); + userInfo.setDmps(dmps); + userInfo.setVerified_email(verified_email); + userInfo.setUserStatus(userStatus); + return userInfo; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/UserRoleBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/UserRoleBuilder.java new file mode 100644 index 000000000..d3b351d90 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/UserRoleBuilder.java @@ -0,0 +1,43 @@ +package eu.eudat.old.logic.builders.entity; + +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.entities.UserRole; +import eu.eudat.old.logic.builders.Builder; + +import java.util.UUID; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public class UserRoleBuilder extends Builder { + + private UUID id; + + private int role; + + private UserInfo userInfo; + + public UserRoleBuilder id(UUID id) { + this.id = id; + return this; + } + + public UserRoleBuilder role(int role) { + this.role = role; + return this; + } + + public UserRoleBuilder userInfo(UserInfo userInfo) { + this.userInfo = userInfo; + return this; + } + + @Override + public UserRole build() { + UserRole userRole = new UserRole(); + userRole.setUserInfo(userInfo); + userRole.setRole(role); + userRole.setId(id); + return userRole; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/UserTokenBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/UserTokenBuilder.java new file mode 100644 index 000000000..925de20ee --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/entity/UserTokenBuilder.java @@ -0,0 +1,52 @@ +package eu.eudat.old.logic.builders.entity; + +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.entities.UserToken; + +import java.util.Date; +import java.util.UUID; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public class UserTokenBuilder extends Builder { + + private UUID token; + + private UserInfo user; + + private Date issuedAt; + + private Date expiresAt; + + public UserTokenBuilder token(UUID token) { + this.token = token; + return this; + } + + public UserTokenBuilder user(UserInfo user) { + this.user = user; + return this; + } + + public UserTokenBuilder issuedAt(Date issuedAt) { + this.issuedAt = issuedAt; + return this; + } + + public UserTokenBuilder expiresAt(Date expiresAt) { + this.expiresAt = expiresAt; + return this; + } + + @Override + public UserToken build() { + UserToken userToken = new UserToken(); + userToken.setExpiresAt(expiresAt); + userToken.setToken(token); + userToken.setUser(user); + userToken.setIssuedAt(issuedAt); + return userToken; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/helpers/BuilderApplier.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/helpers/BuilderApplier.java new file mode 100644 index 000000000..6da02ce6b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/helpers/BuilderApplier.java @@ -0,0 +1,8 @@ +package eu.eudat.old.logic.builders.helpers; + +/** + * Created by ikalyvas on 3/15/2018. + */ +public interface BuilderApplier { + void apply(T builder); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/DataRepositoryCriteriaBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/DataRepositoryCriteriaBuilder.java new file mode 100644 index 000000000..5be8ccc72 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/DataRepositoryCriteriaBuilder.java @@ -0,0 +1,23 @@ +package eu.eudat.old.logic.builders.model.criteria; + +import eu.eudat.old.data.dao.criteria.DataRepositoryCriteria; +import eu.eudat.old.logic.builders.Builder; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public class DataRepositoryCriteriaBuilder extends Builder { + private String like; + + public DataRepositoryCriteriaBuilder like(String like) { + this.like = like; + return this; + } + + @Override + public DataRepositoryCriteria build() { + DataRepositoryCriteria dataRepositoryCriteria = new DataRepositoryCriteria(); + dataRepositoryCriteria.setLike(like); + return dataRepositoryCriteria; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/ExternalDatasetCriteriaBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/ExternalDatasetCriteriaBuilder.java new file mode 100644 index 000000000..d98d71ecc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/ExternalDatasetCriteriaBuilder.java @@ -0,0 +1,23 @@ +package eu.eudat.old.logic.builders.model.criteria; + +import eu.eudat.old.data.dao.criteria.ExternalDatasetCriteria; +import eu.eudat.old.logic.builders.Builder; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public class ExternalDatasetCriteriaBuilder extends Builder { + private String like; + + public ExternalDatasetCriteriaBuilder like(String like) { + this.like = like; + return this; + } + + @Override + public ExternalDatasetCriteria build() { + ExternalDatasetCriteria externalDatasetCriteria = new ExternalDatasetCriteria(); + externalDatasetCriteria.setLike(like); + return externalDatasetCriteria; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/RegistryCriteriaBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/RegistryCriteriaBuilder.java new file mode 100644 index 000000000..6e399e667 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/RegistryCriteriaBuilder.java @@ -0,0 +1,23 @@ +package eu.eudat.old.logic.builders.model.criteria; + +import eu.eudat.old.data.dao.criteria.RegistryCriteria; +import eu.eudat.old.logic.builders.Builder; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public class RegistryCriteriaBuilder extends Builder { + private String like; + + public RegistryCriteriaBuilder like(String like) { + this.like = like; + return this; + } + + @Override + public RegistryCriteria build() { + RegistryCriteria registryCriteria = new RegistryCriteria(); + registryCriteria.setLike(like); + return registryCriteria; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/ServiceCriteriaBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/ServiceCriteriaBuilder.java new file mode 100644 index 000000000..bc72ff7f9 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/criteria/ServiceCriteriaBuilder.java @@ -0,0 +1,23 @@ +package eu.eudat.old.logic.builders.model.criteria; + +import eu.eudat.old.data.dao.criteria.ServiceCriteria; +import eu.eudat.old.logic.builders.Builder; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public class ServiceCriteriaBuilder extends Builder { + private String like; + + public ServiceCriteriaBuilder setLike(String like) { + this.like = like; + return this; + } + + @Override + public ServiceCriteria build() { + ServiceCriteria serviceCriteria = new ServiceCriteria(); + serviceCriteria.setLike(like); + return serviceCriteria; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/DataTableDataBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/DataTableDataBuilder.java new file mode 100644 index 000000000..3f0324fd1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/DataTableDataBuilder.java @@ -0,0 +1,33 @@ +package eu.eudat.old.logic.builders.model.models; + +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.models.data.helpers.common.DataTableData; + +import java.util.List; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public class DataTableDataBuilder extends Builder> { + + private Long totalCount; + private List data; + + public DataTableDataBuilder totalCount(Long totalCount) { + this.totalCount = totalCount; + return this; + } + + public DataTableDataBuilder data(List data) { + this.data = data; + return this; + } + + @Override + public DataTableData build() { + DataTableData dataTableData = new DataTableData<>(); + dataTableData.setTotalCount(totalCount); + dataTableData.setData(data); + return dataTableData; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/FunderBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/FunderBuilder.java new file mode 100644 index 000000000..fe81b5767 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/FunderBuilder.java @@ -0,0 +1,87 @@ +package eu.eudat.old.logic.builders.model.models; + +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.models.data.funder.Funder; + +import java.util.Date; +import java.util.UUID; + +public class FunderBuilder extends Builder { + + private UUID id; + private String label; + private String reference; + private String definition; + private eu.eudat.old.data.entities.Funder.Status status; + private Date created; + private Date modified; + private Integer type; + private String source; + private String key; + + public FunderBuilder id(UUID id) { + this.id = id; + return this; + } + + public FunderBuilder label(String label) { + this.label = label; + return this; + } + + public FunderBuilder reference(String reference) { + this.reference = reference; + return this; + } + + public FunderBuilder definition(String definition) { + this.definition = definition; + return this; + } + + public FunderBuilder status(eu.eudat.old.data.entities.Funder.Status status) { + this.status = status; + return this; + } + + public FunderBuilder created(Date created) { + this.created = created; + return this; + } + + public FunderBuilder modified(Date modified) { + this.modified = modified; + return this; + } + + public FunderBuilder type(int type) { + this.type = type; + return this; + } + + public FunderBuilder source(String source) { + this.source = source; + return this; + } + + public FunderBuilder key(String key) { + this.key = key; + return this; + } + + @Override + public Funder build() { + Funder funder = new Funder(); + funder.setId(id); + funder.setLabel(label); + funder.setReference(reference); + funder.setDefinition(definition); + if (status != null) funder.setStatus(status.getValue()); + funder.setCreated(created); + funder.setModified(modified); + funder.setType(type); + funder.setSource(source); + funder.setKey(key); + return funder; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/GrantBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/GrantBuilder.java new file mode 100644 index 000000000..a7c956f30 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/GrantBuilder.java @@ -0,0 +1,147 @@ +package eu.eudat.old.logic.builders.model.models; + +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.models.data.dmp.DataManagementPlan; +import eu.eudat.old.models.data.grant.Grant; + +import java.util.Date; +import java.util.List; +import java.util.UUID; + +public class GrantBuilder extends Builder { + + private UUID id; + + private List dmps; + + private String label; + + private String abbreviation; + + private String reference; + + private String uri; + + private String definition; + + private Date startDate; + + private Date endDate; + + private eu.eudat.old.data.entities.Grant.Status status; + + private UserInfo creationUser; + + private Date created; + + private Date modified; + + private String description; + + private String source; + + private String key; + + public GrantBuilder id(UUID id) { + this.id = id; + return this; + } + + public GrantBuilder dmps(List dmps) { + this.dmps = dmps; + return this; + } + + public GrantBuilder label(String label) { + this.label = label; + return this; + } + + public GrantBuilder abbreviation(String abbreviation) { + this.abbreviation = abbreviation; + return this; + } + + public GrantBuilder reference(String reference) { + this.reference = reference; + return this; + } + + public GrantBuilder uri(String uri) { + this.uri = uri; + return this; + } + + public GrantBuilder definition(String definition) { + this.definition = definition; + return this; + } + + public GrantBuilder startDate(Date startDate) { + this.startDate = startDate; + return this; + } + + public GrantBuilder endDate(Date endDate) { + this.endDate = endDate; + return this; + } + + public GrantBuilder status(eu.eudat.old.data.entities.Grant.Status status) { + this.status = status; + return this; + } + + public GrantBuilder creationUser(UserInfo creationUser) { + this.creationUser = creationUser; + return this; + } + + public GrantBuilder created(Date created) { + this.created = created; + return this; + } + + public GrantBuilder modified(Date modified) { + this.modified = modified; + return this; + } + + public GrantBuilder description(String description) { + this.description = description; + return this; + } + + public GrantBuilder source(String source) { + this.source = source; + return this; + } + + public GrantBuilder key(String key) { + this.key = key; + return this; + } + + @Override + public Grant build() { + Grant grant = new Grant(); + grant.setStatus(status.getValue()); + grant.setAbbreviation(abbreviation); + grant.setCreated(created); + grant.setCreationUser(creationUser); + grant.setDefinition(definition); + grant.setDescription(description); + grant.setDmps(dmps); + grant.setEndDate(endDate); + grant.setId(id); + grant.setLabel(label); + grant.setModified(modified); + grant.setReference(reference); + grant.setCreationUser(creationUser); + grant.setStartDate(startDate); + grant.setSource(source); + grant.setKey(key); + return grant; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/OrganisationBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/OrganisationBuilder.java new file mode 100644 index 000000000..e934a39ff --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/OrganisationBuilder.java @@ -0,0 +1,88 @@ +package eu.eudat.old.logic.builders.model.models; + +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.models.data.dmp.Organisation; + +public class OrganisationBuilder extends Builder { + private String label; + private String name; + private String id; + private String reference; + private int status; + private String tag; + private String key; + + public String getLabel() { + return label; + } + + public OrganisationBuilder label(String label) { + this.label = label; + return this; + } + + public String getName() { + return name; + } + + public OrganisationBuilder name(String name) { + this.name = name; + return this; + } + + public String getId() { + return id; + } + + public OrganisationBuilder id(String id) { + this.id = id; + return this; + } + + public String getReference() { return reference; } + + public OrganisationBuilder reference(String reference) { + this.reference = reference; + return this; + } + + public int getStatus() { + return status; + } + + public OrganisationBuilder status(int status) { + this.status = status; + return this; + } + + public String getTag() { + return tag; + } + + public OrganisationBuilder tag(String tag) { + this.tag = tag; + return this; + } + + public String getKey() { + return key; + } + + public OrganisationBuilder key(String key) { + this.key = key; + return this; + } + + @Override + public Organisation build() { + Organisation Organisation = new Organisation(); + Organisation.setId(id); + Organisation.setReference(reference); + Organisation.setLabel(label); + Organisation.setName(name); + Organisation.setStatus(status); + Organisation.setTag(tag); + Organisation.setKey(key); + return Organisation; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/PrincipalBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/PrincipalBuilder.java new file mode 100644 index 000000000..10ddf0b8c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/PrincipalBuilder.java @@ -0,0 +1,121 @@ +package eu.eudat.old.logic.builders.model.models; + +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.Authorities; + +import java.time.Instant; +import java.util.Date; +import java.util.Set; +import java.util.UUID; + +/** + * Created by ikalyvas on 2/15/2018. + */ +public class PrincipalBuilder extends Builder { + + private UUID id; + private UUID token; + private String name; + private String email; + private Date expiresAt; + private String avatarUrl; + private Set authorities; + private String culture; + private String language; + private String timezone; + private String zenodoToken; + private Instant zenodoDuration; + private String zenodoEmail; + private String zenodoRefresh; + + public PrincipalBuilder id(UUID id) { + this.id = id; + return this; + } + + public PrincipalBuilder token(UUID token) { + this.token = token; + return this; + } + + public PrincipalBuilder name(String name) { + this.name = name; + return this; + } + + public PrincipalBuilder email(String email) { + this.email = email; + return this; + } + + public PrincipalBuilder expiresAt(Date expiresAt) { + this.expiresAt = expiresAt; + return this; + } + + public PrincipalBuilder authorities(Set authorities) { + this.authorities = authorities; + return this; + } + + public PrincipalBuilder avatarUrl(String avatarUrl) { + this.avatarUrl = avatarUrl; + return this; + } + + public PrincipalBuilder culture(String culture) { + this.culture = culture; + return this; + } + + public PrincipalBuilder language(String language) { + this.language = language; + return this; + } + + public PrincipalBuilder timezone(String timezone) { + this.timezone = timezone; + return this; + } + + public PrincipalBuilder zenodoToken(String zenodoToken) { + this.zenodoToken = zenodoToken; + return this; + } + + public PrincipalBuilder zenodoDuration(Instant zenodoDuration) { + this.zenodoDuration = zenodoDuration; + return this; + } + + public PrincipalBuilder zenodoEmail(String zenodoEmail) { + this.zenodoEmail = zenodoEmail; + return this; + } + + public PrincipalBuilder zenodoRefresh(String zenodoRefresh) { + this.zenodoRefresh = zenodoRefresh; + return this; + } + + @Override + public Principal build() { + Principal principal = new Principal(); + principal.setAuthorities(authorities); + principal.setName(name); + principal.setEmail(email); + principal.setExpiresAt(expiresAt); + principal.setToken(token); + principal.setId(id); + principal.setAvatarUrl(avatarUrl); + principal.setCulture(culture); + principal.setLanguage(language); + principal.setTimezone(timezone); + principal.setZenodoToken(zenodoToken); + principal.setZenodoDuration(zenodoDuration); + principal.setZenodoEmail(zenodoEmail); + principal.setZenodoRefresh(zenodoRefresh); + return principal; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/ProjectBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/ProjectBuilder.java new file mode 100644 index 000000000..8b24cd03f --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/ProjectBuilder.java @@ -0,0 +1,139 @@ +package eu.eudat.old.logic.builders.model.models; + + +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.models.data.dmp.DataManagementPlan; +import eu.eudat.old.models.data.project.Project; + +import java.util.Date; +import java.util.List; +import java.util.UUID; + +public class ProjectBuilder extends Builder { + + private UUID id; + private List dmps; + private String label; + private int type; + private String abbreviation; + private String reference; + private String uri; + private String definition; + private Date startDate; + private Date endDate; + private eu.eudat.old.data.entities.Project.Status status; + private UserInfo creationUser; + private Date created; + private Date modified; + private String description; + private String source; + private String key; + + public ProjectBuilder id(UUID id) { + this.id = id; + return this; + } + + public ProjectBuilder dmps(List dmps) { + this.dmps = dmps; + return this; + } + + public ProjectBuilder label(String label) { + this.label = label; + return this; + } + + public ProjectBuilder type(int type) { + this.type = type; + return this; + } + + public ProjectBuilder abbreviation(String abbreviation) { + this.abbreviation = abbreviation; + return this; + } + + public ProjectBuilder reference(String reference) { + this.reference = reference; + return this; + } + + public ProjectBuilder uri(String uri) { + this.uri = uri; + return this; + } + + public ProjectBuilder definition(String definition) { + this.definition = definition; + return this; + } + + public ProjectBuilder startDate(Date startDate) { + this.startDate = startDate; + return this; + } + + public ProjectBuilder endDate(Date endDate) { + this.endDate = endDate; + return this; + } + + public ProjectBuilder status(eu.eudat.old.data.entities.Project.Status status) { + this.status = status; + return this; + } + + public ProjectBuilder creationUser(UserInfo creationUser) { + this.creationUser = creationUser; + return this; + } + + public ProjectBuilder created(Date created) { + this.created = created; + return this; + } + + public ProjectBuilder modified(Date modified) { + this.modified = modified; + return this; + } + + public ProjectBuilder description(String description) { + this.description = description; + return this; + } + + public ProjectBuilder source(String source) { + this.source = source; + return this; + } + + public ProjectBuilder key(String key) { + this.key = key; + return this; + } + + @Override + public Project build() { + Project project = new Project(); + project.setStatus(status.getValue()); + project.setAbbreviation(abbreviation); + project.setCreated(created); + project.setCreationUser(creationUser); + project.setDefinition(definition); + project.setDescription(description); + project.setDmps(dmps); + project.setEndDate(endDate); + project.setId(id); + project.setLabel(label); + project.setModified(modified); + project.setReference(reference); + project.setCreationUser(creationUser); + project.setStartDate(startDate); + project.setSource(source); + project.setKey(key); + return project; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/RecentActivityDataBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/RecentActivityDataBuilder.java new file mode 100644 index 000000000..72b855d20 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/RecentActivityDataBuilder.java @@ -0,0 +1,52 @@ +package eu.eudat.old.logic.builders.model.models; + +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.models.data.dashboard.recent.RecentActivityData; + +import java.util.Date; + +/** + * Created by ikalyvas on 3/14/2018. + */ +public class RecentActivityDataBuilder extends Builder { + + private String label; + private String id; + private Date timestamp; + + public String getLabel() { + return label; + } + + public RecentActivityDataBuilder label(String label) { + this.label = label; + return this; + } + + public String getId() { + return id; + } + + public RecentActivityDataBuilder id(String id) { + this.id = id; + return this; + } + + public Date getTimestamp() { + return timestamp; + } + + public RecentActivityDataBuilder timestamp(Date timestamp) { + this.timestamp = timestamp; + return this; + } + + @Override + public RecentActivityData build() { + RecentActivityData recentActivityData = new RecentActivityData(); + recentActivityData.setLabel(label); + recentActivityData.setTimestamp(timestamp); + recentActivityData.setId(id); + return recentActivityData; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/ResearcherBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/ResearcherBuilder.java new file mode 100644 index 000000000..bf82837f1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/builders/model/models/ResearcherBuilder.java @@ -0,0 +1,88 @@ +package eu.eudat.old.logic.builders.model.models; + +import eu.eudat.old.logic.builders.Builder; +import eu.eudat.old.models.data.dmp.Researcher; + +public class ResearcherBuilder extends Builder { + private String label; + private String name; + private String id; + private String reference; + private int status; + private String tag; + private String key; + + public String getLabel() { + return label; + } + + public ResearcherBuilder label(String label) { + this.label = label; + return this; + } + + public String getName() { + return name; + } + + public ResearcherBuilder name(String name) { + this.name = name; + return this; + } + + public String getId() { + return id; + } + + public ResearcherBuilder id(String id) { + this.id = id; + return this; + } + + public String getReference() { return reference; } + + public ResearcherBuilder reference(String reference) { + this.reference = reference; + return this; + } + + public int getStatus() { + return status; + } + + public ResearcherBuilder status(int status) { + this.status = status; + return this; + } + + public String getTag() { + return tag; + } + + public ResearcherBuilder tag(String tag) { + this.tag = tag; + return this; + } + + public String getKey() { + return key; + } + + public ResearcherBuilder key(String key) { + this.key = key; + return this; + } + + @Override + public Researcher build() { + Researcher researcher = new Researcher(); + researcher.setId(id); + researcher.setReference(reference); + researcher.setLabel(label); + researcher.setName(name); + researcher.setStatus(status); + researcher.setTag(tag); + researcher.setKey(key); + return researcher; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/handlers/PrincipalArgumentResolver.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/handlers/PrincipalArgumentResolver.java new file mode 100644 index 000000000..4e7d35588 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/handlers/PrincipalArgumentResolver.java @@ -0,0 +1,72 @@ +package eu.eudat.old.logic.handlers; + +import eu.eudat.old.exceptions.security.UnauthorisedException; +import eu.eudat.old.logic.security.claims.ClaimedAuthorities; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.Authorities; +import org.springframework.core.MethodParameter; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; + +import java.lang.annotation.Annotation; +import java.util.*; + + +public final class PrincipalArgumentResolver implements HandlerMethodArgumentResolver { + + private AuthenticationService verifiedUserAuthenticationService; + private AuthenticationService nonVerifiedUserAuthenticationService; + + public PrincipalArgumentResolver(AuthenticationService verifiedUserAuthenticationService, AuthenticationService nonVerifiedUserAuthenticationService) { + this.verifiedUserAuthenticationService = verifiedUserAuthenticationService; + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + } + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + return methodParameter.getParameterType().equals(Principal.class); + } + + @Override + public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception { + String token = nativeWebRequest.getHeader("AuthToken"); + + boolean checkMailNull = ((ServletWebRequest) nativeWebRequest).getRequest().getRequestURI().startsWith("/api/emailConfirmation"); + AuthenticationService authenticationService = checkMailNull ? this.nonVerifiedUserAuthenticationService : this.verifiedUserAuthenticationService; + + Optional claimsAnnotation = Arrays.stream(methodParameter.getParameterAnnotations()).filter(annotation -> annotation.annotationType().equals(ClaimedAuthorities.class)).findAny(); + List claimList = claimsAnnotation.map(annotation -> Arrays.asList(((ClaimedAuthorities) annotation).claims())).orElse(Authorities.all()); + if (claimList.size() == 1 && claimList.get(0).equals(Authorities.ANONYMOUS)) { + return new Principal(); + } else if (claimList.contains(Authorities.ANONYMOUS) && token == null) { + return new Principal(); + } + + if (token == null) throw new UnauthorisedException("Authentication Information Is Missing"); + UUID authToken; + try { + authToken = UUID.fromString(token); + } catch (IllegalArgumentException ex) { + throw new UnauthorisedException("Authentication Information Is Missing"); + } + Principal principal = authenticationService.Touch(authToken); + if (principal == null) throw new UnauthorisedException("Authentication Information Missing"); + if (!claimList.contains(Authorities.ANONYMOUS) && !principal.isAuthorized(claimList)) + throw new UnauthorisedException("You are not Authorized For this Action"); + + return principal; + } + + private Date addADay(Date date) { + Date dt = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(dt); + c.add(Calendar.DATE, 1); + dt = c.getTime(); + return dt; + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/AdminManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/AdminManager.java new file mode 100644 index 000000000..251f26825 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/AdminManager.java @@ -0,0 +1,90 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.dao.criteria.DatasetCriteria; +import eu.eudat.old.data.dao.entities.DatasetDao; +import eu.eudat.old.data.dao.entities.DatasetProfileDao; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.data.entities.DescriptionTemplateType; +import eu.eudat.old.logic.builders.entity.DatasetProfileBuilder; +import eu.eudat.old.logic.utilities.builders.ModelBuilder; +import eu.eudat.old.logic.utilities.builders.XmlBuilder; +import eu.eudat.old.models.data.admin.composite.DatasetProfile; +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Page; +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Section; +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel; +import eu.eudat.old.exceptions.datasetprofile.DatasetProfileWithDatasetsExeption; +import eu.eudat.old.logic.services.ApiContext; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import java.util.Date; +import java.util.UUID; + +public class AdminManager { + + public static DescriptionTemplate generateViewStyleDefinition(DatasetProfile profile, ApiContext apiContext) throws Exception { + ViewStyleModel viewStyleModel = new ViewStyleModel(); + viewStyleModel.setEnablePrefilling(profile.isEnablePrefilling()); + viewStyleModel.setSections(new ModelBuilder().toViewStyleDefinition(profile.getSections(), Section.class)); + viewStyleModel.setPages(new ModelBuilder().toViewStyleDefinition(profile.getPages(), Page.class)); + Document viewStyleDoc = XmlBuilder.getDocument(); + Element elementViewStyle = viewStyleModel.toXml(viewStyleDoc); + viewStyleDoc.appendChild(elementViewStyle); + String xml = XmlBuilder.generateXml(viewStyleDoc); + + if (profile.getDescription() == null) { + profile.setDescription(""); + } + + if (profile.getLanguage() == null) { + profile.setLanguage("en"); + } + + DescriptionTemplateType type; + try { + type = apiContext.getOperationsContext().getDatabaseRepository().getDescriptionTemplateTypeDao().findFromName(profile.getType()); + } + catch (Exception e) { + throw new Exception("Description template type '" + profile.getType() + "' could not be found."); + } + + DescriptionTemplate descriptionTemplate = apiContext.getOperationsContext().getBuilderFactory().getBuilder(DatasetProfileBuilder.class).definition(xml).label(profile.getLabel()) + .status(profile.getStatus()).created(new Date()).description(profile.getDescription()).language(profile.getLanguage()) + .type(type) + .build(); + + if (descriptionTemplate.getGroupId() == null) { + descriptionTemplate.setGroupId(UUID.randomUUID()); + } + + if (descriptionTemplate.getVersion() == null) { + descriptionTemplate.setVersion((short)1); + } + + return descriptionTemplate; + } + + public static DatasetProfile generateDatasetProfileModel(DescriptionTemplate profile) { + Document viewStyleDoc = XmlBuilder.fromXml(profile.getDefinition()); + Element root = viewStyleDoc.getDocumentElement(); + ViewStyleModel viewstyle = new ViewStyleModel().fromXml(root); + + DatasetProfile datasetprofile = new DatasetProfile(); + datasetprofile.buildProfile(viewstyle); + return datasetprofile; + } + + + public static DescriptionTemplate inactivate(DatasetProfileDao datasetProfileRepository, DatasetDao datasetDao, String id) { + DatasetCriteria datasetsForThatDatasetProfile = new DatasetCriteria(); + datasetsForThatDatasetProfile.setProfileDatasetId(UUID.fromString(id)); + if (datasetDao.getWithCriteria(datasetsForThatDatasetProfile).count() == 0) { + DescriptionTemplate detasetProfile = datasetProfileRepository.find(UUID.fromString(id)); + detasetProfile.setStatus(DescriptionTemplate.Status.DELETED.getValue()); + detasetProfile = datasetProfileRepository.createOrUpdate(detasetProfile); + return detasetProfile; + } else { + throw new DatasetProfileWithDatasetsExeption("This profile can not deleted, because Datasets are associated with it"); + } + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/CommonsManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/CommonsManager.java new file mode 100644 index 000000000..bc812b2eb --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/CommonsManager.java @@ -0,0 +1,27 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.models.data.externalurl.ExternalSourcesConfiguration; + +import java.util.stream.Collectors; + +/** + * Created by ikalyvas on 5/17/2018. + */ +public class CommonsManager { + + public static ExternalSourcesConfiguration getExternalSourcesConfiguration(ConfigLoader configLoader){ + ExternalSourcesConfiguration externalSourcesConfiguration = new ExternalSourcesConfiguration(); + externalSourcesConfiguration.setDataRepositories(configLoader.getExternalUrls().getRepositories().getUrls().stream() + .map(item-> new ExternalSourcesConfiguration.ExternalSourcesUrlModel(item.getKey(),item.getLabel())).collect(Collectors.toList())); + externalSourcesConfiguration.setExternalDatasets(configLoader.getExternalUrls().getDatasets().getUrls().stream() + .map(item-> new ExternalSourcesConfiguration.ExternalSourcesUrlModel(item.getKey(),item.getLabel())).collect(Collectors.toList())); + externalSourcesConfiguration.setRegistries(configLoader.getExternalUrls().getRegistries().getUrls().stream() + .map(item-> new ExternalSourcesConfiguration.ExternalSourcesUrlModel(item.getKey(),item.getLabel())).collect(Collectors.toList())); + externalSourcesConfiguration.setServices(configLoader.getExternalUrls().getServices().getUrls().stream() + .map(item-> new ExternalSourcesConfiguration.ExternalSourcesUrlModel(item.getKey(),item.getLabel())).collect(Collectors.toList())); + /*externalSourcesConfiguration.setTags(configLoader.getExternalUrls().getTags().getUrls().stream() + .map(item-> new ExternalSourcesConfiguration.ExternalSourcesUrlModel(item.getKey(),item.getLabel())).collect(Collectors.toList()));*/ + return externalSourcesConfiguration; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ContactEmailManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ContactEmailManager.java new file mode 100644 index 000000000..9f51ea999 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ContactEmailManager.java @@ -0,0 +1,58 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.models.data.ContactEmail.ContactEmailModel; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.ContactEmail.PublicContactEmailModel; +import eu.eudat.old.models.data.mail.SimpleMail; +import eu.eudat.old.models.data.security.Principal; +import org.springframework.core.env.Environment; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.mail.MessagingException; + +@Component +public class ContactEmailManager { + + private ApiContext apiContext; + private Environment environment; + + @Autowired + public ContactEmailManager(ApiContext apiContext, Environment environment) { + this.apiContext = apiContext; + this.environment = environment; + } + + public void sendContactEmail(ContactEmailModel contactEmailModel, Principal principal) throws MessagingException { + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + SimpleMail mail = new SimpleMail(); + String enrichedMail = contactEmailModel.getDescription() + "\n\n" + "Send by user: " + user.getEmail() ; + mail.setSubject(contactEmailModel.getSubject()); + mail.setTo(environment.getProperty("contact_email.mail")); + mail.setContent(enrichedMail); + mail.setFrom(user.getEmail()); + + apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail); + } + + public void sendContactEmailNoAuth(PublicContactEmailModel contactEmailModel) throws MessagingException { + SimpleMail mail = new SimpleMail(); + String enrichedMail = contactEmailModel.getMessage() + "\n\n" + "Send by user: " + contactEmailModel.getEmail() ; + mail.setSubject(contactEmailModel.getAffiliation()); + mail.setTo(environment.getProperty("contact_email.mail")); + mail.setContent(enrichedMail); + mail.setFrom(contactEmailModel.getEmail()); + + apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail); + } + + public void emailValidation(ContactEmailModel contactEmailModel) throws Exception { + if (contactEmailModel.getSubject() == null || contactEmailModel.getSubject().trim().isEmpty()) { + throw new Exception("Subject is empty"); + } + if (contactEmailModel.getDescription() == null || contactEmailModel.getDescription().trim().isEmpty()) { + throw new Exception("Description is empty"); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DashBoardManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DashBoardManager.java new file mode 100644 index 000000000..c33122ce0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DashBoardManager.java @@ -0,0 +1,352 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.dao.criteria.DatasetCriteria; +import eu.eudat.old.data.dao.criteria.OrganisationCriteria; +import eu.eudat.old.elastic.criteria.DmpCriteria; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.models.data.dashboard.recent.model.RecentDmpModel; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.listingmodels.DatasetListingModel; +import eu.eudat.old.types.searchbar.SearchBarItemType; +import eu.eudat.old.data.dao.criteria.DataManagementPlanCriteria; +import eu.eudat.old.data.dao.criteria.GrantCriteria; +import eu.eudat.old.data.dao.entities.DMPDao; +import eu.eudat.old.data.dao.entities.DatasetDao; +import eu.eudat.old.data.dao.entities.GrantDao; +import eu.eudat.old.data.dao.entities.OrganisationDao; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.data.entities.Grant; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.query.items.table.dataset.DatasetTableRequest; +import eu.eudat.old.data.query.items.table.dmp.DataManagementPlanTableRequest; +import eu.eudat.old.logic.builders.model.models.RecentActivityDataBuilder; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.dashboard.recent.RecentActivity; +import eu.eudat.old.models.data.dashboard.recent.RecentActivityData; +import eu.eudat.old.models.data.dashboard.recent.model.RecentActivityModel; +import eu.eudat.old.models.data.dashboard.recent.model.RecentDatasetModel; +import eu.eudat.old.models.data.dashboard.recent.tablerequest.RecentActivityTableRequest; +import eu.eudat.old.models.data.dashboard.searchbar.SearchBarItem; +import eu.eudat.old.models.data.dashboard.statistics.DashBoardStatistics; +import eu.eudat.old.models.data.listingmodels.DataManagementPlanListingModel; +import eu.eudat.old.models.data.security.Principal; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.transaction.Transactional; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Component +public class DashBoardManager { + private static final Logger logger = LoggerFactory.getLogger(DashBoardManager.class); + + private final Map> comparators = Stream.of(new Object[][] { + { "modified", Comparator.comparing(o -> ((RecentActivityModel)o).getModified()).reversed()}, + { "created", Comparator.comparing(o -> ((RecentActivityModel)o).getCreated()).reversed()}, + { "label", Comparator.comparing(o -> ((RecentActivityModel)o).getTitle())}, + { "status", Comparator.comparing(o -> ((RecentActivityModel)o).getStatus()).reversed()}, + { "finalizedAt", Comparator.comparing(o -> ((RecentActivityModel)o).getFinalizedAt(), Comparator.nullsLast(Comparator.naturalOrder())).reversed()}, + { "publishedAt", Comparator.comparing(o -> ((RecentActivityModel)o).getPublishedAt(), Comparator.nullsLast(Comparator.naturalOrder())).reversed()} + }).collect(Collectors.toMap(data -> (String) data[0], data -> (Comparator)data[1])); + + private ApiContext apiContext; + private DatabaseRepository databaseRepository; + private final DataManagementPlanManager dataManagementPlanManager; + private final DatasetManager datasetManager; + + @Autowired + public DashBoardManager(ApiContext apiContext, DataManagementPlanManager dataManagementPlanManager, DatasetManager datasetManager) { + this.apiContext = apiContext; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + this.dataManagementPlanManager = dataManagementPlanManager; + this.datasetManager = datasetManager; + } + + public DashBoardStatistics getStatistics() { + DashBoardStatistics statistics = new DashBoardStatistics(); + + DataManagementPlanCriteria publicCriteria = new DataManagementPlanCriteria(); + publicCriteria.setIsPublic(true); + publicCriteria.setOnlyPublic(true); + publicCriteria.setAllVersions(false); + + List dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(publicCriteria).toList(); + +// DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria(); + OrganisationCriteria organisationCriteria = new OrganisationCriteria(); + /*dataManagementPlanCriteria.setAllVersions(false); + dataManagementPlanCriteria.setIsPublic(true);*/ + organisationCriteria.setPublic(true); + +// List dmps = databaseRepository.getDmpDao().getWithCriteria(dataManagementPlanCriteria).toList(); + long numberOfDatasets = 0; + LinkedList grants = new LinkedList<>(); + for (DMP dmp : dmps) { + numberOfDatasets = numberOfDatasets + dmp.getDataset().stream() + .filter(item -> item.getStatus() == Dataset.Status.FINALISED.getValue()).count(); + if (dmp.getGrant() != null) { + grants.add(dmp.getGrant()); + } + } + + statistics.setTotalDataManagementPlanCount((long) dmps.size()); + statistics.setTotalDataSetCount(numberOfDatasets); + statistics.setTotalGrantCount(grants.stream().distinct().count()); + statistics.setTotalOrganisationCount(databaseRepository.getOrganisationDao().getWithCriteria(organisationCriteria).count()); + + return statistics; + } + + public DashBoardStatistics getMeStatistics(Principal principal) throws IOException { + Long datasets = 0L; + Long dmps = 0L; + DashBoardStatistics statistics = new DashBoardStatistics(); + DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao(); + DatasetDao datasetRepository = databaseRepository.getDatasetDao(); + GrantDao grantRepository = databaseRepository.getGrantDao(); + OrganisationDao organisationRepository = databaseRepository.getOrganisationDao(); + UserInfo user = new UserInfo(); + user.setId(principal.getId()); + DatasetCriteria datasetCriteria = new DatasetCriteria(); + if (apiContext.getOperationsContext().getElasticRepository().getDatasetRepository() != null) { + try { + eu.eudat.old.elastic.criteria.DatasetCriteria datasetElasticCriteria = new eu.eudat.old.elastic.criteria.DatasetCriteria(); + datasetElasticCriteria.setAllowAllVersions(false); + datasetElasticCriteria.setPublic(false); + datasetElasticCriteria.setCollaborators(Collections.singletonList(principal.getId())); + datasets = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().count(datasetElasticCriteria); + }catch (Exception e) { + logger.warn(e.getMessage(), e); + datasets = null; + } + } + datasetCriteria.setAllVersions(false); + datasetCriteria.setIsPublic(false); + DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria(); + if (apiContext.getOperationsContext().getElasticRepository().getDmpRepository() != null) { + try { + DmpCriteria dmpElasticCriteria = new DmpCriteria(); + dmpElasticCriteria.setAllowAllVersions(false); + dmpElasticCriteria.setPublic(false); + dmpElasticCriteria.setCollaborators(Collections.singletonList(principal.getId())); + dmps = apiContext.getOperationsContext().getElasticRepository().getDmpRepository().count(dmpElasticCriteria); + }catch (Exception e) { + logger.warn(e.getMessage(), e); + dmps = null; + } + } + dataManagementPlanCriteria.setAllVersions(false); + dataManagementPlanCriteria.setOnlyPublic(false); + dataManagementPlanCriteria.setIsPublic(false); + + GrantCriteria grantCriteria = new GrantCriteria(); + grantCriteria.setActive(true); + + OrganisationCriteria organisationCriteria = new OrganisationCriteria(); + organisationCriteria.setActive(true); + + List roles = new LinkedList<>(); + if ((dmps == null || dmps == 0L) && (datasets == null || datasets == 0L)) { + CompletableFuture dmpFuture = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), principal.getId(), roles).distinct().countAsync() + .whenComplete((dmpsStats, throwable) -> statistics.setTotalDataManagementPlanCount(dmpsStats)); + CompletableFuture datasetFuture = datasetRepository.getAuthenticated( datasetRepository.getWithCriteria(datasetCriteria), user, roles).distinct().countAsync() + .whenComplete((datasetsStats, throwable) -> statistics.setTotalDataSetCount(datasetsStats)); + CompletableFuture.allOf(dmpFuture, datasetFuture).join(); + } else { + statistics.setTotalDataManagementPlanCount(dmps); + statistics.setTotalDataSetCount(datasets); + } + CompletableFuture grantFuture = grantRepository.getAuthenticated(grantRepository.getWithCriteria(grantCriteria), user).countAsync() + .whenComplete((grantsStats, throwable) -> statistics.setTotalGrantCount(grantsStats)); + CompletableFuture orgnanisationFuture = organisationRepository.getAuthenticated(organisationRepository.getWithCriteria(organisationCriteria).withHint("organisationRecentActivity"), user).countAsync() + .whenComplete((organisationStats, throwable) -> statistics.setTotalOrganisationCount(organisationStats)); + + CompletableFuture.allOf( grantFuture, orgnanisationFuture).join(); + return statistics; + } + + @Deprecated + public RecentActivity getRecentActivity(Principal principal, Integer numberofactivities) { + RecentActivity activity = new RecentActivity(); + DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao(); + DatasetDao datasetRepository = databaseRepository.getDatasetDao(); + GrantDao grantRepository = databaseRepository.getGrantDao(); + UserInfo user = new UserInfo(); + user.setId(principal.getId()); + DatasetCriteria datasetCriteria = new DatasetCriteria(); + datasetCriteria.setAllVersions(false); + DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria(); + dataManagementPlanCriteria.setAllVersions(false); + GrantCriteria grantCriteria = new GrantCriteria(); + RecentActivityDataBuilder recentActivityDataBuilder = apiContext.getOperationsContext().getBuilderFactory().getBuilder(RecentActivityDataBuilder.class); + + List roles = new LinkedList<>(); + CompletableFuture> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), principal.getId(), roles) + .withHint("dmpRecentActivity") + .orderBy((builder, root) -> builder.desc(root.get("modified"))) + .take(numberofactivities) + .selectAsync(item -> recentActivityDataBuilder.label(item.getLabel()).timestamp(item.getModified()).id(item.getId().toString()).build()) + .whenComplete((dmpActivities, throwable) -> activity.setRecentDmpActivities(dmpActivities)); + + CompletableFuture> datasets = datasetRepository.getAuthenticated(datasetRepository.getWithCriteria(datasetCriteria), user, roles).distinct() + .withHint("datasetRecentActivity") + .orderBy((builder, root) -> builder.desc(root.get("modified"))) + .take(numberofactivities) + .selectAsync(item -> recentActivityDataBuilder.label(item.getLabel()).timestamp(item.getModified()).id(item.getId().toString()).build()) + .whenComplete((datasetActivities, throwable) -> activity.setRecentDatasetActivities(datasetActivities)); + + CompletableFuture> grants = grantRepository.getAuthenticated(grantRepository.getWithCriteria(grantCriteria), user) + .withHint("grantRecentActivity") + .orderBy((builder, root) -> builder.desc(root.get("modified"))) + .take(numberofactivities) + .selectAsync(item -> recentActivityDataBuilder.label(item.getLabel()).timestamp(item.getModified()).id(item.getId().toString()).build()) + .whenComplete((grantActivities, throwable) -> activity.setRecentGrantActivities(grantActivities)); + + CompletableFuture.allOf(grants, dmps, datasets).join(); + return activity; + } + + @Transactional + public List getNewRecentActivity(RecentActivityTableRequest tableRequest, Principal principal) throws Exception { + boolean isAuthenticated = principal.getId() != null; + List recentActivityModels = new ArrayList<>(); + UserInfo user = new UserInfo(); + if (isAuthenticated) { + user.setId(principal.getId()); + } + DatasetCriteria datasetCriteria = new DatasetCriteria(); + datasetCriteria.setLike(tableRequest.getCriteria().getLike()); + if(tableRequest.getCriteria().getStatus() != null) { + datasetCriteria.setStatus(tableRequest.getCriteria().getStatus()); + } + datasetCriteria.setAllVersions(false); + datasetCriteria.setIsPublic(!isAuthenticated); + DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria(); + dataManagementPlanCriteria.setAllVersions(false); + dataManagementPlanCriteria.setLike(tableRequest.getCriteria().getLike()); + if(tableRequest.getCriteria().getStatus() != null) { + dataManagementPlanCriteria.setStatus(tableRequest.getCriteria().getStatus()); + } + dataManagementPlanCriteria.setIsPublic(!isAuthenticated); + dataManagementPlanCriteria.setOnlyPublic(!isAuthenticated); + + //GK: Use the managers to get the data in order to be better synced with other lists + DataManagementPlanTableRequest dataManagementPlanTableRequest = new DataManagementPlanTableRequest(); + dataManagementPlanTableRequest.setCriteria(dataManagementPlanCriteria); + dataManagementPlanTableRequest.setOrderings(tableRequest.getOrderings()); + dataManagementPlanTableRequest.setLength(tableRequest.getLength()); + dataManagementPlanTableRequest.setOffset(tableRequest.getDmpOffset()); + DataTableData dmps = this.dataManagementPlanManager.getPaged(dataManagementPlanTableRequest, principal, "listing"); + recentActivityModels.addAll(dmps.getData().stream().map(dataManagementPlanListingModel -> new RecentDmpModel().fromDataModel(dataManagementPlanListingModel.toDataModel())).collect(Collectors.toList())); + DatasetTableRequest datasetTableRequest = new DatasetTableRequest(); + datasetCriteria.setCollaborators(new ArrayList<>()); + datasetTableRequest.setCriteria(datasetCriteria); + datasetTableRequest.setOrderings(tableRequest.getOrderings()); + datasetTableRequest.getOrderings().getFields().addAll(datasetTableRequest.getOrderings().getFields().stream().filter(s -> s.contains("publishedAt")).map(s -> s.charAt(0) + "dmp:" + s.substring(1) + "|join|").collect(Collectors.toList())); + datasetTableRequest.getOrderings().getFields().removeIf(s -> s.contains("publishedAt") && !s.endsWith("|join|")); + datasetTableRequest.setLength(tableRequest.getLength()); + datasetTableRequest.setOffset(tableRequest.getDatasetOffset()); + DataTableData datasets = this.datasetManager.getPaged(datasetTableRequest, principal); + recentActivityModels.addAll(datasets.getData().stream().map(datasetListingModel -> new RecentDatasetModel().fromDataModel(datasetListingModel.toDataModel())).collect(Collectors.toList())); + + //GK: Shuffle the deck otherwise we will summon the DMPodia when sorting with status + /*int pos = -1; + for (int i = (recentActivityModels.size() / 2); i < recentActivityModels.size(); i++) { + RecentActivityModel recentActivityModel = recentActivityModels.remove(i); + while (pos < recentActivityModels.size()) { + pos++; + if (pos % 2 != 0) { + break; + } + } + recentActivityModels.add(pos, recentActivityModel); + }*/ + //GK: No one likes to play shuffle with the recent activities. So just re-sort them based on how they have been sorted already + + String order = tableRequest.getOrderings().getFields().get(0).toCharArray()[0] + ""; + String field = tableRequest.getOrderings().getFields().get(0).substring(1); + if (field.contains(":") && field.contains("|")) { + field = field.substring(field.lastIndexOf(":") + 1, field.indexOf("|")); + } + field = field.equals("label") ? "title" : field; + field = field.substring(0, 1).toUpperCase() + field.substring(1); + String finalField = field; + recentActivityModels = recentActivityModels.stream().sorted((o1, o2) -> { + try { + return (order.equals("+") ? 1 : -1 ) * ((Comparable)o1.getClass().getMethod("get" + finalField).invoke(o1)).compareTo(o2.getClass().getMethod("get" + finalField).invoke(o2)); + } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { + logger.error(e.getLocalizedMessage(), e); + } + return 0; + }).collect(Collectors.toList()); + + return recentActivityModels; + } + + public List searchUserData(String like, Principal principal) { + UserInfo user = new UserInfo(); + user.setId(principal.getId()); + DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao(); + DatasetDao datasetRepository = databaseRepository.getDatasetDao(); + GrantDao grantRepository = databaseRepository.getGrantDao(); + + List roles = new LinkedList<>(); + List searchBarItems = new LinkedList<>(); + + CompletableFuture> publicDmps = dataManagementPlanRepository.asQueryable() + .where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%")) + .where((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue())) + .where((builder, root) -> builder.equal(root.get("isPublic"), true)) + .orderBy((builder, root) -> builder.desc(root.get("modified"))) + .selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.DMP.getValue(), true)) + .whenComplete((dmpItems, throwable) -> searchBarItems.addAll(dmpItems)); + + CompletableFuture> publicDatasets = datasetRepository.asQueryable() + .where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%")) + .where((builder, root) -> builder.equal(root.get("status"), Dataset.Status.FINALISED.getValue())) + .where((builder, root) -> builder.equal(root.get("dmp").get("isPublic"), true)) + .orderBy((builder, root) -> builder.desc(root.get("modified"))) + .selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.DATASET.getValue(), true)) + .whenComplete((dataSetItems, throwable) -> searchBarItems.addAll(dataSetItems)); + + if (principal.getId() != null) { + CompletableFuture> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.asQueryable(), principal.getId(), roles) + .withHint("dmpRecentActivity") + .where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%")) + .where((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue())) + .orderBy((builder, root) -> builder.desc(root.get("modified"))) + .selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.DMP.getValue(), false)) + .whenComplete((dmpItems, throwable) -> searchBarItems.addAll(dmpItems)); + + CompletableFuture> datasets = datasetRepository.getAuthenticated(datasetRepository.asQueryable(), user, roles) + .withHint("datasetRecentActivity") + .where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%")) + .where((builder, root) -> builder.notEqual(root.get("status"), Dataset.Status.DELETED.getValue())) + .where((builder, root) -> builder.notEqual(root.get("status"), Dataset.Status.CANCELED.getValue())) + .orderBy((builder, root) -> builder.desc(root.get("modified"))) + .selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.DATASET.getValue(), false)) + .whenComplete((dataSetItems, throwable) -> searchBarItems.addAll(dataSetItems)); + + CompletableFuture> grants = grantRepository.getAuthenticated(grantRepository.asQueryable(), user) + .withHint("grantRecentActivity") + .where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%")) + .orderBy((builder, root) -> builder.desc(root.get("modified"))) + .selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.GRANT.getValue(), false)) + .whenComplete((grantItems, throwable) -> searchBarItems.addAll(grantItems)); + + CompletableFuture.allOf(grants, dmps, datasets, publicDmps, publicDatasets).join(); + } else { + CompletableFuture.allOf(publicDmps, publicDatasets).join(); + } + + return searchBarItems; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DataManagementPlanManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DataManagementPlanManager.java new file mode 100644 index 000000000..a225bdbf7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DataManagementPlanManager.java @@ -0,0 +1,2716 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.depositinterface.models.DMPDepositModel; +import eu.eudat.depositinterface.repository.RepositoryDeposit; +import eu.eudat.old.configurations.dynamicgrant.DynamicGrantConfiguration; +import eu.eudat.old.configurations.dynamicgrant.entities.Property; +import eu.eudat.old.data.dao.criteria.*; +import eu.eudat.old.data.dao.entities.*; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.data.entities.*; +import eu.eudat.old.data.enumeration.notification.ActiveStatus; +import eu.eudat.old.data.enumeration.notification.ContactType; +import eu.eudat.old.data.enumeration.notification.NotificationType; +import eu.eudat.old.data.enumeration.notification.NotifyState; +import eu.eudat.old.data.query.items.table.dataset.DatasetTableRequest; +import eu.eudat.old.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem; +import eu.eudat.old.data.query.items.table.dmp.DataManagementPlanTableRequest; +import eu.eudat.old.elastic.criteria.DmpCriteria; +import eu.eudat.old.elastic.entities.Dataset; +import eu.eudat.old.elastic.entities.*; +import eu.eudat.old.exceptions.datamanagementplan.DMPNewVersionException; +import eu.eudat.old.exceptions.datamanagementplan.DMPWithDatasetsDeleteException; +import eu.eudat.old.exceptions.security.ForbiddenException; +import eu.eudat.old.exceptions.security.UnauthorisedException; +import eu.eudat.old.logic.builders.entity.UserInfoBuilder; +import eu.eudat.old.logic.mapper.elastic.DmpMapper; +import eu.eudat.old.logic.mapper.elastic.criteria.DmpCriteriaMapper; +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.security.repositorydeposit.mapper.DMPToDepositMapper; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.forms.VisibilityRuleService; +import eu.eudat.old.logic.services.forms.VisibilityRuleServiceImpl; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.logic.utilities.builders.XmlBuilder; +import eu.eudat.old.logic.utilities.documents.helpers.FileEnvelope; +import eu.eudat.old.logic.utilities.documents.pdf.PDFUtils; +import eu.eudat.old.logic.utilities.documents.types.ParagraphStyle; +import eu.eudat.old.logic.utilities.documents.word.WordBuilder; +import eu.eudat.old.logic.utilities.documents.xml.ExportXmlBuilder; +import eu.eudat.old.models.HintedModelFactory; +import eu.eudat.old.models.data.dataset.DatasetOverviewModel; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileListingModel; +import eu.eudat.old.models.data.datasetwizard.DatasetWizardModel; +import eu.eudat.old.models.data.datasetwizard.DatasetsToBeFinalized; +import eu.eudat.old.models.data.dmp.*; +import eu.eudat.old.models.data.doi.DepositRequest; +import eu.eudat.old.models.data.doi.Doi; +import eu.eudat.old.models.data.dynamicfields.DynamicFieldWithValue; +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.*; +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.types.FieldCategory; +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.types.SystemFieldType; +import eu.eudat.old.models.data.funder.Funder; +import eu.eudat.old.models.data.funder.FunderDMPEditorModel; +import eu.eudat.old.models.data.grant.Grant; +import eu.eudat.old.models.data.grant.GrantDMPEditorModel; +import eu.eudat.old.models.data.helpermodels.Tuple; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.listingmodels.*; +import eu.eudat.old.models.data.project.Project; +import eu.eudat.old.models.data.project.ProjectDMPEditorModel; +import eu.eudat.old.data.entities.Researcher; +import eu.eudat.old.data.entities.Organisation; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.user.composite.PagedDatasetProfile; +import eu.eudat.old.models.data.userinfo.UserListingModel; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.types.Authorities; +import eu.eudat.old.types.MetricNames; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.*; +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.transaction.Transactional; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.*; +import java.math.BigInteger; +import java.nio.file.Files; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +@Component +public class DataManagementPlanManager { + private static final Logger logger = LoggerFactory.getLogger(DataManagementPlanManager.class); + private final ObjectMapper objectMapper; + + private final Map notificationPaths = Stream.of(new Object[][] { + {NotificationType.DMP_MODIFIED, "/plans/edit"}, + {NotificationType.DMP_PUBLISH, "/plans/publicEdit"}, + {NotificationType.DMP_FINALISED, "/plans/edit"}, + {NotificationType.DMP_MODIFIED_FINALISED, "/plans/edit"} + }).collect(Collectors.toMap(data -> (NotificationType) data[0], data -> (String) data[1])); + + private ApiContext apiContext; + private DatasetManager datasetManager; + private DataManagementProfileManager dataManagementProfileManager; + private DatabaseRepository databaseRepository; + private Environment environment; + private RDAManager rdaManager; + private UserManager userManager; + private final MetricsManager metricsManager; + private final ConfigLoader configLoader; + private List repositoriesDeposit; + + @Autowired + public DataManagementPlanManager(ApiContext apiContext, DatasetManager datasetManager, DataManagementProfileManager dataManagementProfileManager, Environment environment, RDAManager rdaManager, UserManager userManager, + MetricsManager metricsManager, ConfigLoader configLoader, List repositoriesDeposit) { + this.apiContext = apiContext; + this.datasetManager = datasetManager; + this.dataManagementProfileManager = dataManagementProfileManager; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + this.environment = environment; + this.rdaManager = rdaManager; + this.userManager = userManager; + this.metricsManager = metricsManager; + this.configLoader = configLoader; + this.objectMapper = new ObjectMapper(); + this.repositoriesDeposit = repositoriesDeposit; + } + + /* + * Data Retrieval + * */ + + public DataTableData getPaged(DataManagementPlanTableRequest dataManagementPlanTableRequest, Principal principal, String fieldsGroup) throws Exception { + UUID principalID = principal.getId(); + List dmps = null; + + QueryableList items = null; + QueryableList authItems = null; + Long totalData = 0L; + if (apiContext.getOperationsContext().getElasticRepository().getDmpRepository() != null) { + try { + DmpCriteria criteria = DmpCriteriaMapper.toElasticCriteria(dataManagementPlanTableRequest.getCriteria(), principalID); + criteria.setOffset(dataManagementPlanTableRequest.getOffset()); + criteria.setSize(dataManagementPlanTableRequest.getLength()); + criteria.setSortCriteria(DmpCriteriaMapper.toElasticSorting(dataManagementPlanTableRequest.getOrderings())); + + dmps = apiContext.getOperationsContext().getElasticRepository().getDmpRepository().query(criteria); + if (dmps != null && !dmps.isEmpty()) { + List finalDmps = dmps; + items = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().where((builder, root) -> root.get("id").in(finalDmps.stream().map(Dmp::getId).collect(Collectors.toList()))); + PaginationManager.applyOrder(items, dataManagementPlanTableRequest); + totalData = apiContext.getOperationsContext().getElasticRepository().getDmpRepository().count(criteria); + } + } catch (Exception ex) { + logger.warn(ex.getMessage(), ex); + items = null; + } + } + + if (items == null) { + items = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dataManagementPlanTableRequest.getCriteria()); + } + List roles = new LinkedList<>(); + if (!dataManagementPlanTableRequest.getCriteria().isOnlyPublic()) { + if (dataManagementPlanTableRequest.getCriteria().getRole() != null) + roles.add(dataManagementPlanTableRequest.getCriteria().getRole()); + authItems = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(items, principalID, roles); + } else { + authItems = items; + } + if (dmps == null) { + totalData = authItems.count(); + items = PaginationManager.applyPaging(authItems, dataManagementPlanTableRequest); + } else { + items = authItems; + } + + + + DataTableData dataTable = new DataTableData<>(); + + if (fieldsGroup.equals("listing")) { + if (!dataManagementPlanTableRequest.getCriteria().isOnlyPublic()) { + List dmps1 = items.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class)) + .distinct().toList(); + dataTable.setData(dmps1.stream().map(dmp -> { + DatasetCriteria datasetCriteria = new DatasetCriteria(); + datasetCriteria.setDmpIds(Collections.singletonList(dmp.getId())); + datasetCriteria.setAllVersions(dataManagementPlanTableRequest.getCriteria().getAllVersions()); + datasetCriteria.setIsPublic(dataManagementPlanTableRequest.getCriteria().getIsPublic()); + datasetCriteria.setGroupIds(Collections.singletonList(dmp.getGroupId())); + dmp.setDataset(retrieveRelevantDatasets(datasetCriteria, principalID)); + + + return new DataManagementPlanListingModel().fromDataModelDatasets(dmp); + }).collect(Collectors.toList())); + /*.selectAsync(item -> { + item.setDataset( + item.getDataset().stream() + .filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED.getValue()) && !dataset.getStatus().equals(Dataset.Status.CANCELED.getValue())).collect(Collectors.toList()).stream() + *//*.filter(dataset -> dataset.getDmp().getUsers().stream() + .filter(x -> x.getUser().getId().equals(principalID)) + .collect(Collectors.toList()).size() > 0)*//* + .collect(Collectors.toSet())); + return new DataManagementPlanListingModel().fromDataModelDatasets(item); + }) + .whenComplete((resultList, throwable) -> dataTable.setData(resultList));*/ + } else { + List dmps1 = items.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class)) + .distinct().toList(); + dataTable.setData(dmps1.stream().map(dmp -> { + DatasetCriteria datasetCriteria = new DatasetCriteria(); + datasetCriteria.setDmpIds(Collections.singletonList(dmp.getId())); + datasetCriteria.setIsPublic(true); + datasetCriteria.setAllVersions(dataManagementPlanTableRequest.getCriteria().getAllVersions()); + datasetCriteria.setGroupIds(Collections.singletonList(dmp.getGroupId())); + dmp.setDataset(retrieveRelevantDatasets(datasetCriteria)); + + + return new DataManagementPlanListingModel().fromDataModelDatasets(dmp); + }).collect(Collectors.toList())); + /*.selectAsync(item -> { + item.setDataset( + item.getDataset().stream() + .filter(dataset -> dataset.getStatus().equals(Dataset.Status.FINALISED.getValue())).collect(Collectors.toSet())); + return new DataManagementPlanListingModel().fromDataModelDatasets(item); + }) + .whenComplete((resultList, throwable) -> dataTable.setData(resultList));*/ + } + } else if (fieldsGroup.equals("autocomplete")) { + dataTable.setData(items + .distinct() + .select(item -> new DataManagementPlanListingModel().fromDataModelAutoComplete(item))); + } else { + dataTable.setData(items + .distinct() + .select(item -> new DataManagementPlanListingModel().fromDataModelAssociatedProfiles(item))); + } + + //CompletableFuture countFuture = authItems.distinct().countAsync().whenComplete((count, throwable) -> dataTable.setTotalCount(count)); + dataTable.setTotalCount(totalData); + //CompletableFuture.allOf(itemsFuture).join(); + return dataTable; + } + + private Set retrieveRelevantDatasets(DatasetCriteria datasetCriteria) { + return retrieveRelevantDatasets(datasetCriteria, null); + } + + private Set retrieveRelevantDatasets (DatasetCriteria datasetCriteria, UUID principal) { + QueryableList datasetItems = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(datasetCriteria) + .orderBy((builder, root) -> builder.desc(root.get("modified"))); + if (principal != null) { + UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal); + List roles = new ArrayList<>(); + roles.add(0); + roles.add(1); + datasetItems = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getAuthenticated(datasetItems, userInfo, roles); + } + Long maxDatasets = datasetItems.distinct().count(); + DatasetTableRequest datasetTableRequest = new DatasetTableRequest(); + datasetTableRequest.setOffset(0); + datasetTableRequest.setLength(3); + Set datasetsSet = new LinkedHashSet<>(); + try { + datasetItems = PaginationManager.applyPaging(datasetItems, datasetTableRequest); + List datasets = datasetItems.distinct().toList(); + datasetsSet.addAll(datasets); + for (int i = 0; i < maxDatasets - datasets.size(); i++) { + eu.eudat.old.data.entities.Dataset fakedataset = new eu.eudat.old.data.entities.Dataset(); + fakedataset.setId(UUID.randomUUID()); + datasetsSet.add(fakedataset); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + return datasetsSet; + } + + public DataManagementPlan getSingle(String id, Principal principal, boolean isPublic, boolean includeDatasets) throws Exception { + DataManagementPlan dataManagementPlan = new DataManagementPlan(); + DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); + if (!isPublic && principal == null) { + throw new UnauthorisedException(); + } else if (!isPublic && (dataManagementPlanEntity.getUsers().stream().noneMatch(userInfo -> userInfo.getUser().getId() == principal.getId()))) { + if (!dataManagementPlanEntity.isPublic()) { + throw new UnauthorisedException(); + } + } else if (isPublic && !dataManagementPlanEntity.isPublic()) { + throw new ForbiddenException("Selected DMP is not public"); + } + if (includeDatasets) { + dataManagementPlan.fromDataModel(dataManagementPlanEntity); + dataManagementPlan.getDatasets().forEach(datasetWizardModel -> datasetWizardModel.setDescription(null)); + dataManagementPlan.setDatasets(dataManagementPlan.getDatasets().stream().sorted(Comparator.comparing(DatasetWizardModel::getCreated).reversed()).collect(Collectors.toList())); + //List datasetEnities = new ArrayList<>(dataManagementPlanEntity.getDataset()); + /*for (int i = 0; i < datasetEnities.size(); i++) { + for (int j = i; j < dataManagementPlan.getDatasets().size(); j++) { + if (dataManagementPlan.getDatasets().get(j).getId().equals(datasetEnities.get(i).getId())) { + dataManagementPlan.getDatasets().get(j).setDatasetProfileDefinition(datasetManager.getPagedProfile(dataManagementPlan.getDatasets().get(j), datasetEnities.get(i))); + break; + } + } + }*/ + /*datasetEnities.stream() + .filter(dataset -> !dataset.getStatus().equals(Dataset.Status.DELETED) && !dataset.getStatus().equals(Dataset.Status.CANCELED)) + .forEach(dataset -> { + dataManagementPlan.getDatasets().stream().filter(datasetWizardModel -> datasetWizardModel.getId().equals(dataset.getId())).forEach(datasetWizardModel -> { + DatasetWizardModel wizardModel = datasetManager.getSingle(datasetWizardModel.getId().toString(), principal); + datasetWizardModel.setDatasetProfileDefinition(wizardModel.getDatasetProfileDefinition()); + datasetWizardModel.setTags(wizardModel.getTags()); + }); + });*/ + if (isPublic) { + dataManagementPlan.setDatasets(dataManagementPlan.getDatasets().stream().filter(dataset -> dataset.getStatus() == eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()).collect(Collectors.toList())); + } + } else { + dataManagementPlan.fromDataModelNoDatasets(dataManagementPlanEntity); + } + Map dmpProperties = dataManagementPlanEntity.getDmpProperties() != null ? new org.json.JSONObject(dataManagementPlanEntity.getDmpProperties()).toMap() : null; + + if (dmpProperties != null && dataManagementPlan.getDynamicFields() != null) + dataManagementPlan.getDynamicFields().forEach(item -> { + Map properties = (Map) dmpProperties.get(item.getId()); + if (properties != null) + item.setValue(new Tuple<>(properties.get("id"), properties.get("label"))); + }); + return dataManagementPlan; + } + + public DataManagementPlanOverviewModel getOverviewSingle(String id, Principal principal, boolean isPublic) throws Exception { + DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); + if (dataManagementPlanEntity.getStatus() == DMP.DMPStatus.DELETED.getValue()) { + throw new Exception("DMP is deleted."); + } + if (!isPublic && principal == null) { + throw new UnauthorisedException(); + } else + if (!isPublic && dataManagementPlanEntity.getUsers() + .stream().noneMatch(userInfo -> userInfo.getUser().getId() == principal.getId())) { + throw new UnauthorisedException(); + } else if (isPublic && !dataManagementPlanEntity.isPublic()) { + throw new ForbiddenException("Selected DMP is not public"); + } + DataManagementPlanOverviewModel datamanagementPlan = new DataManagementPlanOverviewModel(); + datamanagementPlan.fromDataModelDatasets(dataManagementPlanEntity); + datamanagementPlan.setDatasets(datamanagementPlan.getDatasets().stream().sorted(Comparator.comparing(DatasetOverviewModel::getCreated).reversed()).collect(Collectors.toList())); + if (isPublic) { + datamanagementPlan.setDatasets(datamanagementPlan.getDatasets().stream().filter(dataset -> dataset.getStatus() == eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()).collect(Collectors.toList())); + } + + return datamanagementPlan; + } + + public List> getDynamicFields(String id, DynamicGrantConfiguration dynamicGrantConfiguration, DynamicFieldsCriteria criteria) throws IllegalAccessException, InstantiationException { + List> result = new LinkedList<>(); + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity<>("parameters", headers); + + Property property = dynamicGrantConfiguration.getConfiguration().getConfigurationProperties().stream() + .filter(item -> item.getId().equals(id)).findFirst().orElse(null); + StringBuilder stringBuilder = new StringBuilder(); + if (criteria.getLike() != null) stringBuilder.append("?search=" + criteria.getLike()); + if (property.getDependencies() != null && !property.getDependencies().isEmpty() && criteria.getDynamicFields() != null && !criteria.getDynamicFields().isEmpty()) { + property.getDependencies().stream().forEach(item -> { + DynamicFieldsCriteria.DynamicFieldDependencyCriteria dependencyCriteria = criteria.getDynamicFields().stream().filter(dfield -> dfield.getProperty().equals(item.getId())) + .findFirst().orElse(null); + if (dependencyCriteria != null) { + if (criteria.getLike() != null || property.getDependencies().indexOf(item) > 0) + stringBuilder.append("&"); + stringBuilder.append(item.getQueryProperty() + "=" + dependencyCriteria.getValue()); + } + }); + + ResponseEntity response = restTemplate.exchange(property.getSourceUrl() + stringBuilder.toString(), HttpMethod.GET, entity, ArrayList.class); + response.getBody().forEach(item -> { + Tuple tuple = new Tuple<>(); + tuple.setId((String) (((Map) item).get(property.getExternalFieldId()))); + tuple.setLabel((String) (((Map) item).get(property.getExternalFieldLabel()))); + result.add(tuple); + }); + + } else { + ResponseEntity response = restTemplate.exchange(property.getSourceUrl() + stringBuilder.toString(), HttpMethod.GET, entity, ArrayList.class); + response.getBody().forEach(item -> { + Tuple tuple = new Tuple<>(); + tuple.setId((String) (((Map) item).get(property.getExternalFieldId()))); + tuple.setLabel((String) (((Map) item).get(property.getExternalFieldLabel()))); + result.add(tuple); + }); + } + return result; + } + + public DataTableData getDatasetProfilesUsedByDMP(DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) { + datasetProfileTableRequestItem.getCriteria().setFilter(DatasetProfileCriteria.DatasetProfileFilter.DMPs.getValue()); + datasetProfileTableRequestItem.getCriteria().setUserId(principal.getId()); + + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria()); + List listingModels = items.select(item -> new DatasetProfileListingModel().fromDataModel(item)); + + DataTableData data = new DataTableData<>(); + data.setData(listingModels); + data.setTotalCount((long) listingModels.size()); + + return data; + } + + public List getAllVersions(String groupId, Principal principal, Boolean isPublic) { + UUID principalId = principal != null ? principal.getId() : null; + List versions = new ArrayList<>(); + QueryableList items = null; + QueryableList authItems = null; + List roles = new LinkedList<>(); + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setGroupIds(Collections.singletonList(UUID.fromString(groupId))); + criteria.setAllVersions(true); + criteria.setIsPublic(isPublic); + criteria.setOnlyPublic(isPublic); + items = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria); + if (!isPublic) { + authItems = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(items, principalId, roles); + } else { + authItems = items; + } + CompletableFuture> versionFuture = authItems.withHint(HintedModelFactory.getHint(VersionListingModel.class)) + .orderBy(((builder, root) -> builder.desc(root.get("version")))) + .selectAsync(item -> new VersionListingModel().fromDataModel(item)) + .whenComplete(((versionListingModels, throwable) -> versions.addAll(versionListingModels))); + + CompletableFuture.allOf(versionFuture).join(); + + return versions; + } + + /* + * Data Management + * */ + + @Transactional + public DMP createOrUpdate(DataManagementPlanEditorModel dataManagementPlan, Principal principal) throws Exception { + boolean setNotification = false; + if (dataManagementPlan.getId() != null) { + DMP dmp1 = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId()); + + Instant dbTime = Instant.ofEpochMilli(dmp1.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS); + Instant modelTime = Instant.ofEpochMilli(dataManagementPlan.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS); + + if (!isUserOwnerOfDmp(dmp1, principal)) { + throw new Exception("User not being the creator is not authorized to edit this DMP."); + } + if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) { + throw new Exception("Another user have already edit that DMP."); + } + List datasetList = dmp1.getDataset().stream().filter(dataset -> dataset.getStatus() != 99).collect(Collectors.toList()); + for (eu.eudat.old.data.entities.Dataset dataset : datasetList) { + if (dataManagementPlan.getProfiles().stream().filter(associatedProfile -> dataset.getProfile().getId().equals(associatedProfile.getDescriptionTemplateId())).findAny().orElse(null) == null) + throw new Exception("Dataset Template for Dataset Description is missing from the DMP."); + } + if (dataManagementPlan.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue() && dmp1.getStatus().equals(DMP.DMPStatus.FINALISED.getValue())) + throw new Exception("DMP is finalized, therefore cannot be edited."); + + setNotification = true; + } else { + metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); + } + + DMP newDmp = dataManagementPlan.toDataModel(); + if(dataManagementPlan.getProfile() != null){ + DMPProfile dmpProfile = apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().find(dataManagementPlan.getProfile()); + newDmp.setProfile(dmpProfile); + } + if (newDmp.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue()) { + checkDmpValidationRules(newDmp); + } + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + newDmp.setCreator(user); + + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS, principal)) { + createOrganisationsIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao()); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.RESEARCHERS, principal)) { + createResearchersIfTheyDontExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao(), user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) { + createFunderIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getFunderDao()); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) { + createGrantIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getGrantDao()); + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) { + if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) { + newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); + } + createProjectIfItDoesntExist(newDmp, apiContext.getOperationsContext().getDatabaseRepository().getProjectDao()); + } + } + + DMP dmp; + if (dataManagementPlan.getId() != null) { + dmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId()); + } else dmp = new DMP(); + + newDmp.setCreated(dmp.getCreated() == null ? new Date() : dmp.getCreated()); + if (newDmp.getUsers()!= null && newDmp.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()) + .collect(Collectors.toList()).size() == 0) { + List userDMPList = new ArrayList<>(newDmp.getUsers()); + for (UserInfoListingModel userInfoListingModel : dataManagementPlan.getUsers()) { + for (UserDMP userDMP : userDMPList) { + if (!(userDMP.getUser().getId().equals(userInfoListingModel.getId()))) { + apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().delete(userDMP); + } + } + } + } + + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) { + if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(eu.eudat.old.data.entities.Grant.GrantType.INTERNAL.getValue())) { + checkIfUserCanEditGrant(newDmp, user); + } + assignGrandUserIfInternal(newDmp, user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) { + assignFunderUserIfInternal(newDmp, user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) { + assignProjectUserIfInternal(newDmp, user); + } + + if(newDmp.getId() != null){ + for(DMPDatasetProfile dmpDatasetProfile : newDmp.getAssociatedDmps()){ + apiContext.getOperationsContext().getDatabaseRepository().getDmpDatasetProfileDao().createOrUpdate(dmpDatasetProfile); + } + } + + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) { + if (newDmp.getGrant() != null) { + apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().createOrUpdate(newDmp.getGrant()); + } + } + newDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp); + + for(DMPDatasetProfile dmpDatasetProfile : newDmp.getAssociatedDmps()){ + apiContext.getOperationsContext().getDatabaseRepository().getDmpDatasetProfileDao().createOrUpdate(dmpDatasetProfile); + } + + if (dataManagementPlan.getUsers() != null && !dataManagementPlan.getUsers().isEmpty()) { + clearUsers(newDmp); + for (UserInfoListingModel userListing : dataManagementPlan.getUsers()) { + UserInfo tempUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userListing.getId()); + assignUser(dmp, tempUser, UserDMP.UserDMPRoles.fromInteger(userListing.getRole())); + } + } + + // Dataset manipulation for when the DMP is set to be finalized. + if (dataManagementPlan.getStatus() == DMP.DMPStatus.FINALISED.getValue()) { + if (dataManagementPlan.getDatasetsToBeFinalized() != null && !dataManagementPlan.getDatasetsToBeFinalized().isEmpty()) { + apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() + .asQueryable().where((builder, root) -> root.get("id").in(dataManagementPlan.getDatasetsToBeFinalized())) + .update(root -> root.get("status"), eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()); + apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() + .asQueryable().where((builder, root) -> root.get("id").in(dataManagementPlan.getDatasetsToBeFinalized())) + .update(root -> root.get("finalizedat"), new Date()); + + List datasetsToBeCanceled = new LinkedList<>(); + for (DatasetWizardModel dataset : dataManagementPlan.getDatasets()) { + if (!(dataset.getStatus() == (int) eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()) && !dataManagementPlan.getDatasetsToBeFinalized().contains(dataset.getId())) { + datasetsToBeCanceled.add(UUID.fromString(dataset.getId().toString())); + } + } + if (!datasetsToBeCanceled.isEmpty()) + apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() + .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeCanceled)) + .update(root -> root.get("status"), eu.eudat.old.data.entities.Dataset.Status.CANCELED.getValue()); + } else { + List datasetsToBeCanceled = new LinkedList<>(); + for (DatasetWizardModel dataset : dataManagementPlan.getDatasets()) { + if (!(dataset.getStatus() == (int) eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue())) { + datasetsToBeCanceled.add(dataset.getId()); + } + } + if (!datasetsToBeCanceled.isEmpty()) + apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() + .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeCanceled)) + .update(root -> root.get("status"), eu.eudat.old.data.entities.Dataset.Status.CANCELED.getValue()); + } + } + + if (dataManagementPlan.getAssociatedUsers().size() == 0) + assignUser(newDmp, user); + + UUID dmpId = newDmp.getId(); + newDmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + + this.updateIndex(newDmp); + + if (setNotification) { + if (newDmp.getStatus() != DMP.DMPStatus.FINALISED.getValue()) { + this.sendNotification(newDmp, user, NotificationType.DMP_MODIFIED); + } else { + this.sendNotification(newDmp, user, NotificationType.DMP_MODIFIED_FINALISED); + } + } + + return newDmp; + } + + public DMP createOrUpdateWithDatasets(DataManagementPlanEditorModel dataManagementPlan, Principal principal) throws Exception { + if (dataManagementPlan.getId() != null) { + DMP dmp1 = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(dataManagementPlan.getId()); + + Instant dbTime = Instant.ofEpochMilli(dmp1.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS); + Instant modelTime = Instant.ofEpochMilli(dataManagementPlan.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS); + + if (!isUserOwnerOfDmp(dmp1, principal)) { + throw new Exception("User not being the creator is not authorized to edit this DMP."); + } + if (dbTime.toEpochMilli() != modelTime.toEpochMilli()) { + throw new Exception("Another user have already edit that DMP."); + } + for (DatasetWizardModel dataset : dataManagementPlan.getDatasets()) { + if (dataManagementPlan.getProfiles().stream().filter(associatedProfile -> dataset.getProfile().getId().equals(associatedProfile.getDescriptionTemplateId())).findAny().orElse(null) == null) + throw new Exception("Dataset Template for Dataset Description is missing from the DMP."); + } + if (dataManagementPlan.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue() && dmp1.getStatus().equals(DMP.DMPStatus.FINALISED.getValue())) + throw new Exception("DMP is finalized, therefore cannot be edited."); + } else { + metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); + } + List datasets = new ArrayList<>(); + DMP tempDMP = dataManagementPlan.toDataModel(); + if (tempDMP.getStatus() == (int) DMP.DMPStatus.FINALISED.getValue()) { + checkDmpValidationRules(tempDMP); + } + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.ORGANIZATIONS, principal)) { + createOrganisationsIfTheyDontExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getOrganisationDao()); + } + if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.RESEARCHERS, principal)) { + createResearchersIfTheyDontExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao(), user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.FUNDER, principal)) { + createFunderIfItDoesntExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getFunderDao()); + } + if(this.dataManagementProfileManager.fieldInBlueprint(tempDMP.getProfile(), SystemFieldType.GRANT, principal)) { + createGrantIfItDoesntExist(tempDMP, apiContext.getOperationsContext().getDatabaseRepository().getGrantDao()); + } + + DMP result = createOrUpdate(dataManagementPlan, principal); + + for (DatasetWizardModel datasetWizardModel: dataManagementPlan.getDatasets()) { + datasetWizardModel.setDmp(new DataManagementPlan().fromDataModel(result)); + eu.eudat.old.data.entities.Dataset dataset = datasetManager.createOrUpdate(datasetWizardModel, principal); + datasets.add(dataset); + } + + UUID dmpId = result.getId(); + result.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + + this.updateIndex(result); + + return result; + } + + public UUID newVersion(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception { + DMP oldDmp = databaseRepository.getDmpDao().find(uuid); + if (!isUserOwnerOfDmp(oldDmp, principal)) { + throw new Exception("User not being the creator is not authorized to perform this action."); + } + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + LinkedList list = new LinkedList<>(); + list.push(oldDmp.getGroupId()); + criteria.setGroupIds(list); + criteria.setAllVersions(false); + QueryableList dataManagementPlanQueryableList = databaseRepository.getDmpDao().getWithCriteria(criteria); + List latestVersionDMP = dataManagementPlanQueryableList.toList(); + + if (latestVersionDMP.get(0).getVersion().equals(oldDmp.getVersion())) { + DMP newDmp = dataManagementPlan.toDataModel(); + newDmp.setProfile(oldDmp.getProfile()); + newDmp.setProperties(oldDmp.getProperties()); + newDmp.setDmpProperties(oldDmp.getDmpProperties()); + UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build(); + newDmp.setCreator(user); + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS, principal)) { + createOrganisationsIfTheyDontExist(newDmp, databaseRepository.getOrganisationDao()); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.RESEARCHERS, principal)) { + createResearchersIfTheyDontExist(newDmp, databaseRepository.getResearcherDao(), user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) { + createFunderIfItDoesntExist(newDmp, databaseRepository.getFunderDao()); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) { + createGrantIfItDoesntExist(newDmp, databaseRepository.getGrantDao()); + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) { + if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) { + newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); + } + createProjectIfItDoesntExist(newDmp, databaseRepository.getProjectDao()); + } + } + + newDmp.setGroupId(oldDmp.getGroupId()); + newDmp.setVersion(oldDmp.getVersion() + 1); + newDmp.setId(null); + + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) { + if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(eu.eudat.old.data.entities.Grant.GrantType.INTERNAL.getValue())) { + checkIfUserCanEditGrant(newDmp, user); + } + assignGrandUserIfInternal(newDmp, user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) { + assignFunderUserIfInternal(newDmp, user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) { + assignProjectUserIfInternal(newDmp, user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) { + if (newDmp.getGrant() != null) { + if (newDmp.getGrant().getStartdate() == null) { + newDmp.getGrant().setStartdate(new Date()); + } + if (newDmp.getGrant().getEnddate() == null) { + newDmp.getGrant().setEnddate(Date.from(Instant.now().plus(365, ChronoUnit.DAYS))); + } + databaseRepository.getGrantDao().createOrUpdate(newDmp.getGrant()); + } + } + DMP tempDmp = databaseRepository.getDmpDao().createOrUpdate(newDmp); + newDmp.setId(tempDmp.getId()); + for(DMPDatasetProfile dmpDatasetProfile : newDmp.getAssociatedDmps()){ + apiContext.getOperationsContext().getDatabaseRepository().getDmpDatasetProfileDao().createOrUpdate(dmpDatasetProfile); + } + + // Assign creator. + //assignUser(newDmp, user); + + copyDatasets(newDmp, databaseRepository.getDatasetDao()); + + databaseRepository + .getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), oldDmp.getId())) + .toList().stream().forEach(userDMP -> { + UserDMP temp = new UserDMP(); + temp.setUser(userDMP.getUser()); + temp.setRole(userDMP.getRole()); + temp.setDmp(newDmp); + apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(temp); + }); + + newDmp.setUsers(new HashSet<>(databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), newDmp.getId())).toList())); + + DatasetCriteria criteria1 = new DatasetCriteria(); + criteria1.setDmpIds(Collections.singletonList(newDmp.getId())); + newDmp.setDataset(new HashSet<>(databaseRepository.getDatasetDao().getWithCriteria(criteria1).toList())); + + this.updateGroupIndex(newDmp.getGroupId()); + return newDmp.getId(); + } else { + throw new DMPNewVersionException("Version to update not the latest."); + } + } + + public UUID clone(UUID uuid, DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception { + DMP oldDmp = databaseRepository.getDmpDao().find(uuid); + DMP newDmp = dataManagementPlan.toDataModel(); + newDmp.setProfile(oldDmp.getProfile()); + newDmp.setProperties(oldDmp.getProperties()); + newDmp.setDmpProperties(oldDmp.getDmpProperties()); + + UserInfo user = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build(); + newDmp.setCreator(user); + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.ORGANIZATIONS, principal)) { + createOrganisationsIfTheyDontExist(newDmp, databaseRepository.getOrganisationDao()); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.RESEARCHERS, principal)) { + createResearchersIfTheyDontExist(newDmp, databaseRepository.getResearcherDao(), user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) { + createFunderIfItDoesntExist(newDmp, databaseRepository.getFunderDao()); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) { + createGrantIfItDoesntExist(newDmp, databaseRepository.getGrantDao()); + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) { + if (newDmp.getProject() != null && newDmp.getGrant() != null && (newDmp.getProject().getLabel() == null || newDmp.getProject().getLabel().trim().isEmpty())) { + newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); + } + createProjectIfItDoesntExist(newDmp, databaseRepository.getProjectDao()); + } + } + + newDmp.setGroupId(UUID.randomUUID()); + newDmp.setVersion(0); + newDmp.setId(null); + + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) { + if (newDmp.getGrant() != null && newDmp.getGrant().getType().equals(eu.eudat.old.data.entities.Grant.GrantType.INTERNAL.getValue())) { + checkIfUserCanEditGrant(newDmp, user); + } + assignGrandUserIfInternal(newDmp, user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.FUNDER, principal)) { + assignFunderUserIfInternal(newDmp, user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.PROJECT, principal)) { + assignProjectUserIfInternal(newDmp, user); + } + if(this.dataManagementProfileManager.fieldInBlueprint(newDmp.getProfile(), SystemFieldType.GRANT, principal)) { + if (newDmp.getGrant() != null) { + databaseRepository.getGrantDao().createOrUpdate(newDmp.getGrant()); + } + } + DMP tempDmp = databaseRepository.getDmpDao().createOrUpdate(newDmp); + newDmp.setId(tempDmp.getId()); + for(DMPDatasetProfile dmpDatasetProfile : newDmp.getAssociatedDmps()){ + apiContext.getOperationsContext().getDatabaseRepository().getDmpDatasetProfileDao().createOrUpdate(dmpDatasetProfile); + } + + assignUser(newDmp, user); + copyDatasets(newDmp, databaseRepository.getDatasetDao()); + + newDmp.setUsers(new HashSet<>(databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), newDmp.getId())).toList())); + + DatasetCriteria criteria1 = new DatasetCriteria(); + criteria1.setDmpIds(Collections.singletonList(newDmp.getId())); + newDmp.setDataset(new HashSet<>(databaseRepository.getDatasetDao().getWithCriteria(criteria1).toList())); + UUID dmpId = newDmp.getId(); + newDmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + + this.updateIndex(newDmp); + metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); + + return newDmp.getId(); + } + + public void delete(UUID uuid) throws DMPWithDatasetsDeleteException, IOException { + DatasetCriteria criteria = new DatasetCriteria(); + List dmpIds = Collections.singletonList(uuid); + criteria.setDmpIds(dmpIds); + if (apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).toList().size() > 0) + throw new DMPWithDatasetsDeleteException("You cannot Remove Datamanagement Plan with Datasets"); + DMP oldDmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(uuid); + switch (oldDmp.getStatus()) { + case 0: + metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); + break; + case 1: + if (oldDmp.getDois() != null && !oldDmp.getDois().isEmpty()) { + metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.DOIED); + } + if (oldDmp.isPublic()) { + metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.PUBLISHED); + } + metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.FINALIZED); + break; + } + oldDmp.setStatus(DMP.DMPStatus.DELETED.getValue()); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(oldDmp); + UUID dmpId = oldDmp.getId(); + oldDmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + this.updateIndex(oldDmp); + DataManagementPlanCriteria criteria1 = new DataManagementPlanCriteria(); + criteria1.setAllVersions(true); + criteria1.setGroupIds(Collections.singletonList(oldDmp.getGroupId())); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria1).toList().forEach(dmp -> { + try { + UUID tdmpId = dmp.getId(); + dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), tdmpId)).toList())); + this.updateIndex(dmp); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + for (eu.eudat.old.data.entities.Dataset dataset: dmp.getDataset()) { + try { + List tags = new ArrayList<>(); + Dataset elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString()); + if (elastic != null) { + tags = elastic.getTags(); + } + dataset.setDmp(dmp); + this.datasetManager.updateTags(dataset, tags); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } + }); + } + + private void createResearchersIfTheyDontExist(DMP newDmp, ResearcherDao researcherRepository, UserInfo user) { + if (newDmp.getResearchers() != null && !newDmp.getResearchers().isEmpty()) { + for (Researcher researcher : newDmp.getResearchers()) { + ResearcherCriteria criteria = new ResearcherCriteria(); + criteria.setReference(researcher.getReference()); + List entries = researcherRepository.getWithCriteria(criteria).toList(); + if (entries != null && !entries.isEmpty()) researcher.setId(entries.get(0).getId()); + else { + researcher.setCreationUser(user); + researcherRepository.createOrUpdate(researcher); + metricsManager.increaseValue(MetricNames.RESEARCHER, 1, null); + } + } + } + } + + private void createOrganisationsIfTheyDontExist(DMP newDmp, OrganisationDao organisationRepository) { + if (newDmp.getOrganisations() != null && !newDmp.getOrganisations().isEmpty()) { + for (Organisation organisation : newDmp.getOrganisations()) { + boolean createNew = false; + if (organisation.getReference() != null) { + OrganisationCriteria criteria = new OrganisationCriteria(); + criteria.setLike(organisation.getReference()); + List entries = organisationRepository.getWithCriteria(criteria).toList(); + if (entries != null && !entries.isEmpty()) organisation.setId(entries.get(0).getId()); + else createNew = true; + } else { + createNew = true; + } + + if (createNew) { + if (organisation.getReference() == null) { + organisation.setReference("Internal:" + UUID.randomUUID().toString()); + } + organisationRepository.createOrUpdate(organisation); + } + } + } + } + + private void createGrantIfItDoesntExist(DMP newDmp, GrantDao grantDao) { + if (newDmp.getGrant() != null) { + eu.eudat.old.data.entities.Grant grant = newDmp.getGrant(); + GrantCriteria criteria = new GrantCriteria(); + if (grant.getReference() != null) { + criteria.setReference(grant.getReference()); + eu.eudat.old.data.entities.Grant grantEntity = grantDao.getWithCriteria(criteria).toList().stream().max(Comparator.comparing(grant1 -> grant1.getModified().getTime())).orElse(null); + if (grantEntity != null) grant.setId(grantEntity.getId()); + else { + grant.setType(eu.eudat.old.data.entities.Grant.GrantType.EXTERNAL.getValue()); + grant.setCreationUser(null); + if (grant.getStartdate() == null) { + grant.setStartdate(new Date()); + } + if (grant.getEnddate() == null) { + grant.setEnddate(Date.from(Instant.now().plus(365, ChronoUnit.DAYS))); + } + grantDao.createOrUpdate(grant); + } + } + else { + grant.setType(eu.eudat.old.data.entities.Grant.GrantType.EXTERNAL.getValue()); + grant.setCreationUser(null); + grantDao.createOrUpdate(grant); + } + } + } + + private void createFunderIfItDoesntExist(DMP newDmp, FunderDao funderDao) { + if (newDmp.getGrant() != null && newDmp.getGrant().getFunder() != null) { + eu.eudat.old.data.entities.Funder funder = newDmp.getGrant().getFunder(); + FunderCriteria criteria = new FunderCriteria(); + if (funder.getReference() != null) { + criteria.setReference(funder.getReference()); + eu.eudat.old.data.entities.Funder funderEntity = funderDao.getWithCritetia(criteria).toList().stream().max(Comparator.comparing(funder1 -> funder1.getModified().getTime())).orElse(null); + if (funderEntity != null) funder.setId(funderEntity.getId()); + else { + funderDao.createOrUpdate(funder); + } + } + else { + funderDao.createOrUpdate(funder); + } + } + } + + private void createProjectIfItDoesntExist(DMP newDmp, ProjectDao projectDao) { + if (newDmp.getProject() != null) { + eu.eudat.old.data.entities.Project project = newDmp.getProject(); + ProjectCriteria criteria = new ProjectCriteria(); + if (project.getReference() != null) { + criteria.setReference(project.getReference()); + eu.eudat.old.data.entities.Project projectEntity = projectDao.getWithCritetia(criteria).toList().stream().max(Comparator.comparing(project1 -> project1.getModified().getTime())).orElse(null); + if (projectEntity != null) project.setId(projectEntity.getId()); + else { + createExternalProject(project, projectDao); + } + } + else { + createExternalProject(project, projectDao); + } + } + } + + private void createExternalProject(eu.eudat.old.data.entities.Project project, ProjectDao projectDao) { + if (project.getStartdate() == null) project.setStartdate(new Date()); + if (project.getEnddate() == null) project.setEnddate(new Date()); + project.setType(eu.eudat.old.data.entities.Project.ProjectType.EXTERNAL.getValue()); + if (project.getId() == null) project.setId(UUID.randomUUID()); + projectDao.createOrUpdate(project); + metricsManager.increaseValue(MetricNames.PROJECT, 1, null); + } + + private void copyDatasets(DMP newDmp, DatasetDao datasetDao) { + List> futures = new LinkedList<>(); + for (eu.eudat.old.data.entities.Dataset dataset : newDmp.getDataset()) { + eu.eudat.old.data.entities.Dataset tempDataset = datasetDao.find(dataset.getId()); + try { + List tags = new ArrayList<>(); + Dataset elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString()); + if (elastic != null) { + tags = elastic.getTags(); + } + UUID dmpId = tempDataset.getDmp().getId(); + tempDataset.getDmp().setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + this.datasetManager.updateTags(tempDataset, tags); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + datasetDao.asQueryable().withHint(HintedModelFactory.getHint(DatasetListingModel.class)).where((builder, root) -> builder.equal(root.get("id"), dataset.getId())).getSingleAsync() + .thenApplyAsync(entityDataset -> { + eu.eudat.old.data.entities.Dataset newDataset = new eu.eudat.old.data.entities.Dataset(); + newDataset.update(entityDataset); + newDataset.setDmp(newDmp); + newDataset.setStatus(eu.eudat.old.data.entities.Dataset.Status.SAVED.getValue()); + if (newDataset.getDatasetDataRepositories() != null) { + newDataset.setDatasetDataRepositories(newDataset.getDatasetDataRepositories().stream().map(item -> { + DataRepository dataRepository = new DataRepository(); + dataRepository.setId(item.getDataRepository().getId()); + + DatasetDataRepository datasetDataRepository = new DatasetDataRepository(); + datasetDataRepository.setDataRepository(dataRepository); + datasetDataRepository.setDataset(newDataset); + datasetDataRepository.setData(item.getData()); + return datasetDataRepository; + }).collect(Collectors.toSet())); + } + + if (newDataset.getDatasetExternalDatasets() != null) { + newDataset.setDatasetExternalDatasets(newDataset.getDatasetExternalDatasets().stream().map(item -> { + ExternalDataset externalDataset = new ExternalDataset(); + externalDataset.setId(item.getExternalDataset().getId()); + DatasetExternalDataset datasetExternalDataset = new DatasetExternalDataset(); + datasetExternalDataset.setExternalDataset(externalDataset); + datasetExternalDataset.setDataset(newDataset); + datasetExternalDataset.setData(item.getData()); + return datasetExternalDataset; + }).collect(Collectors.toSet())); + } + + if (newDataset.getRegistries() != null) { + newDataset.setRegistries(newDataset.getRegistries().stream().map(item -> { + Registry registry = new Registry(); + registry.setId(item.getId()); + return registry; + }).collect(Collectors.toSet())); + } + + if (newDataset.getServices() != null) { + newDataset.setServices(newDataset.getServices().stream().map(item -> { + Service service = new Service(); + service.setId(item.getId()); + DatasetService datasetService = new DatasetService(); + datasetService.setService(service); + datasetService.setDataset(newDataset); + datasetService.setData(item.getData()); + return datasetService; + }).collect(Collectors.toSet())); + } + newDataset.setCreated(new Date()); + return newDataset; + }).thenApplyAsync(item -> { + futures.add(datasetDao.createOrUpdateAsync(item).whenComplete(((dataset1, throwable) -> { + metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.DRAFT); + Dataset datasetElastic = new Dataset(); + datasetElastic.setId(dataset1.getId().toString()); + datasetElastic.setLabel(dataset1.getLabel()); + datasetElastic.setDescription(dataset1.getDescription()); + datasetElastic.setTemplate(dataset1.getProfile().getId()); + datasetElastic.setStatus(dataset1.getStatus()); + datasetElastic.setDmp(dataset1.getDmp().getId()); + datasetElastic.setGroup(dataset1.getDmp().getGroupId()); + if(this.dataManagementProfileManager.fieldInBlueprint(dataset1.getDmp().getProfile(), SystemFieldType.GRANT, null)) { + datasetElastic.setGrant(dataset1.getDmp().getGrant().getId()); + } + if (dataset1.getDmp().getUsers() != null) { + datasetElastic.setCollaborators(dataset1.getDmp().getUsers().stream().map(user -> { + Collaborator collaborator = new Collaborator(); + collaborator.setId(user.getId().toString()); + collaborator.setRole(user.getRole()); + // collaborator.setName(user.getUser().getName()); + return collaborator; + }).collect(Collectors.toList())); + } + datasetElastic.setLastVersion(true); + datasetElastic.setLastPublicVersion(false); + if (dataset1.getDmp().getOrganisations() != null) { + datasetElastic.setOrganizations(dataset1.getDmp().getOrganisations().stream().map(org -> { + Organization organization = new Organization(); + organization.setId(org.getId().toString()); + organization.setName(org.getLabel()); + return organization; + }).collect(Collectors.toList())); + } + datasetElastic.setPublic(dataset1.getDmp().isPublic()); + if(this.dataManagementProfileManager.fieldInBlueprint(dataset1.getDmp().getProfile(), SystemFieldType.GRANT, null)) { + datasetElastic.setGrantStatus(dataset1.getDmp().getGrant().getStatus()); + } + + try { + Dataset oldDatasetElastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString()); + if (oldDatasetElastic != null) { + datasetElastic.setTags(oldDatasetElastic.getTags()); + } + datasetElastic.setFormData(this.datasetManager.getWordDocumentText(dataset1)); + apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().createOrUpdate(datasetElastic); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }))); + return futures; + }).join(); + + } + } + + public void makePublic(UUID id, Principal principal) throws Exception { + DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id); + // Check if dmp is finalized and if user is owner. + if (!isUserOwnerOfDmp(dmp, principal)) + throw new Exception("User does not have the privilege to do this action."); + if (!dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue())) + throw new Exception("DMP is not finalized"); + dmp.setPublic(true); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(dmp); + UUID dmpId = dmp.getId(); + dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + this.updateIndex(dmp); + metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.PUBLISHED); + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setGroupIds(Collections.singletonList(dmp.getGroupId())); + criteria.setAllVersions(true); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).toList().stream().forEach(dmp1 -> { + dmp1.getDataset().forEach(dataset -> { + try { + List tags = new ArrayList<>(); + Dataset elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString()); + if (elastic != null) { + tags = elastic.getTags(); + } + UUID tmdmpId = dataset.getDmp().getId(); + dataset.getDmp().setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), tmdmpId)).toList())); + this.datasetManager.updateTags(dataset, tags); + metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.PUBLISHED); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }); + }); + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + sendNotification(dmp, user, NotificationType.DMP_PUBLISH); + } + + @Transactional + public void makeFinalize(UUID id, Principal principal, DatasetsToBeFinalized datasetsToBeFinalized) throws Exception { + DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id); + if (!isUserOwnerOfDmp(dmp, principal)) + throw new Exception("User does not have the privilege to do this action."); + if (dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue())) + throw new Exception("DMP is already finalized"); + List indexDatasets = new ArrayList<>(); + if (datasetsToBeFinalized != null && datasetsToBeFinalized.getUuids() != null && !datasetsToBeFinalized.getUuids().isEmpty()) { + List finalizedDatasets = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() + .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeFinalized.getUuids())) + .toList(); + for (eu.eudat.old.data.entities.Dataset dataset: finalizedDatasets) { + eu.eudat.old.data.entities.Dataset.Status status = eu.eudat.old.data.entities.Dataset.Status.fromInteger(dataset.getStatus()); + Date finalizedDate = dataset.getFinalizedAt(); + dataset.setStatus(eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()); + dataset.setFinalizedAt(new Date()); + DatasetWizardModel wizardModel = new DatasetWizardModel(); + wizardModel = wizardModel.fromDataModel(dataset); + wizardModel.setDatasetProfileDefinition(this.datasetManager.getPagedProfile(wizardModel, dataset)); + try { + datasetManager.createOrUpdate(wizardModel, principal); + } catch (Exception e) { + dataset.setStatus(status.getValue()); + dataset.setFinalizedAt(finalizedDate); + throw e; + } + dataset.setModified(new Date()); + } + /*apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() + .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeFinalized.getUuids())) + .update(root -> root.get("finalizedAt"), new Date());*/ + //List finalizedDatasets = dmp.getDataset().stream().filter(dataset -> datasetsToBeFinalized.getUuids().contains(dataset.getId())).collect(Collectors.toList()); +/* finalizedDatasets.forEach(dataset ->{ + dataset.setStatus(Dataset.Status.FINALISED.getValue()); + dataset.setFinalizedAt(new Date()); + dataset.setModified(new Date()); + } );*/ + indexDatasets.addAll(finalizedDatasets); + List datasetsToBeCanceled = new LinkedList<>(); + for (eu.eudat.old.data.entities.Dataset dataset : dmp.getDataset()) { + if (!dataset.getStatus().equals(eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()) && !datasetsToBeFinalized.getUuids().contains(dataset.getId())) { + datasetsToBeCanceled.add(dataset.getId()); + } + } + if (!datasetsToBeCanceled.isEmpty()) { + apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() + .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeCanceled)) + .update(root -> root.get("status"), eu.eudat.old.data.entities.Dataset.Status.CANCELED.getValue()); + List cancelledDatasets = dmp.getDataset().stream().filter(dataset -> datasetsToBeCanceled.contains(dataset.getId())).collect(Collectors.toList()); + cancelledDatasets.forEach(dataset -> dataset.setStatus(eu.eudat.old.data.entities.Dataset.Status.CANCELED.getValue())); + indexDatasets.addAll(cancelledDatasets); + } + } else { + List datasetsToBeCanceled = new LinkedList<>(); + for (eu.eudat.old.data.entities.Dataset dataset : dmp.getDataset()) { + if (!dataset.getStatus().equals(eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue())) { + datasetsToBeCanceled.add(dataset.getId()); + } + } + if (!datasetsToBeCanceled.isEmpty()) { + apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao() + .asQueryable().where((builder, root) -> root.get("id").in(datasetsToBeCanceled)) + .update(root -> root.get("status"), eu.eudat.old.data.entities.Dataset.Status.CANCELED.getValue()); + List cancelledDatasets = dmp.getDataset().stream().filter(dataset -> datasetsToBeCanceled.contains(dataset.getId())).collect(Collectors.toList()); + cancelledDatasets.forEach(dataset -> dataset.setStatus(eu.eudat.old.data.entities.Dataset.Status.CANCELED.getValue())); + indexDatasets.addAll(cancelledDatasets); + } + } + dmp.setStatus(DMP.DMPStatus.FINALISED.getValue()); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(dmp); + UUID dmpId = dmp.getId(); + dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + this.updateIndex(dmp); + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + sendNotification(dmp, user, NotificationType.DMP_FINALISED); + metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); + metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.FINALIZED); + this.updateDatasetsIndex(indexDatasets); + metricsManager.decreaseValue(MetricNames.DATASET, indexDatasets.size(), MetricNames.DRAFT); + metricsManager.increaseValue(MetricNames.DATASET, indexDatasets.size(), MetricNames.FINALIZED); + } + + public void undoFinalize(UUID id, Principal principal) throws Exception { + DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id); + if (!isUserOwnerOfDmp(dmp, principal)) + throw new Exception("User does not have the privilege to do this action."); + if (dmp.getStatus().equals(DMP.DMPStatus.ACTIVE.getValue())) + throw new Exception("DMP is already Active"); + if (dmp.isPublic()) + throw new Exception("DMP is publicly available"); + if (!dmp.getDois().isEmpty()) + throw new Exception("DMP is deposited"); + dmp.setStatus(DMP.DMPStatus.ACTIVE.getValue()); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(dmp); + UUID dmpId = dmp.getId(); + dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + this.updateIndex(dmp); + metricsManager.decreaseValue(MetricNames.DMP, 1, MetricNames.FINALIZED); + metricsManager.increaseValue(MetricNames.DMP, 1, MetricNames.DRAFT); + } + + public void updateUsers(UUID id, List users, Principal principal) throws Exception { + DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(id); + if (!isUserOwnerOfDmp(dmp, principal)) + throw new Exception("User does not have the privilege to do this action."); + clearUsers(dmp); + for (UserInfoListingModel userListing : users) { + UserInfo tempUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userListing.getId()); + assignUser(dmp, tempUser, UserDMP.UserDMPRoles.fromInteger(userListing.getRole())); + } + + } + + /* + * Export Data + * */ + + public FileEnvelope getWordDocument(String id, Principal principal, ConfigLoader configLoader) throws IOException { + return this.getWordDocument(id, principal, configLoader, true); + } + + public FileEnvelope getWordDocument(String id, Principal principal, ConfigLoader configLoader, Boolean versioned) throws IOException { + WordBuilder wordBuilder = new WordBuilder(this.environment, configLoader); + VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl(); + DatasetWizardModel dataset = new DatasetWizardModel(); + XWPFDocument document = configLoader.getDocument(); + + DMP dmpEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); + if (!dmpEntity.isPublic() && dmpEntity.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()).collect(Collectors.toList()).size() == 0) + throw new UnauthorisedException(); + + wordBuilder.fillFirstPage(dmpEntity, null, document, false); + +// int powered_pos = document.getParagraphs().size() - 3; + int powered_pos = wordBuilder.findPosOfPoweredBy(document); + XWPFParagraph powered_par = null; + XWPFParagraph argos_img_par = null; + if(powered_pos != -1) { + powered_par = document.getParagraphArray(powered_pos); + argos_img_par = document.getParagraphArray(powered_pos + 1); + } + + +// // DMP info on top of the document. +// wordBuilder.addParagraphContent("Data Management Plan Information", document, ParagraphStyle.HEADER1, BigInteger.ZERO); +// // DMP title custom style. +// wordBuilder.addParagraphContent(dmpEntity.getLabel(), document, ParagraphStyle.HEADER2, BigInteger.ZERO); +// wordBuilder.addParagraphContent(dmpEntity.getDescription(), document, ParagraphStyle.HTML, BigInteger.ZERO); +// +// wordBuilder.addParagraphContent("Funder", document, ParagraphStyle.HEADER3, BigInteger.ZERO); +// if (dmpEntity.getGrant().getFunder() != null) +// wordBuilder.addParagraphContent(dmpEntity.getGrant().getFunder().getLabel(), document, ParagraphStyle.TEXT, BigInteger.ZERO); +// +// wordBuilder.addParagraphContent("Grant", document, ParagraphStyle.HEADER3, BigInteger.ZERO); +// wordBuilder.addParagraphContent(dmpEntity.getGrant().getLabel(), document, ParagraphStyle.TEXT, BigInteger.ZERO); +// +// wordBuilder.addParagraphContent("Organisations", document, ParagraphStyle.HEADER3, BigInteger.ZERO); +// if (dmpEntity.getOrganisations().size() > 0) { +// wordBuilder.addParagraphContent(dmpEntity.getOrganisations().stream().map(Organisation::getLabel).collect(Collectors.joining(", ")) +// , document, ParagraphStyle.TEXT, BigInteger.ZERO); +// } +// +// wordBuilder.addParagraphContent("Researchers", document, ParagraphStyle.HEADER3, BigInteger.ZERO); +// if (dmpEntity.getResearchers().size() > 0) { +// wordBuilder.addParagraphContent(dmpEntity.getResearchers().stream().map(Researcher::getLabel).collect(Collectors.joining(", ")) +// , document, ParagraphStyle.TEXT, BigInteger.ZERO); +// } +// +// /*wordBuilder.addParagraphContent("DMP Profile", document, ParagraphStyle.HEADER2, BigInteger.ZERO); +// if (dmpEntity.getProfile() != null){ +// wordBuilder.addParagraphContent(dmpEntity.getProfile().getLabel(), document, ParagraphStyle.TEXT, BigInteger.ZERO); +// }*/ +// +// // Page break at the end of the DMP title. +// XWPFParagraph parBreakDMP = document.createParagraph(); +// parBreakDMP.setPageBreak(true); +// +// wordBuilder.addParagraphContent("Datasets", document, ParagraphStyle.HEADER1, BigInteger.ZERO); +// // Space below Datasets. +// XWPFParagraph parBreakDatasets = document.createParagraph(); + + DMPProfile dmpProfile = dmpEntity.getProfile(); + DataManagementPlanBlueprintListingModel dmpBlueprintModel = new DataManagementPlanBlueprintListingModel(); + dmpBlueprintModel.fromDataModel(dmpProfile); + DataManagementPlanBlueprint dmpBlueprint = dmpBlueprintModel.getDefinition(); + for(Section section: dmpBlueprint.getSections()){ + wordBuilder.addParagraphContent(section.getOrdinal() + ". " + section.getLabel(), document, ParagraphStyle.HEADER1, BigInteger.ZERO, 0); +// XWPFParagraph sectionInfoParagraph = document.createParagraph(); +// sectionInfoParagraph.setSpacingBetween(1.0); +// XWPFRun runSectionTitle = sectionInfoParagraph.createRun(); +// runSectionTitle.setText("Title: "); +// runSectionTitle.setColor("000000"); +// XWPFRun runSectionTitleText = sectionInfoParagraph.createRun(); +// runSectionTitleText.setText(section.getLabel()); +// runSectionTitleText.setColor("116a78"); +// XWPFParagraph sectionDescriptionParagraph = document.createParagraph(); +// XWPFRun runSectionDescription = sectionDescriptionParagraph.createRun(); +// runSectionDescription.setText("Description: "); +// runSectionDescription.setColor("000000"); +// XWPFRun runSectionDescriptionText = sectionDescriptionParagraph.createRun(); +// runSectionDescriptionText.setText(section.getDescription()); +// runSectionDescriptionText.setColor("116a78"); + + //wordBuilder.addParagraphContent("Section Fields", document, ParagraphStyle.HEADER2, BigInteger.ZERO, 0); + section.getFields().sort(Comparator.comparingInt(FieldModel::getOrdinal)); + for(FieldModel field: section.getFields()){ + if(field.getCategory() == FieldCategory.SYSTEM){ + SystemField systemField = field.toSystemField(); + if (systemField.getType() == SystemFieldType.LANGUAGE) continue; + XWPFParagraph systemFieldParagraph = document.createParagraph(); +// systemFieldParagraph.setSpacingBetween(1.0); + XWPFRun runSyStemFieldTitle = systemFieldParagraph.createRun(); + runSyStemFieldTitle.setText(systemField.getLabel() +": "); + runSyStemFieldTitle.setColor("000000"); +// XWPFRun runSystemFieldTitleText = systemFieldParagraph.createRun(); +// runSystemFieldTitleText.setText(systemField.getLabel()); +// runSystemFieldTitleText.setColor("116a78"); +// if(systemField.getDescription() != null && !systemField.getDescription().isEmpty()){ +// XWPFParagraph systemFieldDescription = document.createParagraph(); +// systemFieldDescription.setSpacingBetween(1.0); +// XWPFRun runSyStemFieldDescription = systemFieldDescription.createRun(); +// runSyStemFieldDescription.setText("Description: "); +// runSyStemFieldDescription.setColor("000000"); +// XWPFRun runSystemFieldDescriptionText = systemFieldDescription.createRun(); +// runSystemFieldDescriptionText.setText(systemField.getDescription()); +// runSystemFieldDescriptionText.setColor("116a78"); +// } +// XWPFParagraph systemFieldInput = document.createParagraph(); +// systemFieldInput.setSpacingBetween(1.0); +// XWPFRun runInput = systemFieldInput.createRun(); +// runInput.setText("Input: "); +// runInput.setColor("000000"); + switch (systemField.getType()) { + case TEXT: + XWPFRun runTitle = systemFieldParagraph.createRun(); + runTitle.setText(dmpEntity.getLabel()); + runTitle.setColor("116a78"); + break; + case HTML_TEXT: + wordBuilder.addParagraphContent(dmpEntity.getDescription(), document, ParagraphStyle.HTML, BigInteger.ZERO, 0); + break; + case RESEARCHERS: + for(Researcher researcher: dmpEntity.getResearchers()){ + XWPFRun runResearcher = systemFieldParagraph.createRun(); + runResearcher.addBreak(); + runResearcher.setText("• " + researcher.getLabel()); + runResearcher.setColor("116a78"); + } + break; + case ORGANIZATIONS: + for(Organisation organisation: dmpEntity.getOrganisations()){ + XWPFRun runOrganisation = systemFieldParagraph.createRun(); + runOrganisation.addBreak(); + runOrganisation.setText("• " + organisation.getLabel()); + runOrganisation.setColor("116a78"); + } + break; +// case LANGUAGE: +// XWPFRun runLanguage = systemFieldParagraph.createRun(); +// runLanguage.setText(objectMapper.readValue(dmpEntity.getExtraProperties(), HashMap.class).get("language").toString()); +// runLanguage.setColor("116a78"); +// break; + case CONTACT: + XWPFRun runContact = systemFieldParagraph.createRun(); + runContact.setText(dmpEntity.getCreator() == null ? "" : dmpEntity.getCreator().getName()); + runContact.setColor("116a78"); + break; + case FUNDER: + if (dmpEntity.getGrant() != null && dmpEntity.getGrant().getFunder() != null) { + XWPFRun runFunder = systemFieldParagraph.createRun(); + runFunder.setText(dmpEntity.getGrant().getFunder().getLabel()); + runFunder.setColor("116a78"); + } + break; + case GRANT: + if (dmpEntity.getGrant() != null) { + XWPFRun runGrant = systemFieldParagraph.createRun(); + runGrant.setText(dmpEntity.getGrant().getLabel()); + runGrant.setColor("116a78"); + } + break; + case PROJECT: + if (dmpEntity.getProject() != null ) { + XWPFRun runProject = systemFieldParagraph.createRun(); + runProject.setText(dmpEntity.getProject().getLabel()); + runProject.setColor("116a78"); + } + break; + case LICENSE: + Map extraProperties = objectMapper.readValue(dmpEntity.getExtraProperties(), HashMap.class); + if (extraProperties.containsKey("license")) { + Map license = ((Map) extraProperties.get("license")); + if(!StringUtils.isEmpty(license.get("pid"))) { + XWPFRun runLicense = systemFieldParagraph.createRun(); + runLicense.setText(license.get("pid").toString()); + runLicense.setColor("116a78"); + } + } + break; + case ACCESS_RIGHTS: + Map extraPropertiesMap = objectMapper.readValue(dmpEntity.getExtraProperties(), HashMap.class); + if (extraPropertiesMap.containsKey("visible")) { + XWPFRun runAccessRights = systemFieldParagraph.createRun(); + runAccessRights.setText(Boolean.valueOf(extraPropertiesMap.get("visible").toString()) ? "Public" : "Restricted"); + runAccessRights.setColor("116a78"); + } + break; + } + //document.createParagraph(); + } + else if(field.getCategory() == FieldCategory.EXTRA){ + + Map dmpProperties = objectMapper.readValue(dmpEntity.getProperties(), HashMap.class); + if (dmpProperties != null && (!dmpProperties.containsKey(field.getId().toString()) || StringUtils.isEmpty((String) dmpProperties.get(field.getId().toString())))) continue; + ExtraField extraField = field.toExtraField(); + XWPFParagraph extraFieldParagraph = document.createParagraph(); + extraFieldParagraph.setSpacingBetween(1.0); + XWPFRun runExtraFieldLabel = extraFieldParagraph.createRun(); + runExtraFieldLabel.setText(extraField.getLabel() + ": "); + runExtraFieldLabel.setColor("000000"); +// if(extraField.getDescription() != null && !extraField.getDescription().isEmpty()){ +// XWPFRun runExtraFieldDescription = extraFieldParagraph.createRun(); +// runExtraFieldDescription.setText(extraField.getDescription()); +// runExtraFieldDescription.setColor("116a78"); +// } + XWPFRun runExtraFieldInput = extraFieldParagraph.createRun(); + switch (extraField.getType()) { + case TEXT: + runExtraFieldInput.setText((String) dmpProperties.get(field.getId().toString())); + runExtraFieldInput.setColor("116a78"); + break; + case RICH_TEXT: + wordBuilder.addParagraphContent(dmpProperties.get(field.getId().toString()), document, ParagraphStyle.HTML, BigInteger.ZERO, 0); +// runExtraFieldInput.setText((String) dmpProperties.get(field.getId().toString())); +// runExtraFieldInput.setColor("116a78"); + break; + case DATE: + runExtraFieldInput.setText((String) dmpProperties.get(field.getId().toString())); + runExtraFieldInput.setColor("116a78"); + break; + case NUMBER: + runExtraFieldInput.setText((String) dmpProperties.get(field.getId().toString())); + runExtraFieldInput.setColor("116a78"); + break; + } + + } + } + + //if(!section.getDescriptionTemplates().isEmpty()){ + wordBuilder.addParagraphContent("Section descriptions", document, ParagraphStyle.HEADER2, BigInteger.ZERO, 0); +// wordBuilder.addParagraphContent("Description Templates", document, ParagraphStyle.HEADER4, BigInteger.ZERO, 0); +// for(eu.eudat.models.data.entities.xmlmodels.dmpprofiledefinition.DescriptionTemplate descriptionTemplate: section.getDescriptionTemplates()){ +// XWPFParagraph templateParagraph = document.createParagraph(); +// XWPFRun runTemplateLabel = templateParagraph.createRun(); +// runTemplateLabel.setText("• " + descriptionTemplate.getLabel()); +// runTemplateLabel.setColor("116a78"); +// } + + final Boolean isFinalized = dmpEntity.getStatus() == DMP.DMPStatus.FINALISED.getValue(); + final Boolean isPublic = dmpEntity.isPublic(); + dmpEntity.getDataset().stream() + .filter(item -> item.getStatus() != eu.eudat.old.data.entities.Dataset.Status.CANCELED.getValue()) + .filter(item -> item.getStatus() != eu.eudat.old.data.entities.Dataset.Status.DELETED.getValue()) + .filter(item -> !isPublic && !isFinalized || item.getStatus() == eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()) + .filter(item -> item.getDmpSectionIndex().equals(section.getOrdinal() - 1)) + .sorted(Comparator.comparing(eu.eudat.old.data.entities.Dataset::getCreated)) + .forEach(datasetEntity -> { + Map properties = new HashMap<>(); + if (datasetEntity.getProperties() != null) { + //ObjectMapper objectMapper = new ObjectMapper(); + try { + properties = objectMapper.readValue(datasetEntity.getProperties(), LinkedHashMap.class); + } catch (IOException e) { + logger.error(e.getLocalizedMessage(), e); + } + /*JSONObject jObject = new JSONObject(datasetEntity.getProperties()); + properties = jObject.toMap();*/ + } + + + // Dataset Description custom style. + XWPFParagraph datasetDescriptionParagraph = document.createParagraph(); + datasetDescriptionParagraph.setStyle("Heading4"); + datasetDescriptionParagraph.setSpacingBetween(1.5); + XWPFRun datasetDescriptionRun = datasetDescriptionParagraph.createRun(); + datasetDescriptionRun.setText("Description"); + //datasetDescriptionRun.setColor("2E75B6"); + //datasetDescriptionRun.setBold(true); + datasetDescriptionRun.setFontSize(15); + + + // Custom style for the Dataset title. + //wordBuilder.addParagraphContent("Title: " + datasetEntity.getLabel(), document, ParagraphStyle.HEADER1, BigInteger.ZERO); + XWPFParagraph datasetLabelParagraph = document.createParagraph(); +// datasetLabelParagraph.setStyle("Heading2"); + datasetLabelParagraph.setSpacingBetween(1.0); + XWPFRun runDatasetTitle1 = datasetLabelParagraph.createRun(); + runDatasetTitle1.setText("Title: "); + runDatasetTitle1.setColor("000000"); + //runDatasetTitle1.setBold(true); + //runDatasetTitle1.setFontSize(12); + XWPFRun runDatasetTitle = datasetLabelParagraph.createRun(); + runDatasetTitle.setText(datasetEntity.getLabel()); + runDatasetTitle.setColor("116a78"); + //runDatasetTitle.setBold(true); + //runDatasetTitle.setFontSize(12); + + XWPFParagraph datasetTemplateParagraph = document.createParagraph(); +// datasetTemplateParagraph.setStyle("Heading3"); + XWPFRun runDatasetTemplate1 = datasetTemplateParagraph.createRun(); + runDatasetTemplate1.setText("Template: "); + runDatasetTemplate1.setColor("000000"); + //runDatasetTemplate1.setBold(true); + //runDatasetTemplate1.setFontSize(12); + XWPFRun runDatasetTemplate = datasetTemplateParagraph.createRun(); + runDatasetTemplate.setText(datasetEntity.getProfile().getLabel()); + runDatasetTemplate.setColor("116a78"); + //runDatasetTemplate.setBold(true); + //runDatasetTemplate.setFontSize(12); + +// /*XWPFParagraph externalReferencesParagraph = document.createParagraph(); +// externalReferencesParagraph.setStyle("Heading3"); +// XWPFRun externalReferencesRun = externalReferencesParagraph.createRun(); +// externalReferencesRun.setText("External References"); +// externalReferencesRun.setColor("2E75B6"); +// externalReferencesRun.setBold(true); +// externalReferencesRun.setFontSize(12); +// +// wordBuilder.addParagraphContent("Data Repositories", document, ParagraphStyle.HEADER4, BigInteger.ZERO); +// if (datasetEntity.getDatasetDataRepositories().size() > 0) { +// wordBuilder.addParagraphContent(datasetEntity.getDatasetDataRepositories().stream().map(DatasetDataRepository::getDataRepository).map(DataRepository::getLabel).collect(Collectors.joining(", ")) +// , document, ParagraphStyle.TEXT, BigInteger.ZERO); +// } +// wordBuilder.addParagraphContent("External Datasets", document, ParagraphStyle.HEADER4, BigInteger.ZERO); +// if (datasetEntity.getDatasetExternalDatasets().size() > 0) { +// wordBuilder.addParagraphContent(datasetEntity.getDatasetExternalDatasets().stream().map(DatasetExternalDataset::getExternalDataset).map(ExternalDataset::getLabel).collect(Collectors.joining(", ")) +// , document, ParagraphStyle.TEXT, BigInteger.ZERO); +// } +// wordBuilder.addParagraphContent("Registries", document, ParagraphStyle.HEADER4, BigInteger.ZERO); +// if (datasetEntity.getRegistries().size() > 0) { +// wordBuilder.addParagraphContent(datasetEntity.getRegistries().stream().map(Registry::getLabel).collect(Collectors.joining(", ")) +// , document, ParagraphStyle.TEXT, BigInteger.ZERO); +// } +// wordBuilder.addParagraphContent("Services", document, ParagraphStyle.HEADER4, BigInteger.ZERO); +// if (datasetEntity.getServices().size() > 0) { +// wordBuilder.addParagraphContent(datasetEntity.getServices().stream().map(DatasetService::getService).map(Service::getLabel).collect(Collectors.joining(", ")) +// , document, ParagraphStyle.TEXT, BigInteger.ZERO); +// } +// *//*wordBuilder.addParagraphContent("Tags", document, ParagraphStyle.HEADER3, BigInteger.ZERO); +// if (datasetEntity.().size() > 0) { +// wordBuilder.addParagraphContent(datasetEntity.getServices().stream().map(DatasetService::getService).map(Service::getLabel).collect(Collectors.joining(", ")) +// , document, ParagraphStyle.HEADER4, BigInteger.ZERO); +// }*/ +// +// + + XWPFParagraph datasetDescParagraph = document.createParagraph(); + XWPFRun runDatasetDescription1 = datasetDescParagraph.createRun(); + runDatasetDescription1.setText("Description: "); + runDatasetDescription1.setColor("000000"); + XWPFRun runDatasetDescription = datasetDescParagraph.createRun(); + runDatasetDescription.setText(datasetEntity.getProfile().getLabel()); + runDatasetDescription.setColor("116a78"); + //wordBuilder.addParagraphContent(datasetEntity.getDescription(), document, ParagraphStyle.HTML, BigInteger.ZERO, 0); + + document.createParagraph(); + + PagedDatasetProfile pagedDatasetProfile = datasetManager.getPagedProfile(dataset, datasetEntity); + visibilityRuleService.setProperties(properties); + visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules()); + try { + wordBuilder.build(document, pagedDatasetProfile, visibilityRuleService); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + // Page break at the end of the Dataset. + XWPFParagraph parBreakDataset = document.createParagraph(); + parBreakDataset.setPageBreak(true); + }); + //} + } + +// // Removes the top empty headings. +// for (int i = 0; i < 6; i++) { +// document.removeBodyElement(0); +// } + + + if(powered_pos != -1) { + document.getLastParagraph().setPageBreak(false); + document.createParagraph(); + document.setParagraph(powered_par, document.getParagraphs().size() - 1); + + document.createParagraph(); + document.setParagraph(argos_img_par, document.getParagraphs().size() - 1); + + document.removeBodyElement(powered_pos + 1); + document.removeBodyElement(powered_pos + 1); + } + + wordBuilder.fillFooter(dmpEntity, null, document, false); + + String fileName; + if (dmpEntity.getGrant() != null && dmpEntity.getGrant().getLabel() != null) { + fileName = "DMP_" + dmpEntity.getGrant().getLabel(); + } + else { + fileName = "DMP_" + dmpEntity.getLabel(); + } + if (versioned) { + fileName += "_" + dmpEntity.getVersion(); + } + // fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", ""); + FileEnvelope exportEnvelope = new FileEnvelope(); + exportEnvelope.setFilename(fileName + ".docx"); + String uuid = UUID.randomUUID().toString(); + File exportFile = new File(this.environment.getProperty("temp.temp") + uuid + ".docx"); + FileOutputStream out = new FileOutputStream(exportFile); + document.write(out); + out.close(); + exportEnvelope.setFile(exportFile); + + return exportEnvelope; + } + + private FileEnvelope getXmlDocument(String id, Principal principal) throws InstantiationException, IllegalAccessException, IOException { + ExportXmlBuilder xmlBuilder = new ExportXmlBuilder(); + VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl(); + DMP dmp = databaseRepository.getDmpDao().find(UUID.fromString(id)); + if (!dmp.isPublic() && dmp.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()).collect(Collectors.toList()).size() == 0) + throw new UnauthorisedException(); + final Boolean isFinalized = dmp.getStatus() == DMP.DMPStatus.FINALISED.getValue(); + final Boolean isPublic = dmp.isPublic(); + List datasets = dmp.getDataset().stream() + .filter(dataset -> dataset.getStatus() != eu.eudat.old.data.entities.Dataset.Status.DELETED.getValue() && + dataset.getStatus() != eu.eudat.old.data.entities.Dataset.Status.CANCELED.getValue()) + .filter(dataset -> !isPublic && !isFinalized || dataset.getStatus() == eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()) + .collect(Collectors.toList()); + /*String fileName = dmp.getLabel(); + fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", "");*/ + String uuid = UUID.randomUUID().toString(); + File xmlFile = new File(this.environment.getProperty("temp.temp") + uuid + ".xml"); + BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile, true)); + Document xmlDoc = XmlBuilder.getDocument(); + Element dmpElement = xmlDoc.createElement("dmp"); + Element dmpDescription = xmlDoc.createElement("description"); + dmpDescription.setTextContent(dmp.getDescription()); + dmpElement.appendChild(dmpDescription); + Element dmpName = xmlDoc.createElement("dmpName"); + dmpName.setTextContent(dmp.getLabel()); + dmpElement.appendChild(dmpName); + + if (dmp.getExtraProperties() != null && !dmp.getExtraProperties().isEmpty()) { + Map extraProperties = new ObjectMapper().readValue(dmp.getExtraProperties(), HashMap.class); + Element language = xmlDoc.createElement("language"); + language.setTextContent(extraProperties.get("language") != null ? extraProperties.get("language").toString() : null); + dmpElement.appendChild(language); + Element visibility = xmlDoc.createElement("visibility"); + visibility.setTextContent(extraProperties.get("visible") != null ? extraProperties.get("visible").toString() : null); + dmpElement.appendChild(visibility); + Element publicDate = xmlDoc.createElement("publicDate"); + publicDate.setTextContent(extraProperties.get("publicDate") != null ? extraProperties.get("publicDate").toString() : null); + dmpElement.appendChild(publicDate); + Element costs = xmlDoc.createElement("costs"); + costs.setTextContent(extraProperties.get("costs") != null ? extraProperties.get("costs").toString() : null); + dmpElement.appendChild(costs); + } + + 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 dmpContactElement = xmlDoc.createElement("contact"); + Element dmpContactName = xmlDoc.createElement("name"); + Element dmpContactEmail = xmlDoc.createElement("email"); + if(dmp.getCreator() != null){ + dmpContactName.setTextContent(dmp.getCreator().getName()); + dmpContactEmail.setTextContent(dmp.getCreator().getEmail()); + } + else{ + Iterator users = dmp.getUsers().iterator(); + if(users.hasNext()){ + UserDMP creator = users.next(); + dmpContactName.setTextContent(creator.getUser().getName()); + dmpContactEmail.setTextContent(creator.getUser().getEmail()); + } + } + dmpContactElement.appendChild(dmpContactName); + dmpContactElement.appendChild(dmpContactEmail); + dmpElement.appendChild(dmpContactElement); + + Element dmpContributorsElement = xmlDoc.createElement("contributors"); + Iterator users = dmp.getUsers().iterator(); + while(users.hasNext()){ + Element dmpContributorElement = xmlDoc.createElement("contributor"); + Element dmpContributorName = xmlDoc.createElement("name"); + Element dmpContributorEmail= xmlDoc.createElement("email"); + UserDMP contributor = users.next(); + dmpContributorName.setTextContent(contributor.getUser().getName()); + dmpContributorEmail.setTextContent(contributor.getUser().getEmail()); + dmpContributorElement.appendChild(dmpContributorName); + dmpContributorElement.appendChild(dmpContributorEmail); + dmpContributorsElement.appendChild(dmpContributorElement); + } + dmpElement.appendChild(dmpContributorsElement); + + // Funder. + Element funder = xmlDoc.createElement("funder"); + if (this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.GRANT, principal) && this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.FUNDER, principal)) { + Element funderLabel = xmlDoc.createElement("label"); + Element funderId = xmlDoc.createElement("id"); + funderLabel.setTextContent(dmp.getGrant().getFunder().getLabel()); + funderId.setTextContent(dmp.getGrant().getFunder().getId().toString()); + funder.appendChild(funderLabel); + funder.appendChild(funderId); + if (dmp.getGrant().getFunder().getReference() != null) { + String referencePrefix = dmp.getGrant().getFunder().getReference().split(":")[0]; + String shortReference = dmp.getGrant().getFunder().getReference().substring(referencePrefix.length() + 1); + Element funderReference = xmlDoc.createElement("reference"); + funderReference.setTextContent(shortReference); + funder.appendChild(funderReference); + } + } + dmpElement.appendChild(funder); + // Grant. + Element grant = xmlDoc.createElement("grant"); + if (this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.GRANT, principal)) { + Element grantLabel = xmlDoc.createElement("label"); + Element grantId = xmlDoc.createElement("id"); + grantLabel.setTextContent(dmp.getGrant().getLabel()); + grantId.setTextContent(dmp.getGrant().getId().toString()); + grant.appendChild(grantLabel); + grant.appendChild(grantId); + if (dmp.getGrant().getReference() != null) { + String referencePrefix = dmp.getGrant().getReference().split(":")[0]; + String shortReference = dmp.getGrant().getReference().substring(referencePrefix.length() + 1); + Element grantReference = xmlDoc.createElement("reference"); + grantReference.setTextContent(shortReference); + grant.appendChild(grantReference); + } + } + dmpElement.appendChild(grant); + // Project. + Element project = xmlDoc.createElement("project"); + if (this.dataManagementProfileManager.fieldInBlueprint(dmp.getProfile(), SystemFieldType.PROJECT, principal)) { + Element projectId = xmlDoc.createElement("id"); + Element projectLabel = xmlDoc.createElement("label"); + Element projectDescription = xmlDoc.createElement("description"); + Element projectStartDate = xmlDoc.createElement("start"); + Element projectEndDate = xmlDoc.createElement("end"); + projectId.setTextContent(dmp.getProject().getId().toString()); + projectLabel.setTextContent(dmp.getProject().getLabel()); + projectDescription.setTextContent(dmp.getProject().getDescription()); + projectStartDate.setTextContent(dmp.getProject().getStartdate().toString()); + projectEndDate.setTextContent(dmp.getProject().getEnddate().toString()); + project.appendChild(projectId); + project.appendChild(projectLabel); + project.appendChild(projectDescription); + project.appendChild(projectStartDate); + project.appendChild(projectEndDate); + } + dmpElement.appendChild(project); + + Element organisationsElement = xmlDoc.createElement("organisations"); + for (Organisation organisation : dmp.getOrganisations()) { + Element organisationElement = xmlDoc.createElement("organisation"); + Element organisationNameElement = xmlDoc.createElement("name"); + organisationNameElement.setTextContent(organisation.getLabel()); + Element organisationReferenceElement = xmlDoc.createElement("reference"); + organisationReferenceElement.setTextContent(organisation.getReference()); + organisationElement.appendChild(organisationNameElement); + organisationElement.appendChild(organisationReferenceElement); + organisationsElement.appendChild(organisationElement); + } + dmpElement.appendChild(organisationsElement); + + Element researchersElement = xmlDoc.createElement("researchers"); + for (Researcher researcher : dmp.getResearchers()) { + Element researcherElement = xmlDoc.createElement("researcher"); + Element researcherNameElement = xmlDoc.createElement("name"); + researcherNameElement.setTextContent(researcher.getLabel()); + Element researcherReferenceElement = xmlDoc.createElement("reference"); + researcherReferenceElement.setTextContent(researcher.getReference()); + researcherElement.appendChild(researcherNameElement); + researcherElement.appendChild(researcherReferenceElement); + researchersElement.appendChild(researcherElement); + } + dmpElement.appendChild(researchersElement); + + Element extraFields = xmlDoc.createElement("extraFields"); + Map dmpProperties = new ObjectMapper().readValue(dmp.getProperties(), new TypeReference>() {}); + DataManagementPlanBlueprint blueprint = this.dataManagementProfileManager.getSingleBlueprint(dmp.getProfile().getId().toString(), principal).getDefinition(); + blueprint.getSections().forEach(section -> { + section.getFields().forEach(fieldModel -> { + if (fieldModel.getCategory() == FieldCategory.EXTRA) { + Element extraField = xmlDoc.createElement("extraField"); + Element extraFieldId = xmlDoc.createElement("id"); + extraFieldId.setTextContent(fieldModel.getId().toString()); + Element extraFieldLabel = xmlDoc.createElement("label"); + extraFieldLabel.setTextContent(fieldModel.getLabel()); + Element extraFieldValue = xmlDoc.createElement("value"); + Object value = dmpProperties.get(fieldModel.getId().toString()); + if (value != null) { + extraFieldValue.setTextContent((String) value); + } + extraField.appendChild(extraFieldId); + extraField.appendChild(extraFieldLabel); + extraField.appendChild(extraFieldValue); + extraFields.appendChild(extraField); + } + }); + }); + dmpElement.appendChild(extraFields); + + Element datasetsElement = xmlDoc.createElement("datasets"); + for (eu.eudat.old.data.entities.Dataset dataset : datasets) { + Element datasetElement = xmlDoc.createElement("dataset"); + datasetElement.setAttribute("name", dataset.getLabel()); + + Element datasetDescriptionElement = xmlDoc.createElement("description"); + datasetElement.appendChild(datasetDescriptionElement); + datasetDescriptionElement.setTextContent(dataset.getDescription()); + + Element datasetDmpSectionIndex = xmlDoc.createElement("dmpSectionIndex"); + datasetElement.appendChild(datasetDmpSectionIndex); + datasetDmpSectionIndex.setTextContent(String.valueOf(dataset.getDmpSectionIndex())); + + Element datsetProfileElement = xmlDoc.createElement("profile-id"); + datasetElement.appendChild(datsetProfileElement); + datsetProfileElement.setTextContent(dataset.getProfile().getId().toString()); + + Element datsetProfileLabelElement = xmlDoc.createElement("profile-label"); + datasetElement.appendChild(datsetProfileLabelElement); + datsetProfileLabelElement.setTextContent(dataset.getProfile().getLabel()); + + DatasetWizardModel datasetWizardModel = new DatasetWizardModel(); + Map properties = new HashMap<>(); + if (dataset.getProperties() != null) { + JSONObject jobject = new JSONObject(dataset.getProperties()); + properties = jobject.toMap(); + } + 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. + for (DMPDatasetProfile dmpDescriptionProfile : dmp.getAssociatedDmps()) { + DescriptionTemplate descriptionTemplate = dmpDescriptionProfile.getDatasetprofile(); + Element profile = xmlDoc.createElement("profile"); + Element profileId = xmlDoc.createElement("profileId"); + profileId.setTextContent(descriptionTemplate.getId().toString()); + profile.appendChild(profileId); + Element profileGroupId = xmlDoc.createElement("profileGroupId"); + profileGroupId.setTextContent(descriptionTemplate.getGroupId().toString()); + profile.appendChild(profileGroupId); + Element profileLabel = xmlDoc.createElement("profileLabel"); + profileLabel.setTextContent(descriptionTemplate.getLabel()); + profile.appendChild(profileLabel); + Element profileVersion = xmlDoc.createElement("profileVersion"); + profileVersion.setTextContent(String.valueOf(descriptionTemplate.getVersion())); + profile.appendChild(profileVersion); + Element profileInSections = xmlDoc.createElement("profileInSections"); + Map data = new ObjectMapper().readValue(dmpDescriptionProfile.getData(), new TypeReference>() {}); + List sections = (List) data.get("dmpSectionIndex"); + for(int section: sections) { + Element profileInSection = xmlDoc.createElement("section"); + profileInSection.setTextContent(String.valueOf(section)); + profileInSections.appendChild(profileInSection); + } + profile.appendChild(profileInSections); + profiles.appendChild(profile); + } + dmpElement.appendChild(profiles); + dmpElement.appendChild(datasetsElement); + xmlDoc.appendChild(dmpElement); + String xml = XmlBuilder.generateXml(xmlDoc); + writer.write(xml); + writer.close(); + FileEnvelope fileEnvelope = new FileEnvelope(); + fileEnvelope.setFile(xmlFile); + if (dmp.getGrant() != null && dmp.getGrant().getLabel() != null) { + fileEnvelope.setFilename("DMP_" + dmp.getGrant().getLabel() + "_" + dmp.getVersion() + ".xml"); + } + else { + fileEnvelope.setFilename("DMP_" + dmp.getLabel() + "_" + dmp.getVersion() + ".xml"); + } + + return fileEnvelope; + } + + public FileEnvelope getRDAJsonDocument(String id, Principal principal) throws Exception { + DMP dmp = databaseRepository.getDmpDao().find(UUID.fromString(id)); + if (!dmp.isPublic() && dmp.getUsers().stream().noneMatch(userInfo -> userInfo.getUser().getId() == principal.getId())) + throw new UnauthorisedException(); + final boolean isFinalized = dmp.getStatus() == DMP.DMPStatus.FINALISED.getValue(); + final boolean isPublic = dmp.isPublic(); + dmp.setDataset(dmp.getDataset().stream() + .filter(dataset -> dataset.getStatus() != eu.eudat.old.data.entities.Dataset.Status.DELETED.getValue() && + dataset.getStatus() != eu.eudat.old.data.entities.Dataset.Status.CANCELED.getValue()) + .filter(dataset -> !isPublic && !isFinalized || dataset.getStatus() == eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()) + .collect(Collectors.toSet())); + String result = rdaManager.convertToRDA(dmp); + + String fileName; + if (dmp.getGrant() != null && dmp.getGrant().getLabel() != null) { + fileName = "DMP_" + dmp.getGrant().getLabel() + "_" + dmp.getVersion(); + } + else { + fileName = "DMP_" + dmp.getLabel() + "_" + dmp.getVersion(); + } + fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", "").replace(" ", "_").replace(",", "_"); + String uuid = UUID.randomUUID().toString(); + File file = new File(this.environment.getProperty("temp.temp") + uuid + ".json"); + OutputStream output = new FileOutputStream(file); + try { + output.write(result.getBytes()); + output.flush(); + output.close(); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + + FileEnvelope rdaJsonDocument = new FileEnvelope(); + rdaJsonDocument.setFilename(fileName + ".json"); + rdaJsonDocument.setFile(file); + return rdaJsonDocument; + } + + public ResponseEntity getDocument(String id, String contentType, Principal principal, ConfigLoader configLoader) throws InstantiationException, IllegalAccessException, IOException { + FileEnvelope file; + switch (contentType) { + case "application/xml": + file = getXmlDocument(id, principal); + break; + case "application/msword": + file = getWordDocument(id, principal, configLoader); + break; + default: + file = getXmlDocument(id, principal); + } + String fileName = file.getFilename().replace(" ", "_").replace(",", "_"); + InputStream resource = new FileInputStream(file.getFile()); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(file.getFile().length()); + responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); + responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + + byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource); + resource.close(); + Files.deleteIfExists(file.getFile().toPath()); + return new ResponseEntity<>(content, + responseHeaders, + HttpStatus.OK); + } + + /* + * Data Import + * */ + + public List createDmpFromXml(MultipartFile[] files, Principal principal, String[] profiles) throws IOException, JAXBException, Exception { + List dataManagementPlans = new ArrayList<>(); + // Jaxb approach. + JAXBContext jaxbContext; + + for (MultipartFile multipartFile : Arrays.asList(files)) { // Gets one item from the array. + try { + InputStream in = multipartFile.getInputStream(); // Transforms item to InputStream. + jaxbContext = JAXBContext.newInstance(DmpImportModel.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + DmpImportModel dmpImportModel = (DmpImportModel) jaxbUnmarshaller.unmarshal(in); + dataManagementPlans.add(dmpImportModel); + } catch (IOException | JAXBException ex) { + logger.error(ex.getMessage(), ex); + } + // TODO Iterate through the list of dataManagementPlans. + // Creates new dataManagementPlan to fill it with the data model that was parsed from the xml. + // Creates properties. + DataManagementPlanEditorModel dm = new DataManagementPlanEditorModel(); + + DmpProfileImportModel dmpProfileImportModel = dataManagementPlans.get(0).getDmpProfile(); + UUID profileId = null; + if (dmpProfileImportModel != null) { + profileId = dmpProfileImportModel.getDmpProfileId(); + } + else { + profileId = UUID.fromString("86635178-36a6-484f-9057-a934e4eeecd5"); + } + dm.setProfile(profileId); + + + Map dmpPropertiesMap = new HashMap<>(); + if (dataManagementPlans.get(0).getExtraFieldsImportModels() != null) { + for (ExtraFieldsImportModels extraField: dataManagementPlans.get(0).getExtraFieldsImportModels()) { + dmpPropertiesMap.put(extraField.getId(), extraField.getValue()); + } + } + dm.setProperties(dmpPropertiesMap); + + if (this.dataManagementProfileManager.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId().toString(), SystemFieldType.FUNDER, principal)) { + Funder funder = new Funder(); + FunderImportModels funderImport = dataManagementPlans.get(0).getFunderImportModels(); + funder.setId(funderImport.getId()); + funder.setLabel(funderImport.getLabel()); + FunderDMPEditorModel funderEditor = new FunderDMPEditorModel(); + funderEditor.setExistFunder(funder); + + dm.setFunder(funderEditor); + } + + if (this.dataManagementProfileManager.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId().toString(), SystemFieldType.GRANT, principal)) { + Grant grant = new Grant(); + GrantImportModels grantImport = dataManagementPlans.get(0).getGrantImport(); + grant.setId(grantImport.getId()); + grant.setLabel(grantImport.getLabel()); + grant.setAbbreviation(grantImport.getAbbreviation()); + grant.setDescription(grantImport.getDescription()); + GrantDMPEditorModel grantEditor = new GrantDMPEditorModel(); + grantEditor.setExistGrant(grant); + + dm.setGrant(grantEditor); + } + + if (this.dataManagementProfileManager.fieldInBlueprint(dmpProfileImportModel.getDmpProfileId().toString(), SystemFieldType.PROJECT, principal)) { + Project project = new Project(); + ProjectImportModels projectImport = dataManagementPlans.get(0).getProjectImportModels(); + project.setId(projectImport.getId()); + project.setLabel(projectImport.getLabel()); + ProjectDMPEditorModel projectEditor = new ProjectDMPEditorModel(); + projectEditor.setExistProject(project); + + dm.setProject(projectEditor); + } + + List associatedProfiles = new LinkedList<>(); +// if (profiles != null && profiles.length > 0) { +// for (String profile : profiles) { +// DescriptionTemplate exProfile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(profile)); +// AssociatedProfile associatedProfile = new AssociatedProfile().fromData(exProfile); +// associatedProfiles.add(associatedProfile); +// } +// } + + for (AssociatedProfileImportModels a : dataManagementPlans.get(0).getProfilesImportModels()) { + try { + DescriptionTemplate exProfile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(a.getId()); + AssociatedProfile associatedProfile = new AssociatedProfile().fromData(exProfile); + Map data = new HashMap<>(); + List sections = new ArrayList<>(a.getSection()); + data.put("dmpSectionIndex", sections); + associatedProfile.setData(data); + associatedProfiles.add(associatedProfile); + } catch (Exception ignored) { + } + } + + List organisations = new ArrayList<>(); + for (OrganisationImportModel org : dataManagementPlans.get(0).getOrganisationImportModels()) { + eu.eudat.old.models.data.dmp.Organisation organisation = new eu.eudat.old.models.data.dmp.Organisation(); + organisation.setName(org.getOrganaisationNameImport()); + organisation.setReference(org.getOrganaisationReferenceImport()); + organisation.setKey(organisation.getReference().split(":")[0]); + organisations.add(organisation); + } + + List researchers = new LinkedList<>(); + for (ResearcherImportModels res : dataManagementPlans.get(0).getResearchersImportModels()) { + eu.eudat.old.models.data.dmp.Researcher researcher = new eu.eudat.old.models.data.dmp.Researcher(); + researcher.setLabel(res.getResearcherImportName()); + researcher.setName(res.getResearcherImportName()); + researcher.setReference(res.getResearcherImportReference()); + researcher.setKey(researcher.getReference().split(":")[0]); + researchers.add(researcher); + } + + List associatedUsers = new LinkedList<>(); + List dynamicFields = new LinkedList<>(); + + // Sets properties. + dm.setLabel(files[0].getOriginalFilename()); // Sets label. + dm.setDescription(dataManagementPlans.get(0).getDescriptionImport()); // Sets description property. + dm.setProfiles(associatedProfiles); + dm.setOrganisations(organisations); // Sets organisations property. + dm.setResearchers(researchers); // Sets researchers property. + dm.setAssociatedUsers(associatedUsers); // Sets associatedUsers property. + dm.setDynamicFields(dynamicFields); // Sets dynamicFields property. + //dm.setDefinition(dmpProfile); + //ObjectMapper mapper = new ObjectMapper(); + Map extraPropertiesMap = new HashMap<>(); + if (dataManagementPlans.get(0).getLanguage() != null) { + extraPropertiesMap.put("language", dataManagementPlans.get(0).getLanguage()); + } + if (dataManagementPlans.get(0).getVisibility() != null) { + extraPropertiesMap.put("visible", dataManagementPlans.get(0).getVisibility()); + } + if (dataManagementPlans.get(0).getPublicDate() != null) { + extraPropertiesMap.put("publicDate", dataManagementPlans.get(0).getPublicDate()); + } + if (dataManagementPlans.get(0).getCosts() != null && !dataManagementPlans.get(0).getCosts().isEmpty()) { + extraPropertiesMap.put("costs", objectMapper.readValue(dataManagementPlans.get(0).getCosts(), ArrayList.class)); + } + dm.setExtraProperties(extraPropertiesMap); + + //createOrUpdate(apiContext, dm, principal); + DMP dmp = this.createOrUpdate(dm, principal); + if (dmp.getOrganisations() == null) { + dmp.setOrganisations(new HashSet<>()); + } + if (dmp.getResearchers() == null) { + dmp.setResearchers(new HashSet<>()); + } + if (dmp.getDataset() == null) { + dmp.setDataset(new HashSet<>()); + } + if (dmp.getUsers() == null) { + dmp.setUsers(new HashSet<>()); + } + if (dmp.getAssociatedDmps() == null) { + dmp.setAssociatedDmps(new HashSet<>()); + } + + List datasets = new LinkedList<>(); + for (DatasetImportModels das: dataManagementPlans.get(0).getDatasetImportModels()) { + eu.eudat.old.data.entities.Dataset dataset = new eu.eudat.old.data.entities.Dataset(); + dataset.setLabel(das.getName()); + dataset.setDmpSectionIndex(das.getDmpSectionIndex()); + try { + dataset.setProfile(databaseRepository.getDatasetProfileDao().find(das.getProfile())); + } catch (Exception ignored) { + dataset.setProfile(databaseRepository.getDatasetProfileDao().find(associatedProfiles.get(0).getDescriptionTemplateId())); + } + dataset.setProperties(objectMapper.writeValueAsString(das.getFieldImportModels())); + dataset.setStatus((short) 0); + dataset.setRegistries(new HashSet<>()); + dataset.setDatasetDataRepositories(new HashSet<>()); + dataset.setServices(new HashSet<>()); + dataset.setDatasetExternalDatasets(new HashSet<>()); + dataset.setDmp(dmp); + DatasetWizardModel datasetWizard = new DatasetWizardModel(); + datasetWizard.setDatasetProfileDefinition(this.datasetManager.getPagedProfile(datasetWizard, dataset)); + datasetWizard.fromDataModel(dataset); + this.datasetManager.createOrUpdate(datasetWizard, principal); + // datasets.add(new DatasetListingModel().fromDataModel(dataset)); + } + } + + return dataManagementPlans; + } + + public List createFromRDA(MultipartFile[] files, Principal principal, String[] profiles) throws IOException { + if (principal.getId() == null) { + throw new UnauthorisedException("No user is logged in"); + } + List result = new ArrayList<>(); + for (MultipartFile file: files) { + DMP dmp = rdaManager.convertToEntity(new String(file.getBytes(), "UTF-8"), profiles); + dmp.setLabel(file.getOriginalFilename()); + UserInfo me = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + dmp.setModified(new Date()); + dmp.setCreator(me); + Map extraProperties = objectMapper.readValue(dmp.getExtraProperties(), HashMap.class); + extraProperties.put("contact", me.getId().toString()); + dmp.setExtraProperties(objectMapper.writeValueAsString(extraProperties)); + dmp.setVersion(0); + dmp.setStatus((short)0); + dmp.setGroupId(UUID.randomUUID()); + if (dmp.getResearchers() != null && !dmp.getResearchers().isEmpty()) { + dmp.getResearchers().stream().filter(Objects::nonNull).forEach(researcher -> { + researcher.setId(UUID.randomUUID()); + researcher.setCreated(new Date()); + researcher.setModified(new Date()); + researcher.setStatus((short) 0); + apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao().createOrUpdate(researcher); + }); + } + databaseRepository.getDmpDao().createOrUpdate(dmp); + assignUser(dmp, me); + if (this.apiContext.getOperationsContext().getElasticRepository().getDmpRepository().getClient() != null) { + UUID dmpId = dmp.getId(); + dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + this.updateIndex(dmp); + } + dmp.getDataset().forEach(dataset -> { + dataset.setStatus(eu.eudat.old.data.entities.Dataset.Status.SAVED.getValue()); + dataset.setCreated(new Date()); + dataset.setModified(new Date()); + dataset.setDmp(dmp); + dataset = databaseRepository.getDatasetDao().createOrUpdate(dataset); + dataset.setRegistries(new HashSet<>()); + dataset.setDatasetDataRepositories(new HashSet<>()); + dataset.setDatasetExternalDatasets(new HashSet<>()); + dataset.setServices(new HashSet<>()); + if (dmp.getOrganisations() == null) { + dmp.setOrganisations(new HashSet<>()); + } + if (dmp.getResearchers() == null) { + dmp.setResearchers(new HashSet<>()); + } + dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId())).toList())); + try { + List tags = new ArrayList<>(); + Dataset elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString()); + DatasetWizardModel datasetWizardModel = new DatasetWizardModel().fromDataModel(dataset); + if (elastic != null) { + tags = elastic.getTags(); + datasetWizardModel.setTags(tags); + } + datasetManager.getTagsFromProfile(datasetWizardModel, dataset); + datasetManager.updateTags(dataset, datasetWizardModel.getTags()); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }); + result.add(dmp); + } + + return result; + } + + /* + * Data assignments + * */ + + private void assignUser(DMP dmp, UserInfo userInfo) { + this.assignUser(dmp, userInfo, UserDMP.UserDMPRoles.OWNER); + } + + private void assignUser(DMP dmp, UserInfo userInfo, UserDMP.UserDMPRoles role) { + UserDMP userDMP = new UserDMP(); + userDMP.setDmp(dmp); + userDMP.setUser(userInfo); + userDMP.setRole(role.getValue()); + databaseRepository.getUserDmpDao().createOrUpdate(userDMP); + } + + private void clearUsers(DMP dmp) { + List userDMPs = apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where(((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId()))).toList(); + userDMPs.forEach(userDMP -> apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().delete(userDMP)); + } + + private void assignGrandUserIfInternal(DMP dmp, UserInfo user) { + if (dmp.getGrant() != null && dmp.getGrant().getCreationUser() == null && (dmp.getGrant().getReference() != null && dmp.getGrant().getReference().startsWith("dmp:"))) { + dmp.getGrant().setCreationUser(user); + } + } + + private void assignFunderUserIfInternal(DMP dmp, UserInfo user) { + if (dmp.getGrant() != null && dmp.getGrant().getFunder() != null && dmp.getGrant().getFunder().getCreationUser() == null && ( dmp.getGrant().getFunder().getReference() != null && dmp.getGrant().getFunder().getReference().startsWith("dmp:"))) { + dmp.getGrant().getFunder().setCreationUser(user); + } + } + + private void assignProjectUserIfInternal(DMP dmp, UserInfo user) { + if (dmp.getProject() != null && dmp.getProject().getCreationUser() == null && (dmp.getProject().getReference() != null && dmp.getProject().getReference().startsWith("dmp:"))) { + dmp.getProject().setCreationUser(user); + } + } + + /* + * Data Index + * */ + + private void updateGroupIndex(UUID groupId) { + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setGroupIds(Collections.singletonList(groupId)); + criteria.setAllVersions(true); + List dmps = databaseRepository.getDmpDao().getWithCriteria(criteria).toList(); + for (DMP dmp: dmps) { + try { + if (dmp.getUsers() == null) { + UUID dmpId = dmp.getId(); + dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + } + this.updateIndex(dmp); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + } + } + + private void updateDatasetsIndex(List datasets) { + datasets.forEach(dataset -> { + List tags = new ArrayList<>(); + Dataset elastic = null; + try { + elastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString()); + if (elastic != null) { + tags = elastic.getTags(); + } + UUID dmpId = dataset.getDmp().getId(); + dataset.getDmp().setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + this.datasetManager.updateTags(dataset, tags); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + }); + } + + public void updateIndex(DMP dmp) throws IOException { + DmpMapper mapper = new DmpMapper(apiContext, datasetManager); + Dmp elastic = mapper.toElastic(dmp); + apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createOrUpdate(elastic); + } + + public void generateIndex(Principal principal) { + if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) { + if (apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createIndex()) { + List dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().toList(); + dmps.forEach(dmp -> { + try { + UUID dmpId = dmp.getId(); + dmp.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + this.updateIndex(dmp); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + }); + } + } + } + + public void clearIndex(Principal principal) throws IOException { + if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) { + apiContext.getOperationsContext().getElasticRepository().getDmpRepository().clear(); + } + } + + /* + * Data Checkup + * */ + + private void checkIfUserCanEditGrant(DMP dmp, UserInfo user) throws Exception{ + if (dmp.getGrant() != null && dmp.getGrant().getId() != null) { + eu.eudat.old.data.entities.Grant grant = apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().find(dmp.getGrant().getId()); + if (grant.getFunder() != null && dmp.getGrant().getFunder() != null + && !grant.getFunder().getId().equals(dmp.getGrant().getFunder().getId())) { + if (grant.getCreationUser() == null) { + throw new Exception("Grant has no user, therefore, cannot be edited."); + } + if (!grant.getCreationUser().getId().equals(user.getId())) { + throw new Exception("User is not the owner of the Grant, therefore, cannot edit it."); + } + } + } + } + + private void checkDmpValidationRules(DMP dmp) throws Exception { + if (dmp.getLabel() == null || dmp.getLabel().trim().isEmpty()) { + throw new Exception("DMP has no label."); + } + if (dmp.getAssociatedDmps().size() == 0) { + throw new Exception("DMP does not contain Dataset Templates."); + } + if (dmp.getGrant() == null) { + throw new Exception("DMP has no Grant assigned."); + } + } + + private boolean isUserOwnerOfDmp(DMP dmp, Principal principal) { + return (dmp.getUsers().stream().filter(userDMP -> userDMP.getRole().equals(UserDMP.UserDMPRoles.OWNER.getValue())).map(userDMP -> userDMP.getUser().getId())).collect(Collectors.toList()).contains(principal.getId()); + } + + /* + * DOI Generation + * */ + + private String getPreviousDOI(UUID groupId, UUID selfId, String repositoryId) { + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + List groupIds = new ArrayList<>(); + groupIds.add(groupId); + criteria.setGroupIds(groupIds); + criteria.setAllVersions(true); + List dmps = this.databaseRepository.getDmpDao().getWithCriteria(criteria).toList(); + dmps.sort((DMP d1, DMP d2) -> d2.getVersion() - d1.getVersion()); + for (DMP dmp: dmps) { + if (!dmp.getId().equals(selfId)) { + if (dmp.getDois() != null && !dmp.getDois().isEmpty()) { + for (Iterator it = dmp.getDois().iterator(); it.hasNext(); ) { + EntityDoi entityDoi = it.next(); + if(entityDoi.getRepositoryId().equals(repositoryId)){ + return entityDoi.getDoi(); + } + } + } + } + } + + return null; + } + + public Doi createDoi(DepositRequest depositRequest, Principal principal) throws Exception { + DMP dmp = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(UUID.fromString(depositRequest.getDmpId())); + if (!isUserOwnerOfDmp(dmp, principal)) + throw new Exception("User is not authorized to invoke this action"); + if (!dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue())) + throw new Exception("DMP is not finalized"); + /*if (dmp.getDoi() != null) + throw new Exception("DMP already has a DOI");*/ + + FileEnvelope file = getWordDocument(depositRequest.getDmpId(), principal, configLoader); + String name = file.getFilename().substring(0, file.getFilename().length() - 5).replaceAll("[^a-zA-Z0-9_+ ]", "").replace(" ", "_").replace(",", "_"); + File pdfFile = PDFUtils.convertToPDF(file, environment); + eu.eudat.depositinterface.models.FileEnvelope pdfEnvelope = new eu.eudat.depositinterface.models.FileEnvelope(); + pdfEnvelope.setFile(pdfFile); + pdfEnvelope.setFilename(name + ".pdf"); + eu.eudat.depositinterface.models.FileEnvelope rdaJsonFile = new eu.eudat.depositinterface.models.FileEnvelope(); + try { + FileEnvelope rdaJsonDocument = getRDAJsonDocument(depositRequest.getDmpId(), principal); + rdaJsonFile.setFile(rdaJsonDocument.getFile()); + rdaJsonFile.setFilename(rdaJsonDocument.getFilename()); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + String previousDOI = this.getPreviousDOI(dmp.getGroupId(), dmp.getId(), depositRequest.getRepositoryId()); + + File supportingFilesZip = this.createSupportingFilesZip(dmp); + + DMPDepositModel dmpDepositModel = DMPToDepositMapper.fromDMP(dmp, pdfEnvelope, rdaJsonFile, supportingFilesZip, previousDOI); + + String finalDoi = null; + for(RepositoryDeposit repo: this.repositoriesDeposit){ + if(repo.getConfiguration().stream().anyMatch(x-> x.getRepositoryId().equals(depositRequest.getRepositoryId()))){ + try { + finalDoi = repo.deposit(depositRequest.getRepositoryId(), dmpDepositModel, depositRequest.getAccessToken()); + } catch (Exception e) { + logger.error(e.getMessage(), e); + return null; + } + } + } + Doi doiModel = null; + if (finalDoi != null) { + + EntityDoi doiEntity = new EntityDoi(); + doiEntity.setId(UUID.randomUUID()); + doiEntity.setEntityType(EntityDoi.EntityType.DMP); + doiEntity.setDoi(finalDoi); + doiEntity.setRepositoryId(depositRequest.getRepositoryId()); + Date now = new Date(); + doiEntity.setCreatedAt(now); + doiEntity.setUpdatedAt(now); + doiEntity.setEntityId(dmp); + apiContext.getOperationsContext().getDatabaseRepository().getEntityDoiDao().createOrUpdate(doiEntity); + + dmp.getDois().add(doiEntity); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(dmp); + + doiModel = new Doi().fromDataModel(doiEntity); + + } + if(supportingFilesZip != null) { + Files.deleteIfExists(supportingFilesZip.toPath()); + } + Files.deleteIfExists(rdaJsonFile.getFile().toPath()); + Files.deleteIfExists(pdfFile.toPath()); + Files.deleteIfExists(file.getFile().toPath()); + + return doiModel; + + } + + private File createSupportingFilesZip(DMP dmp) throws IOException { + FileOutputStream fout = new FileOutputStream(this.environment.getProperty("temp.temp") + "supportingFiles.zip"); + ZipOutputStream zout = new ZipOutputStream(fout); + + boolean hasFileUploaded = false; + Set datasets = dmp.getDataset(); + for (eu.eudat.old.data.entities.Dataset dataset : datasets) { + List files = this.apiContext.getOperationsContext().getDatabaseRepository().getFileUploadDao().getFileUploads(dataset.getId()); + for (FileUpload f : files) { + if(!f.getIsDeleted()){ + File exportFile = new File(this.environment.getProperty("file.storage") + f.getId()); + String filename = f.getName().replace(" ", "_").replace(",", "_"); + byte[] content = Files.readAllBytes(exportFile.toPath()); + ZipEntry ze = new ZipEntry(filename); + zout.putNextEntry(ze); + zout.write(content, 0, content.length); + zout.closeEntry(); + hasFileUploaded = true; + } + } + } + zout.close(); + if(!hasFileUploaded){ + Files.deleteIfExists(new File(this.environment.getProperty("temp.temp") + "supportingFiles.zip").toPath()); + } + return hasFileUploaded ? new File(this.environment.getProperty("temp.temp") + "supportingFiles.zip") : null; + } + + /* + * Misc + * */ + + private void sendNotification(DMP dmp, UserInfo user, NotificationType notificationType) { + List userDMPS = databaseRepository.getUserDmpDao().asQueryable().where(((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId()))).toList(); + for (UserDMP userDMP : userDMPS) { + if (!userDMP.getUser().getId().equals(user.getId())) { + Notification notification = new Notification(); + notification.setUserId(user); + notification.setType(notificationType); + notification.setNotifyState(NotifyState.PENDING); + notification.setIsActive(ActiveStatus.ACTIVE); + notification.setData("{" + + "\"userId\": \"" + userDMP.getUser().getId() + "\"" + + ", \"id\": \"" + userDMP.getDmp().getId() + "\"" + + ", \"name\": \"" + userDMP.getDmp().getLabel() + "\"" + + ", \"path\": \"" + notificationPaths.get(notificationType) +"\"" + + "}"); + notification.setCreatedAt(new Date()); + notification.setUpdatedAt(notification.getCreatedAt()); + notification.setContactTypeHint(ContactType.EMAIL); + notification.setContactHint(userDMP.getUser().getEmail()); + databaseRepository.getNotificationDao().createOrUpdate(notification); + } + } + + } + + /*public DataTableData getPublicPaged(DataManagmentPlanPublicTableRequest dataManagementPlanPublicTableRequest, String fieldsGroup, Principal principal) throws Exception { + dataManagementPlanPublicTableRequest.setQuery(databaseRepository.getDmpDao().asQueryable().withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class))); + QueryableList items = dataManagementPlanPublicTableRequest.applyCriteria(); + + if (principal.getId() != null && dataManagementPlanPublicTableRequest.getCriteria().getRole() != null) { + items.where((builder, root) -> { + Join userJoin = root.join("users", JoinType.LEFT); + return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal.getId()), builder.equal(userJoin.get("role"), dataManagementPlanPublicTableRequest.getCriteria().getRole())); + }); + } + QueryableList pagedItems = PaginationManager.applyPaging(items, dataManagementPlanPublicTableRequest); + + DataTableData dataTable = new DataTableData<>(); + + CompletableFuture itemsFuture; + if (fieldsGroup.equals("listing")) { + itemsFuture = pagedItems.withHint(HintedModelFactory.getHint(DataManagementPlanListingModel.class)) + .selectAsync(item -> { + item.setDataset( + item.getDataset().stream() + .filter(dataset -> dataset.getStatus().equals(Dataset.Status.FINALISED.getValue())).collect(Collectors.toSet())); + return new DataManagementPlanListingModel().fromDataModelDatasets(item); + }) + .whenComplete((resultList, throwable) -> dataTable.setData(resultList)); + } else { + itemsFuture = pagedItems + .selectAsync(item -> new DataManagementPlanListingModel().fromDataModel(item)) + .whenComplete((resultList, throwable) -> dataTable.setData(resultList)); + } + + CompletableFuture countFuture = items.countAsync().whenComplete((count, throwable) -> { + dataTable.setTotalCount(count); + }); + CompletableFuture.allOf(itemsFuture, countFuture).join(); + return dataTable; + } +*/ + /*public void unlock(UUID uuid) throws Exception { + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao() + .asQueryable().where((builder, root) -> builder.equal(root.get("id"), uuid)) + .update(root -> root.get("status"), DMP.DMPStatus.ACTIVE.getValue()); + return; + }*/ + /*public File getPdfDocument(String id) throws InstantiationException, IllegalAccessException, InterruptedException, IOException { + File file = this.getWordDocument(id); + String fileName = file.getName(); + if (fileName.endsWith(".docx")){ + fileName = fileName.substring(0, fileName.length() - 5); + } + return this.datasetManager.convertToPDF(file, environment, fileName); + }*/ + /*public eu.eudat.models.data.dmp.DataManagementPlan getSinglePublic(String id, DynamicGrantConfiguration dynamicGrantConfiguration) throws Exception { + DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); + + if (dataManagementPlanEntity != null && dataManagementPlanEntity.getStatus() == 1) { + eu.eudat.models.data.dmp.DataManagementPlan datamanagementPlan = new eu.eudat.models.data.dmp.DataManagementPlan(); + datamanagementPlan.fromDataModel(dataManagementPlanEntity); + datamanagementPlan.setDatasets(datamanagementPlan.getDatasets().stream().filter(dataset -> dataset.getStatus() == Dataset.Status.FINALISED.getValue()).collect(Collectors.toList())); + Map dmpProperties = dataManagementPlanEntity.getDmpProperties() != null ? new org.json.JSONObject(dataManagementPlanEntity.getDmpProperties()).toMap() : null; +// datamanagementPlan.setDynamicFields(dynamicGrantConfiguration.getFields().stream().map(item -> { +// DynamicFieldWithValue fieldWithValue = new DynamicFieldWithValue(); +// fieldWithValue.setId(item.getId()); +// fieldWithValue.setDependencies(item.getDependencies()); +// fieldWithValue.setName(item.getName()); +// fieldWithValue.setQueryProperty(item.getQueryProperty()); +// fieldWithValue.setRequired(item.getRequired()); +// return fieldWithValue; +// }).collect(Collectors.toList())); + + if (dmpProperties != null && datamanagementPlan.getDynamicFields() != null) + datamanagementPlan.getDynamicFields().forEach(item -> { + Map properties = (Map) dmpProperties.get(item.getId()); + if (properties != null) + item.setValue(new Tuple<>(properties.get("id"), properties.get("label"))); + }); + return datamanagementPlan; + } else { + throw new Exception("Selected DMP is not public"); + } + } + + public DataManagementPlanOverviewModel getOverviewSinglePublic(String id) throws Exception { + DMP dataManagementPlanEntity = databaseRepository.getDmpDao().find(UUID.fromString(id)); + if (dataManagementPlanEntity != null && dataManagementPlanEntity.getStatus() == 1) { + DataManagementPlanOverviewModel datamanagementPlan = new DataManagementPlanOverviewModel(); + datamanagementPlan.fromDataModelDatasets(dataManagementPlanEntity); + datamanagementPlan.setDatasets(datamanagementPlan.getDatasets().stream().filter(dataset -> dataset.getStatus() == Dataset.Status.FINALISED.getValue()).collect(Collectors.toList())); + return datamanagementPlan; + } else { + throw new Exception("Selected DMP is not public"); + } + }*/ + /*public List getWithCriteria(DMPDao dmpsRepository, DataManagementPlanCriteriaRequest dataManagementPlanCriteria, Principal principal) throws IllegalAccessException, InstantiationException { + UUID principalID = principal.getId(); + QueryableList items = dmpsRepository.getWithCriteria(dataManagementPlanCriteria.getCriteria()).withHint(HintedModelFactory.getHint(DataManagementPlan.class)); + List roles = new LinkedList<>(); + QueryableList authenticatedItems = dmpsRepository.getAuthenticated(items, principalID, roles); + List datamanagementPlans = authenticatedItems.select(item -> new DataManagementPlan().fromDataModel(item)); + return datamanagementPlans; + }*/ +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DataManagementProfileManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DataManagementProfileManager.java new file mode 100644 index 000000000..d7c647b1c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DataManagementProfileManager.java @@ -0,0 +1,250 @@ +package eu.eudat.old.logic.managers; + +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.JsonPath; +import eu.eudat.old.data.dao.criteria.RequestItem; +import eu.eudat.old.data.entities.DMPProfile; +import eu.eudat.old.data.query.items.dmpblueprint.DataManagementPlanBlueprintTableRequest; +import eu.eudat.old.data.query.items.item.dmpprofile.DataManagementPlanProfileCriteriaRequest; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.logic.utilities.builders.XmlBuilder; +import eu.eudat.old.logic.utilities.documents.helpers.FileEnvelope; +import eu.eudat.old.logic.utilities.documents.xml.dmpXml.ExportXmlBuilderDmpBlueprint; +import eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel.DmpBlueprint; +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.*; +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.types.SystemFieldType; +import eu.eudat.old.models.data.helpermodels.Tuple; +import eu.eudat.old.models.data.helpers.common.AutoCompleteLookupItem; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.listingmodels.DataManagementPlanBlueprintListingModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.dao.criteria.DataManagementPlanCriteria; +import eu.eudat.old.data.query.items.table.dmpprofile.DataManagementPlanProfileTableRequest; +import eu.eudat.old.exceptions.dmpblueprint.DmpBlueprintUsedException; +import eu.eudat.old.logic.utilities.documents.xml.dmpXml.ImportXmlBuilderDmpBlueprint; +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.types.FieldCategory; +import eu.eudat.old.models.data.listingmodels.DataManagementPlanProfileListingModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +import javax.activation.MimetypesFileTypeMap; +import javax.xml.xpath.*; +import java.io.*; +import java.nio.file.Files; +import java.util.*; +import java.util.concurrent.CompletableFuture; + +import org.springframework.http.*; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.multipart.MultipartFile; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Created by ikalyvas on 3/21/2018. + */ +@Component +public class DataManagementProfileManager { + private static final Logger logger = LoggerFactory.getLogger(DataManagementProfileManager.class); + + private ApiContext apiContext; + private DatabaseRepository databaseRepository; + private Environment environment; + + @Autowired + public DataManagementProfileManager(ApiContext apiContext, Environment environment) { + this.apiContext = apiContext; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + this.environment = environment; + } + + public DataTableData getPaged(DataManagementPlanProfileTableRequest dataManagementPlanProfileTableRequest, Principal principal) throws Exception { + + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().getWithCriteria(dataManagementPlanProfileTableRequest.getCriteria()); + QueryableList pagedItems = PaginationManager.applyPaging(items, dataManagementPlanProfileTableRequest); + + DataTableData dataTable = new DataTableData(); + + CompletableFuture itemsFuture = pagedItems + .selectAsync(item -> new DataManagementPlanProfileListingModel().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 DataTableData getPagedBlueprint(DataManagementPlanBlueprintTableRequest dataManagementPlanBlueprintTableRequest, Principal principal) throws Exception { + + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().getWithCriteriaBlueprint(dataManagementPlanBlueprintTableRequest.getCriteria()); + QueryableList pagedItems = PaginationManager.applyPaging(items, dataManagementPlanBlueprintTableRequest); + + DataTableData dataTable = new DataTableData<>(); + + CompletableFuture itemsFuture = pagedItems + .selectAsync(item -> new DataManagementPlanBlueprintListingModel().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 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 DataManagementPlanBlueprintListingModel getSingleBlueprint(String id, Principal principal) { + DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id)); + DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel = new DataManagementPlanBlueprintListingModel(); + dataManagementPlanBlueprintListingModel.fromDataModel(dmpProfile); + return dataManagementPlanBlueprintListingModel; + } + + public boolean fieldInBlueprint(String id, SystemFieldType type, Principal principal) { + DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id)); + return this.fieldInBlueprint(dmpProfile, type, principal); + } + + public boolean fieldInBlueprint(DMPProfile dmpProfile, SystemFieldType type, Principal principal) { + DataManagementPlanBlueprintListingModel dmpBlueprint = new DataManagementPlanBlueprintListingModel(); + dmpBlueprint.fromDataModel(dmpProfile); + for(Section section: dmpBlueprint.getDefinition().getSections()){ + for(FieldModel field: section.getFields()){ + if(field.getCategory().equals(FieldCategory.SYSTEM)){ + SystemField systemField = field.toSystemField(); + if(systemField.getType().equals(type)){ + return true; + } + } + } + } + return false; + } + + public List getWithCriteria(DataManagementPlanProfileCriteriaRequest dataManagementPlanProfileCriteriaRequest) throws IllegalAccessException, InstantiationException { + QueryableList items = databaseRepository.getDmpProfileDao().getWithCriteria(dataManagementPlanProfileCriteriaRequest.getCriteria()); + List datamanagementPlans = items.select(item -> new DataManagementPlanProfileListingModel().fromDataModel(item)); + return datamanagementPlans; + } + + public void createOrUpdate(DataManagementPlanProfileListingModel dataManagementPlanProfileListingModel, Principal principal) throws Exception { + DMPProfile dmpProfile = dataManagementPlanProfileListingModel.toDataModel(); + apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().createOrUpdate(dmpProfile); + } + + public void createOrUpdateBlueprint(DataManagementPlanBlueprintListingModel dataManagementPlanBlueprintListingModel, Principal principal) throws Exception { + DMPProfile dmpProfile = dataManagementPlanBlueprintListingModel.toDataModel(); + apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().createOrUpdate(dmpProfile); + } + + public void inactivate(String id) { + DMPProfile dmpProfile = databaseRepository.getDmpProfileDao().find(UUID.fromString(id)); + DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria(); + dataManagementPlanCriteria.setProfile(dmpProfile); + if (dmpProfile.getStatus() == DMPProfile.Status.SAVED.getValue() || databaseRepository.getDmpDao().getWithCriteria(dataManagementPlanCriteria).count() == 0) { + dmpProfile.setStatus(DMPProfile.Status.DELETED.getValue()); + databaseRepository.getDmpProfileDao().createOrUpdate(dmpProfile); + } else { + throw new DmpBlueprintUsedException("This blueprint can not deleted, because DMPs are associated with it"); + } + } + + public ResponseEntity getDocument(DataManagementPlanBlueprintListingModel dmpProfile) throws IOException { + FileEnvelope envelope = getXmlDocument(dmpProfile); + InputStream resource = new FileInputStream(envelope.getFile()); + logger.info("Mime Type of " + envelope.getFilename() + " is " + + new MimetypesFileTypeMap().getContentType(envelope.getFile())); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(envelope.getFile().length()); + responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); + String fileName = envelope.getFilename().replace(" ", "_").replace(",", "_"); + responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName + ".xml"); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource); + resource.close(); + Files.deleteIfExists(envelope.getFile().toPath()); + return new ResponseEntity<>(content, + responseHeaders, + HttpStatus.OK); + } + + public FileEnvelope getXmlDocument(DataManagementPlanBlueprintListingModel dmpProfile) throws IOException { + ExportXmlBuilderDmpBlueprint xmlBuilder = new ExportXmlBuilderDmpBlueprint(); + File file = xmlBuilder.build(dmpProfile, environment); + FileEnvelope fileEnvelope = new FileEnvelope(); + fileEnvelope.setFile(file); + fileEnvelope.setFilename(dmpProfile.getLabel()); + return fileEnvelope; + } + + + public DmpBlueprint createDmpProfileFromXml(MultipartFile multiPartFile) { + ImportXmlBuilderDmpBlueprint xmlBuilder = new ImportXmlBuilderDmpBlueprint(); + try { + return xmlBuilder.build(convert(multiPartFile)); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + return null; + } + + private File convert(MultipartFile file) throws IOException { + File convFile = new File(this.environment.getProperty("temp.temp") + file.getOriginalFilename()); + convFile.createNewFile(); + FileOutputStream fos = new FileOutputStream(convFile); + fos.write(file.getBytes()); + fos.close(); + return convFile; + } + + public List> getExternalAutocomplete(RequestItem lookupItem) throws XPathExpressionException { + DMPProfile dmpProfile = this.apiContext.getOperationsContext().getDatabaseRepository().getDmpProfileDao().find(UUID.fromString(lookupItem.getCriteria().getProfileID())); + Field field = this.queryForField(dmpProfile.getDefinition(), lookupItem.getCriteria().getFieldID()); + DmpProfileExternalAutoComplete data = field.getExternalAutocomplete(); + return this.externalAutocompleteRequest(data, lookupItem.getCriteria().getLike()); + } + + private Field queryForField(String xml, String fieldId) throws XPathExpressionException { + Field field = new Field(); + Document document = XmlBuilder.fromXml(xml); + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPath xpath = xpathFactory.newXPath(); + XPathExpression expr = xpath.compile("//field[@id='" + fieldId + "']"); + Element name = (Element) expr.evaluate(document, XPathConstants.NODE); + field.fromXml(name); + return field; + } + + private List> externalAutocompleteRequest(DmpProfileExternalAutoComplete data, String like) { + return externalAutocompleteRequest(data.getUrl(), data.getOptionsRoot(), data.getLabel(), data.getValue(), like); + } + + public static List> externalAutocompleteRequest(String url, String optionsRoot, String label, String value, String like) { + List> result = new LinkedList<>(); + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.valueOf("application/vnd.api+json; charset=utf-8"))); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity = new HttpEntity<>("parameters", headers); + + ResponseEntity response = restTemplate.exchange(url + "?search=" + like, HttpMethod.GET, entity, Object.class); + DocumentContext jsonContext = JsonPath.parse(response.getBody()); + + List> jsonItems = jsonContext.read(optionsRoot + "['" + label + "','" + value + "']"); + jsonItems.forEach(item -> result.add(new Tuple<>(item.get(value), item.get(label)))); + return result; + + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DataRepositoryManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DataRepositoryManager.java new file mode 100644 index 000000000..d21d570e5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DataRepositoryManager.java @@ -0,0 +1,96 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.dao.criteria.DataRepositoryCriteria; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.data.entities.DataRepository; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.datarepository.DataRepositoryModel; +import eu.eudat.old.models.data.security.Principal; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Created by ikalyvas on 9/3/2018. + */ +@Component +public class DataRepositoryManager { + private ApiContext apiContext; + + @Autowired + public DataRepositoryManager(ApiContext apiContext) { + this.apiContext = apiContext; + } + + public DataRepository create(DataRepositoryModel dataRepositoryModel, Principal principal) throws Exception { + DataRepository dataRepository = dataRepositoryModel.toDataModel(); + dataRepository.getCreationUser().setId(principal.getId()); + return apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao().createOrUpdate(dataRepository); + } + + public List getDataRepositories(String query, String type, Principal principal) throws HugeResultSet, NoURLFound { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getRepositories(externalUrlCriteria, type); + + DataRepositoryCriteria criteria = new DataRepositoryCriteria(); + if (!query.isEmpty()) criteria.setLike(query); + criteria.setCreationUserId(principal.getId()); + + List dataRepositoryModels = new LinkedList<>(); + if (type.equals("")) { + List dataRepositoryList = (this.apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao().getWithCriteria(criteria)).toList(); + dataRepositoryModels = dataRepositoryList.stream().map(item -> new DataRepositoryModel().fromDataModel(item)).collect(Collectors.toList()); + } + + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + dataRepositoryModels.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, DataRepositoryModel.class)).collect(Collectors.toList())); + + return dataRepositoryModels; + } + public List getPubRepositories(String query, String type, Principal principal) throws HugeResultSet, NoURLFound { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getPubRepositories(externalUrlCriteria, type); + + DataRepositoryCriteria criteria = new DataRepositoryCriteria(); + if (!query.isEmpty()) criteria.setLike(query); + criteria.setCreationUserId(principal.getId()); + + List dataRepositoryModels = new LinkedList<>(); + if (type.equals("")) { + List dataRepositoryList = (this.apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao().getWithCriteria(criteria)).toList(); + dataRepositoryModels = dataRepositoryList.stream().map(item -> new DataRepositoryModel().fromDataModel(item)).collect(Collectors.toList()); + } + + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + dataRepositoryModels.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, DataRepositoryModel.class)).collect(Collectors.toList())); + + return dataRepositoryModels; + } + public List getJournals(String query, String type, Principal principal) throws HugeResultSet, NoURLFound { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getJournals(externalUrlCriteria, type); + + DataRepositoryCriteria criteria = new DataRepositoryCriteria(); + if (!query.isEmpty()) criteria.setLike(query); + criteria.setCreationUserId(principal.getId()); + + List dataRepositoryModels = new LinkedList<>(); + if (type.equals("")) { + List dataRepositoryList = (this.apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao().getWithCriteria(criteria)).toList(); + dataRepositoryModels = dataRepositoryList.stream().map(item -> new DataRepositoryModel().fromDataModel(item)).collect(Collectors.toList()); + } + + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + dataRepositoryModels.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, DataRepositoryModel.class)).collect(Collectors.toList())); + + return dataRepositoryModels; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DatasetManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DatasetManager.java new file mode 100644 index 000000000..f8c6828a8 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DatasetManager.java @@ -0,0 +1,1196 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.dao.criteria.*; +import eu.eudat.old.data.dao.entities.DataRepositoryDao; +import eu.eudat.old.data.dao.entities.DatasetDao; +import eu.eudat.old.data.dao.entities.RegistryDao; +import eu.eudat.old.data.entities.*; +import eu.eudat.old.data.enumeration.notification.ActiveStatus; +import eu.eudat.old.data.enumeration.notification.NotifyState; +import eu.eudat.old.elastic.criteria.DatasetCriteria; +import eu.eudat.old.elastic.repository.DatasetRepository; +import eu.eudat.old.exceptions.security.UnauthorisedException; +import eu.eudat.old.logic.builders.BuilderFactory; +import eu.eudat.old.logic.mapper.elastic.DatasetMapper; +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.services.forms.VisibilityRuleService; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.logic.utilities.documents.helpers.FileEnvelope; +import eu.eudat.old.logic.utilities.helpers.StreamDistinctBy; +import eu.eudat.old.models.data.datasetImport.DatasetImportPagedDatasetProfile; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileListingModel; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileOverviewModel; +import eu.eudat.old.models.data.dmp.AssociatedProfile; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.listingmodels.DatasetListingModel; +import eu.eudat.old.models.data.user.composite.DatasetProfile; +import eu.eudat.old.data.enumeration.notification.ContactType; +import eu.eudat.old.data.enumeration.notification.NotificationType; +import eu.eudat.old.data.query.items.table.dataset.DatasetPublicTableRequest; +import eu.eudat.old.data.query.items.table.dataset.DatasetTableRequest; +import eu.eudat.old.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem; +import eu.eudat.old.elastic.entities.Dataset; +import eu.eudat.old.elastic.entities.Tag; +import eu.eudat.old.exceptions.security.ForbiddenException; +import eu.eudat.old.logic.builders.entity.UserInfoBuilder; +import eu.eudat.old.logic.mapper.elastic.criteria.DmpCriteriaMapper; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.forms.VisibilityRuleServiceImpl; +import eu.eudat.old.logic.utilities.documents.types.ParagraphStyle; +import eu.eudat.old.logic.utilities.documents.word.WordBuilder; +import eu.eudat.old.logic.utilities.documents.xml.ExportXmlBuilder; +import eu.eudat.old.logic.utilities.json.JsonSearcher; +import eu.eudat.old.models.HintedModelFactory; +import eu.eudat.old.models.data.dataset.DatasetOverviewModel; +import eu.eudat.old.models.data.datasetImport.DatasetImportField; +import eu.eudat.old.models.data.datasetwizard.DatasetWizardModel; +import eu.eudat.old.models.data.dmp.DataManagementPlan; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.user.composite.PagedDatasetProfile; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.types.Authorities; +import eu.eudat.old.types.MetricNames; +import org.apache.poi.xwpf.extractor.XWPFWordExtractor; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import javax.activation.MimetypesFileTypeMap; +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.transaction.Transactional; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; +import java.io.*; +import java.math.BigInteger; +import java.nio.file.Files; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Component +public class DatasetManager { + private static final Logger logger = LoggerFactory.getLogger(DatasetManager.class); + + private final Map notificationPaths = Stream.of(new Object[][] { + {NotificationType.DATASET_MODIFIED, "/datasets/edit"}, + {NotificationType.DATASET_MODIFIED_FINALISED, "/datasets/edit"} + }).collect(Collectors.toMap(data -> (NotificationType) data[0], data -> (String) data[1])); + + private ApiContext apiContext; + private DatabaseRepository databaseRepository; + private DatasetRepository datasetRepository; + private BuilderFactory builderFactory; + private UserManager userManager; + private ConfigLoader configLoader; + private Environment environment; + private final MetricsManager metricsManager; + private final FileManager fileManager; + + @Autowired + public DatasetManager(ApiContext apiContext, UserManager userManager, ConfigLoader configLoader, Environment environment, MetricsManager metricsManager, + FileManager fileManager) { + this.apiContext = apiContext; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + this.datasetRepository = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository(); + this.builderFactory = apiContext.getOperationsContext().getBuilderFactory(); + this.userManager = userManager; + this.configLoader = configLoader; + this.environment = environment; + this.metricsManager = metricsManager; + this.fileManager = fileManager; + } + + public DataTableData getPaged(DatasetTableRequest datasetTableRequest, Principal principal) throws Exception { + DatasetCriteria datasetCriteria = new DatasetCriteria(); + datasetCriteria.setLike(datasetTableRequest.getCriteria().getLike()); + datasetCriteria.setDatasetTemplates(datasetTableRequest.getCriteria().getDatasetTemplates()); + if (datasetTableRequest.getCriteria().getStatus() != null) { + datasetCriteria.setStatus(datasetTableRequest.getCriteria().getStatus().shortValue()); + } + datasetCriteria.setDmps(datasetTableRequest.getCriteria().getDmpIds()); + datasetCriteria.setGroupIds(datasetTableRequest.getCriteria().getGroupIds()); + datasetCriteria.setGrants(datasetTableRequest.getCriteria().getGrants()); + datasetCriteria.setCollaborators(datasetTableRequest.getCriteria().getCollaborators()); + datasetCriteria.setAllowAllVersions(datasetTableRequest.getCriteria().getAllVersions()); + datasetCriteria.setOrganiztions(datasetTableRequest.getCriteria().getOrganisations()); + datasetCriteria.setTags(datasetTableRequest.getCriteria().getTags()); + if (datasetTableRequest.getCriteria().getIsPublic() != null) { + datasetCriteria.setPublic(datasetTableRequest.getCriteria().getIsPublic()); + } + + if (!datasetCriteria.isPublic()) { + if (datasetCriteria.getCollaborators() == null) { + datasetCriteria.setSortCriteria(new ArrayList<>()); + } + datasetCriteria.getCollaborators().add(principal.getId()); + } + if (datasetTableRequest.getCriteria().getGrantStatus() != null) { + datasetCriteria.setGrantStatus(datasetTableRequest.getCriteria().getGrantStatus()); + } + if (datasetTableRequest.getOrderings() != null) { + datasetCriteria.setSortCriteria(DmpCriteriaMapper.toElasticSorting(datasetTableRequest.getOrderings())); + } + datasetCriteria.setOffset(datasetTableRequest.getOffset()); + datasetCriteria.setSize(datasetTableRequest.getLength()); + List datasets; + try { + datasets = datasetRepository.exists() ? + datasetRepository.queryIds(datasetCriteria) : null; + } catch (Exception ex) { + logger.warn(ex.getMessage(), ex); + datasets = null; + } + + UserInfo userInfo = builderFactory.getBuilder(UserInfoBuilder.class).id(principal.getId()).build(); +// QueryableList items = databaseRepository.getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria()).withHint(HintedModelFactory.getHint(DatasetListingModel.class)); + QueryableList items; + if (datasets != null) { + + if (!datasets.isEmpty()) { + //items = databaseRepository.getDatasetDao().asQueryable().withHint(HintedModelFactory.getHint(DatasetListingModel.class)); + final List datasetIds = datasets.stream().map(datasetE -> UUID.fromString(datasetE.getId())).distinct().collect(Collectors.toList()); + items = databaseRepository.getDatasetDao().filterFromElastic(datasetTableRequest.getCriteria(), datasetIds).withHint(HintedModelFactory.getHint(DatasetListingModel.class));//.withFields(Collections.singletonList("id")); + //items.where((builder, root) -> root.get("id").in(datasetIds)); + } else { + items = databaseRepository.getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria()).withHint(HintedModelFactory.getHint(DatasetListingModel.class));//.withFields(Collections.singletonList("id")); + //items.where((builder, root) -> root.get("id").in(new UUID[]{UUID.randomUUID()})); + } + } else { + items = databaseRepository.getDatasetDao().getWithCriteria(datasetTableRequest.getCriteria()).withHint(HintedModelFactory.getHint(DatasetListingModel.class));//.withFields(Collections.singletonList("id")); + } + List roles = new LinkedList<>(); + QueryableList pagedItems; + QueryableList authItems; + if (!datasetTableRequest.getCriteria().getIsPublic()) { + if (principal.getId() == null) { + throw new UnauthorisedException("You are not allowed to access those datasets"); + } + if (datasetTableRequest.getCriteria().getRole() != null) { + roles.add(datasetTableRequest.getCriteria().getRole()); + } + authItems = databaseRepository.getDatasetDao().getAuthenticated(items, userInfo, roles).distinct(); + pagedItems = PaginationManager.applyPaging(authItems, datasetTableRequest); + } else { + if (principal.getId() != null && datasetTableRequest.getCriteria().getRole() != null) { + items.where((builder, root) -> { + Join userJoin = root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT); + return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal.getId()), builder.equal(userJoin.get("role"), datasetTableRequest.getCriteria().getRole())); + }); + } + String[] strings = new String[1]; + //strings[0] = "-dmp:publishedAt|join|"; + //datasetTableRequest.getOrderings().setFields(strings); + authItems = items; + pagedItems = PaginationManager.applyPaging(items, datasetTableRequest); + } + DataTableData dataTable = new DataTableData<>(); + + + dataTable.setData(pagedItems.select(this::mapModel).stream().filter(Objects::nonNull).collect(Collectors.toList())); + + dataTable.setTotalCount(authItems.count()); + + //CompletableFuture.allOf(itemsFuture, countFuture).join(); + return dataTable; + } + + public DataTableData getPaged(DatasetPublicTableRequest datasetTableRequest, Principal principal) throws Exception { + Long count = 0L; + DatasetCriteria datasetCriteria = new DatasetCriteria(); + datasetCriteria.setLike(datasetTableRequest.getCriteria().getLike()); + datasetCriteria.setDatasetTemplates(datasetTableRequest.getCriteria().getDatasetProfile()); + datasetCriteria.setDmps(datasetTableRequest.getCriteria().getDmpIds()); + datasetCriteria.setGrants(datasetTableRequest.getCriteria().getGrants()); + if (datasetTableRequest.getOrderings() != null) { + datasetCriteria.setSortCriteria(DmpCriteriaMapper.toElasticSorting(datasetTableRequest.getOrderings())); + } + datasetCriteria.setOffset(datasetTableRequest.getOffset()); + datasetCriteria.setSize(datasetTableRequest.getLength()); + List datasets; + try { + datasets = datasetRepository.exists() ? + datasetRepository.queryIds(datasetCriteria) : new LinkedList<>(); + count = datasetRepository.exists() ? datasetRepository.count(datasetCriteria) : 0L; + } catch (Exception ex) { + logger.warn(ex.getMessage()); + datasets = null; + } + /*datasetTableRequest.setQuery(databaseRepository.getDatasetDao().asQueryable().withHint(HintedModelFactory.getHint(DatasetListingModel.class))); + QueryableList items = datasetTableRequest.applyCriteria();*/ + QueryableList items; + if (datasets != null) { + if (!datasets.isEmpty()) { + items = databaseRepository.getDatasetDao().asQueryable().withHint(HintedModelFactory.getHint(DatasetListingModel.class)); + List finalDatasets = datasets; + items.where((builder, root) -> root.get("id").in(finalDatasets.stream().map(x -> UUID.fromString(x.getId())).collect(Collectors.toList()))); + } else + items = datasetTableRequest.applyCriteria(); + items.where((builder, root) -> root.get("id").in(new UUID[]{UUID.randomUUID()})); + } else { + items = datasetTableRequest.applyCriteria(); + } + + if (principal.getId() != null && datasetTableRequest.getCriteria().getRole() != null) { + items.where((builder, root) -> { + Join userJoin = root.join("dmp", JoinType.LEFT).join("users", JoinType.LEFT); + return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal.getId()), builder.equal(userJoin.get("role"), datasetTableRequest.getCriteria().getRole())); + }); + } + List strings = new ArrayList<>(); + strings.add("-dmp:publishedAt|join|"); + datasetTableRequest.getOrderings().setFields(strings); + if (count == 0L) { + count = items.count(); + } + QueryableList pagedItems = PaginationManager.applyPaging(items, datasetTableRequest); + DataTableData dataTable = new DataTableData<>(); + + List datasetListis = pagedItems. + select(this::mapModel); + + dataTable.setData(datasetListis.stream().filter(Objects::nonNull).collect(Collectors.toList())); + + dataTable.setTotalCount(count); + //CompletableFuture.allOf(countFuture).join(); + return dataTable; + } + + public DatasetWizardModel getSingle(String id, Principal principal) { + DatasetWizardModel dataset = new DatasetWizardModel(); + eu.eudat.old.data.entities.Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); + if (datasetEntity.getDmp().getUsers() + .stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()) + .collect(Collectors.toList()).size() == 0 && !datasetEntity.getDmp().isPublic()) + throw new UnauthorisedException(); + dataset.setDatasetProfileDefinition(getPagedProfile(dataset, datasetEntity)); + dataset.fromDataModel(datasetEntity); + + // Creates the Criteria to get all version of DescriptionTemplate in question. + DatasetProfileCriteria profileCriteria = new DatasetProfileCriteria(); + UUID profileId = datasetEntity.getProfile().getGroupId(); + List uuidList = new LinkedList<>(); + uuidList.add(profileId); + profileCriteria.setGroupIds(uuidList); + profileCriteria.setAllVersions(true); + + List profileVersions = databaseRepository.getDatasetProfileDao().getWithCriteria(profileCriteria) + .orderBy(((builder, root) -> builder.desc(root.get("version")))) + .toList(); + List profileVersionsIncluded = new LinkedList<>(); + + // Iterate through the versions and remove those that are not included in the DMP of the dataset in question. + for (DescriptionTemplate version : profileVersions) { + for (AssociatedProfile p : dataset.getDmp().getProfiles()) { + if (version.getId().toString().equals(p.getDescriptionTemplateId().toString())) { + profileVersionsIncluded.add(version); + } + } + } + + // Sort the list with the included Versions. + Stream sorted = profileVersionsIncluded.stream().sorted(Comparator.comparing(DescriptionTemplate::getVersion).reversed()); + + // Make the Stream into List and get the first item. + List profiles = sorted.collect(Collectors.toList()); + if (profiles.isEmpty()) + throw new NoSuchElementException("No profiles found for the specific Dataset"); + + DescriptionTemplate profile = profiles.get(0); + + // Check if the dataset is on the latest Version. + boolean latestVersion = profile.getVersion().toString().equals(datasetEntity.getProfile().getVersion().toString()); + dataset.setIsProfileLatestVersion(latestVersion); + + Dataset datasetElastic; + try { + datasetElastic = datasetRepository.exists() ? + datasetRepository.findDocument(id) : new Dataset(); + } catch (Exception ex) { + logger.warn(ex.getMessage()); + datasetElastic = null; + } + if (datasetElastic != null && datasetElastic.getTags() != null && !datasetElastic.getTags().isEmpty()) { + dataset.setTags(datasetElastic.getTags()); + } + + /*if (datasetElastic != null && datasetElastic.getLabel() != null && !datasetElastic.getLabel().isEmpty()) { + dataset.setLabel(datasetElastic.getLabel()); + }*/ + return dataset; + } + + public DatasetWizardModel getSinglePublic(String id) throws Exception { + DatasetWizardModel dataset = new DatasetWizardModel(); + eu.eudat.old.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 DatasetOverviewModel getOverviewSingle(String id, Principal principal, boolean isPublic) throws Exception { + eu.eudat.old.data.entities.Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id)); + if (datasetEntity.getStatus() == eu.eudat.old.data.entities.Dataset.Status.DELETED.getValue()) { + throw new Exception("Dataset is deleted."); + } + if (!isPublic && principal == null) { + throw new UnauthorisedException(); + } else + if (!isPublic && datasetEntity.getDmp().getUsers() + .stream().noneMatch(userInfo -> userInfo.getUser().getId() == principal.getId())) { + throw new UnauthorisedException(); + } else if (isPublic && !datasetEntity.getDmp().isPublic()) { + throw new ForbiddenException("Selected Dataset is not public"); + } + DatasetOverviewModel dataset = new DatasetOverviewModel(); + dataset.fromDataModel(datasetEntity); + + return dataset; + } + + public eu.eudat.old.data.entities.Dataset getEntitySingle(UUID id) { + return databaseRepository.getDatasetDao().find(id); + } + + public PagedDatasetProfile getPagedProfile(DatasetWizardModel dataset, eu.eudat.old.data.entities.Dataset datasetEntity) { + DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(datasetEntity.getProfile()); + datasetprofile.setStatus(dataset.getStatus()); + if (datasetEntity.getProperties() != null) { + JSONObject jObject = new JSONObject(datasetEntity.getProperties()); + Map properties = jObject.toMap(); + datasetprofile.fromJsonObject(properties); + } + PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile(); + pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile); + return pagedDatasetProfile; + } + + private XWPFDocument getWordDocument(ConfigLoader configLoader, eu.eudat.old.data.entities.Dataset datasetEntity, VisibilityRuleService visibilityRuleService, Principal principal) throws IOException { + WordBuilder wordBuilder = new WordBuilder(this.environment, configLoader); + DatasetWizardModel dataset = new DatasetWizardModel(); + XWPFDocument document = configLoader.getDatasetDocument(); + + DMP dmpEntity = datasetEntity.getDmp(); + + if (!dmpEntity.isPublic() && dmpEntity.getUsers().stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()).collect(Collectors.toList()).size() == 0) + throw new UnauthorisedException(); + + wordBuilder.fillFirstPage(dmpEntity, datasetEntity, document, true); + wordBuilder.fillFooter(dmpEntity, datasetEntity, document, true); + + int powered_pos = wordBuilder.findPosOfPoweredBy(document); + XWPFParagraph powered_par = null; + XWPFParagraph argos_img_par = null; + if(powered_pos != -1) { + powered_par = document.getParagraphArray(powered_pos); + argos_img_par = document.getParagraphArray(powered_pos + 1); + } + +// wordBuilder.addParagraphContent(datasetEntity.getLabel(), document, ParagraphStyle.HEADER1, BigInteger.ZERO); + + // Space below Dataset title. +// XWPFParagraph parBreakDataset = document.createParagraph(); +// +// XWPFParagraph datasetTemplateParagraph = document.createParagraph(); +// datasetTemplateParagraph.setStyle("Heading2"); +// XWPFRun runDatasetTemplate1 = datasetTemplateParagraph.createRun(); +// runDatasetTemplate1.setText("Template: "); +// runDatasetTemplate1.setBold(true); +// runDatasetTemplate1.setFontSize(12); +// XWPFRun runDatasetTemplate = datasetTemplateParagraph.createRun(); +// runDatasetTemplate.setText(datasetEntity.getProfile().getLabel()); +// runDatasetTemplate.setColor("2E75B6"); +// runDatasetTemplate.setBold(true); +// runDatasetTemplate.setFontSize(12); +// +// wordBuilder.addParagraphContent(datasetEntity.getDescription(), document, ParagraphStyle.HTML, BigInteger.ZERO); + + /*XWPFParagraph externalReferencesParagraph = document.createParagraph(); + externalReferencesParagraph.setStyle("Heading2"); + XWPFRun externalReferencesRun = externalReferencesParagraph.createRun(); + externalReferencesRun.setText("External References"); + externalReferencesRun.setColor("2E75B6"); + externalReferencesRun.setBold(true); + externalReferencesRun.setFontSize(12); + + wordBuilder.addParagraphContent("Data Repositories", document, ParagraphStyle.HEADER3, BigInteger.ZERO); + if (datasetEntity.getDatasetDataRepositories().size() > 0) { + wordBuilder.addParagraphContent(datasetEntity.getDatasetDataRepositories().stream().map(DatasetDataRepository::getDataRepository).map(DataRepository::getLabel).collect(Collectors.joining(", ")) + , document, ParagraphStyle.TEXT, BigInteger.ZERO); + } + wordBuilder.addParagraphContent("External Datasets", document, ParagraphStyle.HEADER3, BigInteger.ZERO); + if (datasetEntity.getDatasetExternalDatasets().size() > 0) { + wordBuilder.addParagraphContent(datasetEntity.getDatasetExternalDatasets().stream().map(DatasetExternalDataset::getExternalDataset).map(ExternalDataset::getLabel).collect(Collectors.joining(", ")) + , document, ParagraphStyle.TEXT, BigInteger.ZERO); + } + wordBuilder.addParagraphContent("Registries", document, ParagraphStyle.HEADER3, BigInteger.ZERO); + if (datasetEntity.getRegistries().size() > 0) { + wordBuilder.addParagraphContent(datasetEntity.getRegistries().stream().map(Registry::getLabel).collect(Collectors.joining(", ")) + , document, ParagraphStyle.TEXT, BigInteger.ZERO); + } + wordBuilder.addParagraphContent("Services", document, ParagraphStyle.HEADER3, BigInteger.ZERO); + if (datasetEntity.getServices().size() > 0) { + wordBuilder.addParagraphContent(datasetEntity.getServices().stream().map(DatasetService::getService).map(Service::getLabel).collect(Collectors.joining(", ")) + , document, ParagraphStyle.TEXT, BigInteger.ZERO); + }*/ + /*wordBuilder.addParagraphContent("Tags", document, ParagraphStyle.HEADER3, BigInteger.ZERO); + if (datasetEntity.().size() > 0) { + wordBuilder.addParagraphContent(datasetEntity.getServices().stream().map(DatasetService::getService).map(Service::getLabel).collect(Collectors.joining(", ")) + , document, ParagraphStyle.HEADER4, BigInteger.ZERO); + }*/ + + Map properties = new HashMap<>(); + if (datasetEntity.getProperties() != null) { + JSONObject jObject = new JSONObject(datasetEntity.getProperties()); + properties = jObject.toMap(); + } + +// wordBuilder.addParagraphContent("Dataset Description", document, ParagraphStyle.HEADER2, BigInteger.ZERO); + PagedDatasetProfile pagedDatasetProfile = getPagedProfile(dataset, datasetEntity); + visibilityRuleService.setProperties(properties); + visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules()); + wordBuilder.build(document, pagedDatasetProfile, visibilityRuleService); + String label = datasetEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", ""); +// File exportFile = new File(label + ".docx"); + + // Removes the top empty headings. +// for (int i = 0; i < 6; i++) { +// document.removeBodyElement(0); +// } + + if(powered_pos != -1) { + document.getLastParagraph().setPageBreak(false); + document.createParagraph(); + document.setParagraph(powered_par, document.getParagraphs().size() - 1); + + document.createParagraph(); + document.setParagraph(argos_img_par, document.getParagraphs().size() - 1); + + document.removeBodyElement(powered_pos + 1); + document.removeBodyElement(powered_pos + 1); + } + + return document; + //FileOutputStream out = new FileOutputStream(exportFile); + // document.write(out); + // out.close(); + // return exportFile; + } + + private XWPFDocument getLightWordDocument(ConfigLoader configLoader, DatasetWizardModel dataset, VisibilityRuleService visibilityRuleService) throws IOException { + WordBuilder wordBuilder = new WordBuilder(this.environment, configLoader); + XWPFDocument document = configLoader.getDocument(); + + // Space below Dataset title. + XWPFParagraph parBreakDataset = document.createParagraph(); + + Map properties = new HashMap<>(); + if (dataset.getDatasetProfileDefinition() != null) { + JSONObject jObject = new JSONObject(propertiesModelToString(dataset.getDatasetProfileDefinition())); + properties = jObject.toMap(); + } + + wordBuilder.addParagraphContent("Dataset Description", document, ParagraphStyle.HEADER2, BigInteger.ZERO, 0); + visibilityRuleService.setProperties(properties); + visibilityRuleService.buildVisibilityContext(dataset.getDatasetProfileDefinition().getRules()); + wordBuilder.build(document, dataset.getDatasetProfileDefinition(), visibilityRuleService); + + // Removes the top empty headings. + for (int i = 0; i < 6; i++) { + document.removeBodyElement(0); + } + + return document; + //FileOutputStream out = new FileOutputStream(exportFile); + // document.write(out); + // out.close(); + // return exportFile; + } + + public FileEnvelope getWordDocumentFile(ConfigLoader configLoader, String id, VisibilityRuleService visibilityRuleService, Principal principal) throws IOException { + eu.eudat.old.data.entities.Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); + if (!datasetEntity.getDmp().isPublic() && datasetEntity.getDmp().getUsers() + .stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()) + .collect(Collectors.toList()).size() == 0) + throw new UnauthorisedException(); + String label = datasetEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", ""); + FileEnvelope exportEnvelope = new FileEnvelope(); + exportEnvelope.setFilename(label + ".docx"); + String uuid = UUID.randomUUID().toString(); + File exportFile = new File(this.environment.getProperty("temp.temp") + uuid + ".docx"); + XWPFDocument document = getWordDocument(configLoader, datasetEntity, visibilityRuleService, principal); + FileOutputStream out = new FileOutputStream(exportFile); + document.write(out); + out.close(); + exportEnvelope.setFile(exportFile); + return exportEnvelope; + } + + public String getWordDocumentText (eu.eudat.old.data.entities.Dataset datasetEntity) throws Exception { + DatasetWizardModel datasetWizardModel = new DatasetWizardModel().fromDataModel(datasetEntity); + datasetWizardModel.setDatasetProfileDefinition(this.getPagedProfile(datasetWizardModel, datasetEntity)); + XWPFDocument document = getLightWordDocument(this.configLoader, datasetWizardModel, new VisibilityRuleServiceImpl()); + XWPFWordExtractor extractor = new XWPFWordExtractor(document); + return extractor.getText();/*.replaceAll("\n\\s*", " ");*/ + } + + public FileEnvelope getXmlDocument(String id, VisibilityRuleService visibilityRuleService, Principal principal) throws InstantiationException, IllegalAccessException, IOException { + ExportXmlBuilder xmlBuilder = new ExportXmlBuilder(); + DatasetWizardModel dataset = new DatasetWizardModel(); + eu.eudat.old.data.entities.Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); + if (!datasetEntity.getDmp().isPublic() && datasetEntity.getDmp().getUsers() + .stream().filter(userInfo -> userInfo.getUser().getId() == principal.getId()) + .collect(Collectors.toList()).size() == 0) + throw new UnauthorisedException(); + Map properties = new HashMap<>(); + if (datasetEntity.getProperties() != null) { + JSONObject jobject = new JSONObject(datasetEntity.getProperties()); + properties = jobject.toMap(); + } + PagedDatasetProfile pagedDatasetProfile = getPagedProfile(dataset, datasetEntity); + visibilityRuleService.setProperties(properties); + visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules()); + File file = xmlBuilder.build(pagedDatasetProfile, datasetEntity.getProfile().getId(), visibilityRuleService, environment); + FileEnvelope fileEnvelope = new FileEnvelope(); + fileEnvelope.setFile(file); + String label = datasetEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", ""); + fileEnvelope.setFilename(label); + return fileEnvelope; + } + + public eu.eudat.old.data.entities.Dataset createOrUpdate(DatasetWizardModel datasetWizardModel, Principal principal) throws Exception { + Boolean sendNotification = false; + eu.eudat.old.data.entities.Dataset tempDataset = null; + DMP dmp = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(datasetWizardModel.getDmp().getId()); + if (datasetWizardModel.getId() != null) { + tempDataset = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().find(datasetWizardModel.getId()); + if (tempDataset != null) { + + Instant dbTime = Instant.ofEpochMilli(tempDataset.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS); + Instant modelTime = Instant.ofEpochMilli(datasetWizardModel.getModified().getTime()).truncatedTo(ChronoUnit.SECONDS); + if (modelTime.toEpochMilli() != dbTime.toEpochMilli()) { + throw new Exception("Dataset has been modified already by another user."); + } + sendNotification = true; + } + } else { + metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.DRAFT); + } + if (dmp.getStatus().equals(DMP.DMPStatus.FINALISED.getValue()) && datasetWizardModel.getId() != null) + throw new Exception("DMP is finalized, therefore Dataset cannot be edited."); + eu.eudat.old.data.entities.Dataset dataset = datasetWizardModel.toDataModel(); + dataset.setDmp(dmp); + dataset.setProperties(propertiesModelToString(datasetWizardModel.getDatasetProfileDefinition())); + if (this.apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().getClient() != null) { + this.getTagsFromProfile(datasetWizardModel, dataset); + } + if (datasetWizardModel.getStatus() == (int) eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()) { + String failedField = checkDatasetValidation(dataset); + if (failedField != null) { + throw new Exception("Field value of " + failedField + " must be filled."); + } + } + UserInfo userInfo = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class).id(principal.getId()).build(); + dataset.setCreator(userInfo); + + createDataRepositoriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao(), dataset); + createExternalDatasetsIfTheyDontExist(dataset); + createRegistriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao(), dataset); + createServicesIfTheyDontExist(dataset); + eu.eudat.old.data.entities.Dataset dataset1 = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(dataset); + datasetWizardModel.setId(dataset1.getId()); + if (datasetWizardModel.getDmp().getGrant() == null) { + datasetWizardModel.setDmp(new DataManagementPlan().fromDataModelNoDatasets(dataset1.getDmp())); + } + dataset1.setProfile(this.apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(datasetWizardModel.getProfile().getId())); +// datasetWizardModel.setDatasetProfileDefinition(getPagedProfile(datasetWizardModel, dataset1)); + UUID dmpId = dataset1.getDmp().getId(); + dataset1.getDmp().setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + updateTags(dataset1, datasetWizardModel.getTags()); + if (sendNotification) { + if (dataset1.getStatus() != eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()) { + this.sendNotification(dataset1, dataset1.getDmp(), userInfo, NotificationType.DATASET_MODIFIED); + } else { + this.sendNotification(dataset1, dataset1.getDmp(), userInfo, NotificationType.DATASET_MODIFIED_FINALISED); + } + } + + this.deleteOldFilesAndAddNew(datasetWizardModel, userInfo); + + + return dataset1; + } + + private void deleteOldFilesAndAddNew(DatasetWizardModel datasetWizardModel, UserInfo userInfo) throws JsonProcessingException { + // Files in DB for this entityId which are NOT DELETED + List fileUploads = fileManager.getCurrentFileUploadsForEntityId(datasetWizardModel.getId()); + List fileUploadIds = fileUploads.stream().map(fileUpload -> fileUpload.getId().toString()).collect(Collectors.toList()); + + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + String json = mapper.writeValueAsString(datasetWizardModel.getDatasetProfileDefinition());; + JsonNode propertiesJson = mapper.readTree(json); + + Set uploadNodes = new HashSet<>(); + uploadNodes.addAll(JsonSearcher.findNodes(propertiesJson, "renderStyle", "upload", true)); + + uploadNodes.forEach(node -> { + JsonNode value = node.get("value"); + if (value != null && !value.toString().equals("\"\"") && !value.toString().equals("null")) { + String stringValue = value.toString().replaceAll("=", ":"); + JSONObject values = new JSONObject(stringValue); + Map data = ((JSONObject) values).toMap(); + + int index = fileUploadIds.indexOf(data.get("id").toString()); + if(index != -1) { + // file in DB is the same as file in the Dataset + fileUploadIds.remove(index); + fileUploads.remove(index); + } else { + // new file + this.fileManager.createFile(data.get("id").toString(), data.get("name").toString(), data.get("type").toString(), datasetWizardModel.getId().toString(), FileUpload.EntityType.DATASET, userInfo); + } + } + }); + + // old files in DB that are not contained anymore in the Dataset -> mark them as Deleted + fileUploads.forEach(fileUpload -> { + fileManager.markOldFileAsDeleted(fileUpload); + }); + } + + private void sendNotification(eu.eudat.old.data.entities.Dataset dataset, DMP dmp, UserInfo user, NotificationType notificationType) { + List userDMPS = databaseRepository.getUserDmpDao().asQueryable().where(((builder, root) -> builder.equal(root.get("dmp").get("id"), dmp.getId()))).toList(); + for (UserDMP userDMP : userDMPS) { + if (!userDMP.getUser().getId().equals(user.getId())) { + Notification notification = new Notification(); + notification.setUserId(user); + notification.setType(notificationType); + notification.setNotifyState(NotifyState.PENDING); + notification.setIsActive(ActiveStatus.ACTIVE); + notification.setData("{" + + "\"userId\": \"" + userDMP.getUser().getId() + "\"" + + ", \"id\": \"" + dataset.getId() + "\"" + + ", \"name\": \"" + dataset.getLabel() + "\"" + + ", \"path\": \"" + notificationPaths.get(notificationType) + "\"" + + "}"); + notification.setCreatedAt(new Date()); + notification.setUpdatedAt(notification.getCreatedAt()); + notification.setContactTypeHint(ContactType.EMAIL); + notification.setContactHint(userDMP.getUser().getEmail()); + databaseRepository.getNotificationDao().createOrUpdate(notification); + } + } + + } + + public String checkDatasetValidation(eu.eudat.old.data.entities.Dataset dataset) throws Exception { + List datasetProfileValidators = new LinkedList<>(); + DescriptionTemplate profile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(dataset.getProfile().getId()); + DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = builderFactory.newDocumentBuilder(); + Document xmlDocument = builder.parse(new ByteArrayInputStream(profile.getDefinition().getBytes())); + + XPath xPath = XPathFactory.newInstance().newXPath(); + String expression = "//validation/@type[.=1]/ancestor::field/@id"; + NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); + + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + datasetProfileValidators.add(node.getNodeValue()); + } + + expression = "//validation/@type[.=1]/ancestor::fieldSet"; + nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); + + + JSONObject obj = new JSONObject(dataset.getProperties()); + VisibilityRuleService visibilityRuleService = new VisibilityRuleServiceImpl(); + visibilityRuleService.setProperties(obj.toMap()); + + dataset.setProfile(profile); + PagedDatasetProfile pagedDatasetProfile = this.getPagedProfile(new DatasetWizardModel(), dataset); + visibilityRuleService.buildVisibilityContext(pagedDatasetProfile.getRules()); + + + String failedField = null; + + for (String validator : datasetProfileValidators) { + if (obj.has(validator) && isNullOrEmpty(obj.getString(validator)) && isElementVisible(nodeList, validator, visibilityRuleService)) { + //throw new Exception("Field value of " + validator + " must be filled."); + failedField = validator; + break; + } + } + + return failedField; + } + + private boolean isNullOrEmpty(String value) { + return value == null || value.trim().isEmpty(); + } + + private boolean isElementVisible(NodeList nodeList, String id, VisibilityRuleService visibilityRuleService) { + Element fieldSet = null; + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + for (int j = 0; j < node.getChildNodes().getLength(); j++) { + Node fcnode = node.getChildNodes().item(j); + if (fcnode.getNodeName().equals("fields")) { + for(int k = 0; k < fcnode.getChildNodes().getLength(); k++) { + Node scnode = fcnode.getChildNodes().item(k); + if (scnode.getNodeName().equals("field") && scnode.getAttributes().getNamedItem("id").getNodeValue().equals(id)) { + fieldSet = (Element) node; + } + } + } + } + } + if (fieldSet != null) { + return visibilityRuleService.isElementVisible(id) && visibilityRuleService.isElementVisible(fieldSet.getAttribute("id")); + } else { + return visibilityRuleService.isElementVisible(id); + } + } + + private String propertiesModelToString(PagedDatasetProfile pagedDatasetProfile) { + Map values = new LinkedHashMap<>(); + pagedDatasetProfile.toMap(values); + JSONObject jobject = new JSONObject(values); + return jobject.toString(); + } + + public void updateTags(eu.eudat.old.data.entities.Dataset datasetEntity, List tags) throws Exception { + // if (datasetWizardModel.getTags() != null && !datasetWizardModel.getTags().isEmpty()) { + /*eu.eudat.elastic.entities.Dataset dataset = new eu.eudat.elastic.entities.Dataset(); + dataset.setId(datasetWizardModel.getId().toString()); + if (datasetWizardModel.getTags() != null && !datasetWizardModel.getTags().isEmpty()) { + DatasetCriteria criteria = new DatasetCriteria(); + criteria.setTags(datasetWizardModel.getTags()); + List tags = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().query(criteria).stream().map(eu.eudat.elastic.entities.Dataset::getTags).flatMap(Collection::stream) + .filter(StreamDistinctBy.distinctByKey(Tag::getId)).filter(tag -> datasetWizardModel.getTags().stream().anyMatch(tag1 -> tag1.getName().equals(tag.getName()))).collect(Collectors.toList()); + if (tags.isEmpty()) { + datasetWizardModel.getTags().forEach(tag -> tag.setId(UUID.randomUUID().toString())); + dataset.setTags(datasetWizardModel.getTags()); + } else { + dataset.setTags(tags); + } + } + dataset.setLabel(datasetWizardModel.getLabel()); + dataset.setDescription(datasetWizardModel.getDescription()); + dataset.setTemplate(datasetWizardModel.getProfile()); + dataset.setStatus(datasetWizardModel.getStatus()); + dataset.setDmp(datasetWizardModel.getDmp().getId()); + dataset.setGroup(datasetWizardModel.getDmp().getGroupId()); + dataset.setGrant(datasetWizardModel.getDmp().getGrant().getId()); + if (datasetWizardModel.getDmp().getUsers() != null) { + dataset.setCollaborators(datasetWizardModel.getDmp().getUsers().stream().map(user -> { + Collaborator collaborator = new Collaborator(); + collaborator.setId(user.getId().toString()); + collaborator.setName(user.getName()); + return collaborator; + }).collect(Collectors.toList())); + } + DataManagementPlanCriteria dmpCriteria = new DataManagementPlanCriteria(); + dmpCriteria.setAllVersions(true); + dmpCriteria.setGroupIds(Collections.singletonList(datasetWizardModel.getDmp().getGroupId())); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dmpCriteria).toList().stream() + .max(Comparator.comparing(DMP::getVersion)).ifPresent(dmp -> dataset.setLastVersion(dmp.getId().equals(datasetWizardModel.getDmp().getId()))); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dmpCriteria).toList().stream().filter(DMP::isPublic) + .max(Comparator.comparing(DMP::getVersion)).ifPresent(dmp -> dataset.setLastPublicVersion(dmp.getId().equals(datasetWizardModel.getDmp().getId()))); + if (dataset.getLastVersion() == null) { + dataset.setLastVersion(true); + } + if (dataset.getLastPublicVersion() == null) { + dataset.setLastPublicVersion(false); + } + if (datasetWizardModel.getDmp().getOrganisations() != null) { + dataset.setOrganizations(datasetWizardModel.getDmp().getOrganisations().stream().map(org -> { + Organization organization = new Organization(); + organization.setId(org.getId()); + organization.setName(org.getName()); + return organization; + }).collect(Collectors.toList())); + } + dataset.setPublic(datasetWizardModel.getDmp().getPublic()); + dataset.setGrantStatus(datasetWizardModel.getDmp().getGrant().getStatus()); + dataset.setFormData(this.getWordDocumentText(datasetWizardModel));*/ + DatasetMapper mapper = new DatasetMapper(apiContext, this); + Dataset dataset = mapper.toElastic(datasetEntity, tags); + apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().createOrUpdate(dataset); + // } + } + + + + private void createRegistriesIfTheyDontExist(RegistryDao registryDao, eu.eudat.old.data.entities.Dataset dataset) { + if (dataset.getRegistries() != null && !dataset.getRegistries().isEmpty()) { + for (Registry registry : dataset.getRegistries()) { + RegistryCriteria criteria = new RegistryCriteria(); + criteria.setLike(registry.getReference()); + List entries = registryDao.getWithCriteria(criteria).toList(); + if (entries != null && !entries.isEmpty()) registry.setId(entries.get(0).getId()); + else { + registry.setCreated(new Date()); + registryDao.createOrUpdate(registry); + } + } + } + } + + private void createDataRepositoriesIfTheyDontExist(DataRepositoryDao dataRepositoryDao, eu.eudat.old.data.entities.Dataset dataset) { + if (dataset.getDatasetDataRepositories() != null && !dataset.getDatasetDataRepositories().isEmpty()) { + for (DatasetDataRepository datasetDataRepository : dataset.getDatasetDataRepositories()) { + DataRepositoryCriteria criteria = new DataRepositoryCriteria(); + criteria.setLike(datasetDataRepository.getDataRepository().getReference()); + List entries = dataRepositoryDao.getWithCriteria(criteria).toList(); + if (entries != null && !entries.isEmpty()) { + datasetDataRepository.getDataRepository().setId(entries.get(0).getId()); + datasetDataRepository.setDataset(dataset); + dataset.getDatasetDataRepositories().add(datasetDataRepository); + } else { + datasetDataRepository.getDataRepository().setId(UUID.randomUUID()); + DataRepository dataRepository = dataRepositoryDao.createOrUpdate(datasetDataRepository.getDataRepository()); + datasetDataRepository.setDataset(dataset); + datasetDataRepository.setDataRepository(dataRepository); + dataset.getDatasetDataRepositories().add(datasetDataRepository); + } + } + } + } + + private void createServicesIfTheyDontExist(eu.eudat.old.data.entities.Dataset dataset) { + if (dataset.getServices() != null && !dataset.getServices().isEmpty()) { + for (DatasetService service : dataset.getServices()) { + ServiceCriteria criteria = new ServiceCriteria(); + criteria.setLike(service.getService().getReference()); + List entries = databaseRepository.getServiceDao().getWithCriteria(criteria).toList(); + if (entries != null && !entries.isEmpty()) { + service.setDataset(dataset); + service.getService().setCreated(new Date()); + service.setService(service.getService()); + this.databaseRepository.getServiceDao().createOrUpdate(service.getService()); + dataset.getServices().add(service); + } + } + } + } + + private void createExternalDatasetsIfTheyDontExist(eu.eudat.old.data.entities.Dataset dataset) { + if (dataset.getDatasetExternalDatasets() != null && !dataset.getDatasetExternalDatasets().isEmpty()) { + for (DatasetExternalDataset datasetExternalDataset : dataset.getDatasetExternalDatasets()) { + ExternalDatasetCriteria criteria = new ExternalDatasetCriteria(); + criteria.setLike(datasetExternalDataset.getExternalDataset().getReference()); + List entries = databaseRepository.getExternalDatasetDao().getWithCriteria(criteria).toList(); + if (entries != null && !entries.isEmpty()) { + datasetExternalDataset.getExternalDataset().setId(entries.get(0).getId()); + datasetExternalDataset.setDataset(dataset); + dataset.getDatasetExternalDatasets().add(datasetExternalDataset); + } else { + datasetExternalDataset.getExternalDataset().setId(UUID.randomUUID()); + datasetExternalDataset.setDataset(dataset); + ExternalDataset externalDataset = databaseRepository.getExternalDatasetDao().createOrUpdate(datasetExternalDataset.getExternalDataset()); + datasetExternalDataset.setExternalDataset(externalDataset); + dataset.getDatasetExternalDatasets().add(datasetExternalDataset); + } + } + } + } + + public void makePublic(DatasetDao datasetDao, UUID id) throws Exception { + eu.eudat.old.data.entities.Dataset dataset = datasetDao.find(id); + if (dataset.getStatus() != eu.eudat.old.data.entities.Dataset.Status.FINALISED.getValue()) + throw new Exception("You cannot make public a Dataset That Has not Been Finalised"); + datasetDao.createOrUpdate(dataset); + metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.PUBLISHED); + } + + public ResponseEntity getDocument(String id, VisibilityRuleService visibilityRuleService, String contentType, Principal principal) throws IllegalAccessException, IOException, InstantiationException { + FileEnvelope envelope = getXmlDocument(id, visibilityRuleService, principal); + InputStream resource = new FileInputStream(envelope.getFile()); + logger.info("Mime Type of " + envelope.getFilename() + " is " + + new MimetypesFileTypeMap().getContentType(envelope.getFile())); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(envelope.getFile().length()); + responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); + String fileName = envelope.getFilename().replace(" ", "_").replace(",", "_"); + responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName + ".xml"); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + + byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource); + resource.close(); + Files.deleteIfExists(envelope.getFile().toPath()); + + return new ResponseEntity<>(content, + responseHeaders, + HttpStatus.OK); + } + + public eu.eudat.old.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) { + logger.error(e.getMessage(), e); + } + + // Checks if XML datasetProfileId GroupId matches the one selected. + try { + DescriptionTemplate importDescriptionTemplate = databaseRepository.getDatasetProfileDao().find(UUID.fromString(importModel.getDatasetProfileId())); + DescriptionTemplate latestVersionDescriptionTemplate = databaseRepository.getDatasetProfileDao().find(UUID.fromString(datasetProfileId)); + if (latestVersionDescriptionTemplate.getGroupId() != importDescriptionTemplate.getGroupId()) { + throw new Exception(); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + return null; + } + + // Creates the Hash Map to place the values of the data set. + Map importMap = importModel.getPages().stream() + .flatMap(s -> s.getSections().getSection().stream() + .flatMap(cFields -> cFields.getCompositeFields().stream() + .flatMap(cField -> cField.getCompositeField().stream() + .filter(Objects::nonNull) + .flatMap(fields -> fields.getFields().stream() + .flatMap(field -> field.getField().stream() + .filter(f -> f.getValue() != null) + ))))) + .collect(Collectors.toMap(DatasetImportField::getId, DatasetImportField::getValue)); + + // Transforms map into json file. + JSONObject jsonDatasetProperties = new JSONObject(importMap); + + // Creates the entity data set to save. + eu.eudat.old.data.entities.Dataset entity = new eu.eudat.old.data.entities.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.setCreated(new Date()); + entity.setModified(new Date()); + DescriptionTemplate profile = new DescriptionTemplate(); + 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().getElasticRepository().getDatasetRepository(), entity); + createRegistriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao(), entity); + createDataRepositoriesIfTheyDontExist(apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao(), entity); + createServicesIfTheyDontExist(entity); + createExternalDatasetsIfTheyDontExist(entity); + + metricsManager.increaseValue(MetricNames.DATASET, 1, MetricNames.DRAFT); + return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(entity); + } + + public void updateTagsXmlImportDataset(DatasetRepository datasetRepository, eu.eudat.old.data.entities.Dataset dataset) throws IOException { + // TODO: When tags functionality return. + } + + public DatasetWizardModel datasetUpdateProfile(String id) { + DatasetWizardModel dataset = new DatasetWizardModel(); + eu.eudat.old.data.entities.Dataset datasetEntity = databaseRepository.getDatasetDao().find(UUID.fromString(id), HintedModelFactory.getHint(DatasetWizardModel.class)); + dataset.setDatasetProfileDefinition(getPagedProfile(dataset, datasetEntity)); + dataset.fromDataModel(datasetEntity); + + // Creates the Criteria to get all version of DescriptionTemplate in question. + DatasetProfileCriteria profileCriteria = new DatasetProfileCriteria(); + UUID profileId = datasetEntity.getProfile().getGroupId(); + List uuidList = new LinkedList<>(); + uuidList.add(profileId); + profileCriteria.setGroupIds(uuidList); + + // Gets the latest version of the datasetProfile. + DescriptionTemplate 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(new DatasetProfileOverviewModel().fromDataModel(item)); + + // Now at latest version. + dataset.setIsProfileLatestVersion(true); + + Dataset datasetElastic; + try { + datasetElastic = datasetRepository.exists() ? + datasetRepository.findDocument(id) : new Dataset(); + } catch (Exception ex) { + logger.warn(ex.getMessage()); + datasetElastic = null; + } + if (datasetElastic != null && datasetElastic.getTags() != null && !datasetElastic.getTags().isEmpty()) { + dataset.setTags(datasetElastic.getTags()); + } + /*if (datasetElastic != null && datasetElastic.getLabel() != null && !datasetElastic.getLabel().isEmpty()) { + dataset.setLabel(datasetElastic.getLabel()); + }*/ + return dataset; + } + + public PagedDatasetProfile getLatestDatasetProfile(eu.eudat.old.data.entities.Dataset datasetEntity, DescriptionTemplate profile) { + DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile); + datasetprofile.setStatus(datasetEntity.getStatus()); + if (datasetEntity.getProperties() != null) { + JSONObject jobject = new JSONObject(datasetEntity.getProperties()); + Map properties = jobject.toMap(); + datasetprofile.fromJsonObject(properties); + } + PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile(); + pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile); + return pagedDatasetProfile; + } + + public DataTableData getDatasetProfilesUsedByDatasets(DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) { + datasetProfileTableRequestItem.getCriteria().setFilter(DatasetProfileCriteria.DatasetProfileFilter.Datasets.getValue()); + datasetProfileTableRequestItem.getCriteria().setUserId(principal.getId()); + + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria()); + List listingModels = items.select(item -> new DatasetProfileListingModel().fromDataModel(item)); + + DataTableData data = new DataTableData<>(); + data.setData(listingModels); + data.setTotalCount((long) listingModels.size()); + + return data; + } + + public void generateIndex(Principal principal) { + if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) { + this.apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable().toList(); + List datasetEntities = new ArrayList<>(this.apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().asQueryable().toList()); + datasetEntities.forEach(datasetEntity -> { + try { + Dataset dataset = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(datasetEntity.getId().toString()); + UUID dmpId = datasetEntity.getDmp().getId(); + datasetEntity.getDmp().setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), dmpId)).toList())); + updateTags(datasetEntity, dataset != null ? dataset.getTags() : null); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }); + } + } + + public void clearIndex(Principal principal) { + if (principal.getAuthorities().contains(Authorities.ADMIN.getValue())) { + try { + this.apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().clear(); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + } + } + + public void getTagsFromProfile(DatasetWizardModel wizardModel, eu.eudat.old.data.entities.Dataset dataset) throws IOException { + dataset.setProfile(apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(dataset.getProfile().getId())); + wizardModel.setDatasetProfileDefinition(this.getPagedProfile(wizardModel, dataset)); + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(wizardModel.getDatasetProfileDefinition()); + JsonNode propertiesJson = mapper.readTree(json); + DatasetCriteria criteria = new DatasetCriteria(); + criteria.setHasTags(true); + List tags = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().query(criteria).stream().map(Dataset::getTags).flatMap(Collection::stream).filter(StreamDistinctBy.distinctByKey(Tag::getId)).collect(Collectors.toList()); + Set tagNodes = new HashSet<>(); + tagNodes.addAll(JsonSearcher.findNodes(propertiesJson, "renderStyle", "tags", true)); + tagNodes.addAll(JsonSearcher.findNodes(propertiesJson, "schematics", "rda.dataset.keyword")); + if(wizardModel.getTags() == null){ + wizardModel.setTags(new ArrayList<>()); + } + if (!tagNodes.isEmpty()) { + tagNodes.forEach(node -> { + JsonNode value = node.get("value"); + if (!value.toString().equals("\"\"") && !value.toString().equals("null")) { + if (value.toString().startsWith("[")) { + String stringValue = value.toString().replaceAll("=", ":"); + JSONArray values = new JSONArray(stringValue); + values.iterator().forEachRemaining(element -> { + Map data = ((JSONObject) element).toMap(); + this.addTag(tags, wizardModel.getTags(), data.get("id").toString(), data.get("name").toString()); + }); + } else { + List values = Arrays.asList(value.textValue().split(", ")); + List tagValues = values.stream().map(stringValue -> new Tag(stringValue, stringValue)).collect(Collectors.toList()); + tagValues.iterator().forEachRemaining(tag -> { + this.addTag(tags, wizardModel.getTags(), tag.getId(), tag.getName()); + }); + } + } + }); + } + } + + private void addTag(List srcTags, List dstTags, String id, String name) { + Tag tag = new Tag(); + if(srcTags.stream().anyMatch(intag -> intag.getName().equals(name))) { + tag = srcTags.stream().filter(intag -> intag.getName().equals(name)).findFirst().get(); + } else { + tag.setName(name); + tag.setId(id); + } + if (dstTags.stream().noneMatch(intag -> intag.getName().equals(name))) { + dstTags.add(tag); + } + } + + @Transactional + private DatasetListingModel mapModel(eu.eudat.old.data.entities.Dataset item) { + /*if (item.getProfile() == null) + return null;*/ + DatasetListingModel listingModel = new DatasetListingModel().fromDataModel(item); + /*DatasetProfileCriteria criteria = new DatasetProfileCriteria(); + criteria.setGroupIds(Collections.singletonList(item.getProfile().getGroupId())); + List profiles = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).toList(); + boolean islast = false; + if (!profiles.isEmpty()) { + profiles = profiles.stream().sorted(Comparator.comparing(DescriptionTemplate::getVersion)).collect(Collectors.toList()); + islast = profiles.get(0).getId().equals(item.getProfile().getId()); + } + listingModel.setProfileLatestVersion(islast);*/ + return listingModel; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DatasetProfileManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DatasetProfileManager.java new file mode 100644 index 000000000..3057a193e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DatasetProfileManager.java @@ -0,0 +1,533 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.dao.criteria.DatasetProfileCriteria; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.data.entities.UserDatasetProfile; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem; +import eu.eudat.old.logic.proxy.config.*; +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.proxy.config.entities.GeneralUrls; +import eu.eudat.old.logic.proxy.fetching.RemoteFetcher; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.logic.utilities.builders.XmlBuilder; +import eu.eudat.old.logic.utilities.documents.helpers.FileEnvelope; +import eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.ImportXmlBuilderDatasetProfile; +import eu.eudat.old.models.data.admin.composite.DatasetProfile; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileAutocompleteItem; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileListingModel; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileWithPrefillingPropertyModel; +import eu.eudat.old.models.data.externaldataset.ExternalAutocompleteFieldModel; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.mail.SimpleMail; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.types.Authorities; +import eu.eudat.old.types.MetricNames; +import eu.eudat.old.data.query.items.item.datasetprofile.DatasetProfileAutocompleteRequest; +import eu.eudat.old.exceptions.datasetprofile.DatasetProfileNewVersionException; +import eu.eudat.old.logic.builders.model.models.DataTableDataBuilder; +import eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.ExportXmlBuilderDatasetProfile; +import eu.eudat.old.models.data.components.commons.datafield.AutoCompleteData; +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Field; +import eu.eudat.old.models.data.listingmodels.UserInfoListingModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import javax.activation.MimetypesFileTypeMap; +import javax.transaction.Transactional; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.xpath.*; +import java.io.*; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.util.*; +import java.util.stream.Collectors; + + +@Component +public class DatasetProfileManager { + private static final Logger logger = LoggerFactory.getLogger(DatasetProfileManager.class); + private static final List cache = new ArrayList<>(); + + private final ApiContext apiContext; + private final DatabaseRepository databaseRepository; + private final Environment environment; + private final ConfigLoader configLoader; + private final MetricsManager metricsManager; + private final RemoteFetcher remoteFetcher; + @Autowired + public DatasetProfileManager(ApiContext apiContext, Environment environment, ConfigLoader configLoader, MetricsManager metricsManager, RemoteFetcher remoteFetcher) { + this.apiContext = apiContext; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + this.environment = environment; + this.configLoader = configLoader; + this.metricsManager = metricsManager; + this.remoteFetcher = remoteFetcher; + } + + @Transactional + public DatasetProfile getDatasetProfile(String id) { + DescriptionTemplate profile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); + DatasetProfile datasetprofile = AdminManager.generateDatasetProfileModel(profile); + datasetprofile.setLabel(profile.getLabel()); + datasetprofile.setStatus(profile.getStatus()); + datasetprofile.setDescription(profile.getDescription()); + datasetprofile.setType(profile.getType().getName()); + datasetprofile.setLanguage(profile.getLanguage()); + datasetprofile.setUsers(new ArrayList<>()); + retrieveUsers(profile, datasetprofile); + return datasetprofile; + } + + public List getWithCriteria(DatasetProfileAutocompleteRequest datasetProfileAutocompleteRequest) throws IllegalAccessException, InstantiationException { + QueryableList items = databaseRepository.getDatasetProfileDao().getWithCriteria(datasetProfileAutocompleteRequest.getCriteria()); + QueryableList pagedItems = datasetProfileAutocompleteRequest.applyPaging(items); + List datasetProfiles = pagedItems.select(item -> new DatasetProfileAutocompleteItem().fromDataModel(item)); + return datasetProfiles; + } + + public DescriptionTemplate clone(String id) { + DescriptionTemplate profile = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); + apiContext.getOperationsContext().getDatabaseRepository().detachEntity(profile); + profile.setId(null); + return profile; + } + + public DataTableData getPaged(DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) throws Exception { + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(datasetProfileTableRequestItem.getCriteria()); + QueryableList authItems = null; + if (principal.getAuthz().contains(Authorities.ADMIN)) { + authItems = items; + } else if (principal.getAuthz().contains(Authorities.DATASET_PROFILE_MANAGER)) { + List roles = Arrays.asList(0, 1); + authItems = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getAuthenticated(items, principal.getId(), roles); + } + QueryableList pagedItems = PaginationManager.applyPaging(authItems, datasetProfileTableRequestItem); + List datasetProfiles = pagedItems.select(item -> new DatasetProfileListingModel().fromDataModel(item)); + return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).data(datasetProfiles).totalCount(items.count()).build(); + } + + public List getAll(DatasetProfileTableRequestItem tableRequestItem) throws IllegalAccessException, InstantiationException { + QueryableList items = databaseRepository.getDatasetProfileDao().getWithCriteria(tableRequestItem.getCriteria()); + List datasetProfiles = items.select(item -> new DatasetProfileListingModel().fromDataModel(item)); + + return datasetProfiles; + } + + public List getAllWithPrefilling(DatasetProfileTableRequestItem tableRequestItem) { + List datasetProfiles = new ArrayList<>(); + if (!tableRequestItem.getCriteria().getIds().isEmpty()) { + tableRequestItem.getCriteria().getIds().forEach(id -> { + DatasetProfile datasetProfile = this.getDatasetProfile(id.toString()); + DatasetProfileWithPrefillingPropertyModel profileModel = new DatasetProfileWithPrefillingPropertyModel(); + profileModel.setId(id); + profileModel.setLabel(datasetProfile.getLabel()); + profileModel.setEnablePrefilling(datasetProfile.isEnablePrefilling()); + datasetProfiles.add(profileModel); + }); + } + return datasetProfiles; + } + + public Field queryForField(String xml, String fieldId) throws XPathExpressionException { + Field field = new Field(); + Document document = XmlBuilder.fromXml(xml); + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPath xpath = xpathFactory.newXPath(); + XPathExpression expr = + xpath.compile("//field[@id='" + fieldId + "']"); + Element name = (Element) expr.evaluate(document, XPathConstants.NODE); + field.fromXml(name); + return field; + } + + public List getAutocomplete(AutoCompleteData data, String like) { + /*List result = new LinkedList<>(); + SimpleClientHttpRequestFactory simpleFactory = new SimpleClientHttpRequestFactory(); + + RestTemplate restTemplate = new RestTemplate(simpleFactory); + HttpHeaders headers = new HttpHeaders(); + DocumentContext jsonContext = null; + HttpEntity entity; + ResponseEntity response; + List> jsonItems; + int i = 0; + for (AutoCompleteData.AutoCompleteSingleData singleData: data.getAutoCompleteSingleDataList()) { + switch (AutoCompleteData.AutocompleteType.fromValue(singleData.getAutocompleteType())) { + case UNCACHED: + + String url = singleData.getUrl(); + String mediaType = ""; + if (url.contains("openaire") || url.contains("zenodo")) { + mediaType = "application/json; charset=utf-8"; + if (url.contains("zenodo")) { + url = url.replace("?", "/?"); + } + + url = url.replace("{like}", like.equals("") ? "*" : like); + url = url.replace("%20", " "); + url = url.replace("%22", "\""); + url = url.replace("&", "&"); + } else { + mediaType = "application/vnd.api+json; charset=utf-8"; + url += "?search=" + like; + } + + if (!url.contains("zenodo")) { + headers.setAccept(Collections.singletonList(MediaType.valueOf(mediaType))); + } + headers.setContentType(MediaType.APPLICATION_JSON); + entity = new HttpEntity<>("parameters", headers); + + + response = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class); + jsonContext = JsonPath.parse(response.getBody()); + jsonItems = jsonContext.read(singleData.getOptionsRoot() + "['" + singleData.getAutoCompleteOptions().getLabel() + "','" + singleData.getAutoCompleteOptions().getValue() + "','" + singleData.getAutoCompleteOptions().getSource() + "','" + "uri" + "']"); + jsonItems.forEach(item -> result.add(new ExternalAutocompleteFieldModel(parseItem(item.get(singleData.getAutoCompleteOptions().getValue())), parseItem(item.get(singleData.getAutoCompleteOptions().getLabel())), item.get(singleData.getAutoCompleteOptions().getSource()) != null ? parseItem(item.get(singleData.getAutoCompleteOptions().getSource())) : singleData.getAutoCompleteOptions().getSource(), parseItem(item.get("uri"))))); + break; + case CACHED: + headers.setAccept(Collections.singletonList(MediaType.valueOf("text/plain; charset=utf-8"))); + headers.setContentType(MediaType.TEXT_PLAIN); + entity = new HttpEntity<>("parameters", headers); + + if (cache.size() <= i) { + response = restTemplate.exchange(singleData.getUrl(), HttpMethod.GET, entity, String.class); + cache.add((String) response.getBody()); + } + jsonContext = JsonPath.parse(cache.get(i)); + jsonItems = jsonContext.read(singleData.getOptionsRoot() + "['" + singleData.getAutoCompleteOptions().getLabel() + "','" + singleData.getAutoCompleteOptions().getValue() + "','" + singleData.getAutoCompleteOptions().getSource() + "','" + "uri" + "']"); + jsonItems.stream().filter(item -> item.get(singleData.getAutoCompleteOptions().getLabel()).toLowerCase().contains(like.toLowerCase())) + .forEach(item -> result.add(new ExternalAutocompleteFieldModel(item.get(singleData.getAutoCompleteOptions().getValue()), item.get(singleData.getAutoCompleteOptions().getLabel()), item.get(singleData.getAutoCompleteOptions().getSource()) != null ? item.get(singleData.getAutoCompleteOptions().getSource()) : singleData.getAutoCompleteOptions().getSource(), item.get("uri")))); + i++; + break; + } + + } + + return result.stream().sorted(Comparator.comparing(ExternalAutocompleteFieldModel::getLabel)).collect(Collectors.toList()); +*/ + List result = new LinkedList<>(); + ExternalUrlCriteria urlCriteria = new ExternalUrlCriteria(); + GeneralUrls genericUrls = new GeneralUrls(); + int ordinal = 1; + List> rawResults = new ArrayList<>(); + genericUrls.setFetchMode(FetchStrategy.FIRST); + urlCriteria.setLike(like); + for (AutoCompleteData.AutoCompleteSingleData singleData : data.getAutoCompleteSingleDataList()) { + UrlConfiguration urlConfiguration = new UrlConfiguration(); + try { + URI uri; + if (singleData.getUrl().contains("?")) { + uri = new URI(singleData.getUrl().substring(0, singleData.getUrl().lastIndexOf("?"))); + } else { + uri = new URI(singleData.getUrl()); + } + String source = singleData.getAutoCompleteOptions().getSource(); + source = source != null && !source.isEmpty() ? source : uri.getHost(); + String uriString = singleData.getAutoCompleteOptions().getUri(); + uriString = uriString != null && !uriString.isEmpty() ? uriString : "uri"; + String parsedUrl = singleData.getUrl(); + parsedUrl = parsedUrl.replace("%20", " "); + parsedUrl = parsedUrl.replace("%22", "\""); + while (parsedUrl.contains("&")) { + parsedUrl = parsedUrl.replace("&", "&"); + } + urlConfiguration.setUrl(parsedUrl); + urlConfiguration.setOrdinal(ordinal); + urlConfiguration.setType("External"); + urlConfiguration.setContentType(MediaType.APPLICATION_JSON_VALUE); + urlConfiguration.setFirstpage("1"); + urlConfiguration.setRequestType(singleData.getMethod() != null ? singleData.getMethod() : "GET"); + DataUrlConfiguration dataUrlConfiguration = new DataUrlConfiguration(); + dataUrlConfiguration.setPath(singleData.getOptionsRoot()); + DataFieldsUrlConfiguration fieldsUrlConfiguration = new DataFieldsUrlConfiguration(); + fieldsUrlConfiguration.setId(singleData.getAutoCompleteOptions().getValue()); + fieldsUrlConfiguration.setName(singleData.getAutoCompleteOptions().getLabel()); + fieldsUrlConfiguration.setSource(singleData.getAutoCompleteOptions().getSource().isEmpty()? null : singleData.getAutoCompleteOptions().getSource()); + fieldsUrlConfiguration.setUri(uriString); + dataUrlConfiguration.setFieldsUrlConfiguration(fieldsUrlConfiguration); + urlConfiguration.setKey(source); + urlConfiguration.setLabel(source); + urlConfiguration.setData(dataUrlConfiguration); + if (singleData.getHasAuth()) { + AuthenticationConfiguration authenticationConfiguration = new AuthenticationConfiguration(); + authenticationConfiguration.setAuthUrl(singleData.getAuth().getUrl()); + authenticationConfiguration.setAuthMethod(singleData.getAuth().getMethod()); + authenticationConfiguration.setAuthTokenPath(singleData.getAuth().getPath()); + authenticationConfiguration.setAuthRequestBody(singleData.getAuth().getBody()); + authenticationConfiguration.setType(singleData.getAuth().getType()); + urlConfiguration.setAuth(authenticationConfiguration); + } + genericUrls.getUrls().add(urlConfiguration); + List> singleResults = this.remoteFetcher.getExternalGeneric(urlCriteria, genericUrls); + if (!singleResults.isEmpty() && !singleResults.get(0).containsKey("source") && !singleData.getAutoCompleteOptions().getSource().isEmpty()) { + singleResults.forEach(singleResult -> singleResult.put("source", singleData.getAutoCompleteOptions().getSource())); + } + rawResults.addAll(singleResults); + genericUrls.getUrls().clear(); + } catch (URISyntaxException e) { + logger.error(e.getMessage(), e); + } + } + rawResults.forEach(item -> result.add(new ExternalAutocompleteFieldModel(parseItem(item.get("pid")), parseItem(item.get("name")), parseItem(item.get("source")), parseItem(item.get("uri"))))); + return result; + } + + private static String parseItem(Object item) { + if (item instanceof String) { + return (String) item; + } + if (item instanceof List) { + List listedItems = (List) item; + return parseItem(listedItems.get(0)); + } + if (item instanceof Map) { + return String.valueOf(((Map)item).get("$")); + } + return item != null ? item.toString() : null; + } + + public ResponseEntity getDocument(eu.eudat.old.models.data.user.composite.DatasetProfile datasetProfile, String label) throws IllegalAccessException, IOException, InstantiationException { + FileEnvelope envelope = getXmlDocument(datasetProfile, label); + InputStream resource = new FileInputStream(envelope.getFile()); + logger.info("Mime Type of " + envelope.getFilename() + " is " + + new MimetypesFileTypeMap().getContentType(envelope.getFile())); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(envelope.getFile().length()); + responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); + String fileName = envelope.getFilename().replace(" ", "_").replace(",", "_"); + responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName + ".xml"); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + + byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource); + resource.close(); + Files.deleteIfExists(envelope.getFile().toPath()); + + return new ResponseEntity<>(content, + responseHeaders, + HttpStatus.OK); + } + + public FileEnvelope getXmlDocument(eu.eudat.old.models.data.user.composite.DatasetProfile datatasetProfile, String label) throws InstantiationException, IllegalAccessException, IOException { + ExportXmlBuilderDatasetProfile xmlBuilder = new ExportXmlBuilderDatasetProfile(); + File file = xmlBuilder.build(datatasetProfile, environment); + FileEnvelope fileEnvelope = new FileEnvelope(); + fileEnvelope.setFile(file); + fileEnvelope.setFilename(label); + return fileEnvelope; + } + + public eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.DatasetProfile createDatasetProfileFromXml(MultipartFile multiPartFile) { + ImportXmlBuilderDatasetProfile xmlBuilder = new ImportXmlBuilderDatasetProfile(); + try { + File localFile = convert(multiPartFile); + eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.DatasetProfile profile = xmlBuilder.build(localFile); + Files.deleteIfExists(localFile.toPath()); + metricsManager.increaseValue(MetricNames.DATASET_TEMPLATE, 1, MetricNames.DRAFT); + return profile; + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + return null; + } + + private File convert(MultipartFile file) throws IOException { + File convFile = new File(this.environment.getProperty("temp.temp") + file.getOriginalFilename()); + convFile.createNewFile(); + FileOutputStream fos = new FileOutputStream(convFile); + fos.write(file.getBytes()); + fos.close(); + return convFile; + } + + public DescriptionTemplate createNewVersionDatasetProfile(String id, DatasetProfile profile) throws Exception { + // Getting the DescriptionTemplate which we will create its new version. + DescriptionTemplate oldDescriptionTemplate = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id)); + + // Getting the DescriptionTemplate with the latest Version. + DatasetProfileCriteria criteria = new DatasetProfileCriteria(); + LinkedList list = new LinkedList<>(); + list.push(oldDescriptionTemplate.getGroupId()); + criteria.setGroupIds(list); + criteria.setAllVersions(false); + QueryableList datasetProfileQueryableList = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria); + DescriptionTemplate latestVersionDescriptionTemplate = datasetProfileQueryableList.getSingle(); + + if (latestVersionDescriptionTemplate.getVersion().equals(oldDescriptionTemplate.getVersion())){ + DatasetProfile sortedProfile = profile.toShort(); + DescriptionTemplate modelDefinition = AdminManager.generateViewStyleDefinition(sortedProfile, apiContext); +// modelDefinition.setLabel(oldDescriptionTemplate.getLabel()); + modelDefinition.setVersion((short) (oldDescriptionTemplate.getVersion() + 1)); + modelDefinition.setGroupId(oldDescriptionTemplate.getGroupId()); +// modelDefinition.setLanguage(oldDescriptionTemplate.getLanguage()); + apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition); + DescriptionTemplate descriptionTemplate = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().createOrUpdate(modelDefinition); + this.storeDatasetProfileUsers(descriptionTemplate, profile); + return modelDefinition; + } else { + throw new DatasetProfileNewVersionException("Version to update not the latest."); + } + } + + public void storeDatasetProfileUsers(DescriptionTemplate entity, DatasetProfile model) { + if (model.getUsers() != null && !model.getUsers().isEmpty()) { + if (entity.getUsers() == null) { + entity.setUsers(new HashSet<>()); + } + model.getUsers().stream().filter(userInfoListingModel -> entity.getUsers().stream() + .filter(userDatasetProfile -> userDatasetProfile.getUser().getId().equals(userInfoListingModel.getId())).count() == 0) + .forEach(userInfoListingModel -> { + UserDatasetProfile userDatasetProfile1 = new UserDatasetProfile(); + userDatasetProfile1.setDatasetProfile(entity); + UserInfo userInfo1 = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userInfoListingModel.getId()); + userDatasetProfile1.setUser(userInfo1); + userDatasetProfile1.setRole(1); + apiContext.getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile1); + sendJoinMail(userDatasetProfile1); + }); + entity.getUsers().stream().filter(userDatasetProfile -> model.getUsers().stream() + .filter(userInfoListingModel -> userDatasetProfile.getUser().getId().equals(userInfoListingModel.getId())).count() > 0 + && userDatasetProfile.getRole() == 2).forEach(userDatasetProfile -> { + userDatasetProfile.setRole(1); + apiContext.getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile); + sendJoinMail(userDatasetProfile); + }); + } + if (entity.getUsers() != null && !entity.getUsers().isEmpty()) { + entity.getUsers().stream().filter(userDatasetProfile -> model.getUsers().stream() + .filter(userInfoListingModel -> userDatasetProfile.getUser().getId().equals(userInfoListingModel.getId())).count() == 0) + .forEach(userDatasetProfile -> { + userDatasetProfile.setRole(2); + apiContext.getOperationsContext().getDatabaseRepository().getUserDatasetProfileDao().createOrUpdate(userDatasetProfile); + }); + } + } + + @Transactional + public void retrieveUsers(DescriptionTemplate entity, DatasetProfile model) { + if (entity.getUsers() != null && !entity.getUsers().isEmpty()) { + model.setUsers(entity.getUsers().stream().filter(userDatasetProfile -> userDatasetProfile.getRole() < 2).map(userDatasetProfile -> { + UserInfoListingModel userInfoListingModel = new UserInfoListingModel(); + userInfoListingModel.setId(userDatasetProfile.getUser().getId()); + userInfoListingModel.setName(userDatasetProfile.getUser().getName()); + userInfoListingModel.setEmail(userDatasetProfile.getUser().getEmail()); + userInfoListingModel.setRole(userDatasetProfile.getRole()); + return userInfoListingModel; + }).collect(Collectors.toList())); + } + } + + private void sendJoinMail(UserDatasetProfile userDatasetProfile) { + SimpleMail mail = new SimpleMail(); + mail.setSubject(environment.getProperty("admin.mail.subject").replace( "{templateName}", userDatasetProfile.getDatasetProfile().getLabel())); + String content = apiContext.getUtilitiesService().getMailService().getMailTemplateContent(environment.getProperty("email.dataset.template")); + content = content.replace("{recipient}", userDatasetProfile.getUser().getName()); + content = content.replace("{templateName}", userDatasetProfile.getDatasetProfile().getLabel()); + content = content.replace("{host}", this.environment.getProperty("dmp.domain")); + content = content.replace("{templateID}", userDatasetProfile.getDatasetProfile().getId().toString()); + mail.setContent(content); + mail.setTo(userDatasetProfile.getUser().getEmail()); + try { + apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail); + } catch (Exception ex) { + logger.error(ex.getMessage(), ex); + } + + } + + public List getSemantics(String query) { + List semantics = configLoader.getSemantics(); + List filteredSemantics = semantics.stream().map(Semantic::getName).collect(Collectors.toList()); + if(query != null && !query.isEmpty()){ + filteredSemantics = semantics.stream().filter(x -> x.getCategory().contains(query) || x.getName().contains(query)).map(Semantic::getName).collect(Collectors.toList()); + } + return filteredSemantics; + } + + public void addSemanticsInDatasetProfiles() throws XPathExpressionException { + List ids = this.databaseRepository.getDatasetProfileDao().getAllIds(); + for(DescriptionTemplate dp: ids){ + DescriptionTemplate descriptionTemplate = this.databaseRepository.getDatasetProfileDao().find(dp.getId()); + Document document = XmlBuilder.fromXml(descriptionTemplate.getDefinition()); + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPath xpath = xpathFactory.newXPath(); + XPathExpression expr = xpath.compile("//rdaCommonStandard"); + NodeList rdaProperties = (NodeList) expr.evaluate(document, XPathConstants.NODESET); + for(int i = 0; i < rdaProperties.getLength(); i++){ + Node rdaPropertyNode = rdaProperties.item(i); + String rdaProperty = rdaPropertyNode.getTextContent(); + Element schematics = document.createElement("schematics"); + Node fieldParent = rdaPropertyNode.getParentNode(); + if(rdaProperty != null && !rdaProperty.isEmpty()){ + Element schematic = document.createElement("schematic"); + schematic.setTextContent("rda." + rdaProperty); + schematics.appendChild(schematic); + } + fieldParent.insertBefore(schematics, rdaPropertyNode); + fieldParent.removeChild(rdaPropertyNode); + } + this.updateDatasetProfileXml(document, descriptionTemplate); + } + } + + public void addRdaInSemanticsInDatasetProfiles() throws XPathExpressionException { + List ids = this.databaseRepository.getDatasetProfileDao().getAllIds(); + for(DescriptionTemplate dp: ids){ + DescriptionTemplate descriptionTemplate = this.databaseRepository.getDatasetProfileDao().find(dp.getId()); + Document document = XmlBuilder.fromXml(descriptionTemplate.getDefinition()); + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPath xpath = xpathFactory.newXPath(); + XPathExpression expr = xpath.compile("//schematic"); + NodeList schematics = (NodeList) expr.evaluate(document, XPathConstants.NODESET); + for (int i = 0; i < schematics.getLength(); i++) { + Node schematicNode = schematics.item(i); + String schematicRda = schematicNode.getTextContent(); + if (schematicRda != null && !schematicRda.isEmpty() && !schematicRda.startsWith("rda.")) { + schematicNode.setTextContent("rda." + schematicRda); + } + } + this.updateDatasetProfileXml(document, descriptionTemplate); + } + } + + private void updateDatasetProfileXml(Document document, DescriptionTemplate descriptionTemplate) { + try { + DOMSource domSource = new DOMSource(document); + StringWriter writer = new StringWriter(); + StreamResult result = new StreamResult(writer); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer = tf.newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.transform(domSource, result); + String newDefinition = writer.toString(); + if(newDefinition != null){ + descriptionTemplate.setDefinition(newDefinition); + this.databaseRepository.getDatasetProfileDao().createOrUpdate(descriptionTemplate); + } + } + catch(TransformerException ex) { + logger.error(ex.getMessage(), ex); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DatasetWizardManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DatasetWizardManager.java new file mode 100644 index 000000000..683066b6a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DatasetWizardManager.java @@ -0,0 +1,70 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.dao.entities.DatasetProfileDao; +import eu.eudat.old.data.query.items.item.datasetprofile.DatasetProfileWizardAutocompleteRequest; +import eu.eudat.old.models.data.datasetwizard.DataManagentPlanListingModel; +import eu.eudat.old.data.dao.criteria.DatasetProfileCriteria; +import eu.eudat.old.data.dao.entities.DMPDao; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.query.items.item.dataset.DatasetWizardAutocompleteRequest; +import eu.eudat.old.exceptions.datasetwizard.DatasetWizardCannotUnlockException; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.dmp.AssociatedProfile; +import eu.eudat.old.models.data.dmp.DataManagementPlan; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.queryable.QueryableList; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + + +public class DatasetWizardManager { + + public static List getUserDmps(DMPDao dmpRepository, DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, Principal principal) throws InstantiationException, IllegalAccessException { + UserInfo userInfo = new UserInfo(); + userInfo.setId(principal.getId()); + QueryableList items = dmpRepository.getUserDmps(datasetWizardAutocompleteRequest.getCriteria(), userInfo); + List dataManagementPlans = items.select(item -> new DataManagentPlanListingModel().fromDataModel(item)); + return dataManagementPlans; + } + + public static List getAvailableProfiles(DMPDao dmpRepository, DatasetProfileDao profileDao, DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest) throws InstantiationException, IllegalAccessException { + DataManagementPlan dataManagementPlan = new DataManagementPlan().fromDataModel(dmpRepository.find(datasetProfileWizardAutocompleteRequest.getCriteria().getId())); + if (dataManagementPlan.getProfiles() == null || dataManagementPlan.getProfiles().isEmpty()) { + return new LinkedList<>(); + } + DatasetProfileCriteria criteria = new DatasetProfileCriteria(); + criteria.setIds(dataManagementPlan.getProfiles().stream().map(AssociatedProfile::getDescriptionTemplateId).collect(Collectors.toList())); + List descriptionTemplates = profileDao.getWithCriteria(criteria).toList(); + criteria.setIds(null); + criteria.setGroupIds(descriptionTemplates.stream().map(DescriptionTemplate::getGroupId).collect(Collectors.toList())); + descriptionTemplates = profileDao.getWithCriteria(criteria).toList(); + List profiles = descriptionTemplates.stream().map(profile -> new AssociatedProfile().fromData(profile)).collect(Collectors.toList()); + return profiles; + } + + public void unlock(ApiContext apiContext, UUID uuid) throws DatasetWizardCannotUnlockException { + Dataset dataset = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().find(uuid); + if(dataset.getDmp().getStatus() == DMP.DMPStatus.FINALISED.getValue()) throw new DatasetWizardCannotUnlockException("To perform this action you will need to revert DMP's finalisation"); + dataset.setStatus(Dataset.Status.SAVED.getValue()); + apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(dataset); + return; + } + + public void delete(ApiContext apiContext, UUID uuid) throws IOException { + Dataset oldDataset = apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().find(uuid); + eu.eudat.old.elastic.entities.Dataset oldDatasetElastic = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(uuid.toString()); + oldDataset.setStatus(Dataset.Status.DELETED.getValue()); + apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().createOrUpdate(oldDataset); + if (oldDatasetElastic != null && uuid != null && oldDatasetElastic.getId()!= null) { + oldDatasetElastic.setStatus(oldDataset.getStatus()); + apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().createOrUpdate(oldDatasetElastic); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DepositManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DepositManager.java new file mode 100644 index 000000000..2b1482a9e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DepositManager.java @@ -0,0 +1,67 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.depositinterface.repository.RepositoryDeposit; +import eu.eudat.depositinterface.repository.RepositoryDepositConfiguration; +import eu.eudat.old.models.data.doi.DepositRequest; +import eu.eudat.old.models.data.doi.RepositoryConfig; +import eu.eudat.old.models.data.doi.Doi; +import eu.eudat.old.models.data.security.Principal; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@Component +public class DepositManager { + private static final Logger logger = LoggerFactory.getLogger(DepositManager.class); + + private List repositories; + private DataManagementPlanManager dataManagementPlanManager; + + @Autowired + public DepositManager(List repositories, DataManagementPlanManager dataManagementPlanManager){ + this.repositories = repositories; + this.dataManagementPlanManager = dataManagementPlanManager; + } + + public List getAvailableRepos() { + List reposConfigModel = new ArrayList<>(); + for (RepositoryDeposit r: this.repositories) { + List repoConf = r.getConfiguration(); + if(repoConf != null) { + for(RepositoryDepositConfiguration cf: repoConf){ + RepositoryConfig repoModel = new RepositoryConfig(); + reposConfigModel.add(repoModel.toModel(cf)); + } + } + } + return reposConfigModel; + } + + public String authenticate(String id, String code) { + for(RepositoryDeposit r: this.repositories){ + if(r.getConfiguration().stream().anyMatch(x -> x.getRepositoryId().equals(id))){ + return r.authenticate(id, code); + } + } + return null; + } + + public Doi deposit(DepositRequest depositRequest, Principal principal) throws Exception { + return this.dataManagementPlanManager.createDoi(depositRequest, principal); + } + + public String getRepositoryLogo(String repositoryId){ + for(RepositoryDeposit r: this.repositories){ + Optional cf = r.getConfiguration().stream().filter(x -> x.getRepositoryId().equals(repositoryId)).findFirst(); + if(cf.isPresent()){ + return cf.get().isHasLogo() ? r.getLogo(repositoryId) : null; + } + } + return null; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DescriptionTemplateTypeManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DescriptionTemplateTypeManager.java new file mode 100644 index 000000000..51df408f4 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/DescriptionTemplateTypeManager.java @@ -0,0 +1,84 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.entities.DescriptionTemplateType; +import eu.eudat.old.exceptions.descriptiontemplate.DescriptionTemplatesWithTypeException; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.models.data.descriptiontemplatetype.DescriptionTemplateTypeModel; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Component +public class DescriptionTemplateTypeManager { + private static final Logger logger = LoggerFactory.getLogger(DescriptionTemplateTypeManager.class); + + private ApiContext apiContext; + private DatabaseRepository databaseRepository; + + + @Autowired + public DescriptionTemplateTypeManager(ApiContext apiContext, DatabaseRepository databaseRepository) { + this.apiContext = apiContext; + this.databaseRepository = databaseRepository; + } + + public DataTableData get() { + List types = this.databaseRepository.getDescriptionTemplateTypeDao().asQueryable().toList(); + List typesModelList = types.stream().map(type -> new DescriptionTemplateTypeModel().fromDataModel(type)).collect(Collectors.toList()); + DataTableData dataTableData = new DataTableData<>(); + dataTableData.setData(typesModelList); + dataTableData.setTotalCount((long) typesModelList.size()); + return dataTableData; + } + + public DescriptionTemplateTypeModel getSingle(UUID id) throws Exception { + DescriptionTemplateType type = this.databaseRepository.getDescriptionTemplateTypeDao().find(id); + if (type != null) { + return new DescriptionTemplateTypeModel().fromDataModel(type); + } + else { + throw new DescriptionTemplatesWithTypeException("No description template type found with this id"); + } + } + + public void create(DescriptionTemplateTypeModel type) throws Exception { + DescriptionTemplateType existed = this.databaseRepository.getDescriptionTemplateTypeDao().findFromName(type.getName()); + if (existed == null) { + this.databaseRepository.getDescriptionTemplateTypeDao().createOrUpdate(type.toDataModel()); + } + else { + throw new DescriptionTemplatesWithTypeException("There is already a description template type with that name."); + } + } + + public void update(DescriptionTemplateTypeModel type) throws Exception { + DescriptionTemplateType existed = this.databaseRepository.getDescriptionTemplateTypeDao().findFromName(type.getName()); + if (existed != null) { + this.databaseRepository.getDescriptionTemplateTypeDao().createOrUpdate(type.toDataModel()); + } + else { + throw new DescriptionTemplatesWithTypeException("No description template type found."); + } + } + + public void delete(UUID id) throws DescriptionTemplatesWithTypeException { + DescriptionTemplateType type = this.databaseRepository.getDescriptionTemplateTypeDao().find(id); + if (type != null) { + Long descriptionsWithType = this.databaseRepository.getDatasetProfileDao().countWithType(type); + if(descriptionsWithType == 0) { + type.setStatus(DescriptionTemplateType.Status.DELETED.getValue()); + this.databaseRepository.getDescriptionTemplateTypeDao().createOrUpdate(type); + } + else{ + throw new DescriptionTemplatesWithTypeException("This type can not deleted, because Descriptions are associated with it"); + } + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/EmailConfirmationManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/EmailConfirmationManager.java new file mode 100644 index 000000000..9c20f659a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/EmailConfirmationManager.java @@ -0,0 +1,97 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.entities.Credential; +import eu.eudat.old.data.entities.EmailConfirmation; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.entities.UserToken; +import eu.eudat.old.exceptions.emailconfirmation.HasConfirmedEmailException; +import eu.eudat.old.exceptions.emailconfirmation.TokenExpiredException; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.models.data.security.Principal; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.UUID; + +@Component +public class EmailConfirmationManager { + private ApiContext apiContext; + private DatabaseRepository databaseRepository; + + @Autowired + public EmailConfirmationManager(ApiContext apiContext) { + this.apiContext = apiContext; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + } + + public void confirmEmail(String token) throws TokenExpiredException, HasConfirmedEmailException { + EmailConfirmation loginConfirmationEmail = apiContext.getOperationsContext() + .getDatabaseRepository().getLoginConfirmationEmailDao().asQueryable() + .where((builder, root) -> builder.equal(root.get("token"), UUID.fromString(token))).getSingle(); + + UserInfo user = databaseRepository.getUserInfoDao().asQueryable() + .where((builder, root) -> builder.equal(root.get("id"), loginConfirmationEmail.getUserId())).getSingle(); + + if (user.getEmail() != null) + throw new HasConfirmedEmailException("User already has confirmed his Email."); + + if (loginConfirmationEmail.getExpiresAt().compareTo(new Date()) < 0) + throw new TokenExpiredException("Token has expired."); + + loginConfirmationEmail.setIsConfirmed(true); + + // Checks if mail is used by another user. If it is, merges the new the old. + Long existingUsers = databaseRepository.getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), loginConfirmationEmail.getEmail())).count(); + if (existingUsers > 0) { + Credential credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userInfo"), user)).getSingle(); + credential.setEmail(loginConfirmationEmail.getEmail()); + databaseRepository.getCredentialDao().createOrUpdate(credential); + UserInfo oldUser = databaseRepository.getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), loginConfirmationEmail.getEmail())).getSingle(); + mergeNewUserToOld(user, oldUser); + expireUserToken(user); + databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail); + return; + } + + user.setEmail(loginConfirmationEmail.getEmail()); + databaseRepository.getUserInfoDao().createOrUpdate(user); + Credential credential = databaseRepository.getCredentialDao().asQueryable() + .where((builder, root) -> builder.equal(root.get("userInfo"), user)).getSingle(); + if(credential.getEmail() == null){ + credential.setEmail(user.getEmail()); + databaseRepository.getCredentialDao().createOrUpdate(credential); + } + databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail); + } + + public void sendConfirmationEmail(String email, Principal principal) throws HasConfirmedEmailException { + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + if (user.getEmail() != null) + throw new HasConfirmedEmailException("User already has confirmed his Email."); + + apiContext.getUtilitiesService().getConfirmationEmailService().createConfirmationEmail( + databaseRepository.getLoginConfirmationEmailDao(), + apiContext.getUtilitiesService().getMailService(), + email, + principal.getId() + ); + } + + private void mergeNewUserToOld(UserInfo newUser, UserInfo oldUser) { + Credential credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userInfo"), newUser)).getSingle(); + credential.setUserInfo(oldUser); + databaseRepository.getCredentialDao().createOrUpdate(credential); + } + + private void expireUserToken(UserInfo user) { + UserToken userToken = databaseRepository.getUserTokenDao().asQueryable() + .where((builder, root) -> builder.equal(root.get("user"), user)) + .orderBy((builder, root) -> builder.desc(root.get("issuedAt"))) + .take(1) + .getSingle(); + userToken.setExpiresAt(new Date()); + databaseRepository.getUserTokenDao().createOrUpdate(userToken); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ExternalDatasetManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ExternalDatasetManager.java new file mode 100644 index 000000000..b881a2074 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ExternalDatasetManager.java @@ -0,0 +1,85 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.dao.criteria.ExternalDatasetCriteria; +import eu.eudat.old.logic.builders.model.criteria.ExternalDatasetCriteriaBuilder; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.logic.builders.model.models.DataTableDataBuilder; +import eu.eudat.old.data.entities.ExternalDataset; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.models.data.externaldataset.ExternalDatasetListingModel; +import eu.eudat.old.data.query.items.table.externaldataset.ExternalDatasetTableRequest; +import eu.eudat.old.models.data.externaldataset.ExternalDatasetModel; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.proxy.fetching.RemoteFetcher; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.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.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +@Component +public class ExternalDatasetManager { + + 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 getPaged(ExternalDatasetTableRequest externalDatasetTableRequest) throws Exception { + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().getWithCriteria(externalDatasetTableRequest.getCriteria()); + QueryableList pagedItems = PaginationManager.applyPaging(items, externalDatasetTableRequest); + List externalDatasetListingmodels = pagedItems.select(item -> new ExternalDatasetListingModel().fromDataModel(item)); + return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).data(externalDatasetListingmodels).totalCount(items.count()).build(); + } + + public List getWithExternal(String query, String type, Principal principal) throws HugeResultSet, NoURLFound { + // Fetch the local saved external Datasets that belong to the user. + ExternalDatasetCriteria criteria = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ExternalDatasetCriteriaBuilder.class).like(query).build(); + criteria.setCreationUserId(principal.getId()); + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().getWithCriteria(criteria); + + // Fetch external Datasets from external sources. + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = remoteFetcher.getDatasets(externalUrlCriteria, type); + + // Parse items from external sources to listing models. + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + List externalDatasetModels = remoteRepos.stream() + .map(item -> mapper.convertValue(item, ExternalDatasetListingModel.class)) + .collect(Collectors.toCollection(LinkedList::new)); + + // Merge fetched and local. + List externalDatasets = items.select(item -> new ExternalDatasetListingModel().fromDataModel(item)); + externalDatasets.addAll(externalDatasetModels); + + return externalDatasets; + } + + 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 ExternalDataset create(ExternalDatasetModel externalDatasetModel, Principal principal) throws Exception { + ExternalDataset externalDataset = externalDatasetModel.toDataModel(); + externalDataset.getCreationUser().setId(principal.getId()); + return apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().createOrUpdate(externalDataset); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/FileManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/FileManager.java new file mode 100644 index 000000000..3d09e9e82 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/FileManager.java @@ -0,0 +1,95 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.data.entities.FileUpload; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.logic.services.ApiContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Component +public class FileManager { + private static final Logger logger = LoggerFactory.getLogger(FileManager.class); + + private ApiContext apiContext; + private DatabaseRepository databaseRepository; + private Environment environment; + + @Autowired + public FileManager(ApiContext apiContext, Environment environment) { + this.apiContext = apiContext; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + this.environment = environment; + } + + public String moveFromTmpToStorage(String filename) { + File tempFile = new File(this.environment.getProperty("temp.temp") + filename); + File newFile = new File(this.environment.getProperty("file.storage") + filename); + try { + return Files.move(tempFile.toPath(), newFile.toPath()).toString(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + public boolean deleteFromStorage(String filename) { + File toBeDeletedFile = new File(this.environment.getProperty("file.storage") + filename); +// toBeDeletedFile.delete(); + try { + return Files.deleteIfExists(toBeDeletedFile.toPath()); + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + + public void markOldFileAsDeleted(FileUpload fileUpload) { + fileUpload.setIsDeleted(true); + databaseRepository.getFileUploadDao().createOrUpdate(fileUpload); + } + + public List getFileUploadsForEntityId(String entityId) { + return databaseRepository.getFileUploadDao().asQueryable() + .where((builder, root) -> builder.equal(root.get("entityId"), entityId)).toList(); + } + + public List getCurrentFileUploadsForEntityId(UUID entityId) { + return databaseRepository.getFileUploadDao().asQueryable() + .where((builder, root) -> builder.and( + builder.equal(root.get("entityId"), entityId), + builder.equal(root.get("isDeleted"), false))).toList(); + } + + public void markAllFilesOfEntityIdAsDeleted(UUID entityId) { + List fileUploads = this.getCurrentFileUploadsForEntityId(entityId); + fileUploads.forEach(fileUpload -> { + this.markOldFileAsDeleted(fileUpload); + }); + } + + public void createFile(String id, String fileName, String fileType, String entityId, FileUpload.EntityType entityType, UserInfo userInfo) { + FileUpload fileUpload = new FileUpload(); + fileUpload.setId(UUID.fromString(id)); + fileUpload.setName(fileName); + fileUpload.setFileType(fileType); + fileUpload.setEntityId(UUID.fromString(entityId)); + fileUpload.setEntityType(entityType); + fileUpload.setCreatedAt(new Date()); + fileUpload.setIsDeleted(false); + fileUpload.setCreator(userInfo); + databaseRepository.getFileUploadDao().createOrUpdate(fileUpload); + + this.moveFromTmpToStorage(fileUpload.getId().toString()); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/FunderManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/FunderManager.java new file mode 100644 index 000000000..5277294f1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/FunderManager.java @@ -0,0 +1,66 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.logic.builders.model.models.FunderBuilder; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.logic.proxy.fetching.RemoteFetcher; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.utilities.helpers.ListHelper; +import eu.eudat.old.models.data.external.ExternalSourcesItemModel; +import eu.eudat.old.models.data.external.FundersExternalSourcesModel; +import eu.eudat.old.models.data.funder.Funder; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.query.items.item.funder.FunderCriteriaRequest; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import org.springframework.stereotype.Component; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Component +public class FunderManager { + + private ApiContext apiContext; + private RemoteFetcher remoteFetcher; + private ListHelper listHelper; + + public FunderManager(ApiContext apiContext, RemoteFetcher remoteFetcher, ListHelper listHelper) { + this.apiContext = apiContext; + this.remoteFetcher = remoteFetcher; + this.listHelper = listHelper; + } + + public List getCriteriaWithExternal(FunderCriteriaRequest funderCriteria, Principal principal) throws HugeResultSet, NoURLFound { + UserInfo userInfo = new UserInfo(); + userInfo.setId(principal.getId()); + funderCriteria.getCriteria().setReference("dmp:"); + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getFunderDao().getWithCritetia(funderCriteria.getCriteria()); + QueryableList authItems = apiContext.getOperationsContext().getDatabaseRepository().getFunderDao().getAuthenticated(items, userInfo); + List funders = authItems.select(item -> new Funder().fromDataModel(item)); + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(funderCriteria.getCriteria().getLike()); + List> remoteRepos = remoteFetcher.getFunders(externalUrlCriteria); + FundersExternalSourcesModel fundersExternalSourcesModel = new FundersExternalSourcesModel().fromExternalItem(remoteRepos); + for (ExternalSourcesItemModel externalListingItem : fundersExternalSourcesModel) { + Funder funder = apiContext.getOperationsContext().getBuilderFactory().getBuilder(FunderBuilder.class) + .reference(externalListingItem.getRemoteId()).label(externalListingItem.getName()) + .status(eu.eudat.old.data.entities.Funder.Status.fromInteger(0)) + .key(externalListingItem.getKey()) + .source(externalListingItem.getTag()) + .build(); + if (externalListingItem.getSource() != null) { + funder.setSource(externalListingItem.getSource()); + } else { + funder.setSource(externalListingItem.getTag()); + } + + funders.add(funder); + } + funders.sort(Comparator.comparing(Funder::getLabel)); + funders = funders.stream().filter(listHelper.distinctByKey(Funder::getLabel)).collect(Collectors.toList()); + return funders; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/GrantManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/GrantManager.java new file mode 100644 index 000000000..f0a25b50c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/GrantManager.java @@ -0,0 +1,185 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.query.items.item.grant.GrantCriteriaRequest; +import eu.eudat.old.exceptions.grant.GrantWithDMPsDeleteException; +import eu.eudat.old.logic.builders.model.models.GrantBuilder; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.logic.utilities.helpers.ListHelper; +import eu.eudat.old.models.data.grant.GrantListingModel; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.query.items.table.grant.GrantTableRequest; +import eu.eudat.old.data.dao.entities.GrantDao; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.models.data.external.ExternalSourcesItemModel; +import eu.eudat.old.models.data.external.GrantsExternalSourcesModel; +import eu.eudat.old.models.data.grant.Grant; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.proxy.fetching.RemoteFetcher; +import eu.eudat.old.logic.services.ApiContext; +import org.springframework.stereotype.Component; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; + +@Component +public class GrantManager { + + private ApiContext apiContext; + private DatabaseRepository databaseRepository; +// private FileStorageService fileStorageService; + private RemoteFetcher remoteFetcher; + private ListHelper listHelper; + + public GrantManager(ApiContext apiContext, ListHelper listHelper) { + this.apiContext = apiContext; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); +// this.fileStorageService = apiContext.getOperationsContext().getFileStorageService(); + this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher(); + this.listHelper = listHelper; + } + + public DataTableData getPaged(GrantTableRequest grantTableRequest, Principal principal, String fieldsGroup) throws Exception { + UserInfo userInfo = new UserInfo(); + userInfo.setId(principal.getId()); + GrantDao grantRepository = databaseRepository.getGrantDao(); + QueryableList items = grantRepository.getWithCriteria(grantTableRequest.getCriteria()); + QueryableList authItems = grantRepository.getAuthenticated(items, userInfo); + QueryableList pagedItems = PaginationManager.applyPaging(authItems, grantTableRequest); + DataTableData dataTable = new DataTableData<>(); + CompletableFuture grantsFuture; + if (fieldsGroup.equals("listing")) { + grantsFuture = pagedItems.selectAsync(item -> new GrantListingModel().fromDataModelDetails(item)) + .whenComplete((results, throwable) -> + dataTable.setData(results) + ); + } else { + grantsFuture = pagedItems.selectAsync(item -> new GrantListingModel().fromDataModel(item)) + .whenComplete((results, throwable) -> + dataTable.setData(results) + ); + } + CompletableFuture countFuture = pagedItems.countAsync().whenComplete((count, throwable) -> dataTable.setTotalCount(count)); + + CompletableFuture.allOf(grantsFuture, countFuture).join(); + return dataTable; + } + + public DataTableData getPublicPaged(GrantTableRequest grantTableRequest) throws Exception { + GrantDao grantRepository = databaseRepository.getGrantDao(); + grantTableRequest.getCriteria().setPublic(true); + QueryableList items = grantRepository.getWithCriteria(grantTableRequest.getCriteria()); + QueryableList pagedItems = PaginationManager.applyPaging(items, grantTableRequest); + DataTableData dataTable = new DataTableData<>(); + CompletableFuture grantsFuture; + grantsFuture = pagedItems.selectAsync(item -> new GrantListingModel().fromDataModel(item)) + .whenComplete((results, throwable) -> { + dataTable.setData(results); + }); + CompletableFuture countFuture = pagedItems.countAsync().whenComplete((count, throwable) -> dataTable.setTotalCount(count)); + + CompletableFuture.allOf(grantsFuture, countFuture).join(); + return dataTable; + } + + public Grant getSingle(String id) throws InstantiationException, IllegalAccessException { + Grant grant = new Grant(); + grant.fromDataModel(databaseRepository.getGrantDao().find(UUID.fromString(id))); + return grant; + } + + /*public eu.eudat.data.entities.Grant inactivate(String id) throws InstantiationException, IllegalAccessException { + GrantDao grantRepository = databaseRepository.getGrantDao(); + eu.eudat.data.entities.Grant grant = grantRepository.find(UUID.fromString(id)); + grant.setStatus(eu.eudat.data.entities.Grant.Status.DELETED.getValue()); + grant = grantRepository.createOrUpdate(grant); + return grant; + }*/ + + public List getCriteriaWithExternal(GrantCriteriaRequest grantCriteria, Principal principal) throws HugeResultSet, NoURLFound { + UserInfo userInfo = new UserInfo(); + userInfo.setId(principal.getId()); + /*if (grantCriteria.getCriteria().getFunderReference() != null && !grantCriteria.getCriteria().getFunderReference().trim().isEmpty()) { + FunderCriteria funderCriteria = new FunderCriteria(); + funderCriteria.setReference(grantCriteria.getCriteria().getFunderReference()); + Funder funder = apiContext.getOperationsContext().getDatabaseRepository().getFunderDao().getWithCritetia(funderCriteria).getSingleOrDefault(); + if (funder != null) { + grantCriteria.getCriteria().setFunderId(funder.getId().toString()); + } + }*/ + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(grantCriteria.getCriteria().getLike()); + if (grantCriteria.getCriteria().getFunderReference() != null) { + externalUrlCriteria.setFunderId(grantCriteria.getCriteria().getFunderReference()); + grantCriteria.getCriteria().setFunderReference(null); + } + grantCriteria.getCriteria().setReference("dmp:"); + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().getWithCriteria(grantCriteria.getCriteria()); + QueryableList authItems = apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().getAuthenticated(items, userInfo); + List grants = authItems.select(item -> new Grant().fromDataModel(item)); + + List> remoteRepos = remoteFetcher.getGrants(externalUrlCriteria); + + GrantsExternalSourcesModel grantsExternalSourcesModel = new GrantsExternalSourcesModel().fromExternalItem(remoteRepos); + for (ExternalSourcesItemModel externalListingItem : grantsExternalSourcesModel) { + Grant grant = apiContext.getOperationsContext().getBuilderFactory().getBuilder(GrantBuilder.class) + .reference(externalListingItem.getRemoteId()).label(externalListingItem.getName()) + .description(externalListingItem.getDescription()).uri(externalListingItem.getUri()) + .key(externalListingItem.getKey()) + .abbreviation(externalListingItem.getAbbreviation()).status(eu.eudat.old.data.entities.Grant.Status.fromInteger(0)) + .source(externalListingItem.getTag()) + .build(); + + grants.add(grant); + } + grants.sort(Comparator.comparing(Grant::getLabel)); + grants = grants.stream().filter(listHelper.distinctByKey(Grant::getLabel)).collect(Collectors.toList()); + return grants; + } + + public List getCriteria(GrantCriteriaRequest grantCriteria) throws IllegalAccessException, InstantiationException, HugeResultSet, NoURLFound { + GrantDao grantRepository = databaseRepository.getGrantDao(); + QueryableList items = grantRepository.getWithCriteria(grantCriteria.getCriteria()); + if (grantCriteria.getLength() != null) items.take(grantCriteria.getLength()); + List grants = items.select(item -> new Grant().fromDataModel(item)); + return grants; + } + + /*public void createOrUpdate(eu.eudat.models.data.grant.Grant grant, Principal principal) throws ParseException, IOException { + eu.eudat.data.entities.Grant grantEntity = grant.toDataModel(); + if (grant.getFiles() != null) { + for (ContentFile file : grant.getFiles()) { + try { + ContentFile storedFile = fileStorageService.copyFromTempFileSystem(file); + Content content = new ContentBuilder().extension(file.getType()) + .label(file.getFilename()) + .locationType(Content.LocationType.INTERNAL.getValue()) + .parentType(Content.ParentType.GRANT.getValue()) + .uri("LOCAL:" + storedFile.getId()) + .build(); + grantEntity.setContent(databaseRepository.getContentDao().createOrUpdate(content)); + } catch (TempFileNotFoundException e) { + continue; + } + } + } + grantEntity.setType(eu.eudat.data.entities.Grant.GrantType.INTERNAL.getValue()); + grantEntity.setCreationUser(databaseRepository.getUserInfoDao().find(principal.getId())); + databaseRepository.getGrantDao().createOrUpdate(grantEntity); + }*/ + + public void delete(UUID uuid) { + eu.eudat.old.data.entities.Grant oldGrant = apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().find(uuid); + if (oldGrant.getDmps().size() > 0) + throw new GrantWithDMPsDeleteException("You cannot Remove Grants with DMPs"); + oldGrant.setStatus(DMP.DMPStatus.DELETED.getValue()); + apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().createOrUpdate(oldGrant); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/InvitationsManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/InvitationsManager.java new file mode 100644 index 000000000..b386c24f9 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/InvitationsManager.java @@ -0,0 +1,153 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.exceptions.security.UnauthorisedException; +import eu.eudat.old.logic.utilities.helpers.StreamDistinctBy; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.UserDMP; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.query.items.item.userinfo.UserInfoRequestItem; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.invitation.Invitation; +import eu.eudat.old.models.data.invitation.Properties; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.userinfo.UserInfoInvitationModel; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.IOException; +import java.io.StringReader; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Component +public class InvitationsManager { + + private ApiContext apiContext; + private DataManagementPlanManager dataManagementPlanManager; + + @Autowired + public InvitationsManager(ApiContext apiContext, DataManagementPlanManager dataManagementPlanManager) { + this.apiContext = apiContext; + this.dataManagementPlanManager = dataManagementPlanManager; + } + + public void inviteUsers(Invitation invitation, Principal principal) throws Exception { + UserInfo principalUser = new UserInfo(); + principalUser.setId(principal.getId()); + invitation.getUsers().stream().filter(item -> item.getId() == null).forEach(item -> { + UserInfo existingUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), item.getEmail())).getSingleOrDefault(); + if (existingUser != null) { + item.setId(existingUser.getId()); + } + }); + List alreadySignedInUsers = invitation.getUsers().stream().filter(item -> item.getId() != null).collect(Collectors.toList()); + List alreadySignedInUsersEntities = alreadySignedInUsers.stream().map(UserInfoInvitationModel::toDataModel).collect(Collectors.toList()); + List userInfoToUserDmp = new LinkedList<>(); + for (UserInfo userInfo : alreadySignedInUsersEntities) { + UserDMP userDMP = new UserDMP(); + userDMP.setUser(userInfo); + userDMP.setRole(invitation.getRole()); + userInfoToUserDmp.add(userDMP); + /*if (!apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().areAssociated(principalUser, userInfo)) { + UserAssociation userAssociation = new UserAssociation(); + userAssociation.setFirstUser(principalUser); + userAssociation.setSecondUser(userInfo); + apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().createOrUpdate(userAssociation); + }*/ + } + DMP dataManagementPlan = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().find(invitation.getDataManagementPlan()); + apiContext.getUtilitiesService().getInvitationService().createInvitations(apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao(), apiContext.getUtilitiesService().getMailService(), invitation.getUsers().stream().map(UserInfoInvitationModel::toDataModel).collect(Collectors.toList()), dataManagementPlan, invitation.getRole(), principalUser); + apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), userInfoToUserDmp, dataManagementPlan); + } + + public List getUsers(Principal principal) throws InstantiationException, IllegalAccessException { + /*UserInfo principalUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + List users = apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().getAssociated(principalUser).stream().map(userAssociation -> { + if (userAssociation.getFirstUser().getId().equals(principal.getId())) { + return userAssociation.getSecondUser(); + } else { + return userAssociation.getFirstUser(); + } + }).collect(Collectors.toList());*/ + List users = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao() + .getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable() + .where(((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue()))), principal.getId(), Stream.of(0, 1).collect(Collectors.toList())) + .toList().stream().map(DMP::getUsers).flatMap(Collection::stream).map(UserDMP::getUser) + .filter(userInfo -> !userInfo.getId().equals(principal.getId())).filter(StreamDistinctBy.distinctByKey(UserInfo::getId)).collect(Collectors.toList()); + List userModels = users.stream().map(userInfo -> new UserInfoInvitationModel().fromDataModel(userInfo)).collect(Collectors.toList()); + return userModels; + } + + public List getUsersWithCriteria(Principal principal, UserInfoRequestItem userInfoRequestItem) throws IllegalAccessException, InstantiationException { + List users = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao() + .getAuthenticated(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().asQueryable() + .where(((builder, root) -> + builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue()))), principal.getId(), Stream.of(0, 1).collect(Collectors.toList())) + .toList().stream().map(DMP::getUsers).flatMap(Collection::stream).map(UserDMP::getUser) + .filter(userInfo -> !userInfo.getId().equals(principal.getId())).filter(StreamDistinctBy.distinctByKey(UserInfo::getId)) + .filter(userInfo -> (userInfoRequestItem == null || userInfoRequestItem.getCriteria() == null || userInfoRequestItem.getCriteria().getLike() == null + || userInfo.getName().toLowerCase().contains(userInfoRequestItem.getCriteria().getLike().toLowerCase()) + || (userInfo.getEmail().toLowerCase().contains(userInfoRequestItem.getCriteria().getLike().toLowerCase())))) + .collect(Collectors.toList()); +// .where((builder, root) -> builder.like(builder.upper(root.get("name")), "%" + userInfoRequestItem.getCriteria().getLike().toUpperCase() + "%")) + + List userModels = users.stream().map(userInfo -> new UserInfoInvitationModel().fromDataModel(userInfo)).collect(Collectors.toList()); + return userModels; + } + + public UUID assignUserAcceptedInvitation(UUID invitationID, Principal principal) throws UnauthorisedException, JAXBException, IOException { + eu.eudat.old.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()) return invitation.getDmp().getId(); //throw new UnauthorisedException("This Url Has Expired"); + JAXBContext context = JAXBContext.newInstance(Properties.class); + Unmarshaller unmarshaller = context.createUnmarshaller(); + Properties properties = (Properties) unmarshaller.unmarshal(new StringReader(invitation.getProperties())); + UserInfo invitedUser = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + QueryableList userDMPQueryableList = apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where(((builder, root) -> builder.and(builder.equal(root.get("dmp").get("id"), invitation.getDmp().getId()), builder.equal(root.get("user").get("id"), invitedUser.getId())))); + UserDMP existingUserDMP = userDMPQueryableList.getSingleOrDefault(); + if (existingUserDMP != null) { + if (properties.getRole() != null && existingUserDMP.getRole() > properties.getRole()) { + existingUserDMP.setRole(properties.getRole()); + DMP datamanagementPlan = invitation.getDmp(); + apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(existingUserDMP); + apiContext.getUtilitiesService().getInvitationService().assignToDmp(apiContext.getOperationsContext().getDatabaseRepository().getDmpDao(), existingUserDMP, datamanagementPlan); + invitation.setAcceptedInvitation(true); + apiContext.getOperationsContext().getDatabaseRepository().getInvitationDao().createOrUpdate(invitation); + datamanagementPlan.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), datamanagementPlan.getId())).toList())); + dataManagementPlanManager.updateIndex(datamanagementPlan); + return datamanagementPlan.getId(); + } + } else { + UserDMP userDMP = new UserDMP(); + userDMP.setUser(invitedUser); + userDMP.setDmp(invitation.getDmp()); + + if (properties.getRole() != null) { + userDMP.setRole(properties.getRole()); + } else { + userDMP.setRole(UserDMP.UserDMPRoles.USER.getValue()); + } + /*if (!apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().areAssociated(invitedUser, invitation.getUser())) { + UserAssociation userAssociation = new UserAssociation(); + userAssociation.setFirstUser(invitedUser); + userAssociation.setSecondUser(invitation.getUser()); + apiContext.getOperationsContext().getDatabaseRepository().getUserAssociationDao().createOrUpdate(userAssociation); + }*/ + DMP datamanagementPlan = invitation.getDmp(); + 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); + datamanagementPlan.setUsers(new HashSet<>(apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("dmp").get("id"), datamanagementPlan.getId())).toList())); + dataManagementPlanManager.updateIndex(datamanagementPlan); + return datamanagementPlan.getId(); + } + return invitation.getDmp().getId(); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/LicenseManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/LicenseManager.java new file mode 100644 index 000000000..31a223f00 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/LicenseManager.java @@ -0,0 +1,45 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.dao.criteria.DataRepositoryCriteria; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.license.LicenseModel; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.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.Map; +import java.util.stream.Collectors; + +/** + * Created by ikalyvas on 9/3/2018. + */ +@Component +public class LicenseManager { + private ApiContext apiContext; + + @Autowired + public LicenseManager(ApiContext apiContext) { + this.apiContext = apiContext; + } + + public List getLicenses(String query, String type) throws HugeResultSet, NoURLFound { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getlicenses(externalUrlCriteria, type); + + DataRepositoryCriteria criteria = new DataRepositoryCriteria(); + if (!query.isEmpty()) criteria.setLike(query); + + List licenseModels = new LinkedList<>(); + + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + licenseModels.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, LicenseModel.class)).collect(Collectors.toList())); + licenseModels = licenseModels.stream().filter(licenseModel -> licenseModel.getName().toLowerCase().contains(query.toLowerCase())).collect(Collectors.toList()); + return licenseModels; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/LocalFetchManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/LocalFetchManager.java new file mode 100644 index 000000000..4c5e1ce32 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/LocalFetchManager.java @@ -0,0 +1,28 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.logic.proxy.fetching.LocalFetcher; +import eu.eudat.old.logic.utilities.helpers.StreamDistinctBy; +import eu.eudat.old.models.data.local.LocalFetchModel; +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; + +@Component +public class LocalFetchManager { + private LocalFetcher localFetcher; + + @Autowired + public LocalFetchManager(LocalFetcher localFetcher) { + this.localFetcher = localFetcher; + } + + public List getCurrency(String query) throws Exception { + List> data = localFetcher.retrieveCurrency(); + List result = data.stream().map(entry -> new LocalFetchModel(entry.get("name"), entry.get("value"))).collect(Collectors.toList()); + result = result.stream().filter(localFetchModel -> localFetchModel.getValue() != null).filter(StreamDistinctBy.distinctByKey(LocalFetchModel::getValue)).filter(localFetchModel -> localFetchModel.getName().toLowerCase().contains(query.toLowerCase())).collect(Collectors.toList()); + return result; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/LockManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/LockManager.java new file mode 100644 index 000000000..b5952baf1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/LockManager.java @@ -0,0 +1,123 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.dao.criteria.LockCriteria; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.lock.Lock; +import eu.eudat.old.models.data.security.Principal; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import javax.persistence.NoResultException; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Component +public class LockManager { + private final Comparator compareByTouchedAt = Comparator.comparing(o -> o.getTouchedAt().getTime()); + + private ApiContext apiContext; + private Environment environment; + + @Autowired + public LockManager(ApiContext apiContext, Environment environment) { + this.apiContext = apiContext; + this.environment = environment; + } + + public eu.eudat.old.data.entities.Lock createOrUpdate(Lock lock, Principal principal) throws Exception { + if (lock.getId() != null) { + try { + eu.eudat.old.data.entities.Lock entity = this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().find(lock.getId()); + if (entity != null) { + if (!entity.getLockedBy().getId().equals(principal.getId())) { + throw new Exception("Is not locked by that user"); + } + } + }catch(NoResultException e) { + lock.setId(null); + } + } + eu.eudat.old.data.entities.Lock newLock = lock.toDataModel(); + newLock = this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().createOrUpdate(newLock); + + return newLock; + } + + public boolean isLocked(String targetId, Principal principal) throws Exception { + LockCriteria criteria = new LockCriteria(); + criteria.setTarget(UUID.fromString(targetId)); + Long availableLocks = this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().getWithCriteria(criteria).count(); + if (availableLocks == 1) { + eu.eudat.old.data.entities.Lock lock = this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().getWithCriteria(criteria).getSingle(); + if (lock.getLockedBy().getId().equals(principal.getId())) { + lock.setTouchedAt(new Date()); + this.createOrUpdate(new Lock().fromDataModel(lock), principal); + return false; + } + return this.forceUnlock(targetId) > 0; + } else if (availableLocks > 1) { + this.forceUnlock(targetId); + return this.isLocked(targetId, principal); + } + return false; + } + + private Long forceUnlock(String targetId) { + LockCriteria criteria = new LockCriteria(); + criteria.setTarget(UUID.fromString(targetId)); + Long availableLocks = this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().getWithCriteria(criteria).count(); + long deletedLocks = 0L; + if (availableLocks > 0) { + List locks = this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().getWithCriteria(criteria).toList(); + for (eu.eudat.old.data.entities.Lock lock : locks) { + if (new Date().getTime() - lock.getTouchedAt().getTime() > environment.getProperty("database.lock-fail-interval", Integer.class)) { + this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().delete(lock); + deletedLocks++; + } + } + if (deletedLocks == 0) { + eu.eudat.old.data.entities.Lock recentlock = locks.stream().max(compareByTouchedAt).get(); + for (eu.eudat.old.data.entities.Lock lock : locks) { + if (lock != recentlock) { + this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().delete(lock); + deletedLocks++; + } + } + } + } + return availableLocks - deletedLocks; + } + + public void unlock(String targetId, Principal principal) throws Exception { + LockCriteria criteria = new LockCriteria(); + criteria.setTarget(UUID.fromString(targetId)); + Long availableLocks = this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().getWithCriteria(criteria).count(); + if (availableLocks == 1) { + eu.eudat.old.data.entities.Lock lock = this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().getWithCriteria(criteria).getSingle(); + if (!lock.getLockedBy().getId().equals(principal.getId())) { + throw new Exception("Only the user who created that lock can delete it"); + } + this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().delete(lock); + } else if (availableLocks > 1) { + List locks = this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().getWithCriteria(criteria).toList(); + locks.stream().filter(lock -> lock.getLockedBy().getId().equals(principal.getId())).forEach(lock -> this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().delete(lock)); + } + } + + public Lock getFromTarget(String targetId, Principal principal) throws Exception { + LockCriteria criteria = new LockCriteria(); + criteria.setTarget(UUID.fromString(targetId)); + Long availableLocks = this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().getWithCriteria(criteria).count(); + if (availableLocks > 0) { + eu.eudat.old.data.entities.Lock lock = this.apiContext.getOperationsContext().getDatabaseRepository().getLockDao().getWithCriteria(criteria).getSingle(); + if (!lock.getLockedBy().getId().equals(principal.getId())) { + throw new Exception("Only the user who created that lock can access it"); + } + return new Lock().fromDataModel(lock); + } + return null; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/MaterialManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/MaterialManager.java new file mode 100644 index 000000000..dd551d1cc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/MaterialManager.java @@ -0,0 +1,51 @@ +package eu.eudat.old.logic.managers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Component +public class MaterialManager { + + @Autowired + public MaterialManager(){} + + public ResponseEntity getResponseEntity(String lang, Stream paths) throws IOException { + List result = paths.filter(Files::isRegularFile) + .map(Path::toString).collect(Collectors.toList()); + + String fileName = result.stream().filter(about -> about.contains("_" + lang)).findFirst().orElse(null); + if (fileName == null) { + fileName = result.stream().filter(about -> about.contains("_en")).findFirst().get(); + } + InputStream is = new FileInputStream(fileName); + + Path path = Paths.get(fileName); + + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setContentLength(is.available()); + responseHeaders.setContentType(MediaType.TEXT_HTML); + responseHeaders.set("Content-Disposition", "attachment;filename=" + path.getFileName().toString()); + responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition"); + responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type"); + + byte[] content = new byte[is.available()]; + is.read(content); + is.close(); + + return new ResponseEntity<>(content, responseHeaders, HttpStatus.OK); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/MergeEmailConfirmationManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/MergeEmailConfirmationManager.java new file mode 100644 index 000000000..ca6347967 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/MergeEmailConfirmationManager.java @@ -0,0 +1,149 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.elastic.criteria.DmpCriteria; +import eu.eudat.old.elastic.entities.Collaborator; +import eu.eudat.old.elastic.entities.Dmp; +import eu.eudat.old.elastic.repository.DmpRepository; +import eu.eudat.old.exceptions.emailconfirmation.TokenExpiredException; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.data.entities.Credential; +import eu.eudat.old.data.entities.EmailConfirmation; +import eu.eudat.old.data.entities.UserDMP; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.entities.UserToken; +import eu.eudat.old.exceptions.emailconfirmation.HasConfirmedEmailException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import javax.transaction.Transactional; +import java.io.IOException; +import java.util.*; + +@Component +public class MergeEmailConfirmationManager { + private static Logger logger = LoggerFactory.getLogger(MergeEmailConfirmationManager.class); + private ApiContext apiContext; + private DatabaseRepository databaseRepository; + private DmpRepository dmpRepository; + + @Autowired + public MergeEmailConfirmationManager(ApiContext apiContext) { + this.apiContext = apiContext; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + this.dmpRepository = apiContext.getOperationsContext().getElasticRepository().getDmpRepository(); + } + + @Transactional + public String confirmEmail(String token) throws TokenExpiredException, HasConfirmedEmailException { + EmailConfirmation loginConfirmationEmail = apiContext.getOperationsContext() + .getDatabaseRepository().getLoginConfirmationEmailDao().asQueryable() + .where((builder, root) -> builder.equal(root.get("token"), UUID.fromString(token))).getSingle(); + + if (loginConfirmationEmail.getExpiresAt().compareTo(new Date()) < 0) + throw new TokenExpiredException("Token has expired."); + + UserInfo userToBeMerged = databaseRepository.getUserInfoDao().asQueryable() + .where((builder, root) -> builder.equal(root.get("id"), loginConfirmationEmail.getUserId())).getSingle(); + String userToBeMergedEmail = userToBeMerged.getEmail(); + try { + Map map = new ObjectMapper().readValue(loginConfirmationEmail.getData(), HashMap.class); + UUID otherUserId = UUID.fromString((String) map.get("userId")); + UserInfo user = databaseRepository.getUserInfoDao().asQueryable() + .where((builder, root) -> builder.equal(root.get("id"), otherUserId)).getSingle(); + + // Checks if mail is used by another user. If it is, merges the new the old. + mergeNewUserToOld(user, userToBeMerged, Integer.valueOf((String) map.get("provider"))); + expireUserToken(userToBeMerged); + loginConfirmationEmail.setIsConfirmed(true); + databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + return userToBeMergedEmail; + } + + public void sendConfirmationEmail(String email, Principal principal, UUID userId, Integer provider) throws HasConfirmedEmailException { + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + + if (user.getEmail() != null && !user.getEmail().equals(email)) { + apiContext.getUtilitiesService().getConfirmationEmailService().createMergeConfirmationEmail( + databaseRepository.getLoginConfirmationEmailDao(), + apiContext.getUtilitiesService().getMailService(), + email, + userId, + principal, + provider + ); + } + } + + @Transactional + private void mergeNewUserToOld(UserInfo newUser, UserInfo oldUser, Integer provider) { + Credential credential = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.and(builder.equal(root.get("userInfo"), oldUser), builder.equal(root.get("provider"), provider))).getSingle(); + credential.setUserInfo(newUser); + databaseRepository.getCredentialDao().createOrUpdate(credential); + List userDmps = databaseRepository.getUserDmpDao().asQueryable().where((builder, root) -> builder.equal(root.get("user"), oldUser)).toList(); + userDmps.forEach(userDmp -> { + userDmp.setUser(newUser); + databaseRepository.getUserDmpDao().createOrUpdate(userDmp); + }); + try { + DmpCriteria dmpCriteria = new DmpCriteria(); + dmpCriteria.setCollaborators(Collections.singletonList(oldUser.getId())); + List elasticDmpsIds = dmpRepository.query(dmpCriteria); + for(Dmp dmpId: elasticDmpsIds){ + Dmp dmp = dmpRepository.findDocument(dmpId.getId().toString()); + if(dmp.getDatasets() != null) { + dmp.getDatasets().forEach(dataset -> { + if(dataset.getCollaborators() != null) { + for (Collaborator collaborator : dataset.getCollaborators()) { + if (collaborator.getId().equals(oldUser.getId().toString())) { + collaborator.setId(newUser.getId().toString()); + collaborator.setName(newUser.getName()); + } + } + } + }); + } + if(dmp.getCollaborators() != null) { + for (Collaborator collaborator : dmp.getCollaborators()) { + if (collaborator.getId().equals(oldUser.getId().toString())) { + collaborator.setId(newUser.getId().toString()); + collaborator.setName(newUser.getName()); + } + } + } + dmpRepository.createOrUpdate(dmp); + } + } + catch (IOException e){ + logger.warn("Warning: Could not fetch dmps from elastic.", e); + } + oldUser.setUserStatus((short)1); + oldUser.setEmail(null); + List credentials = databaseRepository.getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userInfo"), oldUser)).toList(); + credentials.forEach(cred -> { + if (cred.getId() != credential.getId()) { + databaseRepository.getCredentialDao().delete(cred); + } + }); + databaseRepository.getUserInfoDao().createOrUpdate(oldUser); + } + + private void expireUserToken(UserInfo user) { + UserToken userToken = databaseRepository.getUserTokenDao().asQueryable() + .where((builder, root) -> builder.equal(root.get("user"), user)) + .orderBy((builder, root) -> builder.desc(root.get("issuedAt"))) + .take(1).toList().get(0); + userToken.setExpiresAt(new Date()); + databaseRepository.getUserTokenDao().createOrUpdate(userToken); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/MetricsManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/MetricsManager.java new file mode 100644 index 000000000..bacbea11e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/MetricsManager.java @@ -0,0 +1,415 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.dao.criteria.*; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.types.MetricNames; +import io.micrometer.prometheus.PrometheusMeterRegistry; +import io.prometheus.client.Gauge; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.transaction.Transactional; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Component +public class MetricsManager { + private final static Logger logger = LoggerFactory.getLogger(MetricsManager.class); + private final Map gauges; + + public static final Map datasetTemplateStatus = Stream.of(new Object[][] { + { DescriptionTemplate.Status.SAVED.getValue(), MetricNames.DRAFT }, + { DescriptionTemplate.Status.FINALIZED.getValue(), MetricNames.ACTIVE }, + }).collect(Collectors.toMap(data -> (Short) data[0], data -> (String) data[1])); + + public void increaseValue(String name, int amount, String label) { + + if(label != null) { + gauges.get(name).labels(label).inc(amount); + } else { + gauges.get(name).inc(amount); + } + } + + public void decreaseValue(String name, int amount, String label) { + if(label != null) { + gauges.get(name).labels(label).dec(amount); + } else { + gauges.get(name).dec(amount); + } + } + + public Integer getValue(String name, String label) { + if(label != null) { + return Double.valueOf(gauges.get(name).labels(label).get()).intValue(); + } else { + return Double.valueOf(gauges.get(name).get()).intValue(); + } + } + + public void calculateValue(String name, int amount, String label) { + Integer orig = getValue(name, label); + int diff = orig - amount; + if (diff != 0) { + if (diff > 0) { + decreaseValue(name, diff, label); + } else { + increaseValue(name, Math.abs(diff), label); + } + } + } + + private final ApiContext apiContext; + private final UserManager userManager; + private final Environment environment; + + @Autowired + public MetricsManager(ApiContext apiContext, UserManager userManager, Environment environment, PrometheusMeterRegistry registry) { + this.apiContext = apiContext; + this.userManager = userManager; + this.environment = environment; + registry.clear(); + this.gauges = Stream.of( new Object[][]{ + {MetricNames.DMP, Gauge.build().name(MetricNames.DMP).help("Number of managed DMPs").labelNames("status").register(registry.getPrometheusRegistry())}, + {MetricNames.NEXUS + MetricNames.DMP, Gauge.build().name(MetricNames.NEXUS + MetricNames.DMP).help("Number of managed DMPs during Nexus").labelNames("status").register(registry.getPrometheusRegistry())}, + + {MetricNames.FUNDERS, Gauge.build().name(MetricNames.FUNDERS).help("Number of registered Funders").register(registry.getPrometheusRegistry())}, + {MetricNames.GRANTS, Gauge.build().name(MetricNames.GRANTS).help("Number of registered Grants").register(registry.getPrometheusRegistry())}, + {MetricNames.PROJECT, Gauge.build().name(MetricNames.PROJECT).help("Number of registered Projects").register(registry.getPrometheusRegistry())}, + {MetricNames.RESEARCHER, Gauge.build().name(MetricNames.RESEARCHER).help("Number of Colaborators/Researchers").register(registry.getPrometheusRegistry())}, + + {MetricNames.NEXUS + MetricNames.FUNDERS, Gauge.build().name(MetricNames.NEXUS + MetricNames.FUNDERS).help("Number of registered Funders during Nexus").register(registry.getPrometheusRegistry())}, + {MetricNames.NEXUS + MetricNames.GRANTS, Gauge.build().name(MetricNames.NEXUS + MetricNames.GRANTS).help("Number of registered Grants during Nexus").register(registry.getPrometheusRegistry())}, + {MetricNames.NEXUS + MetricNames.PROJECT, Gauge.build().name(MetricNames.NEXUS + MetricNames.PROJECT).help("Number of registered Projects during Nexus").register(registry.getPrometheusRegistry())}, + {MetricNames.NEXUS + MetricNames.RESEARCHER, Gauge.build().name(MetricNames.NEXUS + MetricNames.RESEARCHER).help("Number of Colaborators/Researchers during Nexus").register(registry.getPrometheusRegistry())}, + + {MetricNames.DATASET, Gauge.build().name(MetricNames.DATASET).help("Number of managed Dataset Descriptions").labelNames("status").register(registry.getPrometheusRegistry())}, + + {MetricNames.NEXUS + MetricNames.DATASET, Gauge.build().name(MetricNames.NEXUS + MetricNames.DATASET).help("Number of managed Dataset Descriptions during Nexus").labelNames("status").register(registry.getPrometheusRegistry())}, + + {MetricNames.DATASET_TEMPLATE, Gauge.build().name(MetricNames.DATASET_TEMPLATE).help("Number of dataset Templates").labelNames("status").register(registry.getPrometheusRegistry())}, + + {MetricNames.NEXUS + MetricNames.DATASET_TEMPLATE, Gauge.build().name(MetricNames.NEXUS + MetricNames.DATASET_TEMPLATE).help("Number of dataset Templates during Nexus").labelNames("status").register(registry.getPrometheusRegistry())}, + + {MetricNames.USERS, Gauge.build().name(MetricNames.USERS).help("Number of users").labelNames("type").register(registry.getPrometheusRegistry())}, + + {MetricNames.LANGUAGES, Gauge.build().name(MetricNames.LANGUAGES).help("Number of Languages").register(registry.getPrometheusRegistry())}, + + {MetricNames.DMP_WITH_GRANT, Gauge.build().name(MetricNames.DMP_WITH_GRANT).help("Number of Grants based on the status of the DMP that is using them").labelNames("status").register(registry.getPrometheusRegistry())}, + + {MetricNames.NEXUS + MetricNames.DMP_WITH_GRANT, Gauge.build().name(MetricNames.NEXUS + MetricNames.DMP_WITH_GRANT).help("Number of Grants based on the status of the DMP that is using them during Nexus").labelNames("status").register(registry.getPrometheusRegistry())}, + + {MetricNames.INSTALLATIONS, Gauge.build().name(MetricNames.INSTALLATIONS).help("Number of Installations").register(registry.getPrometheusRegistry())}, + {MetricNames.NEXUS + MetricNames.INSTALLATIONS, Gauge.build().name(MetricNames.NEXUS + MetricNames.INSTALLATIONS).help("Number of Installations").register(registry.getPrometheusRegistry())}, + + }).collect(Collectors.toMap(data -> (String)data[0], data -> (Gauge) data[1])); + + } + + @PostConstruct + @Transactional + @Scheduled(initialDelay = 1000 * 60 * 60, fixedDelay = 1000 * 60 * 60) + public void init() throws IOException { + logger.info("Start calculating Metrics"); + calculateValue(MetricNames.DMP, (int) countAllDraftDMPs(), MetricNames.DRAFT); + calculateValue(MetricNames.DMP, (int) countAllFinalizedDMPs(), MetricNames.FINALIZED); + calculateValue(MetricNames.DMP, (int) countAllPublishedDMPs(), MetricNames.PUBLISHED); + calculateValue(MetricNames.DMP, (int) countAllDoiedDMPs(), MetricNames.DOIED); + + calculateValue(MetricNames.NEXUS + MetricNames.DMP, (int) countAllDraftDMPs(true), MetricNames.DRAFT); + calculateValue(MetricNames.NEXUS + MetricNames.DMP, (int) countAllFinalizedDMPs(true), MetricNames.FINALIZED); + calculateValue(MetricNames.NEXUS + MetricNames.DMP, (int) countAllPublishedDMPs(true), MetricNames.PUBLISHED); + calculateValue(MetricNames.NEXUS + MetricNames.DMP, (int) countAllDoiedDMPs(true), MetricNames.DOIED); + + calculateValue(MetricNames.DMP_WITH_GRANT, (int) countAllDraftDMPsWithGrantId(), MetricNames.DRAFT); + calculateValue(MetricNames.DMP_WITH_GRANT, (int) countAllFinalizedDMPsWithGrantId(), MetricNames.FINALIZED); + calculateValue(MetricNames.DMP_WITH_GRANT, (int) countAllPublishedDMPsWithGrantId(), MetricNames.PUBLISHED); + calculateValue(MetricNames.DMP_WITH_GRANT, (int) countAllDoiedDMPsWithGrantId(), MetricNames.DOIED); + + calculateValue(MetricNames.NEXUS + MetricNames.DMP_WITH_GRANT, (int) countAllDraftDMPsWithGrantId(true), MetricNames.DRAFT); + calculateValue(MetricNames.NEXUS + MetricNames.DMP_WITH_GRANT, (int) countAllFinalizedDMPsWithGrantId(true), MetricNames.FINALIZED); + calculateValue(MetricNames.NEXUS + MetricNames.DMP_WITH_GRANT, (int) countAllPublishedDMPsWithGrantId(true), MetricNames.PUBLISHED); + calculateValue(MetricNames.NEXUS + MetricNames.DMP_WITH_GRANT, (int) countAllDoiedDMPsWithGrantId(true), MetricNames.DOIED); + + calculateValue(MetricNames.FUNDERS, (int) countAllFunders(), null); + calculateValue(MetricNames.GRANTS, (int) countAllGrants(), null); + calculateValue(MetricNames.PROJECT, (int) countAllProjects(), null); + calculateValue(MetricNames.RESEARCHER, (int) countAllResearchers(), null); + + calculateValue(MetricNames.NEXUS + MetricNames.FUNDERS, (int) countAllFunders(true), null); + calculateValue(MetricNames.NEXUS + MetricNames.GRANTS, (int) countAllGrants(true), null); + calculateValue(MetricNames.NEXUS + MetricNames.PROJECT, (int) countAllProjects(true), null); + calculateValue(MetricNames.NEXUS + MetricNames.RESEARCHER, (int) countAllResearchers(true), null); + + calculateValue(MetricNames.DATASET, (int) countAllDraftDatasets(), MetricNames.DRAFT); + calculateValue(MetricNames.DATASET, (int) countAllFinalizedDatasets(), MetricNames.FINALIZED); + calculateValue(MetricNames.DATASET, (int) countAllPublicDatasets(), MetricNames.PUBLISHED); + calculateValue(MetricNames.DATASET, (int) countAllDatasetsWithDoi(), MetricNames.DOIED); + + calculateValue(MetricNames.NEXUS + MetricNames.DATASET, (int) countAllDraftDatasets(true), MetricNames.DRAFT); + calculateValue(MetricNames.NEXUS + MetricNames.DATASET, (int) countAllFinalizedDatasets(true), MetricNames.FINALIZED); + calculateValue(MetricNames.NEXUS + MetricNames.DATASET, (int) countAllPublicDatasets(true), MetricNames.PUBLISHED); + calculateValue(MetricNames.NEXUS + MetricNames.DATASET, (int) countAllDatasetsWithDoi(true), MetricNames.DOIED); + + calculateValue(MetricNames.DATASET_TEMPLATE, (int) countAllDraftTemplates(), MetricNames.DRAFT); + calculateValue(MetricNames.DATASET_TEMPLATE, (int) countAllFinalizedTemplates(), MetricNames.ACTIVE); + calculateValue(MetricNames.DATASET_TEMPLATE, (int) countAllUsedTemplates(), MetricNames.USED); + + calculateValue(MetricNames.NEXUS + MetricNames.DATASET_TEMPLATE, (int) countAllDraftTemplates(true), MetricNames.DRAFT); + calculateValue(MetricNames.NEXUS + MetricNames.DATASET_TEMPLATE, (int) countAllFinalizedTemplates(true), MetricNames.ACTIVE); + calculateValue(MetricNames.NEXUS + MetricNames.DATASET_TEMPLATE, (int) countAllUsedTemplates(true), MetricNames.USED); + + calculateValue(MetricNames.USERS, (int) userManager.countActiveUsers().intValue(), MetricNames.LOGGEDIN); + calculateValue(MetricNames.USERS, (int) userManager.countAllUsers().intValue(), MetricNames.TOTAL); + + try (Stream paths = Files.list(Paths.get(Objects.requireNonNull(this.environment.getProperty("userguide.path"))))) { + long files = paths.count(); + calculateValue(MetricNames.LANGUAGES, (int) files, null); + } catch (Exception e) { + logger.error("Could not calculate languages."); + } + + calculateValue(MetricNames.INSTALLATIONS, 1, null); + calculateValue(MetricNames.NEXUS + MetricNames.INSTALLATIONS, 1, null); + + logger.info("Metrics calculation Completed"); + } + + private Date getNexusDate() { + try { + return new SimpleDateFormat("yyyy-MM-dd").parse("2021-01-01"); + } catch (ParseException e) { + logger.error(e.getLocalizedMessage(), e); + } + return Date.from(LocalDate.of(2021, 1, 1).atStartOfDay(ZoneId.systemDefault()).toInstant()); + } + + private long countAllDraftDMPs(){ + return countAllDraftDMPs(false); + } + + private long countAllDraftDMPs(boolean countNexus) { + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setStatus(0); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); + } + + private long countAllFinalizedDMPs() { + return countAllFinalizedDMPs(false); + } + + private long countAllFinalizedDMPs(boolean countNexus) { + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setStatus(1); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); + } + + private long countAllPublishedDMPs() { + return countAllPublishedDMPs(false); + } + + private long countAllPublishedDMPs(boolean countNexus) { + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setIsPublic(true); + criteria.setOnlyPublic(true); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); + } + + private long countAllDoiedDMPs() { + return countAllDoiedDMPs(false); + } + + private long countAllDoiedDMPs(boolean countNexus) { + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setHasDoi(true); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).count(); + } + + private long countAllDraftDMPsWithGrantId() { + return countAllDraftDMPsWithGrantId(false); + } + + private long countAllDraftDMPsWithGrantId(boolean countNexus) { + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setStatus(0); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); + } + + private long countAllFinalizedDMPsWithGrantId() { + return countAllFinalizedDMPsWithGrantId(false); + } + + private long countAllFinalizedDMPsWithGrantId(boolean countNexus) { + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setStatus(1); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); + } + + private long countAllPublishedDMPsWithGrantId() { + return countAllPublishedDMPsWithGrantId(false); + } + + private long countAllPublishedDMPsWithGrantId(boolean countNexus) { + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setIsPublic(true); + criteria.setOnlyPublic(true); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); + } + + private long countAllDoiedDMPsWithGrantId() { + return countAllDoiedDMPsWithGrantId(false); + } + + private long countAllDoiedDMPsWithGrantId(boolean countNexus) { + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setHasDoi(true); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria).groupBy((builder, root) -> root.get("grant")).count(); + } + + private long countAllResearchers() { + return countAllResearchers(false); + } + + private long countAllResearchers(boolean countNexus) { + ResearcherCriteria criteria = new ResearcherCriteria(); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao().getWithCriteria(criteria).count(); + } + + private long countAllProjects() { + return countAllProjects(false); + } + + private long countAllProjects(boolean countNexus) { + ProjectCriteria criteria = new ProjectCriteria(); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getProjectDao().getWithCritetia(criteria).count(); + } + + private long countAllFunders() { + return countAllFunders(false); + } + + private long countAllFunders(boolean countNexus) { + FunderCriteria criteria = new FunderCriteria(); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getFunderDao().getWithCritetia(criteria).count(); + } + + private long countAllGrants() { + return countAllGrants(false); + } + + private long countAllGrants(boolean countNexus) { + GrantCriteria criteria = new GrantCriteria(); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().getWithCriteria(criteria).count(); + } + + public long countAllDraftDatasets() { + return countAllDraftDatasets(false); + } + + public long countAllDraftDatasets(boolean countNexus) { + DatasetCriteria criteria = new DatasetCriteria(); + criteria.setStatus(0); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); + } + + public long countAllFinalizedDatasets() { + return countAllFinalizedDatasets(false); + } + + public long countAllFinalizedDatasets(boolean countNexus) { + DatasetCriteria criteria = new DatasetCriteria(); + criteria.setStatus(1); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); + } + + public long countAllPublicDatasets() { + return countAllPublicDatasets(false); + } + + public long countAllPublicDatasets(boolean countNexus) { + DatasetCriteria criteria = new DatasetCriteria(); + criteria.setIsPublic(true); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); + } + + public long countAllDatasetsWithDoi() { + return countAllDatasetsWithDoi(false); + } + + public long countAllDatasetsWithDoi(boolean countNexus) { + DatasetCriteria criteria = new DatasetCriteria(); + criteria.setHasDoi(true); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(criteria).count(); + } + + public long countAllDraftTemplates() { + return countAllDraftTemplates(false); + } + + public long countAllDraftTemplates(boolean countNexus) { + DatasetProfileCriteria criteria = new DatasetProfileCriteria(); + criteria.setStatus(0); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).count(); + } + + public long countAllFinalizedTemplates() { + return countAllFinalizedTemplates(false); + } + + public long countAllFinalizedTemplates(boolean countNexus) { + DatasetProfileCriteria criteria = new DatasetProfileCriteria(); + criteria.setStatus(1); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + return apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).count(); + } + + @Transactional + public long countAllUsedTemplates() { + return countAllUsedTemplates(false); + } + + @Transactional + public long countAllUsedTemplates(boolean countNexus) { + DatasetProfileCriteria criteria = new DatasetProfileCriteria(); + criteria.setStatus(1); + criteria.setAllVersions(false); + if (countNexus) criteria.setPeriodStart(getNexusDate()); + List descriptionTemplates = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().getWithCriteria(criteria).withFields(Collections.singletonList("id")).toList(); + DatasetCriteria datasetCriteria = new DatasetCriteria(); + datasetCriteria.setDatasetTemplates(descriptionTemplates.stream().map(DescriptionTemplate::getId).collect(Collectors.toList())); + return apiContext.getOperationsContext().getDatabaseRepository().getDatasetDao().getWithCriteria(datasetCriteria).select(root -> root.getProfile().getId()).stream().distinct().count(); + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/NotificationManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/NotificationManager.java new file mode 100644 index 000000000..f9c11811b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/NotificationManager.java @@ -0,0 +1,124 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.enumeration.notification.ActiveStatus; +import eu.eudat.old.data.enumeration.notification.NotifyState; +import eu.eudat.old.logic.services.utilities.MailService; +import eu.eudat.old.data.entities.Notification; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.mail.SimpleMail; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import javax.mail.MessagingException; +import javax.transaction.Transactional; +import java.io.IOException; +import java.util.*; + +@Component +public class NotificationManager { + private static final Logger logger = LoggerFactory.getLogger(NotificationManager.class); + + private ApiContext apiContext; + private Environment environment; + private MailService mailService; + + @Autowired + public NotificationManager(ApiContext apiContext, Environment environment, MailService mailService) { + this.apiContext = apiContext; + this.environment = environment; + this.mailService = mailService; + } + + @Transactional + public void sendNotification(Notification notification) throws Exception { + if (notification.getNotifyState() == NotifyState.ERROR) { + if (notification.getRetryCount() == null) { + notification.setRetryCount(0); + } + notification.setRetryCount(notification.getRetryCount() + 1); + if (notification.getRetryCount() >= this.environment.getProperty("notification.maxRetries", Integer.class)) { + notification.setIsActive(ActiveStatus.INACTIVE); + notification.setUpdatedAt(new Date()); + return; + } + } + notification.setNotifyState(NotifyState.PROCESSING); + notification.setNotifiedAt(new Date()); + notification.setUpdatedAt(new Date()); + try { + Map data = new ObjectMapper().readValue(notification.getData(), HashMap.class); + UserInfo userInfo = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(UUID.fromString(data.get("userId"))); + String subjectTemplate = ""; + String contentTemplate = ""; + + switch (notification.getType()) { + case DMP_MODIFIED: + case DATASET_MODIFIED: + subjectTemplate = this.environment.getProperty("notification.modified.subject"); + contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.modified.template")); + break; + case DMP_PUBLISH: + subjectTemplate = this.environment.getProperty("notification.publish.subject"); + contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.publish.template")); + break; + case DMP_FINALISED: + subjectTemplate = this.environment.getProperty("notification.finalised.subject"); + contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.finalised.template")); + break; + case DMP_MODIFIED_FINALISED: + case DATASET_MODIFIED_FINALISED: + subjectTemplate = this.environment.getProperty("notification.modifiedFinalised.subject"); + contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.modified_finalised.template")); + break; + } + + + switch (notification.getContactTypeHint()) { + case EMAIL: + this.sendEmailNotification(notification, userInfo, data, subjectTemplate, contentTemplate); + break; + } + }catch (Exception e) { + notification.setNotifyState(NotifyState.ERROR); + notification.setUpdatedAt(new Date()); + logger.error(e.getMessage(), e); + } + } + + private void sendEmailNotification(Notification notification, UserInfo userInfo, Map data, String subjectTemplate, String contentTemplate) throws IOException { + SimpleMail simpleMail = new SimpleMail(); + simpleMail.setFrom(this.environment.getProperty("mail.from")); + simpleMail.setSubject(makeSubject(data, subjectTemplate)); + simpleMail.setTo(notification.getContactHint()); + simpleMail.setContent(makeContent(data, notification, userInfo, contentTemplate)); + try { + mailService.sendSimpleMail(simpleMail); + notification.setNotifyState(NotifyState.SUCCEEDED); + notification.setUpdatedAt(new Date()); + } catch (MessagingException e) { + notification.setNotifyState(NotifyState.ERROR); + notification.setUpdatedAt(new Date()); + logger.error(e.getMessage(), e); + } + } + + private String makeSubject(Map data, String subjectTemplate) { + return subjectTemplate.replace("{name}", data.get("name")); + } + + private String makeContent(Map data, Notification notification, UserInfo userInfo, String template) { + String content = template; + content = content.replace("{recipient}", userInfo.getName()); + for (String key : data.keySet()) { + content = content.replace("{" + key +"}", data.get(key)); + } + content = content.replace("{host}", this.environment.getProperty("dmp.domain")); + content = content.replace("{reasonName}", notification.getUserId().getName()); + return content; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/OrganisationsManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/OrganisationsManager.java new file mode 100644 index 000000000..2283020c2 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/OrganisationsManager.java @@ -0,0 +1,112 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.query.items.table.organisations.OrganisationsTableRequest; +import eu.eudat.old.logic.builders.model.models.OrganisationBuilder; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.data.dao.entities.OrganisationDao; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.models.data.dmp.Organisation; +import eu.eudat.old.models.data.external.ExternalSourcesItemModel; +import eu.eudat.old.models.data.external.OrganisationsExternalSourcesModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +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 getPagedOrganisations(OrganisationsTableRequest organisationsTableRequest, Principal principal) throws Exception { + UserInfo userInfo = new UserInfo(); + userInfo.setId(principal.getId()); + OrganisationDao organisationDao = databaseRepository.getOrganisationDao(); + + QueryableList items = organisationDao.getWithCriteria(organisationsTableRequest.getCriteria()); + QueryableList authItems = organisationDao.getAuthenticated(items, userInfo); + QueryableList pagedItems = PaginationManager.applyPaging(authItems, organisationsTableRequest); + + List org = pagedItems.toList().stream().distinct().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList()); + DataTableData organisationDataTableData = new DataTableData<>(); + organisationDataTableData.setData(org); + organisationDataTableData.setTotalCount(pagedItems.count()); + + return organisationDataTableData; + } + + public DataTableData getPublicPagedOrganisations(OrganisationsTableRequest organisationsTableRequest) throws Exception { + organisationsTableRequest.getCriteria().setPublic(true); + OrganisationDao organisationDao = databaseRepository.getOrganisationDao(); + + QueryableList items = organisationDao.getWithCriteria(organisationsTableRequest.getCriteria()); + QueryableList pagedItems = PaginationManager.applyPaging(items, organisationsTableRequest); + + List org = pagedItems.toList().stream().distinct().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList()); + DataTableData organisationDataTableData = new DataTableData<>(); + organisationDataTableData.setData(org); + organisationDataTableData.setTotalCount(pagedItems.count()); + + return organisationDataTableData; + } + + public List getWithExternal(OrganisationsTableRequest organisationsTableRequest, Principal principal) throws Exception { + UserInfo userInfo = new UserInfo(); + userInfo.setId(principal.getId()); + OrganisationDao organisationDao = databaseRepository.getOrganisationDao(); + + QueryableList items = organisationDao.getWithCriteria(organisationsTableRequest.getCriteria()); + QueryableList authItems = organisationDao.getAuthenticated(items, userInfo); + QueryableList pagedItems = PaginationManager.applyPaging(authItems, organisationsTableRequest); + + List org = pagedItems.toList().stream().distinct().map(item -> new Organisation().fromDataModel(item)).collect(Collectors.toList()); + + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(organisationsTableRequest.getCriteria().getLabelLike()); + List> remoteRepos = apiContext.getOperationsContext().getRemoteFetcher().getOrganisations(externalUrlCriteria, null); + OrganisationsExternalSourcesModel organisationsExternalSourcesModel = new OrganisationsExternalSourcesModel().fromExternalItem(remoteRepos); + for (ExternalSourcesItemModel externalListingItem : organisationsExternalSourcesModel) { + Organisation organisation = apiContext.getOperationsContext().getBuilderFactory().getBuilder(OrganisationBuilder.class) + .name(externalListingItem.getName()) + .reference(externalListingItem.getRemoteId()) + .tag(externalListingItem.getTag()) + .key(externalListingItem.getKey()) + .build(); + org.add(organisation); + } + return org; + } + + public List getCriteriaWithExternal(String query, String type) throws HugeResultSet, NoURLFound { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = apiContext.getOperationsContext().getRemoteFetcher().getOrganisations(externalUrlCriteria, type); + OrganisationsExternalSourcesModel organisationsExternalSourcesModel = new OrganisationsExternalSourcesModel().fromExternalItem(remoteRepos); + List organisations = new LinkedList<>(); + for (ExternalSourcesItemModel externalListingItem : organisationsExternalSourcesModel) { + Organisation organisation = apiContext.getOperationsContext().getBuilderFactory().getBuilder(OrganisationBuilder.class) + .name(externalListingItem.getName()) + .reference(externalListingItem.getRemoteId()) + .tag(externalListingItem.getTag()) + .key(externalListingItem.getKey()) + .build(); + organisations.add(organisation); + } + return organisations.stream().distinct().collect(Collectors.toList()); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/PaginationManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/PaginationManager.java new file mode 100644 index 000000000..e3dac1724 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/PaginationManager.java @@ -0,0 +1,56 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.query.definition.TableQuery; +import eu.eudat.old.data.query.definition.helpers.ColumnOrderings; +import eu.eudat.old.data.query.definition.helpers.Ordering; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.queryable.queryableentity.DataEntity; + +import java.util.Arrays; +import java.util.Collection; + +public class PaginationManager { + + public static QueryableList applyPaging(QueryableList items, TableQuery tableRequest) throws Exception { + if (tableRequest.getOrderings() != null) applyOrder(items, tableRequest); + if (tableRequest.getLength() != null) items.take(tableRequest.getLength()); + if (tableRequest.getOffset() != null) items.skip(tableRequest.getOffset()); + if (tableRequest.getSelection() != null && tableRequest.getSelection().getFields() != null && tableRequest.getSelection().getFields().length > 0) + items.withFields(Arrays.asList(tableRequest.getSelection().getFields())); + return items; + } + + public static void applyOrder(QueryableList items, TableQuery tableRequest) throws Exception { + ColumnOrderings columnOrderings = tableRequest.getOrderings(); + for (Ordering ordering : columnOrderings.getFieldOrderings()) { + if (ordering.getOrderByType() == Ordering.OrderByType.ASC) + applyAscOrder(items, ordering); + if (ordering.getOrderByType() == Ordering.OrderByType.DESC) { + applyDescOrder(items, ordering); + } + } + return; + } + + private static void applyAscOrder(QueryableList items, Ordering ordering) { + if (ordering.getColumnType() == Ordering.ColumnType.COUNT) { + items.orderBy((builder, root) -> builder.asc(builder.size(root.get(ordering.getFieldName())))); + } else if (ordering.getColumnType() == Ordering.ColumnType.JOIN_COLUMN) { + String[] fields = ordering.getFieldName().split(":"); + items.orderBy((builder, root) -> builder.asc(root.get(fields[0]).get(fields[1]))); + } else { + items.orderBy((builder, root) -> builder.asc(root.get(ordering.getFieldName()))); + } + } + + private static void applyDescOrder(QueryableList items, Ordering ordering) { + if (ordering.getColumnType() == Ordering.ColumnType.COUNT) { + items.orderBy((builder, root) -> builder.desc(builder.size(root.get(ordering.getFieldName())))); + } else if (ordering.getColumnType() == Ordering.ColumnType.JOIN_COLUMN) { + String[] fields = ordering.getFieldName().split(":"); + items.orderBy((builder, root) -> builder.desc(root.get(fields[0]).get(fields[1]))); + } else { + items.orderBy((builder, root) -> builder.desc(root.get(ordering.getFieldName()))); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/PrefillingManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/PrefillingManager.java new file mode 100644 index 000000000..7e021465e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/PrefillingManager.java @@ -0,0 +1,86 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.logic.mapper.prefilling.PrefillingMapper; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.proxy.config.entities.PrefillingGet; +import eu.eudat.old.models.data.prefilling.Prefilling; +import eu.eudat.old.logic.proxy.config.entities.PrefillingConfig; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.datasetwizard.DatasetWizardModel; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.util.*; +import java.util.stream.Collectors; + +@Service +public class PrefillingManager { + + private final ApiContext apiContext; + private final ConfigLoader configLoader; + private final ObjectMapper objectMapper; + private final DatasetManager datasetManager; + private final LicenseManager licenseManager; + private final PrefillingMapper prefillingMapper; + + @Autowired + public PrefillingManager(ApiContext apiContext, ConfigLoader configLoader, DatasetManager datasetManager, LicenseManager licenseManager, PrefillingMapper prefillingMapper) { + this.apiContext = apiContext; + this.configLoader = configLoader; + this.prefillingMapper = prefillingMapper; + this.objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + this.datasetManager = datasetManager; + this.licenseManager = licenseManager; + } + + public List getPrefillings(String like) { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(); + externalUrlCriteria.setLike(like); + List prefillings = new ArrayList<>(); + List> map; + Map prefillingConfigs = configLoader.getExternalUrls().getPrefillings(); + for (PrefillingConfig prefillingConfig: prefillingConfigs.values()) { + map = apiContext.getOperationsContext().getRemoteFetcher().getExternalGeneric(externalUrlCriteria, prefillingConfig.getPrefillingSearch()); + prefillings.addAll(map.stream().map(submap -> objectMapper.convertValue(submap, Prefilling.class)).collect(Collectors.toList())); + if (prefillingConfig.getPrefillingSearch().getUrlConfig().isDataInListing()) { + List> mapData = apiContext.getOperationsContext().getRemoteFetcher().getExternalGenericWithData(externalUrlCriteria, prefillingConfig.getPrefillingSearch()); + for (int i = 0; i < mapData.size(); i++) { + prefillings.get(i).setData(mapData.get(i)); + } + prefillings = prefillings.stream().filter(prefilling -> prefilling.getData() != null).collect(Collectors.toList()); + } + } + return prefillings; + } + + public DatasetWizardModel getPrefilledDataset(String prefillId, String configId, UUID profileId) throws Exception { + PrefillingConfig prefillingConfig = configLoader.getExternalUrls().getPrefillings().get(configId); + PrefillingGet prefillingGet = prefillingConfig.getPrefillingGet(); + Map prefillingEntity = getSingle(prefillingGet.getUrl(), prefillId); + DescriptionTemplate descriptionTemplate = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(profileId); + return prefillingMapper.mapPrefilledEntityToDatasetWizard(prefillingEntity, prefillingGet, prefillingConfig.getType(), descriptionTemplate, datasetManager, licenseManager); + } + + public DatasetWizardModel getPrefilledDatasetUsingData(Map data, String configId, UUID profileId) throws Exception { + PrefillingConfig prefillingConfig = configLoader.getExternalUrls().getPrefillings().get(configId); + PrefillingGet prefillingGet = prefillingConfig.getPrefillingGet(); + DescriptionTemplate descriptionTemplate = apiContext.getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(profileId); + return prefillingMapper.mapPrefilledEntityToDatasetWizard(data, prefillingGet, prefillingConfig.getType(), descriptionTemplate, datasetManager, licenseManager); + } + + private Map getSingle(String url, String id) { + RestTemplate restTemplate = new RestTemplate(); + String parsedUrl = url.replace("{id}", id); + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + HttpEntity entity = new HttpEntity("", headers); + + return restTemplate.exchange(parsedUrl, HttpMethod.GET, entity, LinkedHashMap.class).getBody(); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ProjectManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ProjectManager.java new file mode 100644 index 000000000..6dbefc966 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ProjectManager.java @@ -0,0 +1,62 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.query.items.item.project.ProjectCriteriaRequest; +import eu.eudat.old.logic.builders.model.models.ProjectBuilder; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.logic.utilities.helpers.ListHelper; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.models.data.external.ProjectsExternalSourcesModel; +import eu.eudat.old.models.data.project.Project; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.proxy.fetching.RemoteFetcher; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.external.ExternalSourcesItemModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.queryable.QueryableList; +import org.springframework.stereotype.Component; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Component +public class ProjectManager { + + private ApiContext apiContext; + private RemoteFetcher remoteFetcher; + private ListHelper listHelper; + + public ProjectManager(ApiContext apiContext, ListHelper listHelper) { + this.apiContext = apiContext; + this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher(); + this.listHelper = listHelper; + } + + public List getCriteriaWithExternal(ProjectCriteriaRequest projectCriteria, Principal principal) throws HugeResultSet, NoURLFound { + UserInfo userInfo = new UserInfo(); + userInfo.setId(principal.getId()); + projectCriteria.getCriteria().setReference("dmp:"); + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getProjectDao().getWithCritetia(projectCriteria.getCriteria()); + QueryableList authItems = apiContext.getOperationsContext().getDatabaseRepository().getProjectDao().getAuthenticated(items, userInfo); + List projects = authItems.select(item -> new Project().fromDataModel(item)); + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(projectCriteria.getCriteria().getLike()); + List> remoteRepos = remoteFetcher.getProjects(externalUrlCriteria); + ProjectsExternalSourcesModel projectsExternalSourcesModel = new ProjectsExternalSourcesModel().fromExternalItem(remoteRepos); + for (ExternalSourcesItemModel externalListingItem : projectsExternalSourcesModel) { + Project project = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ProjectBuilder.class) + .reference(externalListingItem.getRemoteId()).label(externalListingItem.getName()) + .description(externalListingItem.getDescription()).uri(externalListingItem.getUri()) + .abbreviation(externalListingItem.getAbbreviation()).status(eu.eudat.old.data.entities.Project.Status.fromInteger(0)) + .key(externalListingItem.getKey()) + .source(externalListingItem.getTag()) + .build(); + + projects.add(project); + } + projects.sort(Comparator.comparing(Project::getLabel)); + projects = projects.stream().filter(listHelper.distinctByKey(Project::getLabel)).collect(Collectors.toList()); + return projects; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/PublicationManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/PublicationManager.java new file mode 100644 index 000000000..35e8ed69b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/PublicationManager.java @@ -0,0 +1,42 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.dao.criteria.DataRepositoryCriteria; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.publication.PublicationModel; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.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.Map; +import java.util.stream.Collectors; + +@Component +public class PublicationManager { + private ApiContext apiContext; + + @Autowired + public PublicationManager(ApiContext apiContext) { + this.apiContext = apiContext; + } + + public List getPublications(String query, String type) throws HugeResultSet, NoURLFound { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getPublications(externalUrlCriteria, type); + + DataRepositoryCriteria criteria = new DataRepositoryCriteria(); + if (!query.isEmpty()) criteria.setLike(query); + + List publicationModels = new LinkedList<>(); + + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + publicationModels.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, PublicationModel.class)).collect(Collectors.toList())); +// publicationModels = publicationModels.stream().filter(publicationModel -> publicationModel.getName().toLowerCase().contains(query.toLowerCase())).collect(Collectors.toList()); + return publicationModels; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/QuickWizardManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/QuickWizardManager.java new file mode 100644 index 000000000..27675dadc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/QuickWizardManager.java @@ -0,0 +1,132 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.data.dao.criteria.FunderCriteria; +import eu.eudat.old.data.dao.criteria.ProjectCriteria; +import eu.eudat.old.data.entities.*; +import eu.eudat.old.elastic.entities.Dmp; +import eu.eudat.old.logic.mapper.elastic.DmpMapper; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.data.dao.criteria.GrantCriteria; +import eu.eudat.old.models.data.dmp.DataManagementPlan; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.text.ParseException; +import java.util.UUID; + +@Component +public class QuickWizardManager { + + private ApiContext apiContext; + private DatabaseRepository databaseRepository; + private DatasetManager datasetManager; + + @Autowired + public QuickWizardManager(ApiContext apiContext, DatasetManager datasetManager) { + this.apiContext = apiContext; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + this.datasetManager = datasetManager; + } + + public Funder createOrUpdate(eu.eudat.old.models.data.funder.Funder funder, Principal principal) { + Funder funderEntity = funder.toDataModel(); + return databaseRepository.getFunderDao().createOrUpdate(funderEntity); + } + + public Grant createOrUpdate(eu.eudat.old.models.data.grant.Grant grant, Principal principal) throws ParseException, IOException { + Grant grantEntity = grant.toDataModel(); + grantEntity.setType(Grant.GrantType.INTERNAL.getValue()); + grantEntity.setCreationUser(databaseRepository.getUserInfoDao().find(principal.getId())); + return databaseRepository.getGrantDao().createOrUpdate(grantEntity); + } + + public Project createOrUpdate(eu.eudat.old.models.data.project.Project project, Principal principal) { + Project projectEntity = project.toDataModel(); + projectEntity.setCreationUser(databaseRepository.getUserInfoDao().find(principal.getId())); + return databaseRepository.getProjectDao().createOrUpdate(projectEntity); + } + + public DMP createOrUpdate(DataManagementPlan dataManagementPlan, Funder funderEntity, Principal principal) throws Exception { + DMP newDmp = dataManagementPlan.toDataModel(); + if (funderEntity != null) { + newDmp.getGrant().setFunder(funderEntity); + } + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + createFunderIfItDoesntExist(newDmp, user); + createGrantIfItDoesntExist(newDmp, user); + if (newDmp.getProject() == null) { + newDmp.setProject(new Project()); + newDmp.setProject(newDmp.getProject().projectFromGrant(newDmp.getGrant())); + } + createProjectIfItDoesntExist(newDmp, user); + + apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().createOrUpdate(newDmp.getGrant()); + DMP dmpret = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().createOrUpdate(newDmp); + if (dataManagementPlan.getAssociatedUsers().size() == 0) + assignUser(newDmp, user, apiContext); + + this.updateIndex(dmpret); + + return dmpret; + } + + private void updateIndex(DMP dmp) throws IOException { + DmpMapper mapper = new DmpMapper(apiContext, datasetManager); + Dmp elastic = mapper.toElastic(dmp); + apiContext.getOperationsContext().getElasticRepository().getDmpRepository().createOrUpdate(elastic); + } + + private void assignUser(DMP dmp, UserInfo userInfo, ApiContext apiContext) { + UserDMP userDMP = new UserDMP(); + userDMP.setDmp(dmp); + userDMP.setUser(userInfo); + userDMP.setRole(UserDMP.UserDMPRoles.OWNER.getValue()); + apiContext.getOperationsContext().getDatabaseRepository().getUserDmpDao().createOrUpdate(userDMP); + } + + private void createGrantIfItDoesntExist(DMP newDmp, UserInfo userInfo) { + if (newDmp.getGrant() != null) { + Grant grant = newDmp.getGrant(); + GrantCriteria criteria = new GrantCriteria(); + criteria.setReference(grant.getReference()); + Grant grantEntity = databaseRepository.getGrantDao().getWithCriteria(criteria).getSingleOrDefault(); + if (grantEntity != null) grant.setId(grantEntity.getId()); + else { + grant.setType(Grant.GrantType.EXTERNAL.getValue()); + databaseRepository.getGrantDao().createOrUpdate(grant); + } + } + } + + private void createFunderIfItDoesntExist(DMP newDmp, UserInfo userInfo) { + if (newDmp.getGrant().getFunder() != null) { + Funder funder = newDmp.getGrant().getFunder(); + FunderCriteria criteria = new FunderCriteria(); + criteria.setReference(funder.getReference()); + Funder funderEntity = databaseRepository.getFunderDao().getWithCritetia(criteria).getSingleOrDefault(); + if (funderEntity != null) funder.setId(funderEntity.getId()); + else { + funder.setType(Funder.FunderType.EXTERNAL.getValue()); + databaseRepository.getFunderDao().createOrUpdate(funder); + } + } + } + + private void createProjectIfItDoesntExist(DMP newDmp, UserInfo userInfo) { + if (newDmp.getProject() != null) { + Project project = newDmp.getProject(); + ProjectCriteria criteria = new ProjectCriteria(); + criteria.setReference(project.getReference()); + Project projectEntity = databaseRepository.getProjectDao().getWithCritetia(criteria).getSingleOrDefault(); + if (projectEntity != null) project.setId(projectEntity.getId()); + else { + if (project.getId() == null) project.setId(UUID.randomUUID()); + project.setType(Project.ProjectType.EXTERNAL.getValue()); + databaseRepository.getProjectDao().createOrUpdate(project); + } + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/RDAManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/RDAManager.java new file mode 100644 index 000000000..74170e3d7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/RDAManager.java @@ -0,0 +1,48 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.models.rda.Dmp; +import eu.eudat.old.models.rda.RDAModel; +import eu.eudat.old.models.rda.mapper.DmpRDAMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.transaction.Transactional; +import java.io.IOException; +import java.text.SimpleDateFormat; + +@Component +public class RDAManager { + + private DmpRDAMapper dmpRDAMapper; + + @Autowired + public RDAManager(DmpRDAMapper dmpRDAMapper) { + this.dmpRDAMapper = dmpRDAMapper; + } + + @Transactional + public String convertToRDA(DMP dmp) throws JsonProcessingException { + String result = ""; + + Dmp rdaDmp = dmpRDAMapper.toRDA(dmp); + + ObjectMapper mapper = new ObjectMapper(); + mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")); + + RDAModel model = new RDAModel(); + model.setDmp(rdaDmp); + result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(model); + + return result; + } + + public DMP convertToEntity(String json, String[] profiles) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + Dmp rda = mapper.readValue(json, RDAModel.class).getDmp(); + return dmpRDAMapper.toEntity(rda, profiles); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/RegistryManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/RegistryManager.java new file mode 100644 index 000000000..e574bd992 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/RegistryManager.java @@ -0,0 +1,57 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.dao.criteria.RegistryCriteria; +import eu.eudat.old.data.entities.Registry; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.registries.RegistryModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Component +public class RegistryManager { + + private ApiContext apiContext; + + @Autowired + public RegistryManager(ApiContext apiContext) { + this.apiContext = apiContext; + } + + public Registry create(RegistryModel registryModel, Principal principal) throws Exception { + if (registryModel.getLabel() == null || registryModel.getAbbreviation() == null || registryModel.getUri() == null) { + throw new Exception("Missing mandatory entity."); + } + Registry registry = registryModel.toDataModel(); + registry.getCreationUser().setId(principal.getId()); + return apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao().createOrUpdate(registry); + } + + public List getRegistries(String query, String type, Principal principal) throws HugeResultSet, NoURLFound { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getRegistries(externalUrlCriteria, type); + + RegistryCriteria criteria = new RegistryCriteria(); + if (!query.isEmpty()) criteria.setLike(query); + criteria.setCreationUserId(principal.getId()); + List registryModels = new LinkedList<>(); + if (type.equals("")) { + List registryList = (this.apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao().getWithCriteria(criteria)).toList(); + registryModels = registryList.stream().map(item -> new RegistryModel().fromDataModel(item)).collect(Collectors.toList()); + } + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + registryModels.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, RegistryModel.class)).collect(Collectors.toList())); + + return registryModels; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ResearcherManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ResearcherManager.java new file mode 100644 index 000000000..b6399b19b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ResearcherManager.java @@ -0,0 +1,75 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.external.ResearchersExternalSourcesModel; +import eu.eudat.old.models.data.researcher.Researcher; +import eu.eudat.old.logic.builders.model.models.ResearcherBuilder; +import eu.eudat.old.models.data.external.ExternalSourcesItemModel; +import eu.eudat.old.data.query.items.item.researcher.ResearcherCriteriaRequest; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.proxy.fetching.RemoteFetcher; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.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 { + + private ApiContext apiContext; + private RemoteFetcher remoteFetcher; + private ConfigLoader configLoader; + + @Autowired + public ResearcherManager(ApiContext apiContext, ConfigLoader configLoader) { + this.apiContext = apiContext; + this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher(); + this.configLoader = configLoader; + } + + public eu.eudat.old.data.entities.Researcher create(Researcher researcher, Principal principal) throws Exception { + eu.eudat.old.data.entities.Researcher researcherEntity = researcher.toDataModel(); + researcherEntity.setCreationUser(apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId())); + return apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao().createOrUpdate(researcherEntity); + } + + public List getCriteriaWithExternal(ResearcherCriteriaRequest researcherCriteriaRequest, Principal principal) throws HugeResultSet, NoURLFound { + + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao().getWithCriteria(researcherCriteriaRequest.getCriteria()); + items.where((builder, root) -> builder.equal(root.get("creationUser").get("id"), principal.getId())); + List researchers = items.select(item -> new eu.eudat.old.models.data.dmp.Researcher().fromDataModel(item)); + researchers = researchers.stream().filter(item -> item.getKey().equals("Internal")).collect(Collectors.toList()); + Map keyToSourceMap = configLoader.getKeyToSourceMap(); + for (eu.eudat.old.models.data.dmp.Researcher item : researchers) { + if (item.getKey().equals("Internal")) + item.setTag(item.getKey()); + else + item.setTag(keyToSourceMap.get(item.getKey())); + } + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(researcherCriteriaRequest.getCriteria().getName()); + List> remoteRepos = remoteFetcher.getResearchers(externalUrlCriteria,null); + ResearchersExternalSourcesModel researchersExternalSourcesModel = new ResearchersExternalSourcesModel().fromExternalItem(remoteRepos); + for (ExternalSourcesItemModel externalListingItem : researchersExternalSourcesModel) { + eu.eudat.old.models.data.dmp.Researcher researcher = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ResearcherBuilder.class) + .label(externalListingItem.getAbbreviation()) + .id(externalListingItem.getId()) + .reference(externalListingItem.getRemoteId()) + .name(externalListingItem.getName()) + .tag(externalListingItem.getTag()) + .key(externalListingItem.getKey()) + .build(); + researchers.add(researcher); + } + return researchers.stream().distinct().collect(Collectors.toList()); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ServiceManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ServiceManager.java new file mode 100644 index 000000000..1eac63d46 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ServiceManager.java @@ -0,0 +1,54 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.dao.criteria.ServiceCriteria; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.data.entities.Service; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.services.ServiceModel; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Component +public class ServiceManager { + + private ApiContext apiContext; + + @Autowired + public ServiceManager(ApiContext apiContext) { + this.apiContext = apiContext; + } + + public Service create(ServiceModel serviceModel, Principal principal) throws Exception { + Service service = serviceModel.toDataModel(); + service.getCreationUser().setId(principal.getId()); + return apiContext.getOperationsContext().getDatabaseRepository().getServiceDao().createOrUpdate(service); + } + + public List getServices(String query, String type, Principal principal) throws HugeResultSet, NoURLFound { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getServices(externalUrlCriteria, type); + + ServiceCriteria criteria = new ServiceCriteria(); + if (!query.isEmpty()) criteria.setLike(query); + criteria.setCreationUserId(principal.getId()); + List serviceModels = new LinkedList<>(); + if (type.equals("")) { + List serviceList = (this.apiContext.getOperationsContext().getDatabaseRepository().getServiceDao().getWithCriteria(criteria)).toList(); + serviceModels = serviceList.stream().map(item -> new ServiceModel().fromDataModel(item)).collect(Collectors.toList()); + } + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + serviceModels.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, ServiceModel.class)).collect(Collectors.toList())); + + return serviceModels; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/TaxonomyManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/TaxonomyManager.java new file mode 100644 index 000000000..eaed2fbb4 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/TaxonomyManager.java @@ -0,0 +1,43 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.dao.criteria.DataRepositoryCriteria; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.models.data.taxonomy.TaxonomyModel; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.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.Map; +import java.util.stream.Collectors; + + +@Component +public class TaxonomyManager { + private ApiContext apiContext; + + @Autowired + public TaxonomyManager(ApiContext apiContext) { + this.apiContext = apiContext; + } + + public List getTaxonomies(String query, String type) throws HugeResultSet, NoURLFound { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); + List> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getTaxonomies(externalUrlCriteria, type); + + DataRepositoryCriteria criteria = new DataRepositoryCriteria(); + if (!query.isEmpty()) criteria.setLike(query); + + List taxonomyModels = new LinkedList<>(); + + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + taxonomyModels.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, TaxonomyModel.class)).collect(Collectors.toList())); + taxonomyModels = taxonomyModels.stream().filter(licenseModel -> licenseModel.getName().toLowerCase().contains(query.toLowerCase())).collect(Collectors.toList()); + return taxonomyModels; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/UnlinkEmailConfirmationManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/UnlinkEmailConfirmationManager.java new file mode 100644 index 000000000..4b7035f2b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/UnlinkEmailConfirmationManager.java @@ -0,0 +1,88 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.entities.Credential; +import eu.eudat.old.data.entities.EmailConfirmation; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.exceptions.emailconfirmation.HasConfirmedEmailException; +import eu.eudat.old.exceptions.emailconfirmation.TokenExpiredException; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.operations.DatabaseRepository; +import eu.eudat.old.models.data.security.Principal; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.transaction.Transactional; +import java.util.*; + +@Component +public class UnlinkEmailConfirmationManager { + + private static Logger logger = LoggerFactory.getLogger(UnlinkEmailConfirmationManager.class); + + private ApiContext apiContext; + private DatabaseRepository databaseRepository; + + @Autowired + public UnlinkEmailConfirmationManager(ApiContext apiContext) { + this.apiContext = apiContext; + this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository(); + } + + @Transactional + public void confirmEmail(String token) throws TokenExpiredException, HasConfirmedEmailException { + EmailConfirmation loginConfirmationEmail = apiContext.getOperationsContext() + .getDatabaseRepository().getLoginConfirmationEmailDao().asQueryable() + .where((builder, root) -> builder.equal(root.get("token"), UUID.fromString(token))).getSingle(); + + if (loginConfirmationEmail.getExpiresAt().compareTo(new Date()) < 0) + throw new TokenExpiredException("Token has expired."); + + if(loginConfirmationEmail.getIsConfirmed()) + throw new HasConfirmedEmailException("Email is already confirmed."); + +// UserInfo userAskingForUnlink = databaseRepository.getUserInfoDao().asQueryable() +// .where((builder, root) -> builder.equal(root.get("id"), loginConfirmationEmail.getUserId())).getSingle(); + + try { + Map map = new ObjectMapper().readValue(loginConfirmationEmail.getData(), new TypeReference>() {}); + String emailTobeUnlinked = (String) map.get("email"); + Integer provider = Integer.valueOf((String) map.get("provider")); + + unlinkUser(emailTobeUnlinked, provider); + + loginConfirmationEmail.setIsConfirmed(true); + databaseRepository.getLoginConfirmationEmailDao().createOrUpdate(loginConfirmationEmail); + } + catch (Exception e) { + logger.error(e.getMessage(), e); + } + } + + @Transactional + private void unlinkUser(String emailTobeUnlinked, Integer provider){ + Credential credential = databaseRepository.getCredentialDao().asQueryable() + .where((builder, root) -> builder.and(builder.equal(root.get("email"), emailTobeUnlinked), builder.equal(root.get("provider"), provider))).getSingle(); + if(credential != null) { + databaseRepository.getCredentialDao().delete(credential); + } + } + + public void sendConfirmationEmail(String email, Principal principal, UUID userId, Integer provider) { + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + + if (user.getEmail() != null && !user.getEmail().equals(email)) { + apiContext.getUtilitiesService().getConfirmationEmailService().createUnlinkConfirmationEmail( + databaseRepository.getLoginConfirmationEmailDao(), + apiContext.getUtilitiesService().getMailService(), + email, + userId, + principal, + provider + ); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/UserManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/UserManager.java new file mode 100644 index 000000000..1a68a00ff --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/UserManager.java @@ -0,0 +1,232 @@ +package eu.eudat.old.logic.managers; + +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.dao.entities.UserInfoDao; +import eu.eudat.old.data.entities.*; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.exceptions.security.UnauthorisedException; +import eu.eudat.old.logic.security.customproviders.Zenodo.ZenodoCustomProvider; +import eu.eudat.old.logic.security.validators.zenodo.helpers.ZenodoResponseToken; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.logic.utilities.builders.XmlBuilder; +import eu.eudat.old.models.HintedModelFactory; +import eu.eudat.old.models.data.doi.DOIRequest; +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel; +import eu.eudat.old.models.data.helpers.common.DataTableData; +import eu.eudat.old.models.data.login.Credentials; +import eu.eudat.old.models.data.principal.PrincipalModel; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.user.composite.DatasetProfile; +import eu.eudat.old.models.data.userinfo.UserCredential; +import eu.eudat.old.models.data.userinfo.UserListingModel; +import eu.eudat.old.models.data.userinfo.UserProfile; +import eu.eudat.old.queryable.QueryableList; +import eu.eudat.old.types.Authorities; +import eu.eudat.old.data.dao.criteria.DataManagementPlanCriteria; +import eu.eudat.old.data.query.items.table.userinfo.UserInfoTableRequestItem; +import eu.eudat.old.logic.builders.entity.UserRoleBuilder; +import eu.eudat.old.logic.builders.model.models.DataTableDataBuilder; +import eu.eudat.old.logic.security.customproviders.Zenodo.ZenodoAccessType; +import eu.eudat.old.models.data.dmp.DataManagementPlan; + +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.time.Instant; +import java.util.*; +import java.util.stream.Collectors; + +@Component +public class UserManager { + private static final Logger logger = LoggerFactory.getLogger(UserManager.class); + + private ApiContext apiContext; + private ZenodoCustomProvider zenodoCustomProvider; + private Environment environment; + + @Autowired + public UserManager(ApiContext apiContext, ZenodoCustomProvider zenodoCustomProvider, Environment environment) { + this.apiContext = apiContext; + this.zenodoCustomProvider = zenodoCustomProvider; + this.environment = environment; + } + + public DatasetProfile generateDatasetProfileModel(DescriptionTemplate profile) { + Document viewStyleDoc = XmlBuilder.fromXml(profile.getDefinition()); + Element root = (Element) viewStyleDoc.getDocumentElement(); + ViewStyleModel viewstyle = new ViewStyleModel().fromXml(root); + + DatasetProfile datasetprofile = new DatasetProfile(); + datasetprofile.buildProfile(viewstyle); + + return datasetprofile; + } + + public DataTableData getPaged(UserInfoTableRequestItem userInfoTableRequestItem) throws Exception { + QueryableList users = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().getWithCriteria(userInfoTableRequestItem.getCriteria()).withHint(HintedModelFactory.getHint(UserListingModel.class)); + QueryableList pagedUsers = PaginationManager.applyPaging(users, userInfoTableRequestItem); + + List modelUsers = pagedUsers.select(item -> new UserListingModel().fromDataModel(item)); + return apiContext.getOperationsContext().getBuilderFactory().getBuilder(DataTableDataBuilder.class).totalCount(users.count()).data(modelUsers).build(); + } + + public List getCredentials(UUID userId) { + List results = new ArrayList<>(); + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userId); + List credentials = apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().asQueryable().where((builder, root) -> builder.equal(root.get("userInfo"), user)).toList(); + credentials.forEach(credential -> { + UserCredential userCredential = new UserCredential(); + userCredential.setEmail(credential.getEmail()); + userCredential.setProvider(credential.getProvider()); + results.add(userCredential); + }); + return results; + } + + public UserProfile getSingle(UUID userId) throws Exception { + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(userId); + UserProfile profile = new UserProfile().fromDataModel(user); + List roles = new LinkedList<>(); + DataManagementPlanCriteria criteria = new DataManagementPlanCriteria(); + criteria.setAllVersions(false); + QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(criteria); + List dmps = apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getAuthenticated(items, userId, roles).take(5).toList(); + profile.setAssociatedDmps(dmps.stream().map(x -> new DataManagementPlan().fromDataModel(x)).collect(Collectors.toList())); + return profile; + } + + public void editRoles(UserListingModel user) { + UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(user.getId()); + userInfo.getUserRoles().stream().forEach(item -> apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().delete(item)); + for (Integer role : user.getAppRoles()) { + UserRole userRole = apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserRoleBuilder.class).role(role).userInfo(userInfo).build(); + apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(userRole); + } + } + + public void updateSettings(Map settings, Principal principal) throws IOException { + UserInfo userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()); + apiContext.getOperationsContext().getDatabaseRepository().detachEntity(userInfo); + HashMap result = + new ObjectMapper().readValue(userInfo.getAdditionalinfo(), HashMap.class); + userInfo.setName(settings.entrySet().stream().filter(entry -> entry.getKey().equals("name")).filter(Objects::nonNull).map(entry -> entry.getValue().toString()).findFirst().orElse(userInfo.getName())); + settings.remove("name"); + result.putAll(settings); + userInfo.setAdditionalinfo(new JSONObject(result).toString()); + apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao() + .createOrUpdate(userInfo); + } + + public PrincipalModel authenticate(AuthenticationService authenticationServiceImpl, Credentials credentials) throws NullEmailException { + Principal principal = authenticationServiceImpl.Touch(credentials); + if (principal == null) throw new UnauthorisedException("Could not Sign In User"); + PrincipalModel principalModel = PrincipalModel.fromEntity(principal); + return principalModel; + } + + public DataTableData getCollaboratorsPaged(UserInfoTableRequestItem userInfoTableRequestItem, Principal principal) throws Exception { + UserInfoDao userInfoDao = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao(); + QueryableList users = userInfoDao.getWithCriteria(userInfoTableRequestItem.getCriteria()); + + List colaborators = userInfoDao.getAuthenticated(users, principal.getId()) + .withHint(HintedModelFactory.getHint(UserListingModel.class)) + .select(colaborator -> new UserListingModel().fromDataModel(colaborator)); + + DataTableData dataTableData = new DataTableData<>(); + dataTableData.setData(colaborators); + dataTableData.setTotalCount((long) colaborators.size()); + return dataTableData; + } + + public void registerDOIToken(DOIRequest doiRequest, Principal principal) throws IOException { + ZenodoResponseToken responseToken = this.zenodoCustomProvider.getAccessToken(ZenodoAccessType.AUTHORIZATION_CODE, + doiRequest.getZenodoRequest().getCode(), this.environment.getProperty("zenodo.login.client_id"), + this.environment.getProperty("zenodo.login.client_secret"), doiRequest.getRedirectUri()); + Map settings = new HashMap<>(); + settings.put("zenodoEmail", responseToken.getEmail()); + settings.put("zenodoRefresh", responseToken.getRefreshToken()); + settings.put("zenodoToken", responseToken.getAccessToken()); + settings.put("expirationDate", Instant.now().plusSeconds(responseToken.getExpiresIn()).toEpochMilli()); + this.updateSettings(settings, principal); + } + + public void deleteDOIToken(Principal principal) throws IOException { + Map settings = new HashMap<>(); + settings.put("zenodoEmail", ""); + settings.put("zenodoRefresh", ""); + settings.put("zenodoToken", ""); + settings.put("expirationDate", 0); + this.updateSettings(settings, principal); + } + + public ResponseEntity exportToCsv(Principal principal) throws IOException { + if (!principal.getAuthz().contains(Authorities.ADMIN)) + throw new UnauthorisedException(); + + List users = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().toList(); + StringBuilder resultBuilder = new StringBuilder(); + resultBuilder.append("User Id").append(",").append("User Name").append(",").append("User Email").append("\n"); + users.stream().forEach(user -> resultBuilder.append(user.getId().toString()).append(",") + .append(user.getName()).append(",") + .append(user.getEmail()).append("\n")); + String result = resultBuilder.toString(); + String fileName = "Users_dump";//dmp.getLabel(); + fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", ""); + String uuid = UUID.randomUUID().toString(); + File file = new File(this.environment.getProperty("temp.temp") + uuid + ".csv"); + OutputStream output = new FileOutputStream(file); + try { +// mapper.writeValue(file, rdaExportModel); + output.write(result.getBytes()); + output.flush(); + output.close(); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + + 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=" + fileName + ".csv"); + 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 UserProfile getFromEmail(String email) { + UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().where((builder, root) -> builder.equal(root.get("email"), email)).getSingle(); + return new UserProfile().fromDataModel(user); + } + + public Long countActiveUsers(){ + return apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().asQueryable().where(((builder, root) -> builder.greaterThan(root.get("expiresAt"), new Date()))).count(); + } + + public Long countAllUsers(){ + return apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().count(); + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ValidationManager.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ValidationManager.java new file mode 100644 index 000000000..779138f43 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/managers/ValidationManager.java @@ -0,0 +1,31 @@ +package eu.eudat.old.logic.managers; + +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.proxy.fetching.RemoteFetcher; +import eu.eudat.old.models.data.security.Principal; + +@Component +public class ValidationManager { + + private RemoteFetcher remoteFetcher; + + @Autowired + public ValidationManager(RemoteFetcher remoteFetcher) { + super(); + this.remoteFetcher = remoteFetcher; + } + + public Boolean validateIdentifier(String identifier, String type, Principal principal) throws NoURLFound, HugeResultSet { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(identifier); + Integer count = this.remoteFetcher.findEntries(externalUrlCriteria, type); + return principal != null && count > 0; + } + + + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/CollaboratorMapper.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/CollaboratorMapper.java new file mode 100644 index 000000000..9ab132cd7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/CollaboratorMapper.java @@ -0,0 +1,15 @@ +package eu.eudat.old.logic.mapper.elastic; + +import eu.eudat.old.elastic.entities.Collaborator; +import eu.eudat.old.data.entities.UserInfo; + +public class CollaboratorMapper { + + public static Collaborator toElastic(UserInfo user, Integer role) { + Collaborator elastic = new Collaborator(); + elastic.setId(user.getId().toString()); + elastic.setName(user.getName()); + elastic.setRole(role); + return elastic; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/DatasetMapper.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/DatasetMapper.java new file mode 100644 index 000000000..0752509af --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/DatasetMapper.java @@ -0,0 +1,86 @@ +package eu.eudat.old.logic.mapper.elastic; + +import eu.eudat.old.elastic.criteria.DatasetCriteria; +import eu.eudat.old.logic.utilities.helpers.StreamDistinctBy; +import eu.eudat.old.data.dao.criteria.DataManagementPlanCriteria; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.elastic.entities.Dataset; +import eu.eudat.old.elastic.entities.Tag; +import eu.eudat.old.logic.managers.DatasetManager; +import eu.eudat.old.logic.services.ApiContext; + +import java.util.*; +import java.util.stream.Collectors; + +public class DatasetMapper { + + private final ApiContext apiContext; + private final DatasetManager datasetManager; + + public DatasetMapper(ApiContext apiContext, DatasetManager datasetManager) { + this.apiContext = apiContext; + this.datasetManager = datasetManager; + } + + public Dataset toElastic(eu.eudat.old.data.entities.Dataset dataset, List tags) throws Exception { + if (dataset.getProfile() == null) { + return null; + } + Dataset elastic = new Dataset(); + elastic.setId(dataset.getId().toString()); + if (tags != null && !tags.isEmpty()) { + DatasetCriteria criteria = new DatasetCriteria(); + criteria.setTags(tags); + criteria.setHasTags(true); + List tags1 = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().query(criteria).stream().map(Dataset::getTags).flatMap(Collection::stream) + .filter(StreamDistinctBy.distinctByKey(Tag::getId)).filter(tag -> tags.stream().anyMatch(tag1 -> tag1.getName().equals(tag.getName()))).collect(Collectors.toList()); + if (tags1.isEmpty()) { + tags.forEach(tag -> tag.setId(UUID.randomUUID().toString())); + elastic.setTags(tags); + } else { + if (tags1.size() < tags.size()) { + tags.stream().filter(tag -> tag.getId() == null || tag.getId().equals("")).forEach(tag -> tags1.add(new Tag(UUID.randomUUID().toString(), tag.getName()))); + } + elastic.setTags(tags1); + } + } + elastic.setLabel(dataset.getLabel()); + elastic.setDescription(dataset.getDescription()); + elastic.setTemplate(dataset.getProfile().getId()); + elastic.setStatus(dataset.getStatus()); + elastic.setDmp(dataset.getDmp().getId()); + elastic.setGroup(dataset.getDmp().getGroupId()); + if (dataset.getDmp().getGrant() != null) { + elastic.setGrant(dataset.getDmp().getGrant().getId()); + } + elastic.setCreated(dataset.getCreated()); + elastic.setModified(dataset.getModified()); + elastic.setFinalizedAt(dataset.getFinalizedAt()); + if (dataset.getDmp().getUsers() != null) { + elastic.setCollaborators(dataset.getDmp().getUsers().stream().map(user -> CollaboratorMapper.toElastic(user.getUser(), user.getRole())).collect(Collectors.toList())); + } + DataManagementPlanCriteria dmpCriteria = new DataManagementPlanCriteria(); + dmpCriteria.setAllVersions(true); + dmpCriteria.setGroupIds(Collections.singletonList(dataset.getDmp().getGroupId())); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dmpCriteria).toList().stream() + .max(Comparator.comparing(DMP::getVersion)).ifPresent(dmp -> elastic.setLastVersion(dmp.getId().equals(dataset.getDmp().getId()))); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dmpCriteria).toList().stream().filter(DMP::isPublic) + .max(Comparator.comparing(DMP::getVersion)).ifPresent(dmp -> elastic.setLastPublicVersion(dmp.getId().equals(dataset.getDmp().getId()))); + if (elastic.getLastVersion() == null) { + elastic.setLastVersion(true); + } + if (elastic.getLastPublicVersion() == null) { + elastic.setLastPublicVersion(false); + } + if (dataset.getDmp().getOrganisations() != null) { + elastic.setOrganizations(dataset.getDmp().getOrganisations().stream().map(OrganizationMapper::toElastic).collect(Collectors.toList())); + } + elastic.setPublic(dataset.getDmp().isPublic()); + if (dataset.getDmp().getGrant() != null) { + elastic.setGrantStatus(dataset.getDmp().getGrant().getStatus()); + } + elastic.setFormData(datasetManager.getWordDocumentText(dataset)); + + return elastic; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/DatasetTemplateMapper.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/DatasetTemplateMapper.java new file mode 100644 index 000000000..bafda8be6 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/DatasetTemplateMapper.java @@ -0,0 +1,25 @@ +package eu.eudat.old.logic.mapper.elastic; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.elastic.entities.DatasetTempalate; +import eu.eudat.old.data.entities.DMPDatasetProfile; + +import java.util.HashMap; +import java.util.Map; + +public class DatasetTemplateMapper { + + public static DatasetTempalate toElastic(DMPDatasetProfile profile) { + DatasetTempalate elastic = new DatasetTempalate(); + elastic.setId(profile.getDatasetprofile().getId()); + elastic.setName(profile.getDatasetprofile().getLabel()); + try { + elastic.setData(new ObjectMapper().readValue(profile.getData(), new TypeReference>() {})); + } + catch (Exception e){ + elastic.setData(new HashMap<>()); + } + return elastic; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/DmpMapper.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/DmpMapper.java new file mode 100644 index 000000000..cb69544b7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/DmpMapper.java @@ -0,0 +1,91 @@ +package eu.eudat.old.logic.mapper.elastic; + +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.elastic.entities.Dataset; +import eu.eudat.old.elastic.entities.Dmp; +import eu.eudat.old.elastic.entities.Tag; +import eu.eudat.old.logic.managers.DatasetManager; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.data.dao.criteria.DataManagementPlanCriteria; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public class DmpMapper { + private static final Logger logger = LoggerFactory.getLogger(DmpMapper.class); + + private final ApiContext apiContext; + private final DatasetManager datasetManager; + private final DatasetMapper datasetMapper; + + public DmpMapper(ApiContext apiContext, DatasetManager datasetManager) { + this.apiContext = apiContext; + this.datasetManager = datasetManager; + this.datasetMapper = new DatasetMapper(apiContext, datasetManager); + } + + public Dmp toElastic(DMP dmp) { + Dmp elastic = new Dmp(); + elastic.setId(dmp.getId()); + elastic.setGroupId(dmp.getGroupId()); + if (dmp.getUsers() != null) { + elastic.setCollaborators(dmp.getUsers().stream().map(user -> CollaboratorMapper.toElastic(user.getUser(), user.getRole())).collect(Collectors.toList())); + } + elastic.setDescription(dmp.getDescription()); + if (dmp.getGrant() != null) { + elastic.setGrant(dmp.getGrant().getId()); + } + elastic.setLabel(dmp.getLabel()); + elastic.setPublic(dmp.isPublic()); + elastic.setStatus(dmp.getStatus()); + elastic.setCreated(dmp.getCreated()); + elastic.setModified(dmp.getModified()); + elastic.setFinalizedAt(dmp.getFinalizedAt()); + elastic.setPublishedAt(dmp.getPublishedAt()); + DataManagementPlanCriteria dmpCriteria = new DataManagementPlanCriteria(); + dmpCriteria.setAllVersions(true); + dmpCriteria.setGroupIds(Collections.singletonList(dmp.getGroupId())); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dmpCriteria).toList().stream() + .max(Comparator.comparing(DMP::getVersion)).ifPresent(dmp1 -> elastic.setLastVersion(dmp1.getId().equals(dmp.getId()))); + apiContext.getOperationsContext().getDatabaseRepository().getDmpDao().getWithCriteria(dmpCriteria).toList().stream().filter(DMP::isPublic) + .max(Comparator.comparing(DMP::getVersion)).ifPresent(dmp1 -> elastic.setLastPublicVersion(dmp1.getId().equals(dmp.getId()))); + if (elastic.getLastVersion() == null) { + elastic.setLastVersion(false); + } + if (elastic.getLastPublicVersion() == null) { + elastic.setLastPublicVersion(false); + } + if (dmp.getDataset() != null) { + + elastic.setDatasets(dmp.getDataset().stream().filter(dataset -> dataset.getId() != null).map(dataset -> { + List tags = null; + try { + Dataset dataset1 = apiContext.getOperationsContext().getElasticRepository().getDatasetRepository().findDocument(dataset.getId().toString()); + if (dataset1 != null) { + tags = dataset1.getTags(); + } + dataset.setDmp(dmp); + return datasetMapper.toElastic(dataset, tags); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + return null; + }).filter(Objects::nonNull).collect(Collectors.toList())); + } + if (dmp.getAssociatedDmps() != null) { + elastic.setTemplates(dmp.getAssociatedDmps().stream().map(DatasetTemplateMapper::toElastic).collect(Collectors.toList())); + } + if (dmp.getOrganisations() != null) { + elastic.setOrganizations(dmp.getOrganisations().stream().map(OrganizationMapper::toElastic).collect(Collectors.toList())); + } + if (dmp.getGrant() != null) { + elastic.setGrantStatus(dmp.getGrant().getStatus()); + } + return elastic; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/OrganizationMapper.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/OrganizationMapper.java new file mode 100644 index 000000000..33e37a851 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/OrganizationMapper.java @@ -0,0 +1,14 @@ +package eu.eudat.old.logic.mapper.elastic; + +import eu.eudat.old.data.entities.Organisation; +import eu.eudat.old.elastic.entities.Organization; + +public class OrganizationMapper { + + public static Organization toElastic(Organisation organisation) { + Organization elastic = new Organization(); + elastic.setId(organisation.getId().toString()); + elastic.setName(organisation.getLabel()); + return elastic; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/criteria/DmpCriteriaMapper.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/criteria/DmpCriteriaMapper.java new file mode 100644 index 000000000..2b2a40deb --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/elastic/criteria/DmpCriteriaMapper.java @@ -0,0 +1,59 @@ +package eu.eudat.old.logic.mapper.elastic.criteria; + +import eu.eudat.old.data.entities.Grant; +import eu.eudat.old.data.query.definition.helpers.Ordering; +import eu.eudat.old.elastic.criteria.DmpCriteria; +import eu.eudat.old.elastic.criteria.SortCriteria; +import eu.eudat.old.data.dao.criteria.DataManagementPlanCriteria; +import eu.eudat.old.data.query.definition.helpers.ColumnOrderings; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +public class DmpCriteriaMapper { + + public static DmpCriteria toElasticCriteria(DataManagementPlanCriteria criteria, UUID principalID) { + DmpCriteria elastic = new DmpCriteria(); + + elastic.setAllowAllVersions(criteria.getAllVersions()); + elastic.setCollaborators(criteria.getCollaborators()); + if (criteria.getGrants() != null) { + elastic.setGrants(criteria.getGrants().stream().map(Grant::getId).collect(Collectors.toList())); + } + elastic.setGroupIds(criteria.getGroupIds()); + elastic.setLike(criteria.getLike()); + if (criteria.getOrganisations() != null) { + elastic.setOrganizations(criteria.getOrganisations().stream().map(UUID::fromString).collect(Collectors.toList())); + } + elastic.setPublic(criteria.getIsPublic()); + if (!elastic.isPublic()) { + elastic.setCollaborators(Collections.singletonList(principalID)); + } + if (criteria.getRole() != null) { + elastic.setRoles(Collections.singletonList(criteria.getRole())); + } + if (criteria.getStatus() != null) { + elastic.setStatus(criteria.getStatus().shortValue()); + } + elastic.setTemplates(criteria.getDatasetTemplates()); + elastic.setGrantStatus(criteria.getGrantStatus()); + return elastic; + } + + public static List toElasticSorting(ColumnOrderings columnOrderings) { + List sortCriteria = new ArrayList<>(); + if (columnOrderings.getFieldOrderings() != null && !columnOrderings.getFieldOrderings().isEmpty()) { + for (Ordering ordering: columnOrderings.getFieldOrderings()) { + SortCriteria sortCriteria1 = new SortCriteria(); + sortCriteria1.setFieldName(ordering.getFieldName() + (ordering.getFieldName().contains("label") ?".keyword" : "")); + sortCriteria1.setColumnType(ordering.getColumnType() != null ? SortCriteria.ColumnType.valueOf(ordering.getColumnType().name()): SortCriteria.ColumnType.COLUMN); + sortCriteria1.setOrderByType(SortCriteria.OrderByType.valueOf(ordering.getOrderByType().name())); + sortCriteria.add(sortCriteria1); + } + } + return sortCriteria; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/prefilling/PrefillingMapper.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/prefilling/PrefillingMapper.java new file mode 100644 index 000000000..26fa5550a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/mapper/prefilling/PrefillingMapper.java @@ -0,0 +1,283 @@ +package eu.eudat.old.logic.mapper.prefilling; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.logic.proxy.config.entities.PrefillingGet; +import eu.eudat.old.logic.proxy.config.entities.PrefillingMapping; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.logic.utilities.helpers.StreamDistinctBy; +import eu.eudat.old.models.data.datasetprofile.DatasetProfileOverviewModel; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.elastic.entities.Tag; +import eu.eudat.old.logic.managers.DatasetManager; +import eu.eudat.old.logic.managers.DatasetProfileManager; +import eu.eudat.old.logic.managers.LicenseManager; +import eu.eudat.old.logic.proxy.config.entities.DefaultPrefillingMapping; +import eu.eudat.old.logic.proxy.config.entities.PrefillingFixedMapping; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import eu.eudat.old.logic.utilities.json.JsonSearcher; +import eu.eudat.old.models.data.components.commons.datafield.AutoCompleteData; +import eu.eudat.old.models.data.datasetprofile.RenderStyle; +import eu.eudat.old.models.data.datasetwizard.DatasetWizardModel; +import eu.eudat.old.models.data.externaldataset.ExternalAutocompleteFieldModel; +import eu.eudat.old.models.data.license.LicenseModel; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; + +@Component +public class PrefillingMapper { + private static final Logger logger = LoggerFactory.getLogger(PrefillingMapper.class); + private static final ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + private final DatasetProfileManager datasetProfileManager; + + @Autowired + public PrefillingMapper(DatasetProfileManager datasetProfileManager) { + this.datasetProfileManager = datasetProfileManager; + } + + public DatasetWizardModel mapPrefilledEntityToDatasetWizard(Map prefilledEntity, PrefillingGet prefillingGet, String type, + DescriptionTemplate profile, DatasetManager datasetManager, LicenseManager licenseManager) throws Exception { + DatasetWizardModel datasetWizardModel = new DatasetWizardModel(); + datasetWizardModel.setProfile(new DatasetProfileOverviewModel().fromDataModel(profile)); + Dataset dataset = new Dataset(); + dataset.setProfile(profile); + Map properties = new HashMap<>(); + JsonNode parentNode = mapper.readTree(mapper.writeValueAsString(datasetManager.getPagedProfile(datasetWizardModel, dataset))); + for (DefaultPrefillingMapping prefillingMapping: prefillingGet.getMappings()) { + List sourceKeys = Arrays.asList(prefillingMapping.getSource().split("\\.")); + Object sourceValue = null; + for (String sourceKey: sourceKeys) { + if (sourceValue == null) { + sourceValue = prefilledEntity.get(sourceKey); + } else if (sourceValue instanceof Map) { + sourceValue = ((Map)sourceValue).get(sourceKey); + } + } + try { + setValue(prefillingMapping, mapper.writeValueAsString(sourceValue), datasetWizardModel, parentNode, properties, type, licenseManager); + } + catch (Exception e) { + if (prefillingMapping.getSemanticTarget() != null && !prefillingMapping.getSemanticTarget().isEmpty()) { + logger.warn("Couldn't map " + prefillingMapping.getSemanticTarget()); + } + else if (prefillingMapping.getTarget() != null && !prefillingMapping.getTarget().isEmpty()) { + logger.warn("Couldn't map " + prefillingMapping.getTarget()); + } + } + } + for (PrefillingFixedMapping fixedMapping: prefillingGet.getFixedMappings()) { + setValue(fixedMapping, fixedMapping.getValue(), datasetWizardModel, parentNode, properties, type, licenseManager); + } + dataset.setProperties(mapper.writeValueAsString(properties)); + datasetWizardModel.setDatasetProfileDefinition(datasetManager.getPagedProfile(datasetWizardModel, dataset)); + return datasetWizardModel; + } + + private void setValue(PrefillingMapping prefillingMapping, String value, DatasetWizardModel datasetWizardModel, JsonNode parentNode, Map properties, String type, LicenseManager licenseManager) throws InvocationTargetException, IllegalAccessException, JsonProcessingException { + String trimRegex = prefillingMapping.getTrimRegex() != null ? prefillingMapping.getTrimRegex() : ""; + if (!value.startsWith("\"") && !value.startsWith("[") && !value.equals("null")) { + value = "\"" + value + "\""; + } + JsonNode valueNode = mapper.readTree(value); + List parsedValues = new ArrayList<>(); + if (valueNode.isArray() && (valueNode.get(0) != null && !valueNode.get(0).isTextual())) { + if (prefillingMapping.getSubSource() == null || prefillingMapping.getSubSource().isEmpty()) { + throw new IllegalArgumentException("Source value is an array but no subSource field have been set"); + } + String parsedValue; + for(int i = 0; i < valueNode.size(); i++){ + JsonNode jsonObj = valueNode.get(i); + String subSource = jsonObj.get(prefillingMapping.getSubSource()).asText(); + parsedValue = subSource.replaceAll(trimRegex, ""); + parsedValues.add(parsedValue); + } + parsedValues = parsedValues.stream().distinct().collect(Collectors.toList()); + } + String parsedValue = null; + if (valueNode.isTextual()) { + parsedValue = valueNode.textValue().replace(trimRegex, ""); + }else if (valueNode.isArray() && (valueNode.get(0) != null && valueNode.get(0).isTextual())) { + List values = new LinkedList<>(); + for (int i = 0; i < valueNode.size(); i++) { + values.add(valueNode.get(i).textValue().replace(trimRegex, "")); + } + parsedValue = String.join(", ", values); + } + + if (prefillingMapping.getTarget() != null) { + try { + String methodName = "set" + prefillingMapping.getTarget().substring(0, 1).toUpperCase(Locale.ROOT) + prefillingMapping.getTarget().substring(1); + Method setterMethod = Arrays.stream(DatasetWizardModel.class.getDeclaredMethods()) + .filter(method -> method.getName().equals(methodName)).collect(Collectors.toList()).get(0); + Class[] params = setterMethod.getParameterTypes(); + //GK: Tags Special logic + if (parsedValue != null && !parsedValue.equals("null") && prefillingMapping.getTarget().equals("tags")) { + parsedValue = mapper.valueToTree(parseTags(parsedValue)).toString(); + } + else if(!parsedValues.isEmpty() && prefillingMapping.getTarget().equals("tags")) { + parsedValue = mapper.valueToTree(parseTags(String.join(", ", parsedValues))).toString(); + } + else { + parsedValue = mapper.valueToTree(parsedValue).toString(); + } + setterMethod.invoke(datasetWizardModel, mapper.readValue(parsedValue, params[0])); + }catch (InvocationTargetException | IllegalAccessException | JsonProcessingException e) { + throw e; + } + } else { + List nodes = JsonSearcher.findNodes(parentNode, "schematics", prefillingMapping.getSemanticTarget()); + + // zenodo prefilling customizations + if(type.equals("zenodo")){ + if(prefillingMapping.getSemanticTarget().equals("rda.dataset.distribution.data_access")){ + if(parsedValue != null && parsedValue.equals("open")){ + List issuedNodes = JsonSearcher.findNodes(parentNode, "schematics", "rda.dataset.issued"); + if(!issuedNodes.isEmpty()){ + String issuedIdNode = issuedNodes.get(0).get("id").asText(); + String issuedValue = (String) properties.get(issuedIdNode); + List licStartDateNodes = JsonSearcher.findNodes(parentNode, "schematics", "rda.dataset.distribution.license.start_date"); + for (JsonNode licStartDateNode : licStartDateNodes) { + String licStartDateId = licStartDateNode.get(0) != null ? licStartDateNode.get(0).get("id").asText() : licStartDateNode.get("id").asText(); + properties.put(licStartDateId, issuedValue); + } + } + } + } + + if (prefillingMapping.getSemanticTarget().equals("rda.dataset.distribution.available_until") && parsedValue != null && !parsedValue.equals("null")) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd"); + LocalDate date = LocalDate.parse(parsedValue, formatter); + date = date.plusYears(20); + parsedValue = date.toString(); + } + } + + for (JsonNode node: nodes) { + String id = node.isArray() ? node.get(0).get("id").asText() : node.get("id").asText(); + String renderStyle = node.isArray() ? node.get(0).get("viewStyle").get("renderStyle").asText() : node.get("viewStyle").get("renderStyle").asText(); + + switch (RenderStyle.fromValue(renderStyle)) { + case COMBO_BOX: + if (parsedValues.isEmpty()) + parsedValues.add(parsedValue); + if (!parsedValues.stream().allMatch(Objects::isNull)) { + properties.put(id, parseComboBoxValues(node, parsedValues)); + } + break; + case TAGS: + if(parsedValues.isEmpty()) { + properties.put(id, mapper.valueToTree(parseTags(parsedValue)).toString()); + } + else { + properties.put(id, mapper.valueToTree(parseTags(String.join(", ", parsedValues))).toString()); + } + break; + case DATASET_IDENTIFIER: + JSONObject datasetID = new JSONObject(); + datasetID.put("identifier", parsedValue); + if(type.equals("zenodo")){ + datasetID.put("type", "doi"); + } + properties.put(id, datasetID.toString()); + break; + case LICENSES: + try { + List licenses = licenseManager.getLicenses("", ""); + String finalParsedValue = parsedValue; + licenses = licenses.stream().filter(license -> license.getPid().equals(finalParsedValue)).collect(Collectors.toList()); + boolean isMultiAutocomplete = node.isArray() ? node.get(0).get("data").get("multiAutoComplete").booleanValue() : node.get("data").get("multiAutoComplete").booleanValue(); + if(isMultiAutocomplete){ + List lic = new ArrayList<>(); + for(LicenseModel license: licenses){ + lic.add(mapper.writeValueAsString(license)); + } + properties.put(id, mapper.writeValueAsString(lic)); + } else { + properties.put(id, mapper.writeValueAsString(licenses.get(0))); + } + } + catch (NoURLFound | HugeResultSet e){ + properties.put(id, parsedValue); + } + break; + default: + if (!parsedValues.isEmpty()) + properties.put(id, String.join(", ", parsedValues)); + else { + properties.put(id, parsedValue); + } + break; + } + } + } + } + + private Object parseComboBoxValues(JsonNode node, List parsedValues) throws JsonProcessingException { + List normalizedValues = new ArrayList<>(); + boolean isMultiSelect; + String type = node.isArray() ? node.get(0).get("data").get("type").asText() : node.get("data").get("type").asText(); + if(type.equals("autocomplete")) { + JsonNode dataNode = node.isArray() ? node.get(0).get("data") : node.get("data"); + AutoCompleteData autoCompleteData = mapper.treeToValue(dataNode, AutoCompleteData.class); + isMultiSelect = autoCompleteData.getMultiAutoComplete(); + for (String format : parsedValues) { + List result = new ArrayList<>(); + try { + result = datasetProfileManager.getAutocomplete(autoCompleteData, format); + } + catch (Exception e) { + logger.error(e.getMessage(), e); + } + result = result.stream().filter(StreamDistinctBy.distinctByKey(ExternalAutocompleteFieldModel::getId)).collect(Collectors.toList()); + if(!result.isEmpty()){ + List tempValues = new LinkedList<>(); + for (ExternalAutocompleteFieldModel f : result) { + if (format.equals(f.getId()) || f.getLabel().toUpperCase(Locale.ROOT).contains(format.toUpperCase(Locale.ROOT))) + tempValues.add(mapper.valueToTree(f).toString()); + } + if (isMultiSelect) + normalizedValues.addAll(tempValues); + else if (!tempValues.isEmpty()) + normalizedValues.add(tempValues.get(0)); + } + } + return !normalizedValues.isEmpty() ? (isMultiSelect ? normalizedValues : normalizedValues.get(0)) : null; + } else { + JsonNode optionsNode = node.isArray() ? node.get(0).get("data").get("options") : node.get("data").get("options"); + isMultiSelect = node.isArray() ? node.get(0).get("data").get("multiList").booleanValue() : node.get("data").get("multiList").booleanValue(); + for (int i = 0; i < optionsNode.size(); i++) { + String value = optionsNode.get(i).get("value").textValue(); + if (parsedValues.contains(value)) { + normalizedValues.add(value); + } + } + List normalizedStringValues = normalizedValues.stream().map(Object::toString).collect(Collectors.toList()); + + return !normalizedValues.isEmpty() ? (isMultiSelect ? String.join(", ", normalizedStringValues) : normalizedValues.get(0)) : null; + } + } + + private static List parseTags(String value) throws JsonProcessingException { + if (value == null || value.isEmpty()) + return new LinkedList<>(); + String[] rawTags = value.split(", "); + List parsedTags = new LinkedList<>(); + for (String rawTag : rawTags) { + parsedTags.add(new Tag(rawTag, rawTag)); + } + return parsedTags; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/Proxy.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/Proxy.java new file mode 100644 index 000000000..8547cfdd8 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/Proxy.java @@ -0,0 +1,64 @@ +package eu.eudat.old.logic.proxy; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.*; + + +@RestController +@CrossOrigin +public class Proxy { + + private String allowedHost; + + public Proxy(String allowedHost) throws MalformedURLException { + this.allowedHost = new URL(allowedHost).getHost(); + } + + public Proxy() { + + } + + @RequestMapping(method = RequestMethod.GET, value = {"/eu/eudat/logic/proxy"}, produces = "application/json") + public @ResponseBody + ResponseEntity proxy(@RequestParam("url") String remoteUrl) { + + StringBuffer response = new StringBuffer(); + URL url; + try { + URL tempUrl = new URL(remoteUrl); +// URI uri = new URI(scheme, userInfo, host, port, path, query, fragment); + URI uri = new URI(tempUrl.getProtocol(), null, tempUrl.getHost(), tempUrl.getPort(), tempUrl.getPath(), (tempUrl.getQuery() != null) ? URLEncoder.encode(tempUrl.getQuery()) : null, tempUrl.getRef()); + url = uri.toURL(); + + if (!url.getHost().equals(allowedHost)) + return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{'reason': 'You are not allowed to eu.eudat.logic.proxy -> " + url.getHost() + "'}"); + //if allowed, proceed + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("Accept", "application/vnd.api+json; charset=utf-8"); + + int responseCode = con.getResponseCode(); + if (responseCode == HttpURLConnection.HTTP_OK) { // success + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) + response.append(inputLine); + in.close(); + return ResponseEntity.status(HttpStatus.OK).body(response.toString()); + } else { + return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{'reason': 'Remote server responded with: " + responseCode + "'}"); + } + + } catch (IOException | URISyntaxException e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{'reason': 'Could not eu.eudat.logic.proxy to given host'}"); + } + + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/AuthType.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/AuthType.java new file mode 100644 index 000000000..d94c257c6 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/AuthType.java @@ -0,0 +1,23 @@ +package eu.eudat.old.logic.proxy.config; + +public enum AuthType { + ; + private final String name; + + AuthType(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public static AuthType fromName(String name) { + for (AuthType authType : AuthType.values()) { + if (authType.getName().equals(name)) { + return authType; + } + } + throw new IllegalArgumentException("AuthType [" + name + "] is not supported"); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/AuthenticationConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/AuthenticationConfiguration.java new file mode 100644 index 000000000..5d95424f4 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/AuthenticationConfiguration.java @@ -0,0 +1,57 @@ +package eu.eudat.old.logic.proxy.config; + +import javax.xml.bind.annotation.XmlElement; + +public class AuthenticationConfiguration { + + private String authUrl; + private String authMethod = "GET"; + private String authTokenPath; + private String authRequestBody; + private String type; + + public String getAuthUrl() { + return authUrl; + } + + @XmlElement(name = "authUrl") + public void setAuthUrl(String authUrl) { + this.authUrl = authUrl; + } + + public String getAuthMethod() { + return authMethod; + } + + @XmlElement(name = "authUrlMethod") + public void setAuthMethod(String authMethod) { + this.authMethod = authMethod; + } + + public String getAuthTokenPath() { + return authTokenPath; + } + + @XmlElement(name = "authTokenJpath") + public void setAuthTokenPath(String authTokenPath) { + this.authTokenPath = authTokenPath; + } + + public String getAuthRequestBody() { + return authRequestBody; + } + + @XmlElement(name = "authUrlBody") + public void setAuthRequestBody(String authRequestBody) { + this.authRequestBody = authRequestBody; + } + + public String getType() { + return type; + } + + @XmlElement(name = "authType") + public void setType(String type) { + this.type = type; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/DataFieldsUrlConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/DataFieldsUrlConfiguration.java new file mode 100644 index 000000000..a2098aceb --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/DataFieldsUrlConfiguration.java @@ -0,0 +1,134 @@ +package eu.eudat.old.logic.proxy.config; + +import javax.xml.bind.annotation.XmlElement; + +/** + * Created by ikalyvas on 6/29/2018. + */ +public class DataFieldsUrlConfiguration { + private String id; + private String name; + private String pid; + private String pidTypeField; + private String uri; + private String description; + private String source; + private String count; + private String path; + private String host; + private String types; + private String firstName; + private String lastName; + + public String getId() { + return id; + } + + @XmlElement(name = "id") + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + @XmlElement(name = "name") + public void setName(String name) { + this.name = name; + } + + public String getPid() { + return pid; + } + + @XmlElement(name = "pid") + public void setPid(String pid) { + this.pid = pid; + } + + public String getPidTypeField() { + return pidTypeField; + } + + @XmlElement(name = "pidTypeField") + public void setPidTypeField(String pidTypeField) { + this.pidTypeField = pidTypeField; + } + + public String getUri() { + return uri; + } + + @XmlElement(name = "uri") + public void setUri(String uri) { + this.uri = uri; + } + + public String getDescription() { + return description; + } + + @XmlElement(name = "description") + public void setDescription(String description) { + this.description = description; + } + + public String getSource() { + return source; + } + + @XmlElement(name = "source") + public void setSource(String source) { + this.source = source; + } + + public String getCount() { + return count; + } + + @XmlElement(name = "count") + public void setCount(String count) { + this.count = count; + } + + public String getPath() { + return path; + } + @XmlElement(name = "path") + public void setPath(String path) { + this.path = path; + } + + public String getHost() { + return host; + } + @XmlElement(name = "host") + public void setHost(String host) { + this.host = host; + } + + @XmlElement(name = "types") + public String getTypes() { + return types; + } + public void setTypes(String types) { + this.types = types; + } + + @XmlElement(name = "firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + @XmlElement(name = "lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/DataSearchConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/DataSearchConfiguration.java new file mode 100644 index 000000000..a85f72bbc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/DataSearchConfiguration.java @@ -0,0 +1,24 @@ +package eu.eudat.old.logic.proxy.config; + +import javax.xml.bind.annotation.XmlElement; + +public class DataSearchConfiguration { + private String type; + private String queryParam; + + public String getType() { + return type; + } + @XmlElement(name = "type") + public void setType(String type) { + this.type = type; + } + + public String getQueryParam() { + return queryParam; + } + @XmlElement(name = "queryparam") + public void setQueryParam(String queryParam) { + this.queryParam = queryParam; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/DataUrlConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/DataUrlConfiguration.java new file mode 100644 index 000000000..5185dcfbc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/DataUrlConfiguration.java @@ -0,0 +1,82 @@ +package eu.eudat.old.logic.proxy.config; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +/** + * Created by ikalyvas on 6/29/2018. + */ +public class DataUrlConfiguration { + private String path; + private DataFieldsUrlConfiguration fieldsUrlConfiguration; + private UrlConfiguration urlConfiguration; + private String parseClass; + private String parseField; + private List mergedFields; + private String mergedFieldName; + + public String getPath() { + return path; + } + + @XmlElement(name = "path") + public void setPath(String path) { + this.path = path; + } + + public DataFieldsUrlConfiguration getFieldsUrlConfiguration() { + return fieldsUrlConfiguration; + } + + @XmlElement(name = "fields") + public void setFieldsUrlConfiguration(DataFieldsUrlConfiguration fieldsUrlConfiguration) { + this.fieldsUrlConfiguration = fieldsUrlConfiguration; + } + + public UrlConfiguration getUrlConfiguration() { + return urlConfiguration; + } + + @XmlElement(name = "urlConfig") + public void setUrlConfiguration(UrlConfiguration urlConfiguration) { + this.urlConfiguration = urlConfiguration; + } + + public String getParseClass() { + return parseClass; + } + + @XmlElement(name = "parse-class") + public void setParseClass(String parseClass) { + this.parseClass = parseClass; + } + + public String getParseField() { + return parseField; + } + + @XmlElement(name = "parse-field") + public void setParseField(String parseField) { + this.parseField = parseField; + } + + public List getMergedFields() { + return mergedFields; + } + + @XmlElementWrapper(name = "merge-fields") + @XmlElement(name = "field") + public void setMergedFields(List mergedFields) { + this.mergedFields = mergedFields; + } + + public String getMergedFieldName() { + return mergedFieldName; + } + + @XmlElement(name = "merge-field-name") + public void setMergedFieldName(String mergedFieldName) { + this.mergedFieldName = mergedFieldName; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/ExternalUrlCriteria.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/ExternalUrlCriteria.java new file mode 100644 index 000000000..c431869c5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/ExternalUrlCriteria.java @@ -0,0 +1,73 @@ +package eu.eudat.old.logic.proxy.config; + +public class ExternalUrlCriteria { + private String like; + private String page; + private String pageSize; + private String funderId; + private String path; + private String host; + + public String getLike() { + return like; + } + public void setLike(String like) { + this.like = like; + } + + public String getPage() { + return page; + } + public void setPage(String page) { + this.page = page; + } + + public String getPageSize() { + return pageSize; + } + public void setPageSize(String pageSize) { + this.pageSize = pageSize; + } + + public String getFunderId() { + return funderId; + } + public void setFunderId(String funderId) { + this.funderId = funderId; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public ExternalUrlCriteria(String like) { + this.like = like; + } + + public ExternalUrlCriteria() { + } + + @Override + public String toString() { + return "{" + + "like='" + like + '\'' + + ", page='" + page + '\'' + + ", pageSize='" + pageSize + '\'' + + ", funderId='" + funderId + '\'' + + ", path='" + path + '\'' + + ", host='" + host + '\'' + + '}'; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/ExternalUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/ExternalUrls.java new file mode 100644 index 000000000..fee223f82 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/ExternalUrls.java @@ -0,0 +1,214 @@ +package eu.eudat.old.logic.proxy.config; + +import eu.eudat.old.logic.proxy.config.entities.*; +import eu.eudat.old.logic.proxy.config.prefilling.PrefillingConfigMapAdapter; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import java.io.Serializable; +import java.util.Map; + +@XmlRootElement +public class ExternalUrls implements Serializable { + + private static final long serialVersionUID = -5076364662014107275L; + + Long maxresults; + + GrantUrls grants; + ProjectUrls projects; + RegistryUrls registries; + RepositoryUrls repositories; + PubRepositoryUrls pubRepositories; + JournalUrls journals; + TaxonomiesUrls taxonomies; + PublicationsUrls publications; + ServiceUrls services; + ResearcherUrls researchers; + OrganisationUrls organisations; + DatasetUrls datasets; + /*TagUrls tags;*/ + FunderUrls funders; + LicenseUrls licenses; + ValidationUrls validations; + Map prefillings; + + + public RegistryUrls getRegistries() { + return registries; + } + + @XmlElement(name = "registries") + public void setRegistries(RegistryUrls registries) { + this.registries = registries; + } + + + public RepositoryUrls getRepositories() { + return repositories; + } + + @XmlElement(name = "repositories") + public void setRepositories(RepositoryUrls repositories) { + this.repositories = repositories; + } + + public PubRepositoryUrls getPubRepositories() { + return pubRepositories; + } + + public void setPubRepositories(PubRepositoryUrls pubRepositories) { + this.pubRepositories = pubRepositories; + } + + public void setJournals(JournalUrls journals) { + this.journals = journals; + } + + public JournalUrls getJournals() { + return journals; + } + + public JournalUrls getJournal() { + return journals; + } + @XmlElement(name = "journals") + public void setJournal(JournalUrls journal) { + this.journals = journal; + } + + public TaxonomiesUrls getTaxonomies() { + return taxonomies; + } + @XmlElement(name = "taxonomies") + public void setTaxonomies(TaxonomiesUrls taxonomies) { + this.taxonomies = taxonomies; + } + + public PublicationsUrls getPublications() { + return publications; + } + + public void setPublications(PublicationsUrls publications) { + this.publications = publications; + } + + public ServiceUrls getServices() { + return services; + } + + @XmlElement(name = "services") + public void setServices(ServiceUrls services) { + this.services = services; + } + + + public ResearcherUrls getResearchers() { + return researchers; + } + + @XmlElement(name = "researchers") + public void setResearchers(ResearcherUrls researchers) { + this.researchers = researchers; + } + + + /*public TagUrls getTags() { + return tags; + } + + @XmlElement(name = "tags") + public void setTags(TagUrls tags) { + this.tags = tags; + }*/ + + + public OrganisationUrls getOrganisations() { + return organisations; + } + + @XmlElement(name = "organisations") + public void setOrganisations(OrganisationUrls organisations) { + this.organisations = organisations; + } + + + public GrantUrls getGrants() { + return grants; + } + + @XmlElement(name = "grants") + public void setGrants(GrantUrls grants) { + this.grants = grants; + } + + + public ProjectUrls getProjects() { + return projects; + } + + @XmlElement(name = "projects") + public void setProjects(ProjectUrls projects) { + this.projects = projects; + } + + + public FunderUrls getFunders() { + return funders; + } + + public void setFunders(FunderUrls funders) { + this.funders = funders; + } + + + public Long getMaxresults() { + return maxresults; + } + + @XmlElement(name = "maxresults") + public void setMaxresults(Long maxresults) { + this.maxresults = maxresults; + } + + + public DatasetUrls getDatasets() { + return datasets; + } + + @XmlElement(name = "datasets") + public void setDatasets(DatasetUrls datasets) { + this.datasets = datasets; + } + + public LicenseUrls getLicenses() { + return licenses; + } + + @XmlElement(name = "licenses") + public void setLicenses(LicenseUrls licenses) { + this.licenses = licenses; + } + + public ValidationUrls getValidations() { + return validations; + } + + @XmlElement(name = "validators") + public void setValidations(ValidationUrls validations) { + this.validations = validations; + } + + public Map getPrefillings() { + return prefillings; + } + + @XmlJavaTypeAdapter(PrefillingConfigMapAdapter.class) + @XmlElement(name = "prefillings") + public void setPrefillings(Map prefillings) { + this.prefillings = prefillings; + } +} + + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/FetchStrategy.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/FetchStrategy.java new file mode 100644 index 000000000..fb774b393 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/FetchStrategy.java @@ -0,0 +1,8 @@ +package eu.eudat.old.logic.proxy.config; + +public enum FetchStrategy { + + FIRST, + ALL + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/QueryConfig.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/QueryConfig.java new file mode 100644 index 000000000..03f4e60c1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/QueryConfig.java @@ -0,0 +1,48 @@ +package eu.eudat.old.logic.proxy.config; + +import javax.xml.bind.annotation.XmlElement; + +public class QueryConfig { + + private String condition; + private String separator; + private String value; + private Integer ordinal; + + + public String getCondition() { + return condition; + } + + @XmlElement(name = "condition") + public void setCondition(String condition) { + this.condition = condition; + } + + public String getSeparator() { + return separator; + } + + @XmlElement(name = "separator") + public void setSeparator(String separator) { + this.separator = separator; + } + + public String getValue() { + return value; + } + + @XmlElement(name = "value") + public void setValue(String value) { + this.value = value; + } + + public Integer getOrdinal() { + return ordinal; + } + + @XmlElement(name = "ordinal") + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/Semantic.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/Semantic.java new file mode 100644 index 000000000..b6fbbb8bc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/Semantic.java @@ -0,0 +1,25 @@ +package eu.eudat.old.logic.proxy.config; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Semantic { + + @JsonProperty("category") + private String category; + @JsonProperty("name") + private String name; + + public String getCategory() { + return category; + } + public void setCategory(String category) { + this.category = category; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/UrlConfiguration.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/UrlConfiguration.java new file mode 100644 index 000000000..2881bb8fb --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/UrlConfiguration.java @@ -0,0 +1,156 @@ +package eu.eudat.old.logic.proxy.config; + + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class UrlConfiguration { + + private String key; + private String label; + private Integer ordinal; + private String url; + private boolean dataInListing; + private DataUrlConfiguration data; + private String type; + private String paginationPath; + private String contentType; + private String funderQuery; + private String firstpage; + private String requestType = "GET"; + private String requestBody = ""; + private String filterType = "remote"; + private AuthenticationConfiguration auth; + + private List queries; + + public String getKey() { + return key; + } + @XmlElement(name = "key") + public void setKey(String key) { + this.key = key; + } + + public String getLabel() { + return label; + } + @XmlElement(name = "label") + public void setLabel(String label) { + this.label = label; + } + + public String getUrl() { + return url; + } + @XmlElement(name = "url") + public void setUrl(String url) { + this.url = url; + } + + public boolean isDataInListing() { + return dataInListing; + } + @XmlElement(name = "dataInListing") + public void setDataInListing(boolean dataInListing) { + this.dataInListing = dataInListing; + } + + public Integer getOrdinal() { + return ordinal; + } + @XmlElement(name = "ordinal") + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } + + public DataUrlConfiguration getData() { + return data; + } + @XmlElement(name = "data") + public void setData(DataUrlConfiguration data) { + this.data = data; + } + + public String getPaginationPath() { + return paginationPath; + } + @XmlElement(name = "paginationpath") + public void setPaginationPath(String paginationPath) { + this.paginationPath = paginationPath; + } + + public String getType() { + return type; + } + @XmlElement(name = "type") + public void setType(String type) { + this.type = type; + } + + public String getContentType() { + return contentType; + } + @XmlElement(name = "contenttype") + public void setContentType(String contentType) { + this.contentType = contentType; + } + + public String getFunderQuery() { + return funderQuery; + } + @XmlElement(name = "funderQuery") + public void setFunderQuery(String funderQuery) { + this.funderQuery = funderQuery; + } + + public String getFirstpage() { + return firstpage; + } + @XmlElement(name = "firstPage") + public void setFirstpage(String firstpage) { + this.firstpage = firstpage; + } + + public String getRequestType() { + return requestType; + } + @XmlElement(name = "request") + public void setRequestType(String requestType) { + this.requestType = requestType != null ? requestType : "GET"; + } + public String getRequestBody() { + return requestBody; + } + @XmlElement(name = "requestBody") + public void setRequestBody(String requestBody) { + this.requestBody = requestBody != null ? requestBody : ""; + } + public String getFilterType() { + return filterType; + } + @XmlElement(name = "filterType") + public void setFilterType(String filterType) { + this.filterType = filterType; + } + + public List getQueries() { + return queries; + } + + @XmlElementWrapper + @XmlElement(name = "query") + public void setQueries(List queries) { + this.queries = queries; + } + + public AuthenticationConfiguration getAuth() { + return auth; + } + + @XmlElement(name="authentication") + public void setAuth(AuthenticationConfiguration auth) { + this.auth = auth; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/configloaders/ConfigLoader.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/configloaders/ConfigLoader.java new file mode 100644 index 000000000..e1da8ece8 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/configloaders/ConfigLoader.java @@ -0,0 +1,20 @@ +package eu.eudat.old.logic.proxy.config.configloaders; + +import eu.eudat.old.logic.proxy.config.ExternalUrls; +import eu.eudat.old.logic.proxy.config.Semantic; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.ConfigurableProviders; +import eu.eudat.old.models.data.pid.PidLinks; +import org.apache.poi.xwpf.usermodel.XWPFDocument; + +import java.util.List; +import java.util.Map; + +public interface ConfigLoader { + ExternalUrls getExternalUrls(); + List getSemantics(); + XWPFDocument getDocument(); + XWPFDocument getDatasetDocument(); + ConfigurableProviders getConfigurableProviders(); + PidLinks getPidLinks(); + Map getKeyToSourceMap(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/configloaders/DefaultConfigLoader.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/configloaders/DefaultConfigLoader.java new file mode 100644 index 000000000..070d5d276 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/configloaders/DefaultConfigLoader.java @@ -0,0 +1,284 @@ +package eu.eudat.old.logic.proxy.config.configloaders; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.logic.proxy.config.ExternalUrls; +import eu.eudat.old.logic.proxy.config.Semantic; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.ConfigurableProviders; +import eu.eudat.old.models.data.pid.PidLinks; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; +import java.io.*; +import java.util.*; +import java.util.stream.Collectors; + +@Service("configLoader") +//@Profile("devel") +public class DefaultConfigLoader implements ConfigLoader { + private static final Logger logger = LoggerFactory.getLogger(DefaultConfigLoader.class); + private static final ObjectMapper mapper = new ObjectMapper(); + + private ExternalUrls externalUrls; + private List semantics; + private XWPFDocument document; + private XWPFDocument datasetDocument; + private ConfigurableProviders configurableProviders; + private PidLinks pidLinks; + private Map keyToSourceMap; + + @Autowired + private Environment environment; + + private void setExternalUrls() { + String fileUrl = this.environment.getProperty("configuration.externalUrls"); + logger.info("Loaded also config file: " + fileUrl); + InputStream is = null; + try { + JAXBContext jaxbContext = JAXBContext.newInstance(ExternalUrls.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + is = getStreamFromPath(fileUrl); + externalUrls = (ExternalUrls) jaxbUnmarshaller.unmarshal(is); + } catch (Exception ex) { + logger.error("Cannot find resource", ex); + } finally { + try { + if (is != null) is.close(); + } catch (IOException | NullPointerException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + fileUrl, e); + } + } + } + + private void setSemantics() { + String filePath = environment.getProperty("configuration.semantics"); + logger.info("Loaded also config file: " + filePath); + if (filePath != null) { + try { + semantics = mapper.readValue(getStreamFromPath(filePath), new TypeReference>(){}); + } + catch (IOException e) { + logger.error(e.getMessage(), e); + } + } + } + + private void setDocument() { + String filePath = environment.getProperty("configuration.h2020template"); + logger.info("Loaded also config file: " + filePath); + InputStream is = null; + try { + is = getStreamFromPath(filePath); + this.document = new XWPFDocument(is); + } catch (IOException | NullPointerException e) { + logger.error(e.getMessage(), e); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e); + } + } + } + + private void setDatasetDocument() { + String filePath = environment.getProperty("configuration.h2020datasettemplate"); + logger.info("Loaded also config file: " + filePath); + InputStream is = null; + try { + is = getStreamFromPath(filePath); + this.datasetDocument = new XWPFDocument(is); + } catch (IOException | NullPointerException e) { + logger.error(e.getMessage(), e); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e); + } + } + } + + private void setConfigurableProviders() { + String filePath = environment.getProperty("configuration.configurable_login_providers"); + logger.info("Loaded also config file: " + filePath); + InputStream is = null; + try { + is = getStreamFromPath(filePath); + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + this.configurableProviders = mapper.readValue(is, ConfigurableProviders.class); + } catch (IOException | NullPointerException e) { + logger.error(e.getMessage(), e); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e); + } + } + } + + private void setPidLinks() { + String filePath = environment.getProperty("configuration.pid_links"); + logger.info("Loaded also config file: " + filePath); + InputStream is = null; + try { + is = getStreamFromPath(filePath); + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + this.pidLinks = mapper.readValue(is, PidLinks.class); + } catch (IOException | NullPointerException e) { + logger.error(e.getMessage(), e); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e); + } + } + } + + private void setKeyToSourceMap() { + String filePath = this.environment.getProperty("configuration.externalUrls"); + logger.info("Loaded also config file: " + filePath); + Document doc = getXmlDocumentFromFilePath(filePath); + if (doc == null) { + this.keyToSourceMap = null; + return; + } + String xpathExpression = "//key"; + Map keysToSourceMap = new HashMap<>(); + List keys = getXmlValuesFromXPath(doc, xpathExpression); + keys = keys.stream().distinct().collect(Collectors.toList()); + for (String key : keys) { + String sourceExpression = String.format("//urlConfig[key='%s']/label", key); + List sources = getXmlValuesFromXPath(doc, sourceExpression); + if (sources.size() != 0) { + keysToSourceMap.put(key, sources.get(0)); + } + } + this.keyToSourceMap = keysToSourceMap; + } + + + + public ExternalUrls getExternalUrls() { + if (externalUrls == null) { + externalUrls = new ExternalUrls(); + this.setExternalUrls(); + } + return externalUrls; + } + + public List getSemantics() { + if (semantics == null) { + semantics = new ArrayList<>(); + this.setSemantics(); + } + return semantics; + } + + public XWPFDocument getDocument() { + this.setDocument(); + return document; + } + + public XWPFDocument getDatasetDocument() { + this.setDatasetDocument(); + return datasetDocument; + } + + public ConfigurableProviders getConfigurableProviders() { + if (configurableProviders == null) { + configurableProviders = new ConfigurableProviders(); + this.setConfigurableProviders(); + } + return configurableProviders; + } + + public PidLinks getPidLinks() { + if (pidLinks == null) { + pidLinks = new PidLinks(); + this.setPidLinks(); + } + return pidLinks; + } + + public Map getKeyToSourceMap() { + if (keyToSourceMap == null) { + keyToSourceMap = new HashMap<>(); + this.setKeyToSourceMap(); + } + return keyToSourceMap; + } + + + private Document getXmlDocumentFromFilePath(String filePath) { + InputStream is = null; + Document doc; + try { + is = getStreamFromPath(filePath); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + doc = documentBuilder.parse(is); + return doc; + } catch (IOException | ParserConfigurationException | SAXException | NullPointerException e) { + logger.error(e.getMessage(), e); + } finally { + try { + if (is != null) { + is.close(); + } + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e); + } + } + return null; + } + + private List getXmlValuesFromXPath(Document doc, String expression) { + XPath xPath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = null; + List values = new LinkedList<>(); + try { + nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET); + } catch (XPathExpressionException e) { + logger.error(e.getMessage(), e); + } + if (nodeList != null) { + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node.hasChildNodes()) { + values.add(nodeList.item(i).getChildNodes().item(0).getNodeValue()); + } + } + } + return values; + } + + private InputStream getStreamFromPath(String filePath) { + try { + return new FileInputStream(filePath); + } catch (FileNotFoundException e) { + logger.info("loading from classpath"); + return getClass().getClassLoader().getResourceAsStream(filePath); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/configloaders/ProductionConfigLoader.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/configloaders/ProductionConfigLoader.java new file mode 100644 index 000000000..67eb29c11 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/configloaders/ProductionConfigLoader.java @@ -0,0 +1,207 @@ +package eu.eudat.old.logic.proxy.config.configloaders; + +/* +@Service("configLoader") +@Profile({ "production", "staging" }) +public class ProductionConfigLoader implements ConfigLoader { + private static final Logger logger = LoggerFactory.getLogger(ProductionConfigLoader.class); + + private ExternalUrls externalUrls; + private List rdaProperties; + private XWPFDocument document; + private ConfigurableProviders configurableProviders; + private Map keyToSourceMap; + + @Autowired + private Environment environment; + + private void setExternalUrls() { + String fileUrl = this.environment.getProperty("configuration.externalUrls"); + logger.info("Loaded also config file: " + fileUrl); + String current = null; + InputStream is = null; + try { + current = new java.io.File(".").getCanonicalPath(); + JAXBContext jaxbContext = JAXBContext.newInstance(ExternalUrls.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + is = new URL(Paths.get(fileUrl).toUri().toURL().toString()).openStream(); + externalUrls = (ExternalUrls) jaxbUnmarshaller.unmarshal(is); + + } catch (Exception ex) { + logger.error("Cannot find in folder" + current, ex); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + fileUrl, e); + } + } + } + + private void setRdaProperties() { + String filePath = environment.getProperty("configuration.rda"); + BufferedReader reader; + List rdaList = new LinkedList<>(); + for (int i = 0; i < 2; i++) { + try { + if (i == 0) { + reader = new BufferedReader(new FileReader(filePath)); + } else { + reader = new BufferedReader(new FileReader(getClass().getClassLoader().getResource(filePath).getFile())); + } + String line = reader.readLine(); + while (line != null) { + rdaList.add(line); + line = reader.readLine(); + } + reader.close(); + break; + } catch (IOException e) { + if (i == 1) { + logger.error(e.getMessage(), e); + } + } + } + + rdaProperties = rdaList; + } + + private void setDocument() { + String filePath = environment.getProperty("configuration.h2020template"); + InputStream is = null; + for (int i = 0; i < 2; i++) { + try { + if (i == 0) { + is = new URL(Paths.get(filePath).toUri().toURL().toString()).openStream(); + } else { + is = getClass().getClassLoader().getResource(filePath).openStream(); + } + this.document = new XWPFDocument(is); + is.close(); + is = null; + break; + } catch (IOException e) { + logger.error(e.getMessage(), e); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e); + } + } + } + } + + private void setConfigurableProviders() { + String filePath = environment.getProperty("configuration.configurable_login_providers"); + InputStream is = null; + try { + File tempFile = new File(filePath); + if (tempFile.exists()) { + is = new URL(Paths.get(filePath).toUri().toURL().toString()).openStream(); + } else { + is = getClass().getClassLoader().getResource(filePath).openStream(); + } + ObjectMapper objectMapper = new ObjectMapper(); + this.configurableProviders = objectMapper.readValue(is, ConfigurableProviders.class); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e); + } + } + } + private void setKeyToSourceMap() { + String filePath = this.environment.getProperty("configuration.externalUrls"); + logger.info("Loaded also config file: " + filePath); + Document doc = getXmlDocumentFromFilePath(filePath); + if (doc == null) { + this.keyToSourceMap = null; + return; + } + String xpathExpression = "//key"; + Map keysToSourceMap = new HashMap<>(); + List keys = getXmlValuesFromXPath(doc, xpathExpression); + keys = keys.stream().distinct().collect(Collectors.toList()); + for (String key : keys) { + String sourceExpression = String.format("//urlConfig[key='%s']/label", key); + List sources = getXmlValuesFromXPath(doc, sourceExpression); + if (sources.size() != 0) { + keysToSourceMap.put(key, sources.get(0)); + } + } + this.keyToSourceMap = keysToSourceMap; + } + + public ExternalUrls getExternalUrls() { + this.setExternalUrls(); + return externalUrls; + } + + public List getRdaProperties() { + this.setRdaProperties(); + return rdaProperties; + } + + public XWPFDocument getDocument() { + this.setDocument(); + return document; + } + + public ConfigurableProviders getConfigurableProviders() { + this.setConfigurableProviders(); + return configurableProviders; + } + + public Map getKeyToSourceMap() { + this.setKeyToSourceMap(); + return keyToSourceMap; + } + + private Document getXmlDocumentFromFilePath(String filePath) { + InputStream is = null; + Document doc; + try { + System.out.println(filePath); + is = new URL(Paths.get(filePath).toUri().toURL().toString()).openStream(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + doc = documentBuilder.parse(is); + return doc; + } catch (IOException | ParserConfigurationException | SAXException e) { + logger.error(e.getMessage(), e); + } finally { + try { + if (is != null) { + is.close(); + } + } catch (IOException e) { + logger.warn("Warning: Could not close a stream after reading from file: " + filePath, e); + } + } + return null; + } + + private List getXmlValuesFromXPath(Document doc, String expression) { + XPath xPath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = null; + List values = new LinkedList<>(); + try { + nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET); + } catch (XPathExpressionException e) { + logger.error(e.getMessage(), e); + } + if (nodeList != null) { + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node.hasChildNodes()) { + values.add(nodeList.item(i).getChildNodes().item(0).getNodeValue()); + } + } + } + return values; + } +}*/ diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/DatasetUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/DatasetUrls.java new file mode 100644 index 000000000..89e0b3902 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/DatasetUrls.java @@ -0,0 +1,33 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + + +public class DatasetUrls extends GenericUrls{ + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/DefaultPrefillingMapping.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/DefaultPrefillingMapping.java new file mode 100644 index 000000000..4e4840d30 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/DefaultPrefillingMapping.java @@ -0,0 +1,58 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "mapping") +public class DefaultPrefillingMapping implements PrefillingMapping{ + private String source; + private String target; + private String semanticTarget; + private String subSource; + private String trimRegex; + + public String getSource() { + return source; + } + + @XmlAttribute(name = "source") + public void setSource(String source) { + this.source = source; + } + + public String getTarget() { + return target; + } + + @XmlAttribute(name = "target") + public void setTarget(String target) { + this.target = target; + } + + public String getSemanticTarget() { + return semanticTarget; + } + + @XmlAttribute(name = "semanticTarget") + public void setSemanticTarget(String semanticTarget) { + this.semanticTarget = semanticTarget; + } + + public String getSubSource() { + return subSource; + } + + @XmlAttribute(name = "subSource") + public void setSubSource(String subSource) { + this.subSource = subSource; + } + + public String getTrimRegex() { + return trimRegex; + } + + @XmlAttribute(name = "trimRegex") + public void setTrimRegex(String trimRegex) { + this.trimRegex = trimRegex; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/FunderUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/FunderUrls.java new file mode 100644 index 000000000..c46a44888 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/FunderUrls.java @@ -0,0 +1,33 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class FunderUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/GeneralUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/GeneralUrls.java new file mode 100644 index 000000000..e9c2c3afc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/GeneralUrls.java @@ -0,0 +1,31 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import java.util.ArrayList; +import java.util.List; + +public class GeneralUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public GeneralUrls() { + this.urls = new ArrayList<>(); + } + + @Override + public List getUrls() { + return urls; + } + + @Override + public FetchStrategy getFetchMode() { + return fetchMode; + } + + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/GenericUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/GenericUrls.java new file mode 100644 index 000000000..7bd95fdc7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/GenericUrls.java @@ -0,0 +1,12 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import java.util.List; + +public abstract class GenericUrls { + + public abstract List getUrls(); + public abstract FetchStrategy getFetchMode(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/GrantUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/GrantUrls.java new file mode 100644 index 000000000..304b42edb --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/GrantUrls.java @@ -0,0 +1,35 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + + +public class GrantUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } + +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/JournalUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/JournalUrls.java new file mode 100644 index 000000000..0aac1a8a6 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/JournalUrls.java @@ -0,0 +1,34 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class JournalUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/LicenseUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/LicenseUrls.java new file mode 100644 index 000000000..de1ad3d9e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/LicenseUrls.java @@ -0,0 +1,33 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + + +public class LicenseUrls extends GenericUrls{ + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/OrganisationUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/OrganisationUrls.java new file mode 100644 index 000000000..a6b23e36c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/OrganisationUrls.java @@ -0,0 +1,34 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class OrganisationUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingConfig.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingConfig.java new file mode 100644 index 000000000..3a3bdca12 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingConfig.java @@ -0,0 +1,41 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "config") +public class PrefillingConfig { + + private PrefillingSearch prefillingSearch; + private PrefillingGet prefillingGet; + + private String type; + + public PrefillingSearch getPrefillingSearch() { + return prefillingSearch; + } + + @XmlElement(name = "prefillingSearch") + public void setPrefillingSearch(PrefillingSearch prefillingSearch) { + this.prefillingSearch = prefillingSearch; + } + + public PrefillingGet getPrefillingGet() { + return prefillingGet; + } + + @XmlElement(name = "prefillingGet") + public void setPrefillingGet(PrefillingGet prefillingGet) { + this.prefillingGet = prefillingGet; + } + + @XmlAttribute(name = "type") + public void setType(String type) { + this.type = type; + } + + public String getType(){ + return type; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingFixedMapping.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingFixedMapping.java new file mode 100644 index 000000000..a058f3ce9 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingFixedMapping.java @@ -0,0 +1,48 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "fixedMapping") +public class PrefillingFixedMapping implements PrefillingMapping{ + private String target; + private String semanticTarget; + private String value; + + public String getTarget() { + return target; + } + + @XmlAttribute(name = "target") + public void setTarget(String target) { + this.target = target; + } + + public String getSemanticTarget() { + return semanticTarget; + } + + @XmlAttribute(name = "semanticTarget") + public void setSemanticTarget(String semanticTarget) { + this.semanticTarget = semanticTarget; + } + + @Override + public String getSubSource() { + return ""; + } + + @Override + public String getTrimRegex() { + return ""; + } + + public String getValue() { + return value; + } + + @XmlAttribute(name = "value") + public void setValue(String value) { + this.value = value; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingGet.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingGet.java new file mode 100644 index 000000000..047963d86 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingGet.java @@ -0,0 +1,40 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class PrefillingGet{ + private String url; + private List mappings; + private List fixedMappings; + + public String getUrl() { + return url; + } + + @XmlElement(name = "url") + public void setUrl(String url) { + this.url = url; + } + + public List getMappings() { + return mappings; + } + + @XmlElement(name = "mapping") + @XmlElementWrapper + public void setMappings(List mappings) { + this.mappings = mappings; + } + + public List getFixedMappings() { + return fixedMappings; + } + + @XmlElement(name = "fixedMapping") + @XmlElementWrapper + public void setFixedMappings(List fixedMappings) { + this.fixedMappings = fixedMappings; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingMapping.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingMapping.java new file mode 100644 index 000000000..a11093628 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingMapping.java @@ -0,0 +1,17 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import javax.xml.bind.annotation.XmlAttribute; + +public interface PrefillingMapping { + String getTarget(); + + void setTarget(String target); + + String getSemanticTarget(); + + void setSemanticTarget(String semanticTarget); + + String getSubSource(); + + String getTrimRegex(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingSearch.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingSearch.java new file mode 100644 index 000000000..e211f2ee5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PrefillingSearch.java @@ -0,0 +1,33 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import java.util.ArrayList; +import java.util.List; + +public class PrefillingSearch extends GenericUrls{ + private UrlConfiguration urlConfig; + + public UrlConfiguration getUrlConfig() { + return urlConfig; + } + + @XmlElement(name = "urlConfig") + public void setUrlConfig(UrlConfiguration urlConfig) { + this.urlConfig = urlConfig; + } + + @Override + public List getUrls() { + List urls = new ArrayList<>(); + urls.add(urlConfig); + return urls; + } + + @Override + public FetchStrategy getFetchMode() { + return null; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ProjectUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ProjectUrls.java new file mode 100644 index 000000000..ef8b20c05 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ProjectUrls.java @@ -0,0 +1,33 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class ProjectUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PubRepositoryUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PubRepositoryUrls.java new file mode 100644 index 000000000..b11974fec --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PubRepositoryUrls.java @@ -0,0 +1,34 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class PubRepositoryUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PublicationsUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PublicationsUrls.java new file mode 100644 index 000000000..01cf24d44 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/PublicationsUrls.java @@ -0,0 +1,34 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class PublicationsUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/RegistryUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/RegistryUrls.java new file mode 100644 index 000000000..0187b71a4 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/RegistryUrls.java @@ -0,0 +1,35 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class RegistryUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } + + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/RepositoryUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/RepositoryUrls.java new file mode 100644 index 000000000..21d310089 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/RepositoryUrls.java @@ -0,0 +1,34 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class RepositoryUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ResearcherUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ResearcherUrls.java new file mode 100644 index 000000000..28ba2f95a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ResearcherUrls.java @@ -0,0 +1,35 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class ResearcherUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } + + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ServiceUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ServiceUrls.java new file mode 100644 index 000000000..a786bcb62 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ServiceUrls.java @@ -0,0 +1,35 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class ServiceUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } + + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/TagUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/TagUrls.java new file mode 100644 index 000000000..396fd3b60 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/TagUrls.java @@ -0,0 +1,35 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +/** + * Created by ikalyvas on 7/9/2018. + */ +public class TagUrls extends GenericUrls{ + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/TaxonomiesUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/TaxonomiesUrls.java new file mode 100644 index 000000000..23302cd01 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/TaxonomiesUrls.java @@ -0,0 +1,34 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import java.util.List; + +public class TaxonomiesUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ValidationUrls.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ValidationUrls.java new file mode 100644 index 000000000..7571b64c5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/entities/ValidationUrls.java @@ -0,0 +1,36 @@ +package eu.eudat.old.logic.proxy.config.entities; + +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; + +import eu.eudat.old.logic.proxy.config.FetchStrategy; +import eu.eudat.old.logic.proxy.config.UrlConfiguration; + +public class ValidationUrls extends GenericUrls{ + + List urls; + FetchStrategy fetchMode; + + public List getUrls() { + return urls; + } + + @XmlElementWrapper + @XmlElement(name = "urlConfig") + public void setUrls(List urls) { + this.urls = urls; + } + + public FetchStrategy getFetchMode() { + return fetchMode; + } + + @XmlElement(name = "fetchMode") + public void setFetchMode(FetchStrategy fetchMode) { + this.fetchMode = fetchMode; + } + + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/exceptions/HugeResultSet.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/exceptions/HugeResultSet.java new file mode 100644 index 000000000..00cc7a146 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/exceptions/HugeResultSet.java @@ -0,0 +1,13 @@ +package eu.eudat.old.logic.proxy.config.exceptions; + +public class HugeResultSet extends Exception { + + private static final long serialVersionUID = -6961447213733280563L; + + + public HugeResultSet(String message) { + super(message); + } + + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/exceptions/NoURLFound.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/exceptions/NoURLFound.java new file mode 100644 index 000000000..c1e8123fb --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/exceptions/NoURLFound.java @@ -0,0 +1,13 @@ +package eu.eudat.old.logic.proxy.config.exceptions; + +public class NoURLFound extends Exception { + + private static final long serialVersionUID = -6961447213733280563L; + + + public NoURLFound(String message) { + super(message); + } + + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/prefilling/PrefillingConfigMapAdapter.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/prefilling/PrefillingConfigMapAdapter.java new file mode 100644 index 000000000..531c7ce09 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/config/prefilling/PrefillingConfigMapAdapter.java @@ -0,0 +1,35 @@ +package eu.eudat.old.logic.proxy.config.prefilling; + +import eu.eudat.old.logic.proxy.config.entities.PrefillingConfig; +import org.w3c.dom.Element; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.adapters.XmlAdapter; +import java.util.HashMap; +import java.util.Map; + +public class PrefillingConfigMapAdapter extends XmlAdapter> { + @Override + public Map unmarshal(Object v) throws Exception { + Map configMap = new HashMap<>(); + Element element = (Element) v; + JAXBContext jaxbContext = JAXBContext.newInstance(PrefillingConfig.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + for (int i = 0; i < element.getChildNodes().getLength(); i++) { + if (element.getChildNodes().item(i).getAttributes() == null) { + continue; + } + String id = element.getChildNodes().item(i).getAttributes().getNamedItem("id").getNodeValue(); + PrefillingConfig prefillingConfig = (PrefillingConfig) jaxbUnmarshaller.unmarshal(element.getChildNodes().item(i)); + prefillingConfig = configMap.put(id, prefillingConfig); + System.out.println(prefillingConfig); + } + return configMap; + } + + @Override + public Object marshal(Map v) throws Exception { + return null; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/LocalFetcher.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/LocalFetcher.java new file mode 100644 index 000000000..283a1452d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/LocalFetcher.java @@ -0,0 +1,100 @@ +package eu.eudat.old.logic.proxy.fetching; + +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.logic.proxy.fetching.entities.Config; +import eu.eudat.old.logic.proxy.fetching.entities.ConfigSingle; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.util.*; + +@Component +public class LocalFetcher { + + @Cacheable("currencies") + public List> retrieveCurrency() throws Exception { + InputStream is = getClass().getClassLoader().getResource("internal/fetchConfig.xml").openStream(); + JAXBContext context = JAXBContext.newInstance(Config.class); + Unmarshaller unmarshaller = context.createUnmarshaller(); + Config config = (Config) unmarshaller.unmarshal(is); + is.close(); + ConfigSingle currencyConfig = config.getConfigs().stream().filter(configSingle -> configSingle.getType().equals("currency")).findFirst().get(); + + return retrieveData(currencyConfig); + } + + public List> retrieveData(ConfigSingle configSingle) throws Exception { + List> result = new ArrayList<>(); + InputStream is = getClass().getClassLoader().getResource(configSingle.getFilePath()).openStream(); + FileType type = FileType.fromName(configSingle.getFileType()); + switch(type) { + case XML: + { + Class aClass = Class.forName(configSingle.getParseClass()); + JAXBContext context = JAXBContext.newInstance(aClass); + Unmarshaller unmarshaller = context.createUnmarshaller(); + + Object object = unmarshaller.unmarshal(is); + is.close(); + Method reader = null; + if (configSingle.getParseField() != null && !configSingle.getParseField().isEmpty()) { + String camelCaseGetter =configSingle.getParseField() != null && !configSingle.getParseField().isEmpty() ? "get" + configSingle.getParseField().substring(0, 1).toUpperCase() + configSingle.getParseField().substring(1) : ""; + reader = aClass.getMethod(camelCaseGetter); + } + ObjectMapper objectMapper = new ObjectMapper(); + List> values = new ArrayList<>(); + int max = 1; + if (reader != null) { + Object invokedField = reader.invoke(object); + if (invokedField instanceof Collection) { + max = ((Collection) invokedField).size(); + } + } + for (int i = 0; i< max; i++) { + Object value; + if (reader != null) { + Object invokedField = reader.invoke(object); + if (invokedField instanceof Collection) { + value = ((Collection) invokedField).toArray()[i]; + } else { + value = invokedField; + } + } else { + value = object; + } + Map map = objectMapper.convertValue(value, Map.class); + result.add(new HashMap<>()); + result.get(result.size() - 1).put("name", map.get(configSingle.getName())); + result.get(result.size() - 1).put("value", map.get(configSingle.getValue())); + } + } + } + return result; + } + + public enum FileType { + XML("xml"), JSON("json"); + private String name; + + FileType(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public static FileType fromName(String name) { + for (FileType type: FileType.values()) { + if (name.equals(type.getName())) { + return type; + } + } + throw new NoSuchElementException("File Type [" + name + "] is not supported"); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/RemoteFetcher.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/RemoteFetcher.java new file mode 100644 index 000000000..1feaaa508 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/RemoteFetcher.java @@ -0,0 +1,611 @@ +package eu.eudat.old.logic.proxy.fetching; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.JsonPath; +import eu.eudat.old.logic.proxy.config.*; +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.proxy.config.entities.GenericUrls; +import eu.eudat.old.logic.proxy.config.exceptions.NoURLFound; +import eu.eudat.old.logic.proxy.fetching.entities.Results; +import eu.eudat.old.logic.proxy.config.exceptions.HugeResultSet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.*; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.http.codec.json.Jackson2JsonDecoder; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.netty.http.client.HttpClient; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import java.io.File; +import java.io.StringReader; +import java.lang.reflect.Method; +import java.nio.file.Paths; +import java.util.*; +import java.util.stream.Collectors; + +@Service +public class RemoteFetcher { + private static final Logger logger = LoggerFactory.getLogger(RemoteFetcher.class); + + private ConfigLoader configLoader; + private final WebClient client; + + @Autowired + public RemoteFetcher(ConfigLoader configLoader) { + this.configLoader = configLoader; + this.client = WebClient.builder().codecs(clientCodecConfigurer -> { + clientCodecConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(new ObjectMapper(), MediaType.APPLICATION_JSON)); + clientCodecConfigurer.defaultCodecs().maxInMemorySize(2 * ((int) Math.pow(1024, 3))); //GK: Why here??? + } + ).clientConnector(new ReactorClientHttpConnector(HttpClient.create().followRedirect(true))).build(); + } + + @Cacheable(value = "repositories", keyGenerator = "externalUrlsKeyGenerator") + public List> getRepositories(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getRepositories().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getRepositories().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getRepositories().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + @Cacheable(value = "pubrepos", keyGenerator = "externalUrlsKeyGenerator") + public List> getPubRepositories(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getPubRepositories().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getPubRepositories().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getPubRepositories().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + @Cacheable(value = "journals", keyGenerator = "externalUrlsKeyGenerator") + public List> getJournals(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getJournals().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getJournals().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getJournals().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + @Cacheable(value = "taxonomies", keyGenerator = "externalUrlsKeyGenerator") + public List> getTaxonomies(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getTaxonomies().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getTaxonomies().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getTaxonomies().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + @Cacheable(value = "publications", keyGenerator = "externalUrlsKeyGenerator") + public List> getPublications(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getPublications().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getPublications().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getPublications().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + + @Cacheable(value = "grants", keyGenerator = "externalUrlsKeyGenerator") + public List> getGrants(ExternalUrlCriteria externalUrlCriteria) throws NoURLFound, HugeResultSet { + List urlConfigs = configLoader.getExternalUrls().getGrants().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getGrants().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + + @Cacheable(value = "projects", keyGenerator = "externalUrlsKeyGenerator") + public List> getProjects(ExternalUrlCriteria externalUrlCriteria) throws NoURLFound, HugeResultSet { + List urlConfigs = configLoader.getExternalUrls().getProjects().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getProjects().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + + @Cacheable(value = "funders", keyGenerator = "externalUrlsKeyGenerator") + public List> getFunders(ExternalUrlCriteria externalUrlCriteria) throws NoURLFound, HugeResultSet { + List urlConfigs = configLoader.getExternalUrls().getFunders().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getFunders().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + + @Cacheable(value = "organisations", keyGenerator = "externalUrlsKeyGenerator") + public List> getOrganisations(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getOrganisations().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getOrganisations().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getOrganisations().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + + @Cacheable(value = "registries", keyGenerator = "externalUrlsKeyGenerator") + public List> getRegistries(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getRegistries().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getRegistries().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getRegistries().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + + @Cacheable(value = "services", keyGenerator = "externalUrlsKeyGenerator") + public List> getServices(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getServices().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getServices().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getServices().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + + @Cacheable(value = "researchers", keyGenerator = "externalUrlsKeyGenerator") + public List> getResearchers(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getResearchers().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getResearchers().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getResearchers().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + + /*@Cacheable("tags") + public List> getTags(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getTags().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getTags().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getTags().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + }*/ + + @Cacheable(value = "externalDatasets", keyGenerator = "externalUrlsKeyGenerator") + public List> getDatasets(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getDatasets().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getDatasets().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getDatasets().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + + @Cacheable(value = "licenses", keyGenerator = "externalUrlsKeyGenerator") + public List> getlicenses(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getLicenses().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getLicenses().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getLicenses().getFetchMode(); + return getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + } + + public Integer findEntries(ExternalUrlCriteria externalUrlCriteria, String key) throws NoURLFound, HugeResultSet { + List urlConfigs = + key != null && !key.isEmpty() ? configLoader.getExternalUrls().getValidations().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) + : configLoader.getExternalUrls().getValidations().getUrls(); + FetchStrategy fetchStrategy = configLoader.getExternalUrls().getValidations().getFetchMode(); + List> data = this.getAll(urlConfigs, fetchStrategy, externalUrlCriteria); + return data.size(); + } + + public List> getExternalGeneric(ExternalUrlCriteria externalUrlCriteria, GenericUrls genericUrls) { + List urlConfigurations = genericUrls.getUrls(); + FetchStrategy fetchStrategy = genericUrls.getFetchMode(); + return getAll(urlConfigurations, fetchStrategy, externalUrlCriteria); + } + + public List> getExternalGenericWithData(ExternalUrlCriteria externalUrlCriteria, GenericUrls genericUrls) { + List urlConfigurations = genericUrls.getUrls(); + return getAllWithData(urlConfigurations, externalUrlCriteria); + } + + private List> getAll(List urlConfigs, FetchStrategy fetchStrategy, ExternalUrlCriteria externalUrlCriteria) { + + List> results = new LinkedList<>(); + + if (urlConfigs == null || urlConfigs.isEmpty()) { + return results; + } +// throw new NoURLFound("No Repository urls found in configuration"); + + urlConfigs.sort(Comparator.comparing(UrlConfiguration::getOrdinal)); + urlConfigs.forEach(urlConfiguration -> { + ifFunderQueryExist(urlConfiguration, externalUrlCriteria); + if (urlConfiguration.getType() == null || urlConfiguration.getType().equals("External")) { + try { + String auth = null; + if (urlConfiguration.getAuth() != null) { + auth = this.getAuthentication(urlConfiguration.getAuth()); + } + results.addAll(getAllResultsFromUrl(urlConfiguration.getUrl(), fetchStrategy, urlConfiguration.getData(), urlConfiguration.getPaginationPath(), externalUrlCriteria, urlConfiguration.getLabel(), urlConfiguration.getKey(), urlConfiguration.getContentType(), urlConfiguration.getFirstpage(), urlConfiguration.getRequestBody(), urlConfiguration.getRequestType(), urlConfiguration.getFilterType(), urlConfiguration.getQueries(), auth)); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + } else if (urlConfiguration.getType() != null && urlConfiguration.getType().equals("Internal")) { + results.addAll(getAllResultsFromMockUpJson(urlConfiguration.getUrl(), externalUrlCriteria.getLike())); + } + }); + /* for (UrlConfiguration urlConfig : urlConfigs) { + ifFunderQueryExist(urlConfig, externalUrlCriteria); + if (urlConfig.getType() == null || urlConfig.getType().equals("External")) { + results.addAll(getAllResultsFromUrl(urlConfig.getUrl(), fetchStrategy, urlConfig.getData(), urlConfig.getPaginationPath(), externalUrlCriteria, urlConfig.getLabel(), urlConfig.getKey(), urlConfig.getContentType(), urlConfig.getFirstpage(), urlConfig.getRequestBody(), urlConfig.getRequestType())); + } else if (urlConfig.getType() != null && urlConfig.getType().equals("Internal")) { + results.addAll(getAllResultsFromMockUpJson(urlConfig.getUrl(), externalUrlCriteria.getLike())); + } + }*/ + return results; + } + + private String getAuthentication(AuthenticationConfiguration authenticationConfiguration) { + HttpMethod method = HttpMethod.valueOf(authenticationConfiguration.getAuthMethod()); + Map reponse = this.client.method(method).uri(authenticationConfiguration.getAuthUrl()) + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(this.parseBodyString(authenticationConfiguration.getAuthRequestBody())) + .exchangeToMono(mono -> mono.bodyToMono(new ParameterizedTypeReference>() { + })).block(); + + + + return authenticationConfiguration.getType() + " " + reponse.get(authenticationConfiguration.getAuthTokenPath()); + } + + private List> getAllWithData(List urlConfigs, ExternalUrlCriteria externalUrlCriteria) { + + List> results = new LinkedList<>(); + + if (urlConfigs == null || urlConfigs.isEmpty()) { + return results; + } + + urlConfigs.sort(Comparator.comparing(UrlConfiguration::getOrdinal)); + urlConfigs.forEach(urlConfiguration -> { + ifFunderQueryExist(urlConfiguration, externalUrlCriteria); + if (urlConfiguration.getType() == null || urlConfiguration.getType().equals("External")) { + try { + results.addAll(getAllResultsFromUrlWithData(urlConfiguration.getUrl(), urlConfiguration.getData(), externalUrlCriteria, urlConfiguration.getContentType(), urlConfiguration.getFirstpage(), urlConfiguration.getRequestBody(), urlConfiguration.getRequestType(), urlConfiguration.getQueries())); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + } + }); + return results; + + } + + private void ifFunderQueryExist(UrlConfiguration urlConfiguration, ExternalUrlCriteria externalUrlCriteria) { + if (urlConfiguration.getFunderQuery() != null) { + if (externalUrlCriteria.getFunderId() != null && !urlConfiguration.getFunderQuery().startsWith("dmp:")) { + urlConfiguration.setUrl(urlConfiguration.getUrl().replace("{funderQuery}", urlConfiguration.getFunderQuery())); + } + else { + urlConfiguration.setUrl(urlConfiguration.getUrl().replace("{funderQuery}", "")); + } + } + } + + private String calculateQuery(ExternalUrlCriteria externalUrlCriteria, List queryConfigs) { + String finalQuery = ""; + QueryConfig queryConfig = queryConfigs.stream().filter(queryConfigl -> externalUrlCriteria.getLike().matches(queryConfigl.getCondition())) + .min((Comparator.comparing(QueryConfig::getOrdinal))).orElse(null); + if (queryConfig != null) { + if (queryConfig.getSeparator() != null) { + String[] likes = externalUrlCriteria.getLike().split(queryConfig.getSeparator()); + finalQuery = queryConfig.getValue(); + for (int i = 0; i < likes.length; i++) { + finalQuery = finalQuery.replaceAll("\\{like" + (i+1) + "}", likes[i]); + } + } else { + finalQuery = queryConfig.getValue().replaceAll("\\{like}", externalUrlCriteria.getLike()); + } + + } + return finalQuery; + } + + protected String replaceCriteriaOnUrl(String path, ExternalUrlCriteria externalUrlCriteria, String firstPage, List queries) { + String completedPath = path; + if (externalUrlCriteria.getLike() != null) { + if ((path.contains("openaire") || path.contains("orcid") || path.contains("ror") || path.contains("fairsharing")) && externalUrlCriteria.getLike().equals("")) { + completedPath = completedPath.replaceAll("\\{like}", "*"); + completedPath = completedPath.replaceAll("\\{query}", "*"); + } else { + if (completedPath.contains("{query}")) { + completedPath = completedPath.replaceAll("\\{query}", this.calculateQuery(externalUrlCriteria, queries)); + } else { + completedPath = completedPath.replaceAll("\\{like}", externalUrlCriteria.getLike()); + } + } + } else { + completedPath = completedPath.replace("{like}", ""); + } + if (externalUrlCriteria.getFunderId() != null) { + String funderPrefix = externalUrlCriteria.getFunderId().split(":")[0]; + String funderId = externalUrlCriteria.getFunderId().replace(funderPrefix + ":", ""); + if (funderId.toCharArray()[0] == ':') { + funderId = externalUrlCriteria.getFunderId(); + } + /* + try { funderId = URLEncoder.encode(funderId, "UTF-8"); } catch + (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } + */ + completedPath = completedPath.replace("{funderId}", funderId); + } + else if(completedPath.contains("{funderId}")){ + logger.warn("FunderId is null."); + completedPath = completedPath.replace("{funderId}", " "); + } + if (externalUrlCriteria.getPage() != null) { + completedPath = completedPath.replace("{page}", externalUrlCriteria.getPage()); + } else { + if (firstPage != null) { + completedPath = completedPath.replace("{page}", firstPage); + } else { + completedPath = completedPath.replace("{page}", "1"); + } + } + if (externalUrlCriteria.getPageSize() != null) { + completedPath = completedPath.replace("{pageSize}", externalUrlCriteria.getPageSize()); + } else { + completedPath = completedPath.replace("{pageSize}", "60"); + } + if (externalUrlCriteria.getHost() != null) { + completedPath = completedPath.replace("{host}", externalUrlCriteria.getHost()); + } else { + completedPath = completedPath.replace("{host}", ""); + } + if (externalUrlCriteria.getPath() != null) { + completedPath = completedPath.replace("{path}", externalUrlCriteria.getPath()); + } else { + completedPath = completedPath.replace("{path}", ""); + } + return completedPath; + } + + private List> getAllResultsFromUrl(String path, FetchStrategy fetchStrategy, final DataUrlConfiguration jsonDataPath, final String jsonPaginationPath, ExternalUrlCriteria externalUrlCriteria, String tag, String key, String contentType, String firstPage, String requestBody, String requestType, String filterType, List queries, String auth) throws Exception { + Set pages = new HashSet<>(); + + String replacedPath = replaceCriteriaOnUrl(path, externalUrlCriteria, firstPage, queries); + String replacedBody = replaceCriteriaOnUrl(requestBody, externalUrlCriteria, firstPage, queries); + + Results results = getResultsFromUrl(replacedPath, jsonDataPath, jsonPaginationPath, contentType, replacedBody, requestType, auth); + if(results != null) { + if (filterType != null && filterType.equals("local") && (externalUrlCriteria.getLike() != null && !externalUrlCriteria.getLike().isEmpty())) { + results.setResults(results.getResults().stream() + .filter(r -> r.get("name").toLowerCase().contains(externalUrlCriteria.getLike().toLowerCase())) + .collect(Collectors.toList())); + } + if (fetchStrategy == FetchStrategy.FIRST) + return results.getResults().stream().peek(x -> x.put("tag", tag)).peek(x -> x.put("key", key)).collect(Collectors.toList()); + + if (results.getPagination() != null && results.getPagination().get("pages") != null) //if has more pages, add them to the pages set + for (int i = 2; i <= results.getPagination().get("pages"); i++) + pages.add(i); + + Long maxResults = configLoader.getExternalUrls().getMaxresults(); + if ((maxResults > 0) && (results.getPagination().get("count") > maxResults)) + throw new HugeResultSet("The submitted search query " + externalUrlCriteria.getLike() + " is about to return " + results.getPagination().get("count") + " results... Please submit a more detailed search query"); + + Optional optionalResults = pages.parallelStream() + .map(page -> getResultsFromUrl(path + "&page=" + page, jsonDataPath, jsonPaginationPath, contentType, replacedBody, requestType, auth)) + .filter(Objects::nonNull) + .reduce((result1, result2) -> { + result1.getResults().addAll(result2.getResults()); + return result1; + }); + Results remainingResults = optionalResults.orElseGet(Results::new); + remainingResults.getResults().addAll(results.getResults()); + + return remainingResults.getResults().stream().peek(x -> x.put("tag", tag)).peek(x -> x.put("key", key)).collect(Collectors.toList()); + } + else { + return new LinkedList<>(); + } + } + + private List> getAllResultsFromUrlWithData(String path, final DataUrlConfiguration jsonDataPath, ExternalUrlCriteria externalUrlCriteria, String contentType, String firstPage, String requestBody, String requestType, List queries) { + + String replacedPath = replaceCriteriaOnUrl(path, externalUrlCriteria, firstPage, queries); + String replacedBody = replaceCriteriaOnUrl(requestBody, externalUrlCriteria, firstPage, queries); + + try { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + HttpEntity entity; + ResponseEntity response; + if (contentType != null && !contentType.isEmpty()) { + headers.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); + headers.setContentType(MediaType.valueOf(contentType)); + } + JsonNode jsonBody = new ObjectMapper().readTree(replacedBody); + entity = new HttpEntity<>(jsonBody, headers); + + response = restTemplate.exchange(replacedPath, HttpMethod.valueOf(requestType), entity, String.class); + if (response.getStatusCode() == HttpStatus.OK) { + if (response.getHeaders().get("Content-Type").get(0).contains("json")) { + DocumentContext jsonContext = JsonPath.parse(response.getBody()); + return jsonContext.read(jsonDataPath.getPath()); + } + } + } + catch (Exception exception) { + logger.error(exception.getMessage(), exception); + } + + return new LinkedList<>(); + } + + + protected Results getResultsFromUrl(String urlString, DataUrlConfiguration jsonDataPath, String jsonPaginationPath, String contentType, String requestBody, String requestType, String auth) { + + try { + //RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory()); + //HttpHeaders headers = new HttpHeaders(); + //HttpEntity entity; + ResponseEntity response; + /* + * URL url = new URL(urlString.replaceAll(" ", "%20")); + * + * HttpURLConnection con = (HttpURLConnection) url.openConnection(); + * con.setRequestMethod("GET"); + */ + /* if (contentType != null && !contentType.isEmpty()) { + headers.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); + headers.setContentType(MediaType.valueOf(contentType)); + } + if (auth != null) { + headers.set("Authorization", auth); + }*/ + JsonNode jsonBody = new ObjectMapper().readTree(requestBody); +// entity = new HttpEntity<>(jsonBody, headers); + + + response = this.client.method(HttpMethod.valueOf(requestType)).uri(urlString).headers(httpHeaders -> { + if (contentType != null && !contentType.isEmpty()) { + httpHeaders.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); + httpHeaders.setContentType(MediaType.valueOf(contentType)); + } + if (auth != null) { + httpHeaders.set("Authorization", auth); + } + }).bodyValue(jsonBody).retrieve().toEntity(String.class).block(); + //response = restTemplate.exchange(urlString, HttpMethod.resolve(requestType), entity, String.class); + if (response.getStatusCode() == HttpStatus.OK) { // success + //do here all the parsing + Results results = new Results(); + if (response.getHeaders().get("Content-Type").get(0).contains("json")) { + DocumentContext jsonContext = JsonPath.parse(response.getBody()); + + if (jsonDataPath.getFieldsUrlConfiguration().getPath() != null) { + results = RemoteFetcherUtils.getFromJsonWithRecursiveFetching(jsonContext, jsonDataPath, this, requestBody, requestType, auth); + } else if (jsonDataPath.getFieldsUrlConfiguration().getFirstName() != null) { + results = RemoteFetcherUtils.getFromJsonWithFirstAndLastName(jsonContext, jsonDataPath); + } else { + results = RemoteFetcherUtils.getFromJson(jsonContext, jsonDataPath); + } + results.setResults(results.getResults().stream().map(e -> e.entrySet().stream().collect(Collectors.toMap(x -> this.transformKey(jsonDataPath,x.getKey()), Map.Entry::getValue))) + .collect(Collectors.toList())); + } + else if (response.getHeaders().get("Content-Type").get(0).contains("xml")) { + Class aClass = Class.forName(jsonDataPath.getParseClass()); + JAXBContext jaxbContext = JAXBContext.newInstance(aClass); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + StringReader stringReader = new StringReader(response.getBody()); + Object data = unmarshaller.unmarshal(stringReader); + Method reader = null; + if (jsonDataPath.getParseField() != null && !jsonDataPath.getParseField().isEmpty()) { + String camelCaseGetter = jsonDataPath.getParseField() != null && !jsonDataPath.getParseField().isEmpty() ? "get" + jsonDataPath.getParseField().substring(0, 1).toUpperCase() + jsonDataPath.getParseField().substring(1) : ""; + reader = aClass.getMethod(camelCaseGetter); + } + ObjectMapper objectMapper = new ObjectMapper(); + List> values = new ArrayList<>(); + int max = 1; + if (reader != null) { + Object invokedField = reader.invoke(data); + if (invokedField instanceof Collection) { + max = ((Collection) invokedField).size(); + } + } + for (int i = 0; i< max; i++) { + Object value; + if (reader != null) { + Object invokedField = reader.invoke(data); + if (invokedField instanceof Collection) { + value = ((Collection) invokedField).toArray()[i]; + } else { + value = invokedField; + } + } else { + value = data; + } + Map map = objectMapper.convertValue(value, Map.class); + if (jsonDataPath.getMergedFields() != null && !jsonDataPath.getMergedFields().isEmpty() && jsonDataPath.getMergedFieldName() != null && !jsonDataPath.getMergedFieldName().isEmpty()) { + Map finalMap = new HashMap<>(); + for (Map.Entry entry : map.entrySet()) { + if (jsonDataPath.getMergedFields().contains(entry.getKey())) { + if (!finalMap.containsKey(jsonDataPath.getMergedFieldName())) { + finalMap.put(jsonDataPath.getMergedFieldName(), entry.getValue()); + } else { + finalMap.put(jsonDataPath.getMergedFieldName(), finalMap.get(jsonDataPath.getMergedFieldName()) + " " + entry.getValue()); + } + } else { + finalMap.put(entry.getKey(), entry.getValue()); + } + } + values.add(finalMap); + } else { + values.add(map); + } + } + results = new Results(values, new HashMap<>(1, 1)); + } + + if (results.getPagination().size() == 0) { + results.getPagination().put("pages", 1); + results.getPagination().put("count", results.getResults().size()); + } + return results; + } + } catch (Exception exception) { + logger.error(exception.getMessage(), exception); + } //maybe print smth... + + return null; + } + + private List> getAllResultsFromMockUpJson(String path, String query) { + List> internalResults; + try { + String filePath = Paths.get(path).toUri().toURL().toString(); + ObjectMapper mapper = new ObjectMapper(); + internalResults = mapper.readValue(new File(filePath), new TypeReference>>(){}); + return searchListMap(internalResults, query); + } catch (Exception e) { + logger.error(e.getMessage(), e); + return new LinkedList<>(); + } + } + + private List> searchListMap(List> internalResults, String query) { + List> list = new LinkedList<>(); + for (Map map : internalResults) + { + if (map.get("name") != null && map.get("name").toUpperCase().contains(query.toUpperCase())) { + list.add(map); + } + if (map.get("label") != null && map.get("label").toUpperCase().contains(query.toUpperCase())) { + list.add(map); + } + } + return list; + } + + private String transformKey(DataUrlConfiguration dataUrlConfiguration, String key) { + if (dataUrlConfiguration.getFieldsUrlConfiguration().getId() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getId().replace("'",""))) { + if(dataUrlConfiguration.getFieldsUrlConfiguration().getPid() == null) + return "pid"; + else + return "originalId"; + } + if (dataUrlConfiguration.getFieldsUrlConfiguration().getPid() != null && key.equals("pid")) return "pid"; + if (dataUrlConfiguration.getFieldsUrlConfiguration().getPidTypeField() != null && key.equals("pidTypeField")) return "pidTypeField"; + if (dataUrlConfiguration.getFieldsUrlConfiguration().getDescription() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getDescription().replace("'",""))) return "description"; + if (dataUrlConfiguration.getFieldsUrlConfiguration().getUri() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getUri().replace("'",""))) return "uri"; + if (dataUrlConfiguration.getFieldsUrlConfiguration().getName() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getName().replace("'",""))) return "name"; + if (dataUrlConfiguration.getFieldsUrlConfiguration().getSource() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getSource().replace("'",""))) return "source"; + if (dataUrlConfiguration.getFieldsUrlConfiguration().getCount() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getCount().replace("'",""))) return "count"; + if (dataUrlConfiguration.getFieldsUrlConfiguration().getPath() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getPath().replace("'",""))) return "path"; + if (dataUrlConfiguration.getFieldsUrlConfiguration().getHost() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getHost().replace("'",""))) return "host"; + return null; + } + + private String parseBodyString(String bodyString) { + String finalBodyString = bodyString; + if (bodyString.contains("{env:")) { + int index = bodyString.indexOf("{env: "); + while (index >= 0) { + int endIndex = bodyString.indexOf("}", index + 6); + String envName = bodyString.substring(index + 6, endIndex); + finalBodyString = finalBodyString.replace("{env: " + envName + "}", System.getenv(envName)); + index = bodyString.indexOf("{env: ", index + 6); + } + } + return finalBodyString; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/RemoteFetcherUtils.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/RemoteFetcherUtils.java new file mode 100644 index 000000000..67296c781 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/RemoteFetcherUtils.java @@ -0,0 +1,152 @@ +package eu.eudat.old.logic.proxy.fetching; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.jayway.jsonpath.DocumentContext; +import eu.eudat.old.logic.proxy.config.DataUrlConfiguration; +import eu.eudat.old.logic.proxy.config.ExternalUrlCriteria; +import eu.eudat.old.logic.proxy.fetching.entities.Results; +import net.minidev.json.JSONArray; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.*; +import java.util.stream.Collectors; + +public class RemoteFetcherUtils { + private final static Logger logger = LoggerFactory.getLogger(RemoteFetcherUtils.class); + private static final ObjectMapper mapper = new ObjectMapper(); + + public static Results getFromJson(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { + return new Results(parseData(jsonContext, jsonDataPath), + new HashMap<>(1, 1)); + } + + public static Results getFromJsonWithRecursiveFetching(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath, RemoteFetcher remoteFetcher, String requestBody, String requestType, String auth) { + Results results = new Results(parseData(jsonContext, jsonDataPath), + new HashMap<>(1, 1)); + + List> multiResults = results.getResults().stream().map(result -> { + ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(); + externalUrlCriteria.setPath(result.get("path")); + externalUrlCriteria.setHost(result.get("host")); + String replacedPath = remoteFetcher.replaceCriteriaOnUrl(jsonDataPath.getUrlConfiguration().getUrl(), externalUrlCriteria, jsonDataPath.getUrlConfiguration().getFirstpage(), jsonDataPath.getUrlConfiguration().getQueries()); + return remoteFetcher.getResultsFromUrl(replacedPath, jsonDataPath.getUrlConfiguration().getData(), jsonDataPath.getUrlConfiguration().getData().getPath(), jsonDataPath.getUrlConfiguration().getContentType(), requestBody, requestType, auth); + }).filter(Objects::nonNull).map(results1 -> results1.getResults().get(0)).collect(Collectors.toList()); + return new Results(multiResults, new HashMap<>(1, 1)); + } + + public static Results getFromJsonWithFirstAndLastName(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { + Results results = new Results(parseData(jsonContext, jsonDataPath), + new HashMap<>(1, 1)); + results.getResults().stream().forEach(entry -> { + String name = entry.get(jsonDataPath.getFieldsUrlConfiguration().getFirstName().replace("'", "")) + " " + entry.get(jsonDataPath.getFieldsUrlConfiguration().getLastName().replace("'", "")); + entry.put("name", name); + entry.remove(jsonDataPath.getFieldsUrlConfiguration().getFirstName().replace("'", "")); + entry.remove(jsonDataPath.getFieldsUrlConfiguration().getLastName().replace("'", "")); + }); + return results; + } + + private static List> parseData (DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { + List > rawData = jsonContext.read(jsonDataPath.getPath()); + List> parsedData = new ArrayList<>(); + rawData.forEach(stringObjectMap -> { + parsedData.add(new LinkedHashMap<>()); + Arrays.stream(jsonDataPath.getFieldsUrlConfiguration().getClass().getDeclaredFields()).forEach(field -> { + String getterMethodName = "get" + field.getName().substring(0, 1).toUpperCase(Locale.ROOT) + field.getName().substring(1); + Method getterMethod = Arrays.stream(jsonDataPath.getFieldsUrlConfiguration().getClass().getDeclaredMethods()).filter(method -> method.getName().equals(getterMethodName)).collect(Collectors.toList()).get(0); + try { + String value = ((String) getterMethod.invoke(jsonDataPath.getFieldsUrlConfiguration())); + if (value != null) { + if (field.getName().equals("pid") || field.getName().equals("pidTypeField")) { + String pid = null; + Object pidObj = stringObjectMap.get(value.split("\\.")[0]); + if(pidObj != null){ + if(pidObj instanceof Map){ + Object o = ((Map) pidObj).get(value.split("\\.")[1]); + if(o instanceof String){ + pid = (String)o; + } + else if(o instanceof Integer){ + pid = String.valueOf(o); + } + } + else if(pidObj instanceof List){ + Object o = ((List>) pidObj).get(0).get(value.split("\\.")[1]); + if(o instanceof String){ + pid = (String)o; + } + else if(o instanceof Integer){ + pid = String.valueOf(o); + } + } + } + if(pid != null) { + if ((field.getName().equals("pid"))){ + parsedData.get(parsedData.size() - 1).put("pid", pid); + } + else{ + parsedData.get(parsedData.size() - 1).put("pidTypeField", pid); + } + } + } else { + value = value.replace("'", ""); + if (value.contains(".")) { + String[] parts = value.split("\\."); + Map tempMap = stringObjectMap; + for (int i = 0; i < parts.length; i++) { + if (tempMap.containsKey(parts[i])) { + if (i + 1 < parts.length) { + tempMap = (Map) tempMap.get(parts[i]); + } else { + parsedData.get(parsedData.size() - 1).put(field.getName().equals("types") ? "tags" : value, normalizeValue(tempMap.get(parts[i]), (field.getName().equals("types") || field.getName().equals("uri")))); + } + } + } + } else { + if (stringObjectMap.containsKey(value)) { + parsedData.get(parsedData.size() - 1).put(field.getName().equals("types") ? "tags" : value, normalizeValue(stringObjectMap.get(value), (field.getName().equals("types") || field.getName().equals("uri")))); + } + } + } + } + } catch (IllegalAccessException | InvocationTargetException e) { + logger.error(e.getLocalizedMessage(), e); + } + }); + }); + return parsedData; + } + + private static String normalizeValue(Object value, boolean jsonString) { + if (value instanceof JSONArray) { + if (jsonString) { + return ((JSONArray)value).toJSONString(); + } + JSONArray jarr = (JSONArray) value; + if (jarr.get(0) instanceof String) { + return jarr.get(0).toString(); + } else { + for (Object o : jarr) { + if ((o instanceof Map) && ((Map) o).containsKey("content")) { + try { + return ((Map) o).get("content"); + } + catch (ClassCastException e){ + if(((Map) o).get("content") instanceof Integer) { + return String.valueOf(((Map) o).get("content")); + } + return null; + } + } + } + } + } else if (value instanceof Map) { + String key = ((Map)value).containsKey("$") ? "$" : "content"; + return ((Map)value).get(key); + } + return value != null ? value.toString() : null; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/Config.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/Config.java new file mode 100644 index 000000000..40a081e4e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/Config.java @@ -0,0 +1,21 @@ +package eu.eudat.old.logic.proxy.fetching.entities; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "fetchConfig") +public class Config { + private List configs; + + @XmlElementWrapper + @XmlElement(name = "config") + public List getConfigs() { + return configs; + } + public void setConfigs(List configs) { + this.configs = configs; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/ConfigSingle.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/ConfigSingle.java new file mode 100644 index 000000000..31c93fe81 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/ConfigSingle.java @@ -0,0 +1,71 @@ +package eu.eudat.old.logic.proxy.fetching.entities; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "config") +public class ConfigSingle { + private String type; + private String fileType; + private String filePath; + private String parseClass; + private String parseField; + private String name; + private String value; + + @XmlElement(name = "type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + @XmlElement(name = "fileType") + public String getFileType() { + return fileType; + } + public void setFileType(String fileType) { + this.fileType = fileType; + } + + @XmlElement(name = "filePath") + public String getFilePath() { + return filePath; + } + public void setFilePath(String filePath) { + this.filePath = filePath; + } + + @XmlElement(name = "parseClass") + public String getParseClass() { + return parseClass; + } + public void setParseClass(String parseClass) { + this.parseClass = parseClass; + } + + @XmlElement(name = "parseField") + public String getParseField() { + return parseField; + } + public void setParseField(String parseField) { + this.parseField = parseField; + } + + @XmlElement(name = "name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @XmlElement(name = "value") + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/CurrencyModel.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/CurrencyModel.java new file mode 100644 index 000000000..e4f7d8244 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/CurrencyModel.java @@ -0,0 +1,21 @@ +package eu.eudat.old.logic.proxy.fetching.entities; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "ISO_4217") +public class CurrencyModel { + private List currencies; + + @XmlElementWrapper(name = "CcyTbl") + @XmlElement(name = "CcyNtry") + public List getCurrencies() { + return currencies; + } + public void setCurrencies(List currencies) { + this.currencies = currencies; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/CurrencySingleModel.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/CurrencySingleModel.java new file mode 100644 index 000000000..c4112bcb7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/CurrencySingleModel.java @@ -0,0 +1,53 @@ +package eu.eudat.old.logic.proxy.fetching.entities; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "CcyNtry") +public class CurrencySingleModel { + private String country; + private String currency; + private String code; + private Integer numericCode; + private Integer unit; + + @XmlElement(name = "CtryNm") + public String getCountry() { + return country; + } + public void setCountry(String country) { + this.country = country; + } + + @XmlElement(name = "CcyNm") + public String getCurrency() { + return currency; + } + public void setCurrency(String currency) { + this.currency = currency; + } + + @XmlElement(name = "Ccy") + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } + + @XmlElement(name = "CcyNbr") + public Integer getNumericCode() { + return numericCode; + } + public void setNumericCode(Integer numericCode) { + this.numericCode = numericCode; + } + + @XmlElement(name = "CcyMnrUnts") + public Integer getUnit() { + return unit; + } + public void setUnit(Integer unit) { + this.unit = unit; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/Results.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/Results.java new file mode 100644 index 000000000..2c3ca4fa0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/proxy/fetching/entities/Results.java @@ -0,0 +1,37 @@ +package eu.eudat.old.logic.proxy.fetching.entities; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Results { + List> results; + Map pagination; + + public Results() { + this.results = new ArrayList<>(); + this.pagination = new HashMap<>(); + } + + public Results(List> results, Map pagination) { + this.results = results; + this.pagination = pagination; + } + + public List> getResults() { + return results; + } + + public void setResults(List> results) { + this.results = results; + } + + public Map getPagination() { + return pagination; + } + + public void setPagination(Map pagination) { + this.pagination = pagination; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/CustomAuthenticationProvider.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/CustomAuthenticationProvider.java new file mode 100644 index 000000000..18303e74e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/CustomAuthenticationProvider.java @@ -0,0 +1,47 @@ +package eu.eudat.old.logic.security; + +import eu.eudat.old.exceptions.security.NonValidTokenException; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.exceptions.security.UnauthorisedException; +import eu.eudat.old.logic.security.validators.TokenValidatorFactory; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.principal.PrincipalModel; +import eu.eudat.old.models.data.security.Principal; +import net.shibboleth.utilities.java.support.component.ComponentInitializationException; +import net.shibboleth.utilities.java.support.resolver.ResolverException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +@Component +public class CustomAuthenticationProvider { + private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class); + + + @Autowired + private TokenValidatorFactory tokenValidatorFactory; + + public PrincipalModel authenticate(LoginInfo credentials) throws GeneralSecurityException, NullEmailException { + String token = credentials.getTicket(); + try { + Principal principal = this.tokenValidatorFactory.getProvider(credentials.getProvider()).validateToken(credentials); + return (principal != null) ? PrincipalModel.fromEntity(principal) : null; + } catch (NonValidTokenException e) { + logger.error("Could not validate a user by his token! Reason: " + e.getMessage(), e); + throw new UnauthorisedException("Token validation failed - Not a valid token"); + } catch (IOException e) { + logger.error(e.getMessage(), e); + throw new UnauthorisedException("IO Exeption"); + } catch (NullEmailException e) { + logger.error(e.getMessage(), e); + throw new NullEmailException(); + } catch (ResolverException | ComponentInitializationException e){ + logger.error(e.getMessage(), e); + throw new GeneralSecurityException(); + } + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/claims/ClaimedAuthorities.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/claims/ClaimedAuthorities.java new file mode 100644 index 000000000..9e9b7951b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/claims/ClaimedAuthorities.java @@ -0,0 +1,17 @@ +package eu.eudat.old.logic.security.claims; + +import eu.eudat.old.types.Authorities; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static eu.eudat.old.types.Authorities.USER; + + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface ClaimedAuthorities { + Authorities[] claims() default {USER}; +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/claims/ClaimedRights.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/claims/ClaimedRights.java new file mode 100644 index 000000000..572342988 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/claims/ClaimedRights.java @@ -0,0 +1,17 @@ +package eu.eudat.old.logic.security.claims; + +import eu.eudat.old.types.Rights; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Created by ikalyvas on 2/8/2018. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface ClaimedRights { + Rights[] claims() default {}; +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/B2Access/B2AccessCustomProvider.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/B2Access/B2AccessCustomProvider.java new file mode 100644 index 000000000..e9dcfdda0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/B2Access/B2AccessCustomProvider.java @@ -0,0 +1,12 @@ +package eu.eudat.old.logic.security.customproviders.B2Access; + +import eu.eudat.old.logic.security.validators.b2access.helpers.B2AccessResponseToken; + +/** + * Created by ikalyvas on 2/22/2018. + */ +public interface B2AccessCustomProvider { + B2AccessUser getUser(String accessToken); + + B2AccessResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/B2Access/B2AccessCustomProviderImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/B2Access/B2AccessCustomProviderImpl.java new file mode 100644 index 000000000..b9c53bb96 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/B2Access/B2AccessCustomProviderImpl.java @@ -0,0 +1,76 @@ +package eu.eudat.old.logic.security.customproviders.B2Access; + +import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64; +import eu.eudat.old.logic.security.validators.b2access.helpers.B2AccessResponseToken; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import java.nio.charset.Charset; +import java.util.Map; + +@Component("b2AccessCustomProvider") +public class B2AccessCustomProviderImpl implements B2AccessCustomProvider { + + private Environment environment; + + @Autowired + public B2AccessCustomProviderImpl(Environment environment) { + this.environment = environment; + } + + public B2AccessUser getUser(String accessToken) { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = this.createBearerAuthHeaders(accessToken); + HttpEntity entity = new HttpEntity<>(headers); + + Map values = restTemplate.exchange(this.environment.getProperty("b2access.externallogin.user_info_url"), HttpMethod.GET, entity, Map.class).getBody(); + B2AccessUser b2AccessUser = new B2AccessUser(); + b2AccessUser.setEmail((String)values.get("email")); + b2AccessUser.setId((String)values.get("urn:oid:2.5.4.49")); + b2AccessUser.setName((String)values.get("name")); + return b2AccessUser; + } + + @Override + public B2AccessResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret) { + RestTemplate template = new RestTemplate(); + HttpHeaders headers = this.createBasicAuthHeaders(clientId, clientSecret); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + MultiValueMap map = new LinkedMultiValueMap(); + map.add("code", code); + map.add("grant_type", "authorization_code"); + map.add("redirect_uri", redirectUri); + HttpEntity> request = new HttpEntity>(map, headers); + + Map values = template.postForObject(this.environment.getProperty("b2access.externallogin.access_token_url"), request, Map.class); + B2AccessResponseToken b2AccessResponseToken = new B2AccessResponseToken(); + b2AccessResponseToken.setAccessToken((String) values.get("access_token")); + return b2AccessResponseToken; + } + + private HttpHeaders createBasicAuthHeaders(String username, String password) { + return new HttpHeaders() {{ + String auth = username + ":" + password; + byte[] encodedAuth = Base64.encodeBase64( + auth.getBytes(Charset.forName("US-ASCII"))); + String authHeader = "Basic " + new String(encodedAuth); + set("Authorization", authHeader); + }}; + } + + private HttpHeaders createBearerAuthHeaders(String accessToken) { + return new HttpHeaders() {{ + String authHeader = "Bearer " + new String(accessToken); + set("Authorization", authHeader); + }}; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/B2Access/B2AccessUser.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/B2Access/B2AccessUser.java new file mode 100644 index 000000000..9032eb1e0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/B2Access/B2AccessUser.java @@ -0,0 +1,34 @@ +package eu.eudat.old.logic.security.customproviders.B2Access; + +/** + * Created by ikalyvas on 2/22/2018. + */ +public class B2AccessUser { + private String id; + private String name; + private String email; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/ConfigurableProviderCustomProvider.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/ConfigurableProviderCustomProvider.java new file mode 100644 index 000000000..41b4995e5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/ConfigurableProviderCustomProvider.java @@ -0,0 +1,11 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider; + +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.oauth2.Oauth2ConfigurableProviderUserSettings; +import eu.eudat.old.logic.security.validators.configurableProvider.helpers.ConfigurableProviderResponseToken; + +public interface ConfigurableProviderCustomProvider { + + ConfigurableProviderResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret, String accessTokenUrl, String grantType, String access_token, String expires_in); + + ConfigurableProviderUser getUser(String accessToken, Oauth2ConfigurableProviderUserSettings user); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/ConfigurableProviderCustomProviderImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/ConfigurableProviderCustomProviderImpl.java new file mode 100644 index 000000000..fca441329 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/ConfigurableProviderCustomProviderImpl.java @@ -0,0 +1,61 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider; + +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.oauth2.Oauth2ConfigurableProviderUserSettings; +import eu.eudat.old.logic.security.validators.configurableProvider.helpers.ConfigurableProviderResponseToken; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import java.util.Map; + +@Component("configurableProviderCustomProvider") +public class ConfigurableProviderCustomProviderImpl implements ConfigurableProviderCustomProvider { + + @Override + public ConfigurableProviderResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret, String accessTokenUrl, + String grantType, String access_token, String expires_in) { + RestTemplate template = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + MultiValueMap map = new LinkedMultiValueMap(); + + map.add("grant_type", grantType); + map.add("code", code); + map.add("redirect_uri", redirectUri); + map.add("client_id", clientId); + map.add("client_secret", clientSecret); + HttpEntity> request = new HttpEntity<>(map, headers); + + Map values = template.postForObject(accessTokenUrl, request, Map.class); + ConfigurableProviderResponseToken responseToken = new ConfigurableProviderResponseToken(); + responseToken.setAccessToken((String) values.get(access_token)); + if (expires_in != null && !expires_in.isEmpty()) { + responseToken.setExpiresIn((Integer) values.get(expires_in)); + } + + return responseToken; + } + + @Override + public ConfigurableProviderUser getUser(String accessToken, Oauth2ConfigurableProviderUserSettings user) { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = this.createBearerAuthHeaders(accessToken); + HttpEntity entity = new HttpEntity<>(headers); + + Map values = restTemplate.exchange(user.getUser_info_url(), HttpMethod.GET, entity, Map.class).getBody(); + return new ConfigurableProviderUser().getConfigurableProviderUser(values, user); + } + + private HttpHeaders createBearerAuthHeaders(String accessToken) { + return new HttpHeaders() {{ + String authHeader = "Bearer " + accessToken; + set("Authorization", authHeader); + }}; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/ConfigurableProviderUser.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/ConfigurableProviderUser.java new file mode 100644 index 000000000..d26a939ac --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/ConfigurableProviderUser.java @@ -0,0 +1,42 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider; + +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.oauth2.Oauth2ConfigurableProviderUserSettings; + +import java.util.Map; + +public class ConfigurableProviderUser { + private String id; + private String name; + private String email; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + ConfigurableProviderUser getConfigurableProviderUser(Map data, Oauth2ConfigurableProviderUserSettings user) { + if (user.getId() != null && !user.getId().isEmpty()) + this.id = (String) data.get(user.getId()); + if (user.getName() != null && !user.getName().isEmpty()) + this.name = (String) data.get(user.getName()); + if (user.getEmail() != null && !user.getEmail().isEmpty()) + this.email = (String) data.get(user.getEmail()); + return this; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/ConfigurableProvider.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/ConfigurableProvider.java new file mode 100644 index 000000000..2096487b3 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/ConfigurableProvider.java @@ -0,0 +1,55 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities; + +import com.fasterxml.jackson.annotation.*; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.oauth2.Oauth2ConfigurableProvider; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.saml2.Saml2ConfigurableProvider; + +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = Oauth2ConfigurableProvider.class, name = "oauth2"), + @JsonSubTypes.Type(value = Saml2ConfigurableProvider.class, name = "saml2") +}) +public class ConfigurableProvider { + + private boolean enabled; + private String configurableLoginId; + private String type; + private String name; + private String logoUrl; + + public boolean isEnabled() { + return enabled; + } + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getConfigurableLoginId() { + return configurableLoginId; + } + public void setConfigurableLoginId(String configurableLoginId) { + this.configurableLoginId = configurableLoginId; + } + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getLogoUrl() { + return logoUrl; + } + public void setLogoUrl(String logoUrl) { + this.logoUrl = logoUrl; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/ConfigurableProviders.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/ConfigurableProviders.java new file mode 100644 index 000000000..dd02ab3b5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/ConfigurableProviders.java @@ -0,0 +1,15 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities; + +import java.util.ArrayList; +import java.util.List; + +public class ConfigurableProviders { + private List providers = new ArrayList<>(); + + public List getProviders() { + return providers; + } + public void setProviders(List providers) { + this.providers = providers; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/oauth2/Oauth2ConfigurableProvider.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/oauth2/Oauth2ConfigurableProvider.java new file mode 100644 index 000000000..740d41522 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/oauth2/Oauth2ConfigurableProvider.java @@ -0,0 +1,88 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.oauth2; + +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.ConfigurableProvider; + +public class Oauth2ConfigurableProvider extends ConfigurableProvider { + + private String clientId; + private String clientSecret; + private String redirect_uri; + private String access_token_url; + private String grant_type; + private Oauth2ConfigurableProviderToken token; + private Oauth2ConfigurableProviderUserSettings user; + private String oauthUrl; + private String scope; + private String state; + + public String getClientId() { + return clientId; + } + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret; + } + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public String getRedirect_uri() { + return redirect_uri; + } + public void setRedirect_uri(String redirect_uri) { + this.redirect_uri = redirect_uri; + } + + public String getAccess_token_url() { + return access_token_url; + } + public void setAccess_token_url(String access_token_url) { + this.access_token_url = access_token_url; + } + + public String getGrant_type() { + return grant_type; + } + public void setGrant_type(String grant_type) { + this.grant_type = grant_type; + } + + public Oauth2ConfigurableProviderToken getToken() { + return token; + } + public void setToken(Oauth2ConfigurableProviderToken token) { + this.token = token; + } + + public Oauth2ConfigurableProviderUserSettings getUser() { + return user; + } + public void setUser(Oauth2ConfigurableProviderUserSettings user) { + this.user = user; + } + + public String getOauthUrl() { + return oauthUrl; + } + public void setOauthUrl(String oauthUrl) { + this.oauthUrl = oauthUrl; + } + + public String getScope() { + return scope; + } + public void setScope(String scope) { + this.scope = scope; + } + + public String getState() { + return state; + } + public void setState(String state) { + this.state = state; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/oauth2/Oauth2ConfigurableProviderToken.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/oauth2/Oauth2ConfigurableProviderToken.java new file mode 100644 index 000000000..892033e07 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/oauth2/Oauth2ConfigurableProviderToken.java @@ -0,0 +1,20 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.oauth2; + +public class Oauth2ConfigurableProviderToken { + private String access_token; + private String expires_in; + + public String getAccess_token() { + return access_token; + } + public void setAccess_token(String access_token) { + this.access_token = access_token; + } + + public String getExpires_in() { + return expires_in; + } + public void setExpires_in(String expires_in) { + this.expires_in = expires_in; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/oauth2/Oauth2ConfigurableProviderUserSettings.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/oauth2/Oauth2ConfigurableProviderUserSettings.java new file mode 100644 index 000000000..6a75fa5da --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/oauth2/Oauth2ConfigurableProviderUserSettings.java @@ -0,0 +1,36 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.oauth2; + +public class Oauth2ConfigurableProviderUserSettings { + private String id; + private String name; + private String email; + private String user_info_url; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + public String getUser_info_url() { + return user_info_url; + } + public void setUser_info_url(String user_info_url) { + this.user_info_url = user_info_url; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/saml2/CertificateInfo.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/saml2/CertificateInfo.java new file mode 100644 index 000000000..8943ce795 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/saml2/CertificateInfo.java @@ -0,0 +1,68 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.saml2; + +import com.fasterxml.jackson.annotation.JsonValue; + +public class CertificateInfo { + + public enum KeyFormat { + JKS("JKS"), PKCS12("PKCS12"); + + private String type; + KeyFormat(String type) { + this.type = type; + } + @JsonValue + public String getType() { return type; } + + public static KeyFormat fromType(String type) { + for (KeyFormat t: KeyFormat.values()) { + if (type.equals(t.getType())) { + return t; + } + } + throw new IllegalArgumentException("Unsupported Keystore format " + type); + } + } + + private String alias; + private String password; + private String keystorePath; + private String keystorePassword; + private KeyFormat keyFormat; + + public String getAlias() { + return alias; + } + public void setAlias(String alias) { + this.alias = alias; + } + + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + public String getKeystorePath() { + return keystorePath; + } + public void setKeystorePath(String keystorePath) { + this.keystorePath = keystorePath; + } + + public String getKeystorePassword() { + return keystorePassword; + } + public void setKeystorePassword(String keystorePassword) { + this.keystorePassword = keystorePassword; + } + + public KeyFormat getKeyFormat() { + return keyFormat; + } + public void setKeyFormat(KeyFormat keyFormat) { + this.keyFormat = keyFormat; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/saml2/Saml2ConfigurableProvider.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/saml2/Saml2ConfigurableProvider.java new file mode 100644 index 000000000..dc0136a4a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/entities/saml2/Saml2ConfigurableProvider.java @@ -0,0 +1,194 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.saml2; + +import com.fasterxml.jackson.annotation.JsonValue; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.ConfigurableProvider; + +import java.util.Map; + +public class Saml2ConfigurableProvider extends ConfigurableProvider { + + public enum SAML2UsingFormat { + NAME("name"), FRIENDLY_NAME("friendly_name"); + + private String name; + SAML2UsingFormat(String name) { + this.name = name; + } + @JsonValue + public String getName() { return name; } + + public static SAML2UsingFormat fromName(String name) { + for (SAML2UsingFormat type: SAML2UsingFormat.values()) { + if (name.equals(type.getName())) { + return type; + } + } + throw new IllegalArgumentException("Unsupported SAML2 Attribute " + name); + } + } + + public enum SAML2AttributeType { + XSSTRING("XSString"), XSINTEGER("XSInteger"), XSDATETIME("XSDateTime"), XSBOOLEAN("XSBoolean"), XSBASE64BINARY("XSBase64Binary"), XSURI("XSURI"), XSQNAME("XSQName"), XSANY("XSAny"); + + private String type; + SAML2AttributeType(String type) { + this.type = type; + } + @JsonValue + public String getType() { return type; } + + public static SAML2AttributeType fromType(String type) { + for (SAML2AttributeType t: SAML2AttributeType.values()) { + if (type.equals(t.getType())) { + return t; + } + } + throw new IllegalArgumentException("Unsupported SAML2 Attribute Type " + type); + } + } + + private String spEntityId; + private String idpEntityId; + private String idpUrl; + private String idpArtifactUrl; + private String idpMetadataUrl; + private boolean assertionEncrypted; + private CertificateInfo encryptionCert; + private CertificateInfo signingCert; + private boolean responseSigned; + private boolean assertionSigned; + private boolean signatureRequired; + private SAML2UsingFormat usingFormat; + private Map attributeTypes; + private Map configurableUserFromAttributes; + private String binding; + private String assertionConsumerServiceUrl; + private boolean wantAssertionsSigned; + private boolean authnRequestsSigned; + + public String getSpEntityId() { + return spEntityId; + } + public void setSpEntityId(String spEntityId) { + this.spEntityId = spEntityId; + } + + public String getIdpEntityId() { + return idpEntityId; + } + public void setIdpEntityId(String idpEntityId) { + this.idpEntityId = idpEntityId; + } + + public String getIdpUrl() { + return idpUrl; + } + public void setIdpUrl(String idpUrl) { + this.idpUrl = idpUrl; + } + + public String getIdpArtifactUrl() { + return idpArtifactUrl; + } + public void setIdpArtifactUrl(String idpArtifactUrl) { + this.idpArtifactUrl = idpArtifactUrl; + } + + public String getIdpMetadataUrl() { + return idpMetadataUrl; + } + public void setIdpMetadataUrl(String idpMetadataUrl) { + this.idpMetadataUrl = idpMetadataUrl; + } + + public boolean isAssertionEncrypted() { + return assertionEncrypted; + } + public void setAssertionEncrypted(boolean assertionEncrypted) { + this.assertionEncrypted = assertionEncrypted; + } + + public CertificateInfo getEncryptionCert() { + return encryptionCert; + } + public void setEncryptionCert(CertificateInfo encryptionCert) { + this.encryptionCert = encryptionCert; + } + + public CertificateInfo getSigningCert() { + return signingCert; + } + public void setSigningCert(CertificateInfo signingCert) { + this.signingCert = signingCert; + } + + public boolean isResponseSigned() { + return responseSigned; + } + public void setResponseSigned(boolean responseSigned) { + this.responseSigned = responseSigned; + } + + public boolean isAssertionSigned() { + return assertionSigned; + } + public void setAssertionSigned(boolean assertionSigned) { + this.assertionSigned = assertionSigned; + } + + public boolean isSignatureRequired() { + return signatureRequired; + } + public void setSignatureRequired(boolean signatureRequired) { + this.signatureRequired = signatureRequired; + } + + public SAML2UsingFormat getUsingFormat() { + return usingFormat; + } + public void setUsingFormat(SAML2UsingFormat usingFormat) { + this.usingFormat = usingFormat; + } + + public Map getConfigurableUserFromAttributes() { + return configurableUserFromAttributes; + } + public void setConfigurableUserFromAttributes(Map configurableUserFromAttributes) { + this.configurableUserFromAttributes = configurableUserFromAttributes; + } + + public Map getAttributeTypes() { + return attributeTypes; + } + public void setAttributeTypes(Map attributeTypes) { + this.attributeTypes = attributeTypes; + } + + public String getBinding() { + return binding; + } + public void setBinding(String binding) { + this.binding = binding; + } + + public String getAssertionConsumerServiceUrl() { + return assertionConsumerServiceUrl; + } + public void setAssertionConsumerServiceUrl(String assertionConsumerServiceUrl) { + this.assertionConsumerServiceUrl = assertionConsumerServiceUrl; + } + + public boolean isWantAssertionsSigned() { + return wantAssertionsSigned; + } + public void setWantAssertionsSigned(boolean wantAssertionsSigned) { + this.wantAssertionsSigned = wantAssertionsSigned; + } + + public boolean isAuthnRequestsSigned() { + return authnRequestsSigned; + } + public void setAuthnRequestsSigned(boolean authnRequestsSigned) { + this.authnRequestsSigned = authnRequestsSigned; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/ConfigurableProviderModel.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/ConfigurableProviderModel.java new file mode 100644 index 000000000..3d38662b3 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/ConfigurableProviderModel.java @@ -0,0 +1,49 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider.models; + +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.ConfigurableProvider; + +public class ConfigurableProviderModel { + + private String configurableLoginId; + private String type; + private String name; + private String logoUrl; + + public String getConfigurableLoginId() { + return configurableLoginId; + } + public void setConfigurableLoginId(String configurableLoginId) { + this.configurableLoginId = configurableLoginId; + } + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getLogoUrl() { + return logoUrl; + } + public void setLogoUrl(String logoUrl) { + this.logoUrl = logoUrl; + } + + public ConfigurableProviderModel fromDataModel(ConfigurableProvider entity) { + ConfigurableProviderModel model = new ConfigurableProviderModel(); + model.setConfigurableLoginId(entity.getConfigurableLoginId()); + model.setType(entity.getType()); + model.setName(entity.getName()); + model.setLogoUrl(entity.getLogoUrl()); + return model; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/ConfigurableProvidersModel.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/ConfigurableProvidersModel.java new file mode 100644 index 000000000..cd44b30f3 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/ConfigurableProvidersModel.java @@ -0,0 +1,41 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider.models; + +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.oauth2.Oauth2ConfigurableProvider; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.models.saml2.Saml2ConfigurableProviderModel; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.ConfigurableProvider; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.ConfigurableProviders; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.saml2.Saml2ConfigurableProvider; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.models.oauth2.Oauth2ConfigurableProviderModel; + +import java.util.LinkedList; +import java.util.List; + +public class ConfigurableProvidersModel { + private List providers; + + public List getProviders() { + return providers; + } + public void setProviders(List providers) { + this.providers = providers; + } + + public ConfigurableProvidersModel fromDataModel(ConfigurableProviders entity) { + ConfigurableProvidersModel model = new ConfigurableProvidersModel(); + List providerModelList = new LinkedList<>(); + if (entity != null) { + for (ConfigurableProvider entityProvider : entity.getProviders()) { + if (entityProvider.isEnabled()){ + if(entityProvider instanceof Oauth2ConfigurableProvider) + providerModelList.add(new Oauth2ConfigurableProviderModel().fromDataModel(entityProvider)); + else if(entityProvider instanceof Saml2ConfigurableProvider) + providerModelList.add(new Saml2ConfigurableProviderModel().fromDataModel(entityProvider)); + else + providerModelList.add(new ConfigurableProviderModel().fromDataModel(entityProvider)); + } + } + } + model.setProviders(providerModelList); + return model; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/oauth2/Oauth2ConfigurableProviderModel.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/oauth2/Oauth2ConfigurableProviderModel.java new file mode 100644 index 000000000..620c91bc1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/oauth2/Oauth2ConfigurableProviderModel.java @@ -0,0 +1,65 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider.models.oauth2; + +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.ConfigurableProvider; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.oauth2.Oauth2ConfigurableProvider; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.models.ConfigurableProviderModel; + +public class Oauth2ConfigurableProviderModel extends ConfigurableProviderModel { + + private String clientId; + private String redirect_uri; + private String oauthUrl; + private String scope; + private String state; + + public String getClientId() { + return clientId; + } + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getRedirect_uri() { + return redirect_uri; + } + public void setRedirect_uri(String redirect_uri) { + this.redirect_uri = redirect_uri; + } + + public String getOauthUrl() { + return oauthUrl; + } + public void setOauthUrl(String oauthUrl) { + this.oauthUrl = oauthUrl; + } + + public String getScope() { + return scope; + } + public void setScope(String scope) { + this.scope = scope; + } + + public String getState() { + return state; + } + public void setState(String state) { + this.state = state; + } + + @Override + public Oauth2ConfigurableProviderModel fromDataModel(ConfigurableProvider entity) { + Oauth2ConfigurableProviderModel model = new Oauth2ConfigurableProviderModel(); + model.setConfigurableLoginId(entity.getConfigurableLoginId()); + model.setType(entity.getType()); + model.setName(entity.getName()); + model.setLogoUrl(entity.getLogoUrl()); + model.setClientId(((Oauth2ConfigurableProvider)entity).getClientId()); + model.setRedirect_uri(((Oauth2ConfigurableProvider)entity).getRedirect_uri()); + model.setOauthUrl(((Oauth2ConfigurableProvider)entity).getOauthUrl()); + model.setScope(((Oauth2ConfigurableProvider)entity).getScope()); + model.setState(((Oauth2ConfigurableProvider)entity).getState()); + return model; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/saml2/Saml2ConfigurableProviderModel.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/saml2/Saml2ConfigurableProviderModel.java new file mode 100644 index 000000000..ea81e2b7a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ConfigurableProvider/models/saml2/Saml2ConfigurableProviderModel.java @@ -0,0 +1,56 @@ +package eu.eudat.old.logic.security.customproviders.ConfigurableProvider.models.saml2; + +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.ConfigurableProvider; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.saml2.Saml2ConfigurableProvider; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.models.ConfigurableProviderModel; + +public class Saml2ConfigurableProviderModel extends ConfigurableProviderModel { + + private String spEntityId; + private String idpUrl; + private String binding; + private String assertionConsumerServiceUrl; + + public String getSpEntityId() { + return spEntityId; + } + public void setSpEntityId(String spEntityId) { + this.spEntityId = spEntityId; + } + + public String getIdpUrl() { + return idpUrl; + } + public void setIdpUrl(String idpUrl) { + this.idpUrl = idpUrl; + } + + public String getBinding() { + return binding; + } + public void setBinding(String binding) { + this.binding = binding; + } + + public String getAssertionConsumerServiceUrl() { + return assertionConsumerServiceUrl; + } + public void setAssertionConsumerServiceUrl(String assertionConsumerServiceUrl) { + this.assertionConsumerServiceUrl = assertionConsumerServiceUrl; + } + + @Override + public Saml2ConfigurableProviderModel fromDataModel(ConfigurableProvider entity) { + Saml2ConfigurableProviderModel model = new Saml2ConfigurableProviderModel(); + model.setConfigurableLoginId(entity.getConfigurableLoginId()); + model.setType(entity.getType()); + model.setName(entity.getName()); + model.setLogoUrl(entity.getLogoUrl()); + model.setSpEntityId(((Saml2ConfigurableProvider)entity).getSpEntityId()); + model.setIdpUrl(((Saml2ConfigurableProvider)entity).getIdpUrl()); + model.setBinding(((Saml2ConfigurableProvider)entity).getBinding()); + model.setAssertionConsumerServiceUrl(((Saml2ConfigurableProvider)entity).getAssertionConsumerServiceUrl()); + return model; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/LinkedIn/LinkedInCustomProvider.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/LinkedIn/LinkedInCustomProvider.java new file mode 100644 index 000000000..ab0fe8a69 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/LinkedIn/LinkedInCustomProvider.java @@ -0,0 +1,10 @@ +package eu.eudat.old.logic.security.customproviders.LinkedIn; + +import eu.eudat.old.logic.security.validators.linkedin.helpers.LinkedInResponseToken; + +public interface LinkedInCustomProvider { + + LinkedInUser getUser(String accessToken); + + LinkedInResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/LinkedIn/LinkedInCustomProviderImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/LinkedIn/LinkedInCustomProviderImpl.java new file mode 100644 index 000000000..d20067020 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/LinkedIn/LinkedInCustomProviderImpl.java @@ -0,0 +1,67 @@ +package eu.eudat.old.logic.security.customproviders.LinkedIn; + +import eu.eudat.old.logic.security.validators.linkedin.helpers.LinkedInResponseToken; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import java.util.Map; + +@Component("LinkedInCustomProvider") +public class LinkedInCustomProviderImpl implements LinkedInCustomProvider { + + private Environment environment; + + public LinkedInCustomProviderImpl(Environment environment) { + this.environment = environment; + } + + public LinkedInUser getUser(String accessToken) { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = this.createBearerAuthHeaders(accessToken); + HttpEntity entity = new HttpEntity<>(headers); + + Map profileValues = restTemplate.exchange(this.environment.getProperty("linkedin.login.user_info_url"), HttpMethod.GET, entity, Map.class).getBody(); + Map emailValues = restTemplate.exchange(this.environment.getProperty("linkedin.login.user_email"), HttpMethod.GET, entity, Map.class).getBody(); + LinkedInUser linkedInUser = new LinkedInUser(); + linkedInUser.setEmail((String)emailValues.get("email")); + linkedInUser.setName((String)profileValues.get("localizedFirstName")); + linkedInUser.setId((String)profileValues.get("id")); + return linkedInUser; + } + + public LinkedInResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret) { + RestTemplate template = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + MultiValueMap map = new LinkedMultiValueMap(); + + map.add("grant_type", "authorization_code"); + map.add("code", code); + map.add("redirect_uri", redirectUri); + map.add("client_id", clientId); + map.add("client_secret", clientSecret); + HttpEntity> request = new HttpEntity>(map, headers); + + Map values = template.postForObject(this.environment.getProperty("linkedin.login.access_token_url"), request, Map.class); + LinkedInResponseToken linkedInResponseToken = new LinkedInResponseToken(); + linkedInResponseToken.setAccessToken((String) values.get("access_token")); + linkedInResponseToken.setExpiresIn((Integer) values.get("expires_in")); + + return linkedInResponseToken; + } + + private HttpHeaders createBearerAuthHeaders(String accessToken) { + return new HttpHeaders() {{ + String authHeader = "Bearer " + new String(accessToken); + set("Authorization", authHeader); + }}; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/LinkedIn/LinkedInUser.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/LinkedIn/LinkedInUser.java new file mode 100644 index 000000000..89e1ed33f --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/LinkedIn/LinkedInUser.java @@ -0,0 +1,29 @@ +package eu.eudat.old.logic.security.customproviders.LinkedIn; + +public class LinkedInUser { + private String id; + private String name; + private String email; + + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ORCID/ORCIDCustomProvider.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ORCID/ORCIDCustomProvider.java new file mode 100644 index 000000000..4482dcb17 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ORCID/ORCIDCustomProvider.java @@ -0,0 +1,7 @@ +package eu.eudat.old.logic.security.customproviders.ORCID; + +import eu.eudat.old.logic.security.validators.orcid.helpers.ORCIDResponseToken; + +public interface ORCIDCustomProvider { + ORCIDResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ORCID/ORCIDCustomProviderImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ORCID/ORCIDCustomProviderImpl.java new file mode 100644 index 000000000..7ae551b0d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ORCID/ORCIDCustomProviderImpl.java @@ -0,0 +1,54 @@ +package eu.eudat.old.logic.security.customproviders.ORCID; + +import eu.eudat.old.logic.security.validators.orcid.helpers.ORCIDResponseToken; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import java.util.Map; + +@Component("ORCIDCustomProvider") +public class ORCIDCustomProviderImpl implements ORCIDCustomProvider { + + private Environment environment; + + @Autowired + public ORCIDCustomProviderImpl(Environment environment) { + this.environment = environment; + } + + @Override + public ORCIDResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret) { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.set("accept", "application/json"); + + MultiValueMap map = new LinkedMultiValueMap(); + map.add("client_id", this.environment.getProperty("orcid.login.client_id")); + map.add("client_secret", this.environment.getProperty("orcid.login.client_secret")); + map.add("grant_type", "authorization_code"); + map.add("code", code); + map.add("redirect_uri", redirectUri); + HttpEntity> request = new HttpEntity>(map, headers); + + Map values = restTemplate.postForObject(this.environment.getProperty("orcid.login.access_token_url"), request, Map.class); + ORCIDResponseToken orcidResponseToken = new ORCIDResponseToken(); + orcidResponseToken.setOrcidId((String) values.get("orcid")); + orcidResponseToken.setName((String) values.get("name")); + orcidResponseToken.setAccessToken((String) values.get("access_token")); + + return orcidResponseToken; + } + + private HttpHeaders createBearerAuthHeaders(String accessToken) { + return new HttpHeaders() {{ + String authHeader = "Bearer " + accessToken; + set("Authorization", authHeader); + }}; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ORCID/ORCIDUser.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ORCID/ORCIDUser.java new file mode 100644 index 000000000..13ef069e3 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/ORCID/ORCIDUser.java @@ -0,0 +1,38 @@ +package eu.eudat.old.logic.security.customproviders.ORCID; + +import java.util.Map; + +public class ORCIDUser { + private String orcidId; + private String name; + private String email; + + public String getOrcidId() { + return orcidId; + } + public void setOrcidId(String orcidId) { + this.orcidId = orcidId; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + public ORCIDUser getOrcidUser(Object data) { + this.orcidId = (String) ((Map) data).get("orcidId"); + this.name = (String) ((Map) data).get("name"); + this.email = (String) ((Map) data).get("email"); + return this; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/OpenAIRE/OpenAIRECustomProvider.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/OpenAIRE/OpenAIRECustomProvider.java new file mode 100644 index 000000000..f7aed26e2 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/OpenAIRE/OpenAIRECustomProvider.java @@ -0,0 +1,10 @@ +package eu.eudat.old.logic.security.customproviders.OpenAIRE; + +import eu.eudat.old.logic.security.validators.openaire.helpers.OpenAIREResponseToken; + +public interface OpenAIRECustomProvider { + + OpenAIREResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret); + + OpenAIREUser getUser(String accessToken); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/OpenAIRE/OpenAIRECustomProviderImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/OpenAIRE/OpenAIRECustomProviderImpl.java new file mode 100644 index 000000000..f7214dfc3 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/OpenAIRE/OpenAIRECustomProviderImpl.java @@ -0,0 +1,62 @@ +package eu.eudat.old.logic.security.customproviders.OpenAIRE; + +import eu.eudat.old.logic.security.validators.openaire.helpers.OpenAIREResponseToken; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import java.util.Map; + +@Component("openAIRECustomProvider") +public class OpenAIRECustomProviderImpl implements OpenAIRECustomProvider { + + private Environment environment; + + public OpenAIRECustomProviderImpl(Environment environment) { + this.environment = environment; + } + + public OpenAIREUser getUser(String accessToken) { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = this.createBearerAuthHeaders(accessToken); + HttpEntity entity = new HttpEntity<>(headers); + + Map values = restTemplate.exchange(this.environment.getProperty("openaire.login.user_info_url"), HttpMethod.GET, entity, Map.class).getBody(); + return new OpenAIREUser().getOpenAIREUser(values); + } + + public OpenAIREResponseToken getAccessToken(String code, String redirectUri, String clientId, String clientSecret) { + RestTemplate template = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + MultiValueMap map = new LinkedMultiValueMap(); + + map.add("grant_type", "authorization_code"); + map.add("code", code); + map.add("redirect_uri", redirectUri); + map.add("client_id", clientId); + map.add("client_secret", clientSecret); + HttpEntity> request = new HttpEntity>(map, headers); + + Map values = template.postForObject(this.environment.getProperty("openaire.login.access_token_url"), request, Map.class); + OpenAIREResponseToken openAIREResponseToken = new OpenAIREResponseToken(); + openAIREResponseToken.setAccessToken((String) values.get("access_token")); + openAIREResponseToken.setExpiresIn((Integer) values.get("expires_in")); + + return openAIREResponseToken; + } + + private HttpHeaders createBearerAuthHeaders(String accessToken) { + return new HttpHeaders() {{ + String authHeader = "Bearer " + accessToken; + set("Authorization", authHeader); + }}; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/OpenAIRE/OpenAIREUser.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/OpenAIRE/OpenAIREUser.java new file mode 100644 index 000000000..dc6d092ba --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/OpenAIRE/OpenAIREUser.java @@ -0,0 +1,37 @@ +package eu.eudat.old.logic.security.customproviders.OpenAIRE; + +import java.util.Map; + +public class OpenAIREUser { + private String id; + private String name; + private String email; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + public OpenAIREUser getOpenAIREUser(Object data) { + this.id = (String) ((Map) data).get("sub"); + this.name = (String) ((Map) data).get("name"); + this.email = (String) ((Map) data).get("email"); + return this; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoAccessType.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoAccessType.java new file mode 100644 index 000000000..0491c9bd0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoAccessType.java @@ -0,0 +1,22 @@ +package eu.eudat.old.logic.security.customproviders.Zenodo; + +public enum ZenodoAccessType { + AUTHORIZATION_CODE("authorization_code", "code"), + REFRESH_TOKEN("refresh_token", "refresh_token"); + + private final String grantType; + private final String property; + + ZenodoAccessType(String grantType, String property) { + this.grantType = grantType; + this.property = property; + } + + public String getGrantType() { + return grantType; + } + + public String getProperty() { + return property; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoCustomProvider.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoCustomProvider.java new file mode 100644 index 000000000..2a55f99cf --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoCustomProvider.java @@ -0,0 +1,7 @@ +package eu.eudat.old.logic.security.customproviders.Zenodo; + +import eu.eudat.old.logic.security.validators.zenodo.helpers.ZenodoResponseToken; + +public interface ZenodoCustomProvider { + ZenodoResponseToken getAccessToken(ZenodoAccessType accessType, String code, String clientId, String clientSecret, String redirectUri); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoCustomProviderImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoCustomProviderImpl.java new file mode 100644 index 000000000..194328f9d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoCustomProviderImpl.java @@ -0,0 +1,70 @@ +package eu.eudat.old.logic.security.customproviders.Zenodo; + +import eu.eudat.old.logic.security.validators.zenodo.helpers.ZenodoResponseToken; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; + +import java.util.Collections; +import java.util.Map; + +@Component("ZenodoCustomProvider") +public class ZenodoCustomProviderImpl implements ZenodoCustomProvider { + private static final Logger logger = LoggerFactory.getLogger(ZenodoCustomProviderImpl.class); + + private Environment environment; + + @Autowired + public ZenodoCustomProviderImpl(Environment environment) { + this.environment = environment; + } + + @Override + public ZenodoResponseToken getAccessToken(ZenodoAccessType accessType, String code, String clientId, String clientSecret, String redirectUri) { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + + MultiValueMap map = new LinkedMultiValueMap<>(); + map.add("client_id", clientId); + map.add("client_secret", clientSecret); + map.add("grant_type", accessType.getGrantType()); + map.add(accessType.getProperty(), code); + map.add("redirect_uri", redirectUri); + HttpEntity> request = new HttpEntity<>(map, headers); + + try { + Map values = restTemplate.postForObject(this.environment.getProperty("zenodo.login.access_token_url"), request, Map.class); + ZenodoResponseToken zenodoResponseToken = new ZenodoResponseToken(); + Map user = (Map) values.get("user"); + zenodoResponseToken.setUserId((String) user.get("id")); + zenodoResponseToken.setEmail((String) user.get("email")); + zenodoResponseToken.setExpiresIn((Integer) values.get("expires_in")); + zenodoResponseToken.setAccessToken((String) values.get("access_token")); + zenodoResponseToken.setRefreshToken((String) values.get("refresh_token")); + + return zenodoResponseToken; + } catch (HttpClientErrorException ex) { + logger.error(ex.getResponseBodyAsString(), ex); + } + + return null; + } + + private HttpHeaders createBearerAuthHeaders(String accessToken) { + return new HttpHeaders() {{ + String authHeader = "Bearer " + accessToken; + set("Authorization", authHeader); + }}; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoUser.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoUser.java new file mode 100644 index 000000000..141b3fe4f --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/customproviders/Zenodo/ZenodoUser.java @@ -0,0 +1,59 @@ +package eu.eudat.old.logic.security.customproviders.Zenodo; + +import java.util.Map; + +public class ZenodoUser { + private String userId; + private String email; + private String accessToken; + private Integer expiresIn; + private String refreshToken; + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public Integer getExpiresIn() { + return expiresIn; + } + + public void setExpiresIn(Integer expiresIn) { + this.expiresIn = expiresIn; + } + + public String getRefreshToken() { + return refreshToken; + } + + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } + + public ZenodoUser getZenodoUser(Object data) { + this.userId = (String) ((Map) data).get("userId"); + this.email = (String) ((Map) data).get("email"); + this.accessToken = (String) ((Map) data).get("accessToken"); + this.expiresIn = (Integer) ((Map) data).get("expiresIn"); + this.refreshToken = (String) ((Map) data).get("refreshToken"); + return this; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/repositorydeposit/mapper/DMPToDepositMapper.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/repositorydeposit/mapper/DMPToDepositMapper.java new file mode 100644 index 000000000..687cb2b49 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/repositorydeposit/mapper/DMPToDepositMapper.java @@ -0,0 +1,156 @@ +package eu.eudat.old.logic.security.repositorydeposit.mapper; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.depositinterface.models.*; +import eu.eudat.old.data.entities.*; +import eu.eudat.old.logic.utilities.builders.XmlBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import javax.xml.xpath.*; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class DMPToDepositMapper { + + private static final Logger logger = LoggerFactory.getLogger(DMPToDepositMapper.class); + private static final ObjectMapper mapper = new ObjectMapper(); + + public static DMPDepositModel fromDMP(DMP entity, FileEnvelope pdfFile, FileEnvelope jsonFile, File supportingFilesZip, String previousDOI) { + DMPDepositModel deposit = new DMPDepositModel(); + deposit.setId(entity.getId()); + deposit.setVersion(entity.getVersion()); + deposit.setLabel(entity.getLabel()); + deposit.setDescription(entity.getDescription()); + deposit.setPublic(entity.isPublic()); + deposit.setDatasets(entity.getDataset().stream().map(DMPToDepositMapper::fromDataset).collect(Collectors.toList())); + deposit.setUsers(entity.getUsers().stream().map(DMPToDepositMapper::fromUserDMP).collect(Collectors.toSet())); + deposit.setOrganisations(entity.getOrganisations().stream().map(DMPToDepositMapper::fromOrganisation).collect(Collectors.toSet())); + deposit.setResearchers(entity.getResearchers().stream().map(DMPToDepositMapper::fromResearcher).collect(Collectors.toSet())); + if (entity.getGrant() != null) { + deposit.setGrant(fromGrant(entity.getGrant())); + } + + deposit.setPdfFile(pdfFile); + deposit.setRdaJsonFile(jsonFile); + deposit.setSupportingFilesZip(supportingFilesZip); + deposit.setPreviousDOI(previousDOI); + + deposit.setExtraProperties(entity.getExtraProperties()); + return deposit; + } + + private static DatasetDepositModel fromDataset(Dataset entity){ + DatasetDepositModel deposit = new DatasetDepositModel(); + deposit.setLabel(entity.getLabel()); + deposit.setDescription(entity.getDescription()); + deposit.setProfileDefinition(entity.getProfile().getDefinition()); + deposit.setProperties(entity.getProperties()); + deposit.setFields(fromDefinitionAndProperties(deposit.getProfileDefinition(), deposit.getProperties())); + return deposit; + } + + private static List fromDefinitionAndProperties(String definition, String properties){ + List deposit = new ArrayList<>(); + try { + + Map datasetAnswers = mapper.readValue(properties, HashMap.class); + + Document document = XmlBuilder.fromXml(definition); + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPath xpath = xpathFactory.newXPath(); + XPathExpression expr = xpath.compile("//schematics"); + NodeList schematics = (NodeList) expr.evaluate(document, XPathConstants.NODESET); + for (int i = 0; i < schematics.getLength(); i++) { + Node schematicsNode = schematics.item(i); + NodeList schematicsList = schematicsNode.getChildNodes(); + DatasetFieldsDepositModel fieldDeposit = new DatasetFieldsDepositModel(); + List schematicsDeposit = new ArrayList<>(); + if(schematicsList != null){ + for(int j = 0; j < schematicsList.getLength(); j++){ + Node schematic = schematicsList.item(j); + if(schematic.getTextContent().matches(".*\\w+.*")) { + schematicsDeposit.add(schematic.getTextContent()); + } + } + } + fieldDeposit.setSchematics(schematicsDeposit); + String fieldId = schematicsNode.getParentNode().getAttributes().getNamedItem("id").getNodeValue(); + Object value = datasetAnswers.get(fieldId); + fieldDeposit.setValue(value); + Element field = (Element) schematicsNode.getParentNode(); + Element viewStyle = (Element) field.getElementsByTagName("viewStyle").item(0); + String renderStyle = viewStyle.getAttribute("renderstyle"); + fieldDeposit.setRenderStyleType(renderStyle); + Element data = (Element) field.getElementsByTagName("data").item(0); + String multipleSelection = data.getAttribute("multiList"); + String multipleAutoComplete = data.getAttribute("multiAutoComplete"); + if(!multipleSelection.isEmpty()){ + fieldDeposit.setMultiple(Boolean.parseBoolean(multipleSelection)); + } + else if(!multipleAutoComplete.isEmpty()){ + fieldDeposit.setMultiple(Boolean.parseBoolean(multipleAutoComplete)); + } + else{ + fieldDeposit.setMultiple(false); + } + deposit.add(fieldDeposit); + } + } + catch (XPathExpressionException | JsonProcessingException ex){ + logger.error(ex.getMessage(), ex); + return null; + } + return deposit; + } + + private static UserDMPDepositModel fromUserDMP(UserDMP entity){ + UserDMPDepositModel deposit = new UserDMPDepositModel(); + deposit.setUser(fromUserInfo(entity.getUser())); + deposit.setRole(entity.getRole()); + return deposit; + } + + private static UserInfoDepositModel fromUserInfo(UserInfo entity){ + UserInfoDepositModel deposit = new UserInfoDepositModel(); + deposit.setName(entity.getName()); + deposit.setEmail(entity.getEmail()); + return deposit; + } + + private static OrganisationDepositModel fromOrganisation(Organisation entity){ + OrganisationDepositModel deposit = new OrganisationDepositModel(); + deposit.setLabel(entity.getLabel()); + return deposit; + } + + private static ResearcherDepositModel fromResearcher(Researcher entity){ + ResearcherDepositModel deposit = new ResearcherDepositModel(); + deposit.setLabel(entity.getLabel()); + deposit.setReference(entity.getReference()); + return deposit; + } + + private static GrantDepositModel fromGrant(Grant entity){ + GrantDepositModel deposit = new GrantDepositModel(); + deposit.setId(entity.getId()); + deposit.setReference(entity.getReference()); + deposit.setFunder(fromFunder(entity.getFunder())); + return deposit; + } + + private static FunderDepositModel fromFunder(Funder entity){ + FunderDepositModel deposit = new FunderDepositModel(); + deposit.setLabel(entity.getLabel()); + return deposit; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/TokenValidator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/TokenValidator.java new file mode 100644 index 000000000..3fb167b5d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/TokenValidator.java @@ -0,0 +1,17 @@ +package eu.eudat.old.logic.security.validators; + +import eu.eudat.old.exceptions.security.NonValidTokenException; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.security.Principal; +import net.shibboleth.utilities.java.support.component.ComponentInitializationException; +import net.shibboleth.utilities.java.support.resolver.ResolverException; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +public interface TokenValidator { + + Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException, ResolverException, ComponentInitializationException; + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/TokenValidatorFactory.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/TokenValidatorFactory.java new file mode 100644 index 000000000..2371d7ce9 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/TokenValidatorFactory.java @@ -0,0 +1,6 @@ +package eu.eudat.old.logic.security.validators; + + +public interface TokenValidatorFactory { + TokenValidator getProvider(TokenValidatorFactoryImpl.LoginProvider provider); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/TokenValidatorFactoryImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/TokenValidatorFactoryImpl.java new file mode 100644 index 000000000..86de5df9a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/TokenValidatorFactoryImpl.java @@ -0,0 +1,120 @@ +package eu.eudat.old.logic.security.validators; + +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.security.customproviders.B2Access.B2AccessCustomProvider; +import eu.eudat.old.logic.security.customproviders.LinkedIn.LinkedInCustomProvider; +import eu.eudat.old.logic.security.customproviders.Zenodo.ZenodoCustomProvider; +import eu.eudat.old.logic.security.validators.b2access.B2AccessTokenValidator; +import eu.eudat.old.logic.security.validators.configurableProvider.ConfigurableProviderTokenValidator; +import eu.eudat.old.logic.security.validators.google.GoogleTokenValidator; +import eu.eudat.old.logic.security.validators.linkedin.LinkedInTokenValidator; +import eu.eudat.old.logic.security.validators.openaire.OpenAIRETokenValidator; +import eu.eudat.old.logic.security.validators.twitter.TwitterTokenValidator; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.ConfigurableProviderCustomProvider; +import eu.eudat.old.logic.security.customproviders.ORCID.ORCIDCustomProvider; +import eu.eudat.old.logic.security.customproviders.OpenAIRE.OpenAIRECustomProvider; +import eu.eudat.old.logic.security.validators.facebook.FacebookTokenValidator; +import eu.eudat.old.logic.security.validators.orcid.ORCIDTokenValidator; +import eu.eudat.old.logic.security.validators.zenodo.ZenodoTokenValidator; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + + +@Service("tokenValidatorFactory") +public class TokenValidatorFactoryImpl implements TokenValidatorFactory { + public enum LoginProvider { + GOOGLE(1), FACEBOOK(2), TWITTER(3), LINKEDIN(4), NATIVELOGIN(5), B2_ACCESS(6), ORCID(7), OPENAIRE(8), CONFIGURABLE(9), ZENODO(10); + + private int value; + + private LoginProvider(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + public static LoginProvider fromInteger(int value) { + switch (value) { + case 1: + return GOOGLE; + case 2: + return FACEBOOK; + case 3: + return TWITTER; + case 4: + return LINKEDIN; + case 5: + return NATIVELOGIN; + case 6: + return B2_ACCESS; + case 7: + return ORCID; + case 8: + return OPENAIRE; + case 9: + return CONFIGURABLE; + case 10: + return ZENODO; + default: + throw new RuntimeException("Unsupported LoginProvider"); + } + } + } + + private Environment environment; + private AuthenticationService nonVerifiedUserAuthenticationService; + private B2AccessCustomProvider b2AccessCustomProvider; + private ORCIDCustomProvider orcidCustomProvider; + private LinkedInCustomProvider linkedInCustomProvider; + private OpenAIRECustomProvider openAIRECustomProvider; + private ConfigurableProviderCustomProvider configurableProviderCustomProvider; + private ConfigLoader configLoader; + private ZenodoCustomProvider zenodoCustomProvider; + + @Autowired + public TokenValidatorFactoryImpl( + Environment environment, + AuthenticationService nonVerifiedUserAuthenticationService, B2AccessCustomProvider b2AccessCustomProvider, + ORCIDCustomProvider orcidCustomProvider, LinkedInCustomProvider linkedInCustomProvider, OpenAIRECustomProvider openAIRECustomProvider, + ConfigurableProviderCustomProvider configurableProviderCustomProvider, ConfigLoader configLoader, + ZenodoCustomProvider zenodoCustomProvider) { + this.environment = environment; + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + this.b2AccessCustomProvider = b2AccessCustomProvider; + this.orcidCustomProvider = orcidCustomProvider; + this.linkedInCustomProvider = linkedInCustomProvider; + this.openAIRECustomProvider = openAIRECustomProvider; + this.configurableProviderCustomProvider = configurableProviderCustomProvider; + this.configLoader = configLoader; + this.zenodoCustomProvider = zenodoCustomProvider; + } + + public TokenValidator getProvider(LoginProvider provider) { + switch (provider) { + case GOOGLE: + return new GoogleTokenValidator(this.environment, this.nonVerifiedUserAuthenticationService); + case FACEBOOK: + return new FacebookTokenValidator(this.environment, this.nonVerifiedUserAuthenticationService); + case LINKEDIN: + return new LinkedInTokenValidator(this.environment, this.nonVerifiedUserAuthenticationService, linkedInCustomProvider); + case TWITTER: + return new TwitterTokenValidator(this.environment, this.nonVerifiedUserAuthenticationService); + case B2_ACCESS: + return new B2AccessTokenValidator(this.environment, this.nonVerifiedUserAuthenticationService, this.b2AccessCustomProvider); + case ORCID: + return new ORCIDTokenValidator(this.environment, this.nonVerifiedUserAuthenticationService, this.orcidCustomProvider); + case OPENAIRE: + return new OpenAIRETokenValidator(this.environment, this.nonVerifiedUserAuthenticationService, this.openAIRECustomProvider); + case CONFIGURABLE: + return new ConfigurableProviderTokenValidator(this.configurableProviderCustomProvider, this.nonVerifiedUserAuthenticationService, this.configLoader); + case ZENODO: + return new ZenodoTokenValidator(this.environment, this.nonVerifiedUserAuthenticationService, this.zenodoCustomProvider); + default: + throw new RuntimeException("Login Provider Not Implemented"); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/b2access/B2AccessTokenValidator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/b2access/B2AccessTokenValidator.java new file mode 100644 index 000000000..e43dd4f5b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/b2access/B2AccessTokenValidator.java @@ -0,0 +1,52 @@ +package eu.eudat.old.logic.security.validators.b2access; + +import eu.eudat.old.logic.security.customproviders.B2Access.B2AccessCustomProvider; +import eu.eudat.old.logic.security.validators.TokenValidator; +import eu.eudat.old.logic.security.validators.b2access.helpers.B2AccessRequest; +import eu.eudat.old.exceptions.security.NonValidTokenException; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.loginprovider.LoginProviderUser; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.logic.security.customproviders.B2Access.B2AccessUser; +import eu.eudat.old.logic.security.validators.b2access.helpers.B2AccessResponseToken; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +@Component("b2AccessTokenValidator ") +public class B2AccessTokenValidator implements TokenValidator { + + private B2AccessCustomProvider b2AccessCustomProvider; + private AuthenticationService nonVerifiedUserAuthenticationService; + private Environment environment; + + @Autowired + public B2AccessTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, B2AccessCustomProvider b2AccessCustomProvider) { + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + this.environment = environment; + this.b2AccessCustomProvider = b2AccessCustomProvider; + } + + @Override + public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException { + B2AccessUser b2AccessUser = this.b2AccessCustomProvider.getUser(credentials.getTicket()); + LoginProviderUser user = new LoginProviderUser(); + user.setId(b2AccessUser.getId()); + user.setEmail(b2AccessUser.getEmail()); + user.setName(b2AccessUser.getName()); + user.setProvider(credentials.getProvider()); + user.setSecret(credentials.getTicket()); + return this.nonVerifiedUserAuthenticationService.Touch(user); + } + + public B2AccessResponseToken getAccessToken(B2AccessRequest b2AccessRequest) { + return this.b2AccessCustomProvider.getAccessToken(b2AccessRequest.getCode(), this.environment.getProperty("b2access.externallogin.redirect_uri") + , this.environment.getProperty("b2access.externallogin.clientid") + , this.environment.getProperty("b2access.externallogin.clientSecret")); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/b2access/helpers/B2AccessRequest.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/b2access/helpers/B2AccessRequest.java new file mode 100644 index 000000000..776b3a58c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/b2access/helpers/B2AccessRequest.java @@ -0,0 +1,16 @@ +package eu.eudat.old.logic.security.validators.b2access.helpers; + +/** + * Created by ikalyvas on 2/22/2018. + */ +public class B2AccessRequest { + private String code; + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/b2access/helpers/B2AccessResponseToken.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/b2access/helpers/B2AccessResponseToken.java new file mode 100644 index 000000000..c1168db2f --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/b2access/helpers/B2AccessResponseToken.java @@ -0,0 +1,16 @@ +package eu.eudat.old.logic.security.validators.b2access.helpers; + +/** + * Created by ikalyvas on 2/22/2018. + */ +public class B2AccessResponseToken { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/ConfigurableProviderTokenValidator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/ConfigurableProviderTokenValidator.java new file mode 100644 index 000000000..431c9543c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/ConfigurableProviderTokenValidator.java @@ -0,0 +1,139 @@ +package eu.eudat.old.logic.security.validators.configurableProvider; + +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.oauth2.Oauth2ConfigurableProvider; +import eu.eudat.old.logic.security.validators.TokenValidator; +import eu.eudat.old.exceptions.security.NullEmailException; + +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.ConfigurableProviderCustomProvider; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.ConfigurableProviderUser; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.ConfigurableProvider; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.saml2.Saml2ConfigurableProvider; +import eu.eudat.old.logic.security.validators.configurableProvider.helpers.ConfigurableProviderRequest; +import eu.eudat.old.logic.security.validators.configurableProvider.helpers.ConfigurableProviderResponseToken; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.loginprovider.LoginProviderUser; +import eu.eudat.old.models.data.security.Principal; + +import org.opensaml.saml.saml2.core.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Component("configurableProviderTokenValidator") +public class ConfigurableProviderTokenValidator implements TokenValidator { + + private static final Logger logger = LoggerFactory.getLogger(ConfigurableProviderTokenValidator.class); + + private ConfigurableProviderCustomProvider configurableProvider; + private AuthenticationService nonVerifiedUserAuthenticationService; + private ConfigLoader configLoader; + + public ConfigurableProviderTokenValidator(ConfigurableProviderCustomProvider configurableProvider, AuthenticationService nonVerifiedUserAuthenticationService, ConfigLoader configLoader) { + this.configurableProvider = configurableProvider; + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + this.configLoader = configLoader; + } + + public ConfigurableProviderResponseToken getAccessToken(ConfigurableProviderRequest configurableProviderRequest) { + Oauth2ConfigurableProvider provider = (Oauth2ConfigurableProvider)getConfigurableProviderFromId(configurableProviderRequest.getConfigurableLoginId()); + return this.configurableProvider.getAccessToken(configurableProviderRequest.getCode(), + provider.getRedirect_uri(), provider.getClientId(), provider.getClientSecret(), + provider.getAccess_token_url(), provider.getGrant_type(), provider.getToken().getAccess_token(), provider.getToken().getExpires_in()); + } + @Override + public Principal validateToken(LoginInfo credentials) throws NullEmailException { + String configurableLoginId = ((Map) credentials.getData()).get("configurableLoginId").toString(); + ConfigurableProvider configurableProvider = getConfigurableProviderFromId(configurableLoginId); + + LoginProviderUser user = new LoginProviderUser(); + if (configurableProvider.getType().equals("oauth2")) { + ConfigurableProviderUser configurableUser = this.configurableProvider.getUser(credentials.getTicket(), ((Oauth2ConfigurableProvider)configurableProvider).getUser()); + user.setId(configurableUser.getId()); + user.setEmail(configurableUser.getEmail()); + user.setName(configurableUser.getName()); + user.setProvider(credentials.getProvider()); + user.setSecret(credentials.getTicket()); + return this.nonVerifiedUserAuthenticationService.Touch(user); + } + else if (configurableProvider.getType().equals("saml2")) { + + Assertion saml2Assertion = null; + try { + Saml2ConfigurableProvider saml2Provider = (Saml2ConfigurableProvider)configurableProvider; + if(saml2Provider.getBinding().equals("Redirect") || saml2Provider.getBinding().equals("Post")) + saml2Assertion = Saml2SSOUtils.processResponse(credentials.getTicket(), saml2Provider); + else if(saml2Provider.getBinding().equals("Artifact")) + saml2Assertion = Saml2SSOUtils.processArtifactResponse(credentials.getTicket(), saml2Provider); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + if(saml2Assertion == null) + return null; + + List attributeStatements = saml2Assertion.getAttributeStatements(); + if(attributeStatements != null && !attributeStatements.isEmpty()){ + + List attributes = attributeStatements.get(0).getAttributes(); + if(attributes != null && !attributes.isEmpty()){ + + Saml2ConfigurableProvider.SAML2UsingFormat usingFormat = ((Saml2ConfigurableProvider)configurableProvider).getUsingFormat(); + Map attributeMapping = ((Saml2ConfigurableProvider)configurableProvider).getConfigurableUserFromAttributes(); + Map attributeType = ((Saml2ConfigurableProvider)configurableProvider).getAttributeTypes(); + Map saml2User = new HashMap<>(); + for(Attribute attribute: attributes){ + + String attributeName = Saml2SSOUtils.getAttributeName(attribute, usingFormat); + if(attributeName != null && attributeMapping.containsValue(attributeName)){ + + Saml2ConfigurableProvider.SAML2AttributeType attrType = attributeType.get(attributeName); + if(attribute.getAttributeValues() != null && !attribute.getAttributeValues().isEmpty() && attrType != null){ + Object attributeValue = Saml2SSOUtils.getAttributeType(attribute.getAttributeValues().get(0), attrType); + if(attributeValue != null) { + saml2User.put(attributeName, attributeValue); + } + } + + } + + } + + try{ + String subjectNameId = saml2Assertion.getSubject().getNameID().getValue(); + String userId = configurableLoginId + ": " + subjectNameId; + user.setId(userId); + } catch(NullPointerException e){ + logger.error("Could not get Subject NameID value of assertion"); + return null; + } + user.setEmail((String)saml2User.get(attributeMapping.get("email"))); + user.setName((String)saml2User.get(attributeMapping.get("name"))); + user.setProvider(credentials.getProvider()); + user.setSecret(credentials.getTicket()); + + } + + } + else + return null; + + return this.nonVerifiedUserAuthenticationService.Touch(user); + + } + return null; + } + + private ConfigurableProvider getConfigurableProviderFromId(String configurableId) { + return this.configLoader.getConfigurableProviders().getProviders().stream() + .filter(prov -> prov.getConfigurableLoginId().equals(configurableId)) + .collect(Collectors.toList()) + .get(0); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/Saml2SSOUtils.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/Saml2SSOUtils.java new file mode 100644 index 000000000..b34e55e43 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/Saml2SSOUtils.java @@ -0,0 +1,898 @@ +package eu.eudat.old.logic.security.validators.configurableProvider; + +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.saml2.CertificateInfo; +import eu.eudat.old.logic.security.customproviders.ConfigurableProvider.entities.saml2.Saml2ConfigurableProvider; +import eu.eudat.old.logic.utilities.builders.XmlBuilder; +import eu.eudat.old.models.data.saml2.AuthnRequestModel; +import jakarta.xml.soap.*; +import net.shibboleth.utilities.java.support.component.ComponentInitializationException; +import net.shibboleth.utilities.java.support.resolver.CriteriaSet; +import net.shibboleth.utilities.java.support.xml.BasicParserPool; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.xml.security.c14n.Canonicalizer; +import org.apache.xml.security.signature.XMLSignature; +import org.opensaml.core.config.ConfigurationService; +import org.opensaml.core.config.InitializationException; +import org.opensaml.core.config.InitializationService; +import org.opensaml.core.criterion.EntityIdCriterion; +import org.opensaml.core.xml.XMLObject; +import org.opensaml.core.xml.XMLObjectBuilder; +import org.opensaml.core.xml.config.XMLObjectProviderRegistry; +import org.opensaml.core.xml.io.*; +import org.opensaml.core.xml.schema.*; +import org.opensaml.saml.common.SAMLObject; +import org.opensaml.saml.common.SAMLVersion; +import org.opensaml.saml.common.xml.SAMLConstants; +import org.opensaml.saml.criterion.EntityRoleCriterion; +import org.opensaml.saml.criterion.ProtocolCriterion; +import org.opensaml.saml.metadata.resolver.impl.HTTPMetadataResolver; +import org.opensaml.saml.metadata.resolver.impl.PredicateRoleDescriptorResolver; +import org.opensaml.saml.saml2.core.*; +import org.opensaml.saml.saml2.encryption.Decrypter; +import org.opensaml.saml.saml2.metadata.*; +import org.opensaml.saml.security.impl.MetadataCredentialResolver; +import org.opensaml.security.credential.Credential; +import org.opensaml.security.credential.CredentialSupport; +import org.opensaml.security.credential.UsageType; +import org.opensaml.security.criteria.UsageCriterion; +import org.opensaml.security.x509.BasicX509Credential; +import org.opensaml.security.x509.X509Credential; +import org.opensaml.security.x509.impl.KeyStoreX509CredentialAdapter; +import org.opensaml.soap.soap11.Body; +import org.opensaml.soap.soap11.Envelope; +import org.opensaml.xml.util.Base64; +import org.opensaml.xmlsec.config.impl.DefaultSecurityConfigurationBootstrap; +import org.opensaml.xmlsec.encryption.EncryptedKey; +import org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver; +import org.opensaml.xmlsec.keyinfo.KeyInfoGenerator; +import org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver; +import org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory; +import org.opensaml.xmlsec.signature.KeyInfo; +import org.opensaml.xmlsec.signature.Signature; +import org.opensaml.xmlsec.signature.X509Data; +import org.opensaml.xmlsec.signature.support.SignatureValidator; +import org.opensaml.xmlsec.signature.support.Signer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.bootstrap.DOMImplementationRegistry; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSOutput; +import org.w3c.dom.ls.LSSerializer; +import org.xml.sax.SAXException; + +import javax.crypto.SecretKey; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.*; +import java.net.URLEncoder; +import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; +import java.security.*; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.*; +import java.util.stream.Collectors; +import java.util.zip.Inflater; +import java.util.zip.InflaterInputStream; + +public class Saml2SSOUtils { + + private static final Logger logger = LoggerFactory.getLogger(Saml2SSOUtils.class); + private static boolean isBootStrapped = false; + private static BasicParserPool parserPool; + private static XMLObjectProviderRegistry registry; + + private Saml2SSOUtils() { + } + + private static void doBootstrap() throws Exception { + if (!isBootStrapped) { + try { + boostrap(); + isBootStrapped = true; + } catch (Exception e) { + throw new Exception("Error in bootstrapping the OpenSAML2 library", e); + } + } + } + + private static void boostrap(){ + parserPool = new BasicParserPool(); + parserPool.setMaxPoolSize(100); + parserPool.setCoalescing(true); + parserPool.setIgnoreComments(true); + parserPool.setIgnoreElementContentWhitespace(true); + parserPool.setNamespaceAware(true); + parserPool.setExpandEntityReferences(false); + parserPool.setXincludeAware(false); + + final Map features = new HashMap(); + features.put("http://xml.org/sax/features/external-general-entities", Boolean.FALSE); + features.put("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE); + features.put("http://apache.org/xml/features/disallow-doctype-decl", Boolean.TRUE); + features.put("http://apache.org/xml/features/validation/schema/normalized-value", Boolean.FALSE); + features.put("http://javax.xml.XMLConstants/feature/secure-processing", Boolean.TRUE); + + parserPool.setBuilderFeatures(features); + + parserPool.setBuilderAttributes(new HashMap()); + + try { + parserPool.initialize(); + } catch (ComponentInitializationException e) { + logger.error(e.getMessage(), e); + } + + registry = new XMLObjectProviderRegistry(); + ConfigurationService.register(XMLObjectProviderRegistry.class, registry); + registry.setParserPool(parserPool); + + try { + InitializationService.initialize(); + } catch (InitializationException e) { + logger.error(e.getMessage(), e); + } + } + + private static XMLObject buildXMLObject(QName objectQName) throws Exception { + + doBootstrap(); + XMLObjectBuilder builder = registry.getBuilderFactory().getBuilder(objectQName); + if (builder == null) { + throw new Exception("Unable to retrieve builder for object QName " + objectQName); + } + return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(), objectQName.getPrefix()); + + } + + public static String getAttributeName(Attribute attribute, Saml2ConfigurableProvider.SAML2UsingFormat usingFormat){ + String friendlyName = attribute.getFriendlyName(); + String name = attribute.getName(); + if(usingFormat.getName().equals(Saml2ConfigurableProvider.SAML2UsingFormat.FRIENDLY_NAME.getName())){ + return (friendlyName != null) ? friendlyName : name; + } + else{ + return (name != null) ? name : friendlyName; + } + } + + public static Object getAttributeType(XMLObject attribute, Saml2ConfigurableProvider.SAML2AttributeType attributeType){ + + if(attributeType.getType().equals(Saml2ConfigurableProvider.SAML2AttributeType.XSSTRING.getType())){ + return ((XSString)attribute).getValue(); + } + else if(attributeType.getType().equals(Saml2ConfigurableProvider.SAML2AttributeType.XSINTEGER.getType())){ + return ((XSInteger)attribute).getValue(); + } + else if(attributeType.getType().equals(Saml2ConfigurableProvider.SAML2AttributeType.XSDATETIME.getType())){ + return ((XSDateTime)attribute).getValue(); + } + else if(attributeType.getType().equals(Saml2ConfigurableProvider.SAML2AttributeType.XSBOOLEAN.getType())){ + return ((XSBoolean)attribute).getValue(); + } + else if(attributeType.getType().equals(Saml2ConfigurableProvider.SAML2AttributeType.XSBASE64BINARY.getType())){ + return ((XSBase64Binary)attribute).getValue(); + } + else if(attributeType.getType().equals(Saml2ConfigurableProvider.SAML2AttributeType.XSURI.getType())){ + return ((XSURI)attribute).getURI(); + } + else if(attributeType.getType().equals(Saml2ConfigurableProvider.SAML2AttributeType.XSQNAME.getType())){ + return ((XSQName)attribute).getValue(); + } + else if(attributeType.getType().equals(Saml2ConfigurableProvider.SAML2AttributeType.XSANY.getType())){ + return ((XSAny)attribute).getTextContent(); + } + else { + return null; + } + + } + + private static String marshall(XMLObject xmlObject) throws Exception { + + try { + MarshallerFactory marshallerFactory = registry.getMarshallerFactory(); + Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject); + Element element = marshaller.marshall(xmlObject); + + ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream(); + DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); + DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); + LSSerializer writer = impl.createLSSerializer(); + LSOutput output = impl.createLSOutput(); + output.setByteStream(byteArrayOutputStrm); + writer.write(element, output); + return byteArrayOutputStrm.toString(); + } catch (Exception e) { + throw new Exception("Error Serializing the SAML Response", e); + } + } + + private static XMLObject unmarshall(String saml2SSOString) throws Exception { + + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + //documentBuilderFactory.setExpandEntityReferences(false); + documentBuilderFactory.setNamespaceAware(true); + try { + DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder(); + ByteArrayInputStream is = new ByteArrayInputStream(saml2SSOString.getBytes(StandardCharsets.UTF_8)); + Document document = docBuilder.parse(is); + Element element = document.getDocumentElement(); + + UnmarshallerFactory unmarshallerFactory = registry.getUnmarshallerFactory(); + Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); + return unmarshaller.unmarshall(element); + } catch (ParserConfigurationException | UnmarshallingException | SAXException | IOException e) { + throw new Exception("Error in unmarshalling SAML2SSO Request from the encoded String", e); + } + + } + + public static Assertion processArtifactResponse(String artifactString, Saml2ConfigurableProvider saml2Provider) throws Exception { + + doBootstrap(); + if (artifactString != null){ + ArtifactResolve artifactResolve = generateArtifactResolveReq(artifactString, saml2Provider); + ArtifactResponse artifactResponse = sendArtifactResolveRequest(artifactResolve, saml2Provider.getIdpArtifactUrl()); + Response saml2Response = (Response)artifactResponse.getMessage(); + return processSSOResponse(saml2Response, saml2Provider); + } + else { + throw new Exception("Invalid SAML2 Artifact. SAML2 Artifact can not be null."); + } + + } + + private static ArtifactResolve generateArtifactResolveReq(String samlArtReceived, Saml2ConfigurableProvider saml2Provider) throws Exception { + + ArtifactResolve artifactResolve = createArtifactResolveObject(samlArtReceived, saml2Provider.getSpEntityId()); + if (saml2Provider.isSignatureRequired()) { + signArtifactResolveReq(artifactResolve, saml2Provider.getSigningCert()); + } + return artifactResolve; + + } + + private static ArtifactResolve createArtifactResolveObject(String samlArtReceived, String spEntityId) throws Exception { + + ArtifactResolve artifactResolve = (ArtifactResolve)buildXMLObject(ArtifactResolve.DEFAULT_ELEMENT_NAME); + artifactResolve.setVersion(SAMLVersion.VERSION_20); + artifactResolve.setID(UUID.randomUUID().toString()); + artifactResolve.setIssueInstant(Instant.now()); + + Artifact artifact = (Artifact)buildXMLObject(Artifact.DEFAULT_ELEMENT_NAME); + artifact.setValue(samlArtReceived); + + Issuer issuer = (Issuer)buildXMLObject(Issuer.DEFAULT_ELEMENT_NAME); + issuer.setValue(spEntityId); + + artifactResolve.setIssuer(issuer); + artifactResolve.setArtifact(artifact); + + return artifactResolve; + + } + + private static void signArtifactResolveReq(ArtifactResolve artifactResolve, CertificateInfo singingCertificateInfo) throws Exception { + + try { + KeyStore ks = KeyStore.getInstance("JKS"); + String archivePassword = singingCertificateInfo.getKeystorePassword(); + char[] pwdArray = (archivePassword != null) ? archivePassword.toCharArray() : "changeit".toCharArray(); + ks.load(new FileInputStream(singingCertificateInfo.getKeystorePath()), pwdArray); + X509Credential cred = new KeyStoreX509CredentialAdapter(ks, singingCertificateInfo.getAlias(), singingCertificateInfo.getPassword().toCharArray()); + Signature signature = setSignatureRaw(XMLSignature.ALGO_ID_SIGNATURE_RSA, cred); + artifactResolve.setSignature(signature); + + List signatureList = new ArrayList<>(); + signatureList.add(signature); + + MarshallerFactory marshallerFactory = registry.getMarshallerFactory(); + Marshaller marshaller = marshallerFactory.getMarshaller(artifactResolve); + + marshaller.marshall(artifactResolve); + + org.apache.xml.security.Init.init(); + Signer.signObjects(signatureList); + } catch (Exception e) { + throw new Exception("Error while signing the SAML Request message", e); + } + } + + private static Signature setSignatureRaw(String signatureAlgorithm, X509Credential cred) throws Exception { + + Signature signature = (Signature)buildXMLObject(Signature.DEFAULT_ELEMENT_NAME); + signature.setSigningCredential(cred); + signature.setSignatureAlgorithm(signatureAlgorithm); + signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); + + try { + KeyInfo keyInfo = (KeyInfo)buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME); + X509Data data = (X509Data)buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME); + org.opensaml.xmlsec.signature.X509Certificate cert = + (org.opensaml.xmlsec.signature.X509Certificate) buildXMLObject( + org.opensaml.xmlsec.signature.X509Certificate.DEFAULT_ELEMENT_NAME); + String value = org.apache.commons.codec.binary.Base64.encodeBase64String(cred.getEntityCertificate().getEncoded()); + cert.setValue(value); + data.getX509Certificates().add(cert); + keyInfo.getX509Datas().add(data); + signature.setKeyInfo(keyInfo); + return signature; + + } catch (CertificateEncodingException e) { + throw new Exception("Error getting certificate", e); + } + } + + private static ArtifactResponse sendArtifactResolveRequest(ArtifactResolve artifactResolve, String idpArtifactUrl) throws Exception { + + Envelope envelope = buildSOAPMessage(artifactResolve); + String envelopeElement; + try { + envelopeElement = marshall(envelope); + } catch (Exception e) { + throw new Exception("Encountered error marshalling SOAP message with artifact " + "resolve, into its DOM representation", e); + } + + String artifactResponseString = sendSOAP(envelopeElement, idpArtifactUrl); + + ArtifactResponse artifactResponse = extractArtifactResponse(artifactResponseString); + validateArtifactResponse(artifactResolve, artifactResponse); + return artifactResponse; + + } + + private static Envelope buildSOAPMessage(SAMLObject samlMessage) throws Exception { + + Envelope envelope = (Envelope)buildXMLObject(Envelope.DEFAULT_ELEMENT_NAME); + Body body = (Body)buildXMLObject(Body.DEFAULT_ELEMENT_NAME); + body.getUnknownXMLObjects().add(samlMessage); + envelope.setBody(body); + return envelope; + + } + + private static String sendSOAP(String message, String idpArtifactUrl) throws Exception { + + if (message == null) { + throw new Exception("Cannot send null SOAP message."); + } + if (idpArtifactUrl == null) { + throw new Exception("Cannot send SOAP message to null URL."); + } + + StringBuilder soapResponse = new StringBuilder(); + try { + HttpPost httpPost = new HttpPost(idpArtifactUrl); + setRequestProperties(idpArtifactUrl, message, httpPost); + HttpClient httpClient = getHttpClient(); + HttpResponse httpResponse = httpClient.execute(httpPost); + + int responseCode = httpResponse.getStatusLine().getStatusCode(); + if (responseCode != 200) { + throw new Exception("Problem in communicating with: " + idpArtifactUrl + ". Received response: " + responseCode); + } else { + soapResponse.append(getResponseBody(httpResponse)); + } + } catch (UnknownHostException e) { + throw new Exception("Unknown targeted host: " + idpArtifactUrl, e); + } catch (IOException e) { + throw new Exception("Could not open connection with host: " + idpArtifactUrl, e); + } + return soapResponse.toString(); + + } + + private static void setRequestProperties(String idpArtifactUrl, String message, HttpPost httpPost) { + + httpPost.addHeader("Content-Type", "text/xml; charset=utf-8"); + httpPost.addHeader("Accept", "text/xml; charset=utf-8"); + String sbSOAPAction = "\"" + idpArtifactUrl + "\""; + httpPost.addHeader("SOAPAction", sbSOAPAction); + httpPost.addHeader("Pragma", "no-cache"); + httpPost.addHeader("Cache-Control", "no-cache, no-store"); + + httpPost.setEntity(new StringEntity(message, ContentType.create("text/xml", StandardCharsets.UTF_8))); + + } + + private static HttpClient getHttpClient() throws Exception { + + CloseableHttpClient httpClient = null; + SSLContextBuilder builder = new SSLContextBuilder(); + try { + builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( + builder.build()); + httpClient = HttpClients.custom().setSSLSocketFactory( + sslsf).build(); + } catch (NoSuchAlgorithmException | KeyStoreException e) { + throw new Exception("Error while building trust store.", e); + } catch (KeyManagementException e) { + throw new Exception("Error while building socket factory.", e); + } + + return httpClient; + + } + + private static String getResponseBody(HttpResponse response) throws Exception { + + ResponseHandler responseHandler = new BasicResponseHandler(); + String responseBody; + try { + responseBody = responseHandler.handleResponse(response); + } catch (IOException e) { + throw new Exception("Error when retrieving the HTTP response body.", e); + } + return responseBody; + + } + + private static ArtifactResponse extractArtifactResponse(String artifactResponseString) throws Exception { + + ArtifactResponse artifactResponse = null; + InputStream stream = new ByteArrayInputStream(artifactResponseString.getBytes(StandardCharsets.UTF_8)); + try { + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage soapMessage = messageFactory.createMessage(new MimeHeaders(), stream); + SOAPBody soapBody = soapMessage.getSOAPBody(); + Iterator iterator = soapBody.getChildElements(); + + while (iterator.hasNext()) { + SOAPBodyElement artifactResponseElement = (SOAPBodyElement) iterator.next(); + + if (StringUtils.equals(SAMLConstants.SAML20P_NS, artifactResponseElement.getNamespaceURI()) && + StringUtils.equals(ArtifactResponse.DEFAULT_ELEMENT_LOCAL_NAME, + artifactResponseElement.getLocalName())) { + + DOMSource source = new DOMSource(artifactResponseElement); + StringWriter stringResult = new StringWriter(); + TransformerFactory.newInstance().newTransformer().transform( + source, new StreamResult(stringResult)); + artifactResponse = (ArtifactResponse) unmarshall(stringResult.toString()); + } else { + throw new Exception("Received invalid artifact response with nameSpaceURI: " + + artifactResponseElement.getNamespaceURI() + " and localName: " + + artifactResponseElement.getLocalName()); + } + } + } catch (SOAPException | IOException | TransformerException e) { + throw new Exception("Didn't receive valid artifact response.", e); + } catch (Exception e) { + throw new Exception("Encountered error unmarshalling response into SAML2 object", e); + } + return artifactResponse; + + } + + private static void validateArtifactResponse(ArtifactResolve artifactResolve, ArtifactResponse artifactResponse) throws Exception { + + if (artifactResponse == null) { + throw new Exception("Received artifact response message was null."); + } + + String artifactResolveId = artifactResolve.getID(); + String artifactResponseInResponseTo = artifactResponse.getInResponseTo(); + if (!artifactResolveId.equals(artifactResponseInResponseTo)) { + throw new Exception("Artifact resolve ID: " + artifactResolveId + " is not equal to " + + "artifact response InResponseTo : " + artifactResponseInResponseTo); + } + + String artifactResponseStatus = artifactResponse.getStatus().getStatusCode().getValue(); + if (!StatusCode.SUCCESS.equals(artifactResponseStatus)) { + throw new Exception("Unsuccessful artifact response with status: " + + artifactResponseStatus); + } + + SAMLObject message = artifactResponse.getMessage(); + if (message == null) { + throw new Exception("No SAML response embedded into the artifact response."); + } + + } + + public static Assertion processResponse(String saml2SSOResponse, Saml2ConfigurableProvider saml2Provider) throws Exception { + + doBootstrap(); + if (saml2SSOResponse != null) { + byte[] decodedResponse = Base64.decode(saml2SSOResponse); + String response; + if(!saml2Provider.getBinding().equals("Post")){ + ByteArrayInputStream bytesIn = new ByteArrayInputStream(decodedResponse); + InflaterInputStream inflater = new InflaterInputStream(bytesIn, new Inflater(true)); + response = new BufferedReader(new InputStreamReader(inflater, StandardCharsets.UTF_8)) + .lines().collect(Collectors.joining("\n")); + } + else{ + response = new String(decodedResponse); + } + Response saml2Response = (Response) Saml2SSOUtils.unmarshall(response); + return processSSOResponse(saml2Response, saml2Provider); + + } else { + throw new Exception("Invalid SAML2 Response. SAML2 Response can not be null."); + } + } + + private static Assertion processSSOResponse(Response saml2Response, Saml2ConfigurableProvider saml2Provider) throws Exception { + + Assertion assertion = null; + if (saml2Provider.isAssertionEncrypted()) { + List encryptedAssertions = saml2Response.getEncryptedAssertions(); + EncryptedAssertion encryptedAssertion; + if (!CollectionUtils.isEmpty(encryptedAssertions)) { + encryptedAssertion = encryptedAssertions.get(0); + try { + assertion = getDecryptedAssertion(encryptedAssertion, saml2Provider.getEncryptionCert()); + } catch (Exception e) { + throw new Exception("Unable to decrypt the SAML2 Assertion"); + } + } + } else { + List assertions = saml2Response.getAssertions(); + if (assertions != null && !assertions.isEmpty()) { + assertion = assertions.get(0); + } + } + if (assertion == null) { + throw new Exception("SAML2 Assertion not found in the Response"); + } + + String idPEntityIdValue = assertion.getIssuer().getValue(); + if (idPEntityIdValue == null || idPEntityIdValue.isEmpty()) { + throw new Exception("SAML2 Response does not contain an Issuer value"); + } else if (!idPEntityIdValue.equals(saml2Provider.getIdpEntityId())) { + throw new Exception("SAML2 Response Issuer verification failed"); + } + + String subject = null; + if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) { + subject = assertion.getSubject().getNameID().getValue(); + } + + if (subject == null) { + throw new Exception("SAML2 Response does not contain the name of the subject"); + } + + validateAudienceRestriction(assertion, saml2Provider.getSpEntityId()); + + final HTTPMetadataResolver metadataResolver = new HTTPMetadataResolver(HttpClientBuilder.create().build(), saml2Provider.getIdpMetadataUrl()); + metadataResolver.setId(metadataResolver.getClass().getCanonicalName()); + metadataResolver.setParserPool(parserPool); + metadataResolver.initialize(); + + final MetadataCredentialResolver metadataCredentialResolver = new MetadataCredentialResolver(); + final PredicateRoleDescriptorResolver roleResolver = new PredicateRoleDescriptorResolver(metadataResolver); + final KeyInfoCredentialResolver keyResolver = DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver(); + metadataCredentialResolver.setKeyInfoCredentialResolver(keyResolver); + metadataCredentialResolver.setRoleDescriptorResolver(roleResolver); + metadataCredentialResolver.initialize(); + roleResolver.initialize(); + + CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add(new UsageCriterion(UsageType.SIGNING)); + criteriaSet.add(new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME)); + criteriaSet.add(new ProtocolCriterion(SAMLConstants.SAML20P_NS)); + criteriaSet.add(new EntityIdCriterion(saml2Provider.getIdpEntityId())); + + Credential credential = metadataCredentialResolver.resolveSingle(criteriaSet); + + validateSignature(saml2Response, assertion, saml2Provider.isResponseSigned(), saml2Provider.isAssertionSigned(), credential); + + return assertion; + + } + + private static Assertion getDecryptedAssertion(EncryptedAssertion encryptedAssertion, CertificateInfo encryptionCertificateInfo) throws Exception { + + try { + KeyStore ks = (encryptionCertificateInfo.getKeyFormat().getType().equals("JKS")) ? KeyStore.getInstance("JKS") : KeyStore.getInstance("PKCS12"); + String archivePassword = encryptionCertificateInfo.getKeystorePassword(); + char[] pwdArray = (archivePassword != null) ? archivePassword.toCharArray() : "changeit".toCharArray(); + ks.load(new FileInputStream(encryptionCertificateInfo.getKeystorePath()), pwdArray); + X509Certificate cert = (X509Certificate)ks.getCertificate(encryptionCertificateInfo.getAlias()); + PrivateKey pk = (PrivateKey) ks.getKey(encryptionCertificateInfo.getAlias(), encryptionCertificateInfo.getPassword().toCharArray()); + KeyInfoCredentialResolver keyResolver = new StaticKeyInfoCredentialResolver( + new BasicX509Credential(cert, pk)); + EncryptedKey key = encryptedAssertion.getEncryptedData().getKeyInfo().getEncryptedKeys().get(0); + Decrypter decrypter = new Decrypter(null, keyResolver, null); + SecretKey dkey = (SecretKey) decrypter.decryptKey(key, encryptedAssertion.getEncryptedData().getEncryptionMethod().getAlgorithm()); + Credential shared = CredentialSupport.getSimpleCredential(dkey); + decrypter = new Decrypter(new StaticKeyInfoCredentialResolver(shared), null, null); + decrypter.setRootInNewDocument(true); + return decrypter.decrypt(encryptedAssertion); + } catch (Exception e) { + throw new Exception("Decrypted assertion error", e); + + } + } + + private static void validateAudienceRestriction(Assertion assertion, String requiredSPEntityId) throws Exception { + + if (assertion != null) { + Conditions conditions = assertion.getConditions(); + if (conditions != null) { + List audienceRestrictions = conditions.getAudienceRestrictions(); + if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) { + boolean audienceFound = false; + for (AudienceRestriction audienceRestriction : audienceRestrictions) { + if (audienceRestriction.getAudiences() != null && !audienceRestriction.getAudiences().isEmpty() + ) { + for (Audience audience : audienceRestriction.getAudiences()) { + if (requiredSPEntityId.equals(audience.getURI())) { + audienceFound = true; + break; + } + } + } + if (audienceFound) { + break; + } + } + if (!audienceFound) { + throw new Exception("SAML2 Assertion Audience Restriction validation failed"); + } + } else { + throw new Exception("SAML2 Response doesn't contain AudienceRestrictions"); + } + } else { + throw new Exception("SAML2 Response doesn't contain Conditions"); + } + } + } + + private static void validateSignature(Response response, Assertion assertion, Boolean isResponseSigned, Boolean isAssertionSigned, Credential credential) throws Exception { + + if (isResponseSigned) { + if (response.getSignature() == null) { + throw new Exception("SAML2 Response signing is enabled, but signature element not found in SAML2 Response element"); + } else { + try { + SignatureValidator.validate(response.getSignature(), credential); + } catch (Exception e) { + throw new Exception("Signature validation failed for SAML2 Response"); + } + } + } + if (isAssertionSigned) { + if (assertion.getSignature() == null) { + throw new Exception("SAML2 Assertion signing is enabled, but signature element not found in SAML2 Assertion element"); + } else { + try { + SignatureValidator.validate(assertion.getSignature(), credential); + } catch (Exception e) { + throw new Exception("Signature validation failed for SAML2 Assertion"); + } + } + } + } + + private static Credential getCredential(CertificateInfo certificateInfo) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException { + KeyStore ks = (certificateInfo.getKeyFormat().getType().equals("JKS")) ? KeyStore.getInstance("JKS") : KeyStore.getInstance("PKCS12"); + String archivePassword = certificateInfo.getKeystorePassword(); + char[] pwdArray = (archivePassword != null) ? archivePassword.toCharArray() : "changeit".toCharArray(); + ks.load(new FileInputStream(certificateInfo.getKeystorePath()), pwdArray); + X509Certificate cert = (X509Certificate)ks.getCertificate(certificateInfo.getAlias()); + PrivateKey pk = (PrivateKey) ks.getKey(certificateInfo.getAlias(), certificateInfo.getPassword().toCharArray()); + return new BasicX509Credential(cert, pk); + } + + public static String getMetadata(Saml2ConfigurableProvider provider) throws Exception { + + EntityDescriptor spEntityDescriptor = (EntityDescriptor) buildXMLObject(EntityDescriptor.DEFAULT_ELEMENT_NAME); + spEntityDescriptor.setEntityID(provider.getSpEntityId()); + SPSSODescriptor spSSODescriptor = (SPSSODescriptor) buildXMLObject(SPSSODescriptor.DEFAULT_ELEMENT_NAME); + + spSSODescriptor.setWantAssertionsSigned(provider.isWantAssertionsSigned()); spSSODescriptor.setAuthnRequestsSigned(provider.isAuthnRequestsSigned()); + + X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory(); + keyInfoGeneratorFactory.setEmitEntityCertificate(true); + KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance(); + + if (provider.isAssertionEncrypted()) { + + KeyDescriptor encKeyDescriptor = (KeyDescriptor) buildXMLObject(KeyDescriptor.DEFAULT_ELEMENT_NAME); + + encKeyDescriptor.setUse(UsageType.ENCRYPTION); //Set usage + + // Generating key info. The element will contain the public key. The key is used to by the IDP to encrypt data + try { + encKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(getCredential(provider.getEncryptionCert()))); + } catch (SecurityException e) { + logger.error(e.getMessage(), e); + } + + spSSODescriptor.getKeyDescriptors().add(encKeyDescriptor); + + } + + if (provider.isWantAssertionsSigned()) { + + KeyDescriptor signKeyDescriptor = (KeyDescriptor) buildXMLObject(KeyDescriptor.DEFAULT_ELEMENT_NAME); + + signKeyDescriptor.setUse(UsageType.SIGNING); //Set usage + + // Generating key info. The element will contain the public key. The key is used to by the IDP to verify signatures + try { + signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(getCredential(provider.getSigningCert()))); + } catch (SecurityException e) { + logger.error(e.getMessage(), e); + } + + spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); + + } + + NameIDFormat nameIDFormat = (NameIDFormat) buildXMLObject(NameIDFormat.DEFAULT_ELEMENT_NAME); + nameIDFormat.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:transient"); + spSSODescriptor.getNameIDFormats().add(nameIDFormat); + + + AssertionConsumerService assertionConsumerService = (AssertionConsumerService) buildXMLObject(AssertionConsumerService.DEFAULT_ELEMENT_NAME); + assertionConsumerService.setIndex(0); + switch (provider.getBinding()) { + case "Redirect": + assertionConsumerService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + break; + case "Artifact": + assertionConsumerService.setBinding(SAMLConstants.SAML2_ARTIFACT_BINDING_URI); + break; + case "Post": + assertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + break; + } + + assertionConsumerService.setLocation(provider.getAssertionConsumerServiceUrl()); + spSSODescriptor.getAssertionConsumerServices().add(assertionConsumerService); + + + spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); + + spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor); + + + String metadataXML = null; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + Marshaller out = registry.getMarshallerFactory().getMarshaller(spEntityDescriptor); + out.marshall(spEntityDescriptor, document); + + metadataXML = XmlBuilder.generateXml(document); + } + catch (MarshallingException | ParserConfigurationException e) { + logger.error(e.getMessage(), e); + } + return metadataXML; + + } + + public static AuthnRequestModel getAuthnRequest(Saml2ConfigurableProvider provider) throws Exception { + + AuthnRequest authnRequest = buildAuthnRequest(provider); + String relayState = "spId=" + provider.getSpEntityId() + "&configurableLoginId=" + provider.getConfigurableLoginId(); + + String authnRequestXml = null; + String signatureBase64 = null; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + Marshaller out = registry.getMarshallerFactory().getMarshaller(authnRequest); + out.marshall(authnRequest, document); + + authnRequestXml = XmlBuilder.generateXml(document); + + if(provider.isAuthnRequestsSigned()) { + signatureBase64 = buildSignature(authnRequestXml, relayState, provider.getSigningCert()); + } + } + catch (MarshallingException | ParserConfigurationException e) { + logger.error(e.getMessage(), e); + } + + AuthnRequestModel authnRequestModel = new AuthnRequestModel(); + authnRequestModel.setAuthnRequestXml(authnRequestXml); + authnRequestModel.setRelayState(relayState); + authnRequestModel.setAlgorithm("http://www.w3.org/2000/09/xmldsig#rsa-sha1"); + authnRequestModel.setSignature(signatureBase64); + return authnRequestModel; + + } + + private static String buildSignature(String authnRequest, String relayState, CertificateInfo signingCertInfo) throws Exception{ + + KeyStore ks = (signingCertInfo.getKeyFormat().getType().equals("JKS")) ? KeyStore.getInstance("JKS") : KeyStore.getInstance("PKCS12"); + String archivePassword = signingCertInfo.getKeystorePassword(); + char[] pwdArray = (archivePassword != null) ? archivePassword.toCharArray() : "changeit".toCharArray(); + ks.load(new FileInputStream(signingCertInfo.getKeystorePath()), pwdArray); + PrivateKey pk = (PrivateKey) ks.getKey(signingCertInfo.getAlias(), signingCertInfo.getPassword().toCharArray()); + + String signAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; + String message = "SAMLRequest=" + URLEncoder.encode(authnRequest, "UTF-8") + + "&RelayState=" + URLEncoder.encode(relayState, "UTF-8") + + "&SigAlg=" + URLEncoder.encode(signAlgorithm, "UTF-8"); + + String signature = null; + try{ + signature = new String(org.apache.commons.codec.binary.Base64.encodeBase64(sign(message, pk)), StandardCharsets.UTF_8); + } + catch(InvalidKeyException | SignatureException | NoSuchAlgorithmException e){ + logger.error(e.getMessage(), e); + } + + return signature; + } + + private static byte[] sign(String message, PrivateKey key) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException { + java.security.Signature instance = java.security.Signature.getInstance("SHA1withRSA"); + instance.initSign(key); + instance.update(message.getBytes()); + return instance.sign(); + } + + private static AuthnRequest buildAuthnRequest(Saml2ConfigurableProvider provider) throws Exception { + AuthnRequest authnRequest = (AuthnRequest) buildXMLObject(AuthnRequest.DEFAULT_ELEMENT_NAME); + authnRequest.setIssueInstant(Instant.now()); + authnRequest.setDestination(provider.getIdpUrl()); + switch (provider.getBinding()) { + case "Redirect": + authnRequest.setProtocolBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + break; + case "Artifact": + authnRequest.setProtocolBinding(SAMLConstants.SAML2_ARTIFACT_BINDING_URI); + break; + case "Post": + authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI); + break; + } + authnRequest.setAssertionConsumerServiceURL(provider.getAssertionConsumerServiceUrl()); + authnRequest.setID('_' + UUID.randomUUID().toString()); + authnRequest.setIssuer(buildIssuer(provider.getSpEntityId())); + authnRequest.setNameIDPolicy(buildNameIdPolicy()); + + return authnRequest; + } + + private static NameIDPolicy buildNameIdPolicy() throws Exception { + NameIDPolicy nameIDPolicy = (NameIDPolicy) buildXMLObject(NameIDPolicy.DEFAULT_ELEMENT_NAME); + nameIDPolicy.setAllowCreate(true); + nameIDPolicy.setFormat(NameIDType.TRANSIENT); + + return nameIDPolicy; + } + + private static Issuer buildIssuer(String spEntityId) throws Exception { + Issuer issuer = (Issuer) buildXMLObject(Issuer.DEFAULT_ELEMENT_NAME); + issuer.setValue(spEntityId); + + return issuer; + } + +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/helpers/ConfigurableProviderRequest.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/helpers/ConfigurableProviderRequest.java new file mode 100644 index 000000000..9f3da3834 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/helpers/ConfigurableProviderRequest.java @@ -0,0 +1,20 @@ +package eu.eudat.old.logic.security.validators.configurableProvider.helpers; + +public class ConfigurableProviderRequest { + private String code; + private String configurableLoginId; + + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } + + public String getConfigurableLoginId() { + return configurableLoginId; + } + public void setConfigurableLoginId(String configurableLoginId) { + this.configurableLoginId = configurableLoginId; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/helpers/ConfigurableProviderResponseToken.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/helpers/ConfigurableProviderResponseToken.java new file mode 100644 index 000000000..875f8873c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/configurableProvider/helpers/ConfigurableProviderResponseToken.java @@ -0,0 +1,20 @@ +package eu.eudat.old.logic.security.validators.configurableProvider.helpers; + +public class ConfigurableProviderResponseToken { + private String accessToken; + private Integer expiresIn; + + public String getAccessToken() { + return accessToken; + } + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public Integer getExpiresIn() { + return expiresIn; + } + public void setExpiresIn(Integer expiresIn) { + this.expiresIn = expiresIn; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/facebook/FacebookTokenValidator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/facebook/FacebookTokenValidator.java new file mode 100644 index 000000000..53fa95145 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/facebook/FacebookTokenValidator.java @@ -0,0 +1,65 @@ +package eu.eudat.old.logic.security.validators.facebook; + +import eu.eudat.old.exceptions.security.UnauthorisedException; +import eu.eudat.old.logic.security.validators.TokenValidator; +import eu.eudat.old.logic.security.validators.TokenValidatorFactoryImpl; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.loginprovider.LoginProviderUser; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.social.facebook.api.User; +import org.springframework.social.facebook.connect.FacebookServiceProvider; +import org.springframework.stereotype.Component; + +import java.util.Calendar; +import java.util.Date; +import java.util.Map; + + +@Component("facebookTokenValidator") +public class FacebookTokenValidator implements TokenValidator { + + private AuthenticationService nonVerifiedUserAuthenticationService; + private FacebookServiceProvider facebookServiceProvider; + + @Autowired + public FacebookTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService) { + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + this.facebookServiceProvider = new FacebookServiceProvider(environment.getProperty("facebook.login.clientId"), environment.getProperty("facebook.login.clientSecret"), environment.getProperty("facebook.login.namespace")); + } + + @Override + public Principal validateToken(LoginInfo credentials) { + User profile = getFacebookUser(credentials.getTicket()); + LoginProviderUser user = new LoginProviderUser(); + if (profile.getEmail() == null) + throw new UnauthorisedException("Cannot login user.Facebook account did not provide email"); + + user.setEmail(profile.getEmail()); + user.setId(profile.getId()); + //user.setIsVerified(profile.isVerified()); + user.setName(profile.getName()); + user.setProvider(TokenValidatorFactoryImpl.LoginProvider.FACEBOOK); + String url = (String) ((Map) ((Map) profile.getExtraData().get("picture")).get("data")).get("url"); + user.setAvatarUrl(url); + user.setSecret(credentials.getTicket()); + return this.nonVerifiedUserAuthenticationService.Touch(user); + } + + + private User getFacebookUser(String accessToken) { + String[] fields = {"id", "email", "first_name", "last_name", "name", "verified", "picture"}; + return this.facebookServiceProvider.getApi(accessToken).fetchObject("me", User.class, fields); + } + + private Date addADay(Date date) { + Date dt = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(dt); + c.add(Calendar.DATE, 1); + dt = c.getTime(); + return dt; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/google/GoogleTokenValidator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/google/GoogleTokenValidator.java new file mode 100644 index 000000000..8833921ca --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/google/GoogleTokenValidator.java @@ -0,0 +1,56 @@ +package eu.eudat.old.logic.security.validators.google; + +import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; +import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload; +import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.jackson2.JacksonFactory; +import eu.eudat.old.logic.security.validators.TokenValidator; +import eu.eudat.old.logic.security.validators.TokenValidatorFactoryImpl; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.loginprovider.LoginProviderUser; +import eu.eudat.old.models.data.security.Principal; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Collections; + +@Component("googleTokenValidator") +public class GoogleTokenValidator implements TokenValidator { + + private static final HttpTransport transport = new NetHttpTransport(); + private AuthenticationService nonVerifiedUserAuthenticationService; + private GoogleIdTokenVerifier verifier; + + @Autowired + public GoogleTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService) { + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + verifier = new GoogleIdTokenVerifier.Builder(transport, JacksonFactory.getDefaultInstance()) + .setAudience(Collections.singletonList(environment.getProperty("google.login.clientId"))) + .build(); + } + + private GoogleIdToken verifyUserAndGetUser(String idTokenString) throws IOException, GeneralSecurityException { + return verifier.verify(idTokenString); + } + + @Override + public Principal validateToken(LoginInfo credentials) throws IOException, GeneralSecurityException { + GoogleIdToken idToken = this.verifyUserAndGetUser(credentials.getTicket()); + Payload payload = idToken.getPayload(); + LoginProviderUser user = new LoginProviderUser(); + user.setAvatarUrl((String) payload.get("picture")); + user.setSecret(credentials.getTicket()); + user.setId(payload.getSubject()); + user.setProvider(TokenValidatorFactoryImpl.LoginProvider.GOOGLE); + user.setName((String) payload.get("name")); + user.setEmail(payload.getEmail()); + user.setIsVerified(payload.getEmailVerified()); + return this.nonVerifiedUserAuthenticationService.Touch(user); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/linkedin/LinkedInTokenValidator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/linkedin/LinkedInTokenValidator.java new file mode 100644 index 000000000..b3ebf39ec --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/linkedin/LinkedInTokenValidator.java @@ -0,0 +1,67 @@ +package eu.eudat.old.logic.security.validators.linkedin; + +import eu.eudat.old.exceptions.security.UnauthorisedException; +import eu.eudat.old.logic.security.validators.TokenValidator; +import eu.eudat.old.logic.security.customproviders.LinkedIn.LinkedInCustomProvider; +import eu.eudat.old.logic.security.customproviders.LinkedIn.LinkedInUser; +import eu.eudat.old.logic.security.validators.linkedin.helpers.LinkedInRequest; +import eu.eudat.old.logic.security.validators.linkedin.helpers.LinkedInResponseToken; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.loginprovider.LoginProviderUser; +import eu.eudat.old.models.data.security.Principal; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + + +@Component("linkedInTokenValidator") +public class LinkedInTokenValidator implements TokenValidator { + + private Environment environment; + private AuthenticationService nonVerifiedUserAuthenticationService; + private LinkedInCustomProvider linkedInCustomProvider; + + @Autowired + public LinkedInTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, LinkedInCustomProvider linkedInCustomProvider) { + this.environment = environment; + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + this.linkedInCustomProvider = linkedInCustomProvider; + } + + @Override + public Principal validateToken(LoginInfo credentials) { + /*AccessGrant accessGrant = this.linkedInServiceProvider.getOAuthOperations().exchangeForAccess(credentials.getTicket(), this.environment.getProperty("linkedin.login.redirect_uri"), null); + LinkedIn linkedInService = this.linkedInServiceProvider.getApi(accessGrant.getAccessToken()); + LinkedInProfile linkedInProfile = linkedInService.profileOperations().getUserProfile(); + LoginProviderUser user = new LoginProviderUser(); + + if (linkedInProfile.getEmailAddress() == null) + throw new UnauthorisedException("Cannot login user.LinkedIn account did not provide email"); + user.setEmail(linkedInProfile.getEmailAddress()); + user.setId(linkedInProfile.getId()); + user.setIsVerified(true); //TODO + user.setAvatarUrl(linkedInProfile.getProfilePictureUrl()); + user.setName(linkedInProfile.getFirstName() + " " + linkedInProfile.getLastName()); + user.setProvider(TokenValidatorFactoryImpl.LoginProvider.LINKEDIN); + user.setSecret(accessGrant.getAccessToken());*/ + + LinkedInUser linkedInUser = this.linkedInCustomProvider.getUser(credentials.getTicket()); + if (linkedInUser.getEmail() == null) + throw new UnauthorisedException("Cannot login user.LinkedIn account did not provide email"); + LoginProviderUser user = new LoginProviderUser(); + user.setId(linkedInUser.getId()); + user.setName(linkedInUser.getName()); + user.setEmail(linkedInUser.getEmail()); + user.setProvider(credentials.getProvider()); + user.setSecret(credentials.getTicket()); + + return this.nonVerifiedUserAuthenticationService.Touch(user); + } + + public LinkedInResponseToken getAccessToken(LinkedInRequest linkedInRequest) { + return this.linkedInCustomProvider.getAccessToken( + linkedInRequest.getCode(), this.environment.getProperty("linkedin.login.redirect_uri"), + this.environment.getProperty("linkedin.login.clientId"), this.environment.getProperty("linkedin.login.clientSecret")); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/linkedin/helpers/LinkedInRequest.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/linkedin/helpers/LinkedInRequest.java new file mode 100644 index 000000000..01f5f483e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/linkedin/helpers/LinkedInRequest.java @@ -0,0 +1,12 @@ +package eu.eudat.old.logic.security.validators.linkedin.helpers; + +public class LinkedInRequest { + private String code; + + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/linkedin/helpers/LinkedInResponseToken.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/linkedin/helpers/LinkedInResponseToken.java new file mode 100644 index 000000000..154010247 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/linkedin/helpers/LinkedInResponseToken.java @@ -0,0 +1,21 @@ +package eu.eudat.old.logic.security.validators.linkedin.helpers; + +public class LinkedInResponseToken { + + private String accessToken; + private Integer expiresIn; + + public String getAccessToken() { + return accessToken; + } + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public Integer getExpiresIn() { + return expiresIn; + } + public void setExpiresIn(Integer expiresIn) { + this.expiresIn = expiresIn; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/openaire/OpenAIRETokenValidator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/openaire/OpenAIRETokenValidator.java new file mode 100644 index 000000000..c813c350c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/openaire/OpenAIRETokenValidator.java @@ -0,0 +1,52 @@ +package eu.eudat.old.logic.security.validators.openaire; + +import eu.eudat.old.logic.security.validators.TokenValidator; +import eu.eudat.old.logic.security.validators.openaire.helpers.OpenAIRERequest; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.exceptions.security.NonValidTokenException; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.logic.security.customproviders.OpenAIRE.OpenAIRECustomProvider; +import eu.eudat.old.logic.security.customproviders.OpenAIRE.OpenAIREUser; +import eu.eudat.old.logic.security.validators.openaire.helpers.OpenAIREResponseToken; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.models.data.loginprovider.LoginProviderUser; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +@Component("openAIRETokenValidator") +public class OpenAIRETokenValidator implements TokenValidator { + + private Environment environment; + private AuthenticationService nonVerifiedUserAuthenticationService; + private OpenAIRECustomProvider openAIRECustomProvider; + + public OpenAIRETokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, OpenAIRECustomProvider openAIRECustomProvider) { + this.environment = environment; + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + this.openAIRECustomProvider = openAIRECustomProvider; + } + + public OpenAIREResponseToken getAccessToken(OpenAIRERequest openAIRERequest) { + return this.openAIRECustomProvider.getAccessToken( + openAIRERequest.getCode(), this.environment.getProperty("openaire.login.redirect_uri"), + this.environment.getProperty("openaire.login.client_id"), this.environment.getProperty("openaire.login.client_secret") + ); + } + + @Override + public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException { + OpenAIREUser openAIREUser = this.openAIRECustomProvider.getUser(credentials.getTicket()); + LoginProviderUser user = new LoginProviderUser(); + user.setId(openAIREUser.getId()); + user.setEmail(openAIREUser.getEmail()); + user.setName(openAIREUser.getName()); + user.setProvider(credentials.getProvider()); + user.setSecret(credentials.getTicket()); + + return this.nonVerifiedUserAuthenticationService.Touch(user); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/openaire/helpers/OpenAIRERequest.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/openaire/helpers/OpenAIRERequest.java new file mode 100644 index 000000000..063b6cb32 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/openaire/helpers/OpenAIRERequest.java @@ -0,0 +1,12 @@ +package eu.eudat.old.logic.security.validators.openaire.helpers; + +public class OpenAIRERequest { + private String code; + + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/openaire/helpers/OpenAIREResponseToken.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/openaire/helpers/OpenAIREResponseToken.java new file mode 100644 index 000000000..b9e6e0789 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/openaire/helpers/OpenAIREResponseToken.java @@ -0,0 +1,20 @@ +package eu.eudat.old.logic.security.validators.openaire.helpers; + +public class OpenAIREResponseToken { + private String accessToken; + private Integer expiresIn; + + public String getAccessToken() { + return accessToken; + } + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public Integer getExpiresIn() { + return expiresIn; + } + public void setExpiresIn(Integer expiresIn) { + this.expiresIn = expiresIn; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/orcid/ORCIDTokenValidator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/orcid/ORCIDTokenValidator.java new file mode 100644 index 000000000..fd71af397 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/orcid/ORCIDTokenValidator.java @@ -0,0 +1,51 @@ +package eu.eudat.old.logic.security.validators.orcid; + +import eu.eudat.old.exceptions.security.NonValidTokenException; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.logic.security.customproviders.ORCID.ORCIDUser; +import eu.eudat.old.logic.security.validators.TokenValidator; +import eu.eudat.old.logic.security.validators.orcid.helpers.ORCIDRequest; +import eu.eudat.old.logic.security.validators.orcid.helpers.ORCIDResponseToken; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.logic.security.customproviders.ORCID.ORCIDCustomProvider; +import eu.eudat.old.models.data.loginprovider.LoginProviderUser; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +@Component("orcidTokenValidator") +public class ORCIDTokenValidator implements TokenValidator { + + private ORCIDCustomProvider orcidCustomProvider; + private Environment environment; + private AuthenticationService nonVerifiedUserAuthenticationService; + + @Autowired + public ORCIDTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, ORCIDCustomProvider orcidCustomProvider) { + this.environment = environment; + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + this.orcidCustomProvider = orcidCustomProvider; + } + + @Override + public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException { + ORCIDUser orcidUser = new ORCIDUser().getOrcidUser(credentials.getData()); + LoginProviderUser user = new LoginProviderUser(); + user.setId(orcidUser.getOrcidId()); + user.setName(orcidUser.getName()); + user.setProvider(credentials.getProvider()); + user.setSecret(credentials.getTicket()); + return this.nonVerifiedUserAuthenticationService.Touch(user); + } + + public ORCIDResponseToken getAccessToken(ORCIDRequest orcidRequest) { + return this.orcidCustomProvider.getAccessToken(orcidRequest.getCode(), this.environment.getProperty("orcid.login.redirect_uri") + , this.environment.getProperty("orcid.login.client_id") + , this.environment.getProperty("orcid.login.client_secret")); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/orcid/helpers/ORCIDRequest.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/orcid/helpers/ORCIDRequest.java new file mode 100644 index 000000000..3ba49b961 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/orcid/helpers/ORCIDRequest.java @@ -0,0 +1,12 @@ +package eu.eudat.old.logic.security.validators.orcid.helpers; + +public class ORCIDRequest { + private String code; + + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/orcid/helpers/ORCIDResponseToken.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/orcid/helpers/ORCIDResponseToken.java new file mode 100644 index 000000000..fd674eea0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/orcid/helpers/ORCIDResponseToken.java @@ -0,0 +1,28 @@ +package eu.eudat.old.logic.security.validators.orcid.helpers; + +public class ORCIDResponseToken { + private String orcidId; + private String name; + private String accessToken; + + public String getOrcidId() { + return orcidId; + } + public void setOrcidId(String orcidId) { + this.orcidId = orcidId; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getAccessToken() { + return accessToken; + } + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/twitter/TwitterTokenValidator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/twitter/TwitterTokenValidator.java new file mode 100644 index 000000000..e9bfefe7e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/twitter/TwitterTokenValidator.java @@ -0,0 +1,73 @@ +package eu.eudat.old.logic.security.validators.twitter; + +import eu.eudat.old.logic.security.validators.TokenValidator; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.exceptions.security.NonValidTokenException; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.logic.security.validators.TokenValidatorFactoryImpl; +import eu.eudat.old.models.data.loginprovider.LoginProviderUser; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.social.oauth1.AuthorizedRequestToken; +import org.springframework.social.oauth1.OAuthToken; +import org.springframework.social.twitter.api.TwitterProfile; +import org.springframework.social.twitter.api.impl.TwitterTemplate; +import org.springframework.social.twitter.connect.TwitterServiceProvider; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Map; + + +@Component("twitterTokenValidator") +public class TwitterTokenValidator implements TokenValidator { + + private Environment environment; + private AuthenticationService nonVerifiedUserAuthenticationService; + private TwitterServiceProvider twitterServiceProvider; + + @Autowired + public TwitterTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService) { + this.environment = environment; + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + this.twitterServiceProvider = new TwitterServiceProvider(this.environment.getProperty("twitter.login.clientId"), this.environment.getProperty("twitter.login.clientSecret")); + } + + @Override + public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException { + String verifier = (String) ((Map)credentials.getData()).get("verifier"); + String email = (String) ((Map) credentials.getData()).get("email"); + OAuthToken oAuthToken = new OAuthToken(credentials.getTicket(), verifier); + AuthorizedRequestToken authorizedRequestToken = new AuthorizedRequestToken(oAuthToken, verifier); + OAuthToken finalOauthToken = this.twitterServiceProvider.getOAuthOperations().exchangeForAccessToken(authorizedRequestToken, null); + TwitterTemplate twitterTemplate = new TwitterTemplate(this.environment.getProperty("twitter.login.clientId"), this.environment.getProperty("twitter.login.clientSecret"), finalOauthToken.getValue(), finalOauthToken.getSecret()); + TwitterProfile profile = this.twitterServiceProvider.getApi(finalOauthToken.getValue(), finalOauthToken.getSecret()).userOperations().getUserProfile(); + LoginProviderUser user = new LoginProviderUser(); + + Map values = twitterTemplate.getRestTemplate().getForObject("https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true", Map.class); + if (values.get("email") == null) { +// throw new UnauthorisedException("Cannot login user.Twitter account did not provide email"); + user.setIsVerified(false); //TODO + if (email != null && !email.isEmpty()) { + user.setEmail(email); + } + } + else { + user.setEmail((String) values.get("email")); + user.setIsVerified(true); //TODO + } + user.setAvatarUrl(profile.getProfileImageUrl()); + user.setId("" + profile.getId()); + user.setName(profile.getName()); + user.setProvider(TokenValidatorFactoryImpl.LoginProvider.TWITTER); + user.setSecret(finalOauthToken.getValue()); + return this.nonVerifiedUserAuthenticationService.Touch(user); + } + + public OAuthToken getRequestToken() { + return this.twitterServiceProvider.getOAuthOperations().fetchRequestToken(this.environment.getProperty("twitter.login.redirect_uri"), null); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/zenodo/ZenodoTokenValidator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/zenodo/ZenodoTokenValidator.java new file mode 100644 index 000000000..627616b37 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/zenodo/ZenodoTokenValidator.java @@ -0,0 +1,57 @@ +package eu.eudat.old.logic.security.validators.zenodo; + +import eu.eudat.old.exceptions.security.NonValidTokenException; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.logic.security.customproviders.Zenodo.ZenodoAccessType; +import eu.eudat.old.logic.security.customproviders.Zenodo.ZenodoCustomProvider; +import eu.eudat.old.logic.security.customproviders.Zenodo.ZenodoUser; +import eu.eudat.old.logic.security.validators.TokenValidator; +import eu.eudat.old.logic.security.validators.zenodo.helpers.ZenodoRequest; +import eu.eudat.old.logic.security.validators.zenodo.helpers.ZenodoResponseToken; +import eu.eudat.old.logic.services.operations.authentication.AuthenticationService; +import eu.eudat.old.models.data.login.LoginInfo; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.models.data.loginprovider.LoginProviderUser; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +@Component("zenodoTokenValidator") +public class ZenodoTokenValidator implements TokenValidator { + + private ZenodoCustomProvider zenodoCustomProvider; + private Environment environment; + private AuthenticationService nonVerifiedUserAuthenticationService; + + @Autowired + public ZenodoTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, ZenodoCustomProvider zenodoCustomProvider) { + this.environment = environment; + this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService; + this.zenodoCustomProvider = zenodoCustomProvider; + } + + @Override + public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException { + ZenodoUser zenodoUser = new ZenodoUser().getZenodoUser(credentials.getData()); + LoginProviderUser user = new LoginProviderUser(); + user.setId(zenodoUser.getUserId()); + user.setName(zenodoUser.getEmail()); + user.setEmail(zenodoUser.getEmail()); + user.setZenodoId(zenodoUser.getAccessToken()); + user.setZenodoExpire(zenodoUser.getExpiresIn()); + user.setZenodoRefresh(zenodoUser.getRefreshToken()); + user.setProvider(credentials.getProvider()); + user.setSecret(credentials.getTicket()); + return this.nonVerifiedUserAuthenticationService.Touch(user); + } + + public ZenodoResponseToken getAccessToken(ZenodoRequest zenodoRequest) { + return this.zenodoCustomProvider.getAccessToken(ZenodoAccessType.AUTHORIZATION_CODE, zenodoRequest.getCode() + , this.environment.getProperty("zenodo.login.client_id") + , this.environment.getProperty("zenodo.login.client_secret") + , this.environment.getProperty("zenodo.login.redirect_uri")); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/zenodo/helpers/ZenodoRequest.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/zenodo/helpers/ZenodoRequest.java new file mode 100644 index 000000000..68fdd4590 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/zenodo/helpers/ZenodoRequest.java @@ -0,0 +1,12 @@ +package eu.eudat.old.logic.security.validators.zenodo.helpers; + +public class ZenodoRequest { + private String code; + + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/zenodo/helpers/ZenodoResponseToken.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/zenodo/helpers/ZenodoResponseToken.java new file mode 100644 index 000000000..bf838631e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/security/validators/zenodo/helpers/ZenodoResponseToken.java @@ -0,0 +1,47 @@ +package eu.eudat.old.logic.security.validators.zenodo.helpers; + +public class ZenodoResponseToken { + private String userId; + private String email; + private Integer expiresIn; + private String accessToken; + private String refreshToken; + + public String getUserId() { + return userId; + } + public void setUserId(String userId) { + this.userId = userId; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Integer getExpiresIn() { + return expiresIn; + } + + public void setExpiresIn(Integer expiresIn) { + this.expiresIn = expiresIn; + } + + public String getAccessToken() { + return accessToken; + } + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public String getRefreshToken() { + return refreshToken; + } + + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/ApiContext.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/ApiContext.java new file mode 100644 index 000000000..9b963545e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/ApiContext.java @@ -0,0 +1,14 @@ +package eu.eudat.old.logic.services; + +import eu.eudat.old.logic.services.helpers.HelpersService; +import eu.eudat.old.logic.services.operations.OperationsContext; +import eu.eudat.old.logic.services.utilities.UtilitiesService; + +public interface ApiContext { + + HelpersService getHelpersService(); + + OperationsContext getOperationsContext(); + + UtilitiesService getUtilitiesService(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/ApiContextImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/ApiContextImpl.java new file mode 100644 index 000000000..81ce21b2a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/ApiContextImpl.java @@ -0,0 +1,38 @@ +package eu.eudat.old.logic.services; + +import eu.eudat.old.logic.services.helpers.HelpersService; +import eu.eudat.old.logic.services.operations.OperationsContext; +import eu.eudat.old.logic.services.utilities.UtilitiesService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + + +@Service("apiContext") +public class ApiContextImpl implements ApiContext { + + private OperationsContext operationsContext; + private HelpersService helpersService; + private UtilitiesService utilitiesService; + + @Autowired + public ApiContextImpl(OperationsContext operationsContext, HelpersService helpersService, UtilitiesService utilitiesService) { + this.operationsContext = operationsContext; + this.helpersService = helpersService; + this.utilitiesService = utilitiesService; + } + + @Override + public OperationsContext getOperationsContext() { + return operationsContext; + } + + @Override + public HelpersService getHelpersService() { + return helpersService; + } + + @Override + public UtilitiesService getUtilitiesService() { + return utilitiesService; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityContext.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityContext.java new file mode 100644 index 000000000..c14750240 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityContext.java @@ -0,0 +1,45 @@ +package eu.eudat.old.logic.services.forms; + +import eu.eudat.old.models.data.user.components.commons.Rule; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; + +/** + * Created by ikalyvas on 3/5/2018. + */ +public class VisibilityContext { + private List visibilityRules = new LinkedList<>(); + + public List getVisibilityRules() { + return visibilityRules; + } + + public VisibilityRule get(String id) { + Optional rule = visibilityRules.stream().filter(item -> item.getVisibilityRuleTargetId().equals(id)).findFirst(); + if (rule.isPresent()) return rule.get(); + return null; + } + + public void buildVisibilityContext(List sources) { + sources.forEach(this::addToVisibilityRulesContext); + } + + private void addToVisibilityRulesContext(Rule item) { + VisibilityRuleSource source = new VisibilityRuleSource(); + source.setVisibilityRuleSourceId(item.getSourceField()); + source.setVisibilityRuleSourceValue(item.getRequiredValue()); + + Optional visibilityRuleOptional = visibilityRules.stream().filter(rule -> rule.getVisibilityRuleTargetId().equals(item.getTargetField())).findFirst(); + if (visibilityRuleOptional.isPresent()) visibilityRuleOptional.get().getVisibilityRuleSources().add(source); + else { + List sources = new LinkedList<>(); + sources.add(source); + VisibilityRule visibilityRule = new VisibilityRule(); + visibilityRule.setVisibilityRuleTargetId(item.getTargetField()); + visibilityRule.setVisibilityRuleSources(sources); + this.visibilityRules.add(visibilityRule); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRule.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRule.java new file mode 100644 index 000000000..668344b28 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRule.java @@ -0,0 +1,27 @@ +package eu.eudat.old.logic.services.forms; + +import java.util.List; + +/** + * Created by ikalyvas on 3/5/2018. + */ +public class VisibilityRule { + private String visibilityRuleTargetId; + private List visibilityRuleSources; + + public String getVisibilityRuleTargetId() { + return visibilityRuleTargetId; + } + + public void setVisibilityRuleTargetId(String visibilityRuleTargetId) { + this.visibilityRuleTargetId = visibilityRuleTargetId; + } + + public List getVisibilityRuleSources() { + return visibilityRuleSources; + } + + public void setVisibilityRuleSources(List visibilityRuleSources) { + this.visibilityRuleSources = visibilityRuleSources; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRuleService.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRuleService.java new file mode 100644 index 000000000..f1f367ff6 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRuleService.java @@ -0,0 +1,17 @@ +package eu.eudat.old.logic.services.forms; + +import eu.eudat.old.models.data.user.components.commons.Rule; + +import java.util.List; +import java.util.Map; + +/** + * Created by ikalyvas on 3/5/2018. + */ +public interface VisibilityRuleService { + boolean isElementVisible(String id); + + void buildVisibilityContext(List sources); + + void setProperties(Map properties); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRuleServiceImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRuleServiceImpl.java new file mode 100644 index 000000000..24919fe36 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRuleServiceImpl.java @@ -0,0 +1,60 @@ +package eu.eudat.old.logic.services.forms; + +import eu.eudat.old.models.data.user.components.commons.Rule; + +import java.util.*; + +/** + * Created by ikalyvas on 3/5/2018. + */ +public class VisibilityRuleServiceImpl implements VisibilityRuleService { + private final Map elementVisibility = new HashMap<>(); + private Map properties; + + public boolean isElementVisible(String id) { + return !this.elementVisibility.containsKey(id) || this.elementVisibility.get(id); + } + + public void setProperties(Map properties) { + this.properties = properties; + this.properties.entrySet().stream() + .filter(stringObjectEntry -> stringObjectEntry.getValue() instanceof String && ((String) stringObjectEntry.getValue()).startsWith("[") + && ((String) stringObjectEntry.getValue()).endsWith("]")) + .forEach(stringObjectEntry -> stringObjectEntry.setValue(parseArray((String) stringObjectEntry.getValue()))); + } + + private List parseArray(String original) { + String parsed = original.replace("[", "").replace("\"", "").replace("]", ""); + return Arrays.asList(parsed.split(",")); + } + + public void buildVisibilityContext(List sources) { + VisibilityContext visibilityContext = new VisibilityContext(); + visibilityContext.buildVisibilityContext(sources); + visibilityContext.getVisibilityRules().forEach(this::evaluateVisibility); + } + + private void evaluateVisibility(VisibilityRule rule) { + List sources = rule.getVisibilityRuleSources(); + for(VisibilityRuleSource source: sources){ + if (properties.containsKey(source.getVisibilityRuleSourceId()) + && isContained(properties.get(source.getVisibilityRuleSourceId()), source.getVisibilityRuleSourceValue())) { + this.elementVisibility.put(rule.getVisibilityRuleTargetId(), true); + } else { + this.elementVisibility.put(rule.getVisibilityRuleTargetId(), + this.elementVisibility.getOrDefault(rule.getVisibilityRuleTargetId(), false)); + } + } + } + + private Boolean isContained(Object values, String source) { + if (values instanceof List) { + return ((Collection) values).contains(source); + } else { + if (values != null) { + return values.equals(source); + } + return false; + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRuleSource.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRuleSource.java new file mode 100644 index 000000000..7a1f225ec --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/forms/VisibilityRuleSource.java @@ -0,0 +1,25 @@ +package eu.eudat.old.logic.services.forms; + +/** + * Created by ikalyvas on 3/5/2018. + */ +public class VisibilityRuleSource { + private String visibilityRuleSourceId; + private String visibilityRuleSourceValue; + + public String getVisibilityRuleSourceId() { + return visibilityRuleSourceId; + } + + public void setVisibilityRuleSourceId(String visibilityRuleSourceId) { + this.visibilityRuleSourceId = visibilityRuleSourceId; + } + + public String getVisibilityRuleSourceValue() { + return visibilityRuleSourceValue; + } + + public void setVisibilityRuleSourceValue(String visibilityRuleSourceValue) { + this.visibilityRuleSourceValue = visibilityRuleSourceValue; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/helpers/HelpersService.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/helpers/HelpersService.java new file mode 100644 index 000000000..86b0f1ae2 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/helpers/HelpersService.java @@ -0,0 +1,13 @@ +package eu.eudat.old.logic.services.helpers; + +import org.springframework.context.MessageSource; + +/** + * Created by ikalyvas on 3/1/2018. + */ +public interface HelpersService { + + MessageSource getMessageSource(); + +// LoggerService getLoggerService(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/helpers/HelpersServiceImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/helpers/HelpersServiceImpl.java new file mode 100644 index 000000000..99af27d7f --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/helpers/HelpersServiceImpl.java @@ -0,0 +1,31 @@ +package eu.eudat.old.logic.services.helpers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.stereotype.Service; + +/** + * Created by ikalyvas on 3/1/2018. + */ +@Service("helpersService") +public class HelpersServiceImpl implements HelpersService { + + private MessageSource messageSource; +// private LoggerService loggerService; + + @Autowired + public HelpersServiceImpl(MessageSource messageSource/*, LoggerService loggerService*/) { + this.messageSource = messageSource; +// this.loggerService = loggerService; + } + + @Override + public MessageSource getMessageSource() { + return messageSource; + } + + /*@Override + public LoggerService getLoggerService() { + return loggerService; + }*/ +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/helpers/LoggerService.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/helpers/LoggerService.java new file mode 100644 index 000000000..366b5f474 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/helpers/LoggerService.java @@ -0,0 +1,12 @@ +package eu.eudat.old.logic.services.helpers; + +import eu.eudat.old.types.WarningLevel; + +/** + * Created by ikalyvas on 3/1/2018. + */ +public interface LoggerService { + void log(String message); + + void log(String message, WarningLevel level); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/DatabaseRepository.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/DatabaseRepository.java new file mode 100644 index 000000000..0834985f1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/DatabaseRepository.java @@ -0,0 +1,68 @@ +package eu.eudat.old.logic.services.operations; + +import eu.eudat.old.data.dao.entities.*; +import eu.eudat.old.data.dao.entities.security.UserTokenDao; +import eu.eudat.old.data.dao.entities.security.CredentialDao; +public interface DatabaseRepository { + DataRepositoryDao getDataRepositoryDao(); + + DatasetDao getDatasetDao(); + + DatasetProfileDao getDatasetProfileDao(); + + DMPDao getDmpDao(); + + DmpDatasetProfileDao getDmpDatasetProfileDao(); + + OrganisationDao getOrganisationDao(); + + GrantDao getGrantDao(); + + RegistryDao getRegistryDao(); + + ResearcherDao getResearcherDao(); + + ServiceDao getServiceDao(); + + UserInfoDao getUserInfoDao(); + + UserRoleDao getUserRoleDao(); + + InvitationDao getInvitationDao(); + + CredentialDao getCredentialDao(); + + UserTokenDao getUserTokenDao(); + + ExternalDatasetDao getExternalDatasetDao(); + + UserDatasetProfileDao getUserDatasetProfileDao(); + + UserDmpDao getUserDmpDao(); + + ContentDao getContentDao(); + + DMPProfileDao getDmpProfileDao(); + + DatasetExternalDatasetDao getDatasetExternalDatasetDao(); + + DatasetServiceDao getDatasetServiceDao(); + + EmailConfirmationDao getLoginConfirmationEmailDao(); + + ProjectDao getProjectDao(); + + FunderDao getFunderDao(); + + LockDao getLockDao(); + + NotificationDao getNotificationDao(); + + FileUploadDao getFileUploadDao(); + + EntityDoiDao getEntityDoiDao(); + + DescriptionTemplateTypeDao getDescriptionTemplateTypeDao(); + + void detachEntity(T entity); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/DatabaseRepositoryImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/DatabaseRepositoryImpl.java new file mode 100644 index 000000000..12bc90f5b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/DatabaseRepositoryImpl.java @@ -0,0 +1,356 @@ +package eu.eudat.old.logic.services.operations; + +import eu.eudat.old.data.dao.entities.*; +import eu.eudat.old.data.dao.entities.security.UserTokenDao; +import eu.eudat.old.data.dao.entities.security.CredentialDao; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.persistence.EntityManager; + + +@Service("databaseRepository") +public class DatabaseRepositoryImpl implements DatabaseRepository { + + private DataRepositoryDao dataRepositoryDao; + private DatasetDao datasetDao; + private DatasetProfileDao datasetProfileDao; + private DMPDao dmpDao; + private DmpDatasetProfileDao dmpDatasetProfileDao; + private OrganisationDao organisationDao; + private GrantDao GrantDao; + private RegistryDao registryDao; + private ResearcherDao researcherDao; + private ServiceDao serviceDao; + private UserInfoDao userInfoDao; + private InvitationDao invitationDao; + private CredentialDao credentialDao; + private UserTokenDao userTokenDao; + private ExternalDatasetDao externalDatasetDao; + private UserRoleDao userRoleDao; + private UserDatasetProfileDao userDatasetProfileDao; + private UserDmpDao userDmpDao; + private ContentDao contentDao; + private DMPProfileDao dmpProfileDao; + private DatasetExternalDatasetDao datasetExternalDatasetDao; + private DatasetServiceDao datasetServiceDao; + private EmailConfirmationDao loginConfirmationEmailDao; + private ProjectDao projectDao; + private FunderDao funderDao; + private LockDao lockDao; + private NotificationDao notificationDao; + private FileUploadDao fileUploadDao; + private EntityDoiDao entityDoiDao; + private DescriptionTemplateTypeDao descriptionTemplateTypeDao; + + private EntityManager entityManager; + + @Autowired + private void setDataRepositoryDao(DataRepositoryDao dataRepositoryDao) { + this.dataRepositoryDao = dataRepositoryDao; + } + + @Autowired + private void setDatasetDao(DatasetDao datasetDao) { + this.datasetDao = datasetDao; + } + + @Autowired + private void setDatasetProfileDao(DatasetProfileDao datasetProfileDao) { + this.datasetProfileDao = datasetProfileDao; + } + + @Autowired + private void setDmpDao(DMPDao dmpDao) { + this.dmpDao = dmpDao; + } + + @Autowired + private void setDmpDatasetProfileDao(DmpDatasetProfileDao dmpDatasetProfileDao) { + this.dmpDatasetProfileDao = dmpDatasetProfileDao; + } + + @Autowired + private void setOrganisationDao(OrganisationDao organisationDao) { + this.organisationDao = organisationDao; + } + + @Autowired + private void setGrantDao(GrantDao GrantDao) { + this.GrantDao = GrantDao; + } + + @Autowired + private void setRegistryDao(RegistryDao registryDao) { + this.registryDao = registryDao; + } + + @Autowired + private void setResearcherDao(ResearcherDao researcherDao) { + this.researcherDao = researcherDao; + } + + @Autowired + public void setServiceDao(ServiceDao serviceDao) { + this.serviceDao = serviceDao; + } + + @Autowired + private void setUserInfoDao(UserInfoDao userInfoDao) { + this.userInfoDao = userInfoDao; + } + + @Override + public DataRepositoryDao getDataRepositoryDao() { + return dataRepositoryDao; + } + + @Override + public DatasetDao getDatasetDao() { + return datasetDao; + } + + @Override + public DatasetProfileDao getDatasetProfileDao() { + return datasetProfileDao; + } + + @Override + public DMPDao getDmpDao() { + return dmpDao; + } + + @Override + public DmpDatasetProfileDao getDmpDatasetProfileDao() { + return dmpDatasetProfileDao; + } + + @Override + public OrganisationDao getOrganisationDao() { + return organisationDao; + } + + @Override + public GrantDao getGrantDao() { + return GrantDao; + } + + @Override + public RegistryDao getRegistryDao() { + return registryDao; + } + + @Override + public ResearcherDao getResearcherDao() { + return researcherDao; + } + + @Override + public ServiceDao getServiceDao() { + return serviceDao; + } + + @Override + public UserInfoDao getUserInfoDao() { + return userInfoDao; + } + + @Override + public InvitationDao getInvitationDao() { + return invitationDao; + } + + @Autowired + public void setInvitationDao(InvitationDao invitationDao) { + this.invitationDao = invitationDao; + } + + @Override + public CredentialDao getCredentialDao() { + return credentialDao; + } + + @Autowired + public void setCredentialDao(CredentialDao credentialDao) { + this.credentialDao = credentialDao; + } + + @Override + public UserTokenDao getUserTokenDao() { + return userTokenDao; + } + + @Autowired + public void setUserTokenDao(UserTokenDao userTokenDao) { + this.userTokenDao = userTokenDao; + } + + @Override + public ExternalDatasetDao getExternalDatasetDao() { + return externalDatasetDao; + } + + @Autowired + public void setExternalDatasetDao(ExternalDatasetDao externalDatasetDao) { + this.externalDatasetDao = externalDatasetDao; + } + + @Override + public UserRoleDao getUserRoleDao() { + return userRoleDao; + } + + @Autowired + public void setUserRoleDao(UserRoleDao userRoleDao) { + this.userRoleDao = userRoleDao; + } + + @Autowired + public void setEntityManager(EntityManager entityManager) { + this.entityManager = entityManager; + } + + @Override + public UserDmpDao getUserDmpDao() { + return userDmpDao; + } + + @Autowired + public void setUserDmpDao(UserDmpDao userDmpDao) { + this.userDmpDao = userDmpDao; + } + + @Override + public ContentDao getContentDao() { + return this.contentDao; + } + + @Autowired + public void setContentDao(ContentDao contentDao) { + this.contentDao = contentDao; + } + + @Override + public DMPProfileDao getDmpProfileDao() { + return dmpProfileDao; + } + + @Autowired + public void setDmpProfileDao(DMPProfileDao dmpProfileDao) { + this.dmpProfileDao = dmpProfileDao; + } + + @Override + public DatasetExternalDatasetDao getDatasetExternalDatasetDao() { + return datasetExternalDatasetDao; + } + + @Autowired + public void setDatasetExternalDatasetDao(DatasetExternalDatasetDao datasetExternalDatasetDao) { + this.datasetExternalDatasetDao = datasetExternalDatasetDao; + } + + @Override + public DatasetServiceDao getDatasetServiceDao() { + return datasetServiceDao; + } + + @Autowired + public void setDatasetServiceDao(DatasetServiceDao datasetServiceDao) { + this.datasetServiceDao = datasetServiceDao; + } + + @Override + public EmailConfirmationDao getLoginConfirmationEmailDao() { + return loginConfirmationEmailDao; + } + + @Autowired + public void setLoginConfirmationEmailDao(EmailConfirmationDao loginConfirmationEmailDao) { + this.loginConfirmationEmailDao = loginConfirmationEmailDao; + } + + @Override + public ProjectDao getProjectDao() { + return projectDao; + } + + @Autowired + public void setProjectDao(ProjectDao projectDao) { + this.projectDao = projectDao; + } + + @Override + public FunderDao getFunderDao() { + return funderDao; + } + + @Autowired + public void setFunderDao(FunderDao funderDao) { + this.funderDao = funderDao; + } + + @Autowired + public void setLockDao(LockDao lockDao) { + this.lockDao = lockDao; + } + + @Override + public LockDao getLockDao() { + return lockDao; + } + + @Override + public NotificationDao getNotificationDao() { + return notificationDao; + } + + @Autowired + public void setNotificationDao(NotificationDao notificationDao) { + this.notificationDao = notificationDao; + } + + @Override + public UserDatasetProfileDao getUserDatasetProfileDao() { + return userDatasetProfileDao; + } + + @Autowired + public void setUserDatasetProfileDao(UserDatasetProfileDao userDatasetProfileDao) { + this.userDatasetProfileDao = userDatasetProfileDao; + } + + @Override + public FileUploadDao getFileUploadDao() { + return fileUploadDao; + } + + @Autowired + public void setFileUploadDao(FileUploadDao fileUploadDao) { + this.fileUploadDao = fileUploadDao; + } + + @Override + public EntityDoiDao getEntityDoiDao() { + return entityDoiDao; + } + + @Autowired + public void setEntityDoiDao(EntityDoiDao entityDoiDao) { + this.entityDoiDao = entityDoiDao; + } + + @Override + public DescriptionTemplateTypeDao getDescriptionTemplateTypeDao() { + return descriptionTemplateTypeDao; + } + + @Autowired + public void setDescriptionTemplateTypeDao(DescriptionTemplateTypeDao descriptionTemplateTypeDao) { + this.descriptionTemplateTypeDao = descriptionTemplateTypeDao; + } + + public void detachEntity(T entity) { + this.entityManager.detach(entity); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/ElasticRepository.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/ElasticRepository.java new file mode 100644 index 000000000..e7a268ff0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/ElasticRepository.java @@ -0,0 +1,11 @@ +package eu.eudat.old.logic.services.operations; + +import eu.eudat.old.elastic.repository.DatasetRepository; +import eu.eudat.old.elastic.repository.DmpRepository; + +public interface ElasticRepository { + + DatasetRepository getDatasetRepository(); + + DmpRepository getDmpRepository(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/ElasticRepositoryImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/ElasticRepositoryImpl.java new file mode 100644 index 000000000..4b9010df3 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/ElasticRepositoryImpl.java @@ -0,0 +1,29 @@ +package eu.eudat.old.logic.services.operations; + +import eu.eudat.old.elastic.repository.DatasetRepository; +import eu.eudat.old.elastic.repository.DmpRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service("elasticRepository") +public class ElasticRepositoryImpl implements ElasticRepository { + + private final DatasetRepository datasetRepository; + private final DmpRepository dmpRepository; + + @Autowired + public ElasticRepositoryImpl(DatasetRepository datasetRepository, DmpRepository dmpRepository) { + this.datasetRepository = datasetRepository; + this.dmpRepository = dmpRepository; + } + + @Override + public DatasetRepository getDatasetRepository() { + return datasetRepository; + } + + @Override + public DmpRepository getDmpRepository() { + return dmpRepository; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/OperationsContext.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/OperationsContext.java new file mode 100644 index 000000000..ce0a635aa --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/OperationsContext.java @@ -0,0 +1,23 @@ +package eu.eudat.old.logic.services.operations; + +import eu.eudat.old.logic.builders.BuilderFactory; +import eu.eudat.old.logic.proxy.fetching.RemoteFetcher; +import org.springframework.context.ApplicationContext; + +/** + * Created by ikalyvas on 3/1/2018. + */ +public interface OperationsContext { + + DatabaseRepository getDatabaseRepository(); + + ApplicationContext getApplicationContext(); + + BuilderFactory getBuilderFactory(); + + RemoteFetcher getRemoteFetcher(); + +// FileStorageService getFileStorageService(); + + ElasticRepository getElasticRepository(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/OperationsContextImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/OperationsContextImpl.java new file mode 100644 index 000000000..907d86e82 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/OperationsContextImpl.java @@ -0,0 +1,62 @@ +package eu.eudat.old.logic.services.operations; + +import eu.eudat.old.logic.builders.BuilderFactory; +import eu.eudat.old.logic.proxy.fetching.RemoteFetcher; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Service; + +/** + * Created by ikalyvas on 3/1/2018. + */ +@Service("operationsContext") +public class OperationsContextImpl implements OperationsContext { + + private final DatabaseRepository databaseRepository; + private final ApplicationContext applicationContext; + private final RemoteFetcher remoteFetcher; + private final BuilderFactory builderFactory; +// private final FileStorageService fileStorageService; + private final ElasticRepository elasticRepository; + + @Autowired + public OperationsContextImpl(DatabaseRepository databaseRepository, ApplicationContext applicationContext, RemoteFetcher remoteFetcher + , BuilderFactory builderFactory, /*FileStorageService fileStorageService,*/ ElasticRepository elasticRepository) { + this.databaseRepository = databaseRepository; + this.applicationContext = applicationContext; + this.remoteFetcher = remoteFetcher; + this.builderFactory = builderFactory; +// this.fileStorageService = fileStorageService; + this.elasticRepository = elasticRepository; + } + + @Override + public DatabaseRepository getDatabaseRepository() { + return databaseRepository; + } + + @Override + public ApplicationContext getApplicationContext() { + return applicationContext; + } + + @Override + public RemoteFetcher getRemoteFetcher() { + return remoteFetcher; + } + + @Override + public BuilderFactory getBuilderFactory() { + return builderFactory; + } + +// @Override +// public FileStorageService getFileStorageService() { +// return fileStorageService; +// } + + @Override + public ElasticRepository getElasticRepository() { + return elasticRepository; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/AbstractAuthenticationService.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/AbstractAuthenticationService.java new file mode 100644 index 000000000..443a012bb --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/AbstractAuthenticationService.java @@ -0,0 +1,214 @@ +package eu.eudat.old.logic.services.operations.authentication; + +import eu.eudat.old.data.entities.Credential; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.entities.UserRole; +import eu.eudat.old.data.entities.UserToken; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.logic.builders.entity.CredentialBuilder; +import eu.eudat.old.logic.builders.entity.UserInfoBuilder; +import eu.eudat.old.logic.builders.entity.UserTokenBuilder; +import eu.eudat.old.logic.managers.MetricsManager; +import eu.eudat.old.logic.security.validators.TokenValidatorFactoryImpl; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.login.Credentials; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.Authorities; +import eu.eudat.old.types.MetricNames; +import eu.eudat.old.models.data.loginprovider.LoginProviderUser; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDateTime; +import java.util.*; + +public abstract class AbstractAuthenticationService implements AuthenticationService { + private static final Logger logger = LoggerFactory.getLogger(AbstractAuthenticationService.class); + + protected ApiContext apiContext; + protected Environment environment; + protected MetricsManager metricsManager; + + public AbstractAuthenticationService(ApiContext apiContext, Environment environment, MetricsManager metricsManager) { + this.apiContext = apiContext; + this.environment = environment; + this.metricsManager = metricsManager; + } + + protected Date addADay(Date date) { + Date dt = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(dt); + c.add(Calendar.DATE, 1); + dt = c.getTime(); + return dt; + } + + abstract Principal Touch(UserToken token); + + @Transactional + protected Credential autoCreateUser(String username, String password) { + if (!environment.getProperty("autouser.root.username").equals(username) || !environment.getProperty("autouser.root.password").equals(password)) + return null; + + UserInfo userInfo = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class) + .name(username).email(environment.getProperty("autouser.root.email")).created(new Date()) + .lastloggedin(new Date()).authorization_level((short) 1).usertype((short) 1).userStatus((short)0) + .build(); + + userInfo = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo); + + UserRole role = new UserRole(); + role.setRole(Authorities.ADMIN.getValue()); + role.setUserInfo(userInfo); + this.apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(role); + + Credential credential = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(CredentialBuilder.class) + .id(UUID.randomUUID()).userInfo(userInfo).publicValue(username).secret(password) + .provider((int) TokenValidatorFactoryImpl.LoginProvider.NATIVELOGIN.getValue()) + .creationTime(new Date()).lastUpdateTime(new Date()).status(0) + .build(); + + return this.apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential); + } + + public Principal Touch(UUID token) { + UserToken tokenEntry = this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().find(token); + if (tokenEntry == null || tokenEntry.getExpiresAt().before(new Date())) return null; + + return this.Touch(tokenEntry); + } + + public void Logout(UUID token) { + UserToken tokenEntry = this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().find(token); + this.apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().delete(tokenEntry); + } + + public Principal Touch(Credentials credentials) throws NullEmailException { + Credential credential = this.apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().getLoggedInCredentials(credentials.getUsername(), credentials.getSecret(), TokenValidatorFactoryImpl.LoginProvider.NATIVELOGIN.getValue()); + + if (credential == null && credentials.getUsername().equals(environment.getProperty("autouser.root.username"))) { + try { + credential = this.autoCreateUser(credentials.getUsername(), credentials.getSecret()); + metricsManager.increaseValue(MetricNames.USERS, 1, MetricNames.TOTAL); + } catch (Exception e) { + logger.error(e.getMessage(), e); + return null; + } + } + if (credential == null) return null; + + UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class) + .issuedAt(new Date()).user(credential.getUserInfo()) + .token(UUID.randomUUID()).expiresAt(Timestamp.valueOf(LocalDateTime.now().plusDays(10))) + .build(); + + userToken = apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken); + + return this.Touch(userToken); + + } + + public Principal Touch(LoginProviderUser profile) throws NullEmailException { + + UserInfo userInfo;// = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().withHint("userInfo").where((builder, root) -> builder.and(builder.equal(root.get("email"), profile.getEmail()), builder.equal(root.get("userStatus"), 0))).getSingleOrDefault(); + + //if (userInfo == null) { + Optional optionalCredential = Optional.ofNullable(apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao() + .asQueryable().withHint("credentialUserInfo") + .where((builder, root) -> builder.and(builder.equal(root.get("provider"), profile.getProvider().getValue()), builder.equal(root.get("externalId"), profile.getId()))) + .getSingleOrDefault()); + userInfo = optionalCredential.map(Credential::getUserInfo).orElse(null); + if (userInfo != null) { + if (userInfo.getUserStatus() == 1) { + userInfo = null; + } + } + //} + if (userInfo == null) { + userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().asQueryable().withHint("userInfo").where((builder, root) -> builder.and(builder.equal(root.get("email"), profile.getEmail()), builder.equal(root.get("userStatus"), 0))).getSingleOrDefault(); + } + + final Credential credential = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(CredentialBuilder.class) + .id(UUID.randomUUID()) + .creationTime(new Date()) + .status(1) + .lastUpdateTime(new Date()) + .provider(profile.getProvider().getValue()) + .secret(profile.getSecret()) + .externalId(profile.getId()) + .email(profile.getEmail()) + .build(); + + if (userInfo == null) { + userInfo = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserInfoBuilder.class) + .name(profile.getName()).verified_email(profile.getIsVerified()) + .email(profile.getEmail()).created(new Date()).lastloggedin(new Date()) + .additionalinfo("{\"data\":{\"avatar\":{\"url\":\"" + profile.getAvatarUrl() + + "\"},\"zenodoToken\":\"" + profile.getZenodoId() + + "\", \"expirationDate\": \"" + Instant.now().plusSeconds((profile.getZenodoExpire() != null ? profile.getZenodoExpire(): 0)).toEpochMilli() + + "\", \"zenodoRefresh\": \"" + profile.getZenodoRefresh() + + (profile.getProvider() == TokenValidatorFactoryImpl.LoginProvider.ZENODO ? "\", \"zenodoEmail\": \"" + profile.getEmail() : "") +"\"}}") + .authorization_level((short) 1).usertype((short) 1).userStatus((short)0) + .build(); + + userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo); + credential.setPublicValue(userInfo.getName()); + credential.setEmail(userInfo.getEmail()); + credential.setUserInfo(userInfo); + apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential); + + UserRole role = new UserRole(); + role.setRole(Authorities.USER.getValue()); + role.setUserInfo(userInfo); + apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().createOrUpdate(role); + metricsManager.increaseValue(MetricNames.USERS, 1, MetricNames.TOTAL); + } else { + Map additionalInfo = userInfo.getAdditionalinfo() != null ? + new JSONObject(userInfo.getAdditionalinfo()).toMap() : new HashMap<>(); + if (profile.getAvatarUrl() != null && !profile.getAvatarUrl().isEmpty() && !profile.getAvatarUrl().equals("null")) { + additionalInfo.put("avatarUrl", profile.getAvatarUrl()); + } + if (profile.getZenodoId() != null && !profile.getZenodoId().isEmpty() && !profile.getZenodoId().equals("null")) { + additionalInfo.put("zenodoToken", profile.getZenodoId()); + } + if (profile.getZenodoExpire() != null) { + additionalInfo.put("expirationDate", Instant.now().plusSeconds(profile.getZenodoExpire()).toEpochMilli()); + } + if (profile.getZenodoRefresh() != null) { + additionalInfo.put("zenodoRefresh", profile.getZenodoRefresh()); + } + if (profile.getProvider() == TokenValidatorFactoryImpl.LoginProvider.ZENODO) { + additionalInfo.put("zenodoEmail", profile.getEmail()); + } + userInfo.setLastloggedin(new Date()); + userInfo.setAdditionalinfo(new JSONObject(additionalInfo).toString()); + Set credentials = userInfo.getCredentials(); + if (credentials.contains(credential)) { + Credential oldCredential = credentials.stream().filter(item -> credential.getProvider().equals(item.getProvider())).findFirst().get(); + credential.setId(oldCredential.getId()); + } else { + credential.setUserInfo(userInfo); + credential.setId(UUID.randomUUID()); + credential.setPublicValue(userInfo.getName()); + credential.setEmail(userInfo.getEmail()); + apiContext.getOperationsContext().getDatabaseRepository().getCredentialDao().createOrUpdate(credential); + userInfo.getCredentials().add(credential); + } + userInfo = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().createOrUpdate(userInfo); + } + + UserToken userToken = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(UserTokenBuilder.class) + .token(UUID.randomUUID()).user(userInfo) + .expiresAt(Timestamp.valueOf(LocalDateTime.now().plusDays(10))).issuedAt(new Date()) + .build(); + + apiContext.getOperationsContext().getDatabaseRepository().getUserTokenDao().createOrUpdate(userToken); + return Touch(userToken.getToken()); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/AuthenticationService.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/AuthenticationService.java new file mode 100644 index 000000000..93f288ea8 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/AuthenticationService.java @@ -0,0 +1,22 @@ +package eu.eudat.old.logic.services.operations.authentication; + +import eu.eudat.old.models.data.login.Credentials; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.models.data.loginprovider.LoginProviderUser; + +import java.util.UUID; + +/** + * Created by ikalyvas on 3/1/2018. + */ +public interface AuthenticationService { + + Principal Touch(LoginProviderUser profile) throws NullEmailException; + + Principal Touch(Credentials credentials) throws NullEmailException; + + void Logout(UUID token); + + Principal Touch(UUID token) throws NullEmailException; +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/NonVerifiedUserEmailAuthenticationService.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/NonVerifiedUserEmailAuthenticationService.java new file mode 100644 index 000000000..89a885b56 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/NonVerifiedUserEmailAuthenticationService.java @@ -0,0 +1,102 @@ +package eu.eudat.old.logic.services.operations.authentication; + +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.entities.UserRole; +import eu.eudat.old.data.entities.UserToken; +import eu.eudat.old.logic.builders.model.models.PrincipalBuilder; +import eu.eudat.old.logic.managers.MetricsManager; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.Authorities; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import java.time.Instant; +import java.util.Date; +import java.util.HashSet; +import java.util.List; + +@Service("nonVerifiedUserAuthenticationService") +public class NonVerifiedUserEmailAuthenticationService extends AbstractAuthenticationService { + + public NonVerifiedUserEmailAuthenticationService(ApiContext apiContext, Environment environment, MetricsManager metricsManager) { + super(apiContext, environment, metricsManager); + } + + public Principal Touch(UserToken token) { + if (token == null || token.getExpiresAt().before(new Date())) return null; + + UserInfo user = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(token.getUser().getId()); + if (user == null) return null; + String avatarUrl; + try { + avatarUrl = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("avatarUrl").asText() : ""; + } catch (Exception e) { + avatarUrl = ""; + } + String zenodoToken; + try { + zenodoToken = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("zenodoToken").asText() : ""; + } catch (Exception e) { + zenodoToken = ""; + } + Instant zenodoDuration; + try { + zenodoDuration = user.getAdditionalinfo() != null ? Instant.ofEpochMilli(new ObjectMapper().readTree(user.getAdditionalinfo()).get("expirationDate").asLong()) : Instant.now(); + } catch (Exception e) { + zenodoDuration = Instant.now(); + } + String zenodoEmail; + try { + zenodoEmail = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("zenodoEmail").asText() : ""; + } catch (Exception e) { + zenodoEmail = ""; + } + String zenodoRefresh; + try { + zenodoRefresh = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("zenodoRefresh").asText() : ""; + } catch (Exception e) { + zenodoRefresh = ""; + } + String culture; + try { + culture = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("culture").get("name").asText() : ""; + } catch (Exception e) { + culture = ""; + } + String language; + try { + language = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("language").get("value").asText() : ""; + } catch (Exception e) { + language = ""; + } + String timezone; + try { + timezone = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("timezone").asText() : ""; + } catch (Exception e) { + timezone = ""; + } + Principal principal = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(PrincipalBuilder.class) + .id(user.getId()).token(token.getToken()) + .expiresAt(token.getExpiresAt()) + .name(user.getName()) + .email(user.getEmail()) + .avatarUrl(avatarUrl) + .culture(culture) + .language(language) + .timezone(timezone) + .zenodoToken(zenodoToken) + .zenodoDuration(zenodoDuration) + .zenodoEmail(zenodoEmail) + .zenodoRefresh(zenodoRefresh) + .build(); + + List userRoles = apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().getUserRoles(user); + for (UserRole item : userRoles) { + if (principal.getAuthz() == null) principal.setAuthorities(new HashSet<>()); + principal.getAuthz().add(Authorities.fromInteger(item.getRole())); + } + return principal; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/VerifiedUserAuthenticationService.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/VerifiedUserAuthenticationService.java new file mode 100644 index 000000000..a4500ae7d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/operations/authentication/VerifiedUserAuthenticationService.java @@ -0,0 +1,103 @@ +package eu.eudat.old.logic.services.operations.authentication; + +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.data.entities.UserRole; +import eu.eudat.old.data.entities.UserToken; +import eu.eudat.old.exceptions.security.NullEmailException; +import eu.eudat.old.logic.builders.model.models.PrincipalBuilder; +import eu.eudat.old.logic.services.ApiContext; +import eu.eudat.old.models.data.security.Principal; +import eu.eudat.old.types.Authorities; +import eu.eudat.old.logic.managers.MetricsManager; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import java.time.Instant; +import java.util.*; + + +@Service("verifiedUserAuthenticationService") +public class VerifiedUserAuthenticationService extends AbstractAuthenticationService { + + public VerifiedUserAuthenticationService(ApiContext apiContext, Environment environment, MetricsManager metricsManager) { + super(apiContext, environment, metricsManager); + } + + public Principal Touch(UserToken token) { + if (token == null || token.getExpiresAt().before(new Date())) return null; + + UserInfo user = this.apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(token.getUser().getId()); + if (user == null) return null; + if (user.getEmail() == null) throw new NullEmailException(); + String avatarUrl; + try { + avatarUrl = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("avatarUrl").asText() : ""; + } catch (Exception e) { + avatarUrl = ""; + } + String zenodoToken; + try { + zenodoToken = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("zenodoToken").asText() : ""; + } catch (Exception e) { + zenodoToken = ""; + } + Instant zenodoDuration; + try { + zenodoDuration = user.getAdditionalinfo() != null ? Instant.ofEpochMilli(new ObjectMapper().readTree(user.getAdditionalinfo()).get("expirationDate").asLong()) : Instant.now(); + } catch (Exception e) { + zenodoDuration = Instant.now(); + } + String zenodoEmail; + try { + zenodoEmail = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("zenodoEmail").asText() : ""; + } catch (Exception e) { + zenodoEmail = ""; + } + String zenodoRefresh; + try { + zenodoRefresh = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("zenodoRefresh").asText() : ""; + } catch (Exception e) { + zenodoRefresh = ""; + } + String culture; + try { + culture = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("culture").get("name").asText() : ""; + } catch (Exception e) { + culture = ""; + } + String language; + try { + language = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("language").get("value").asText() : ""; + } catch (Exception e) { + language = ""; + } + String timezone; + try { + timezone = user.getAdditionalinfo() != null ? new ObjectMapper().readTree(user.getAdditionalinfo()).get("timezone").asText() : ""; + } catch (Exception e) { + timezone = ""; + } + Principal principal = this.apiContext.getOperationsContext().getBuilderFactory().getBuilder(PrincipalBuilder.class) + .id(user.getId()).token(token.getToken()) + .expiresAt(token.getExpiresAt()) + .name(user.getName()) + .email(user.getEmail()) + .avatarUrl(avatarUrl) + .culture(culture) + .language(language) + .timezone(timezone) + .zenodoToken(zenodoToken) + .zenodoDuration(zenodoDuration) + .zenodoEmail(zenodoEmail) + .zenodoRefresh(zenodoRefresh) + .build(); + + List userRoles = apiContext.getOperationsContext().getDatabaseRepository().getUserRoleDao().getUserRoles(user); + for (UserRole item : userRoles) { + if (principal.getAuthz() == null) principal.setAuthorities(new HashSet<>()); + principal.getAuthz().add(Authorities.fromInteger(item.getRole())); + } + return principal; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/ConfirmationEmailService.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/ConfirmationEmailService.java new file mode 100644 index 000000000..bfbdb3077 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/ConfirmationEmailService.java @@ -0,0 +1,22 @@ +package eu.eudat.old.logic.services.utilities; + +import eu.eudat.old.data.dao.entities.EmailConfirmationDao; +import eu.eudat.old.data.entities.EmailConfirmation; +import eu.eudat.old.models.data.security.Principal; + +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +public interface ConfirmationEmailService { + public void createConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId); + + public void createMergeConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId, Principal principal, Integer provider); + + public void createUnlinkConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId, Principal principal, Integer provider); + + public CompletableFuture sentConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService); + + public CompletableFuture sentMergeConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService, String userName); + + public CompletableFuture sentUnlinkConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService); +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/ConfirmationEmailServiceImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/ConfirmationEmailServiceImpl.java new file mode 100644 index 000000000..00ad9c013 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/ConfirmationEmailServiceImpl.java @@ -0,0 +1,192 @@ +package eu.eudat.old.logic.services.utilities; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.data.dao.entities.EmailConfirmationDao; +import eu.eudat.old.data.entities.EmailConfirmation; +import eu.eudat.old.models.data.mail.SimpleMail; +import eu.eudat.old.models.data.security.Principal; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +@Service("ConfirmationEmailService") +public class ConfirmationEmailServiceImpl implements ConfirmationEmailService { + private static final Logger logger = LoggerFactory.getLogger(ConfirmationEmailServiceImpl.class); + //private Logger logger; + private Environment environment; + + public ConfirmationEmailServiceImpl(/*Logger logger,*/ Environment environment) { +// this.logger = logger; + this.environment = environment; + } + + @Override + public void createConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId) { + EmailConfirmation confirmationEmail = new EmailConfirmation(); + confirmationEmail.setEmail(email); + confirmationEmail.setExpiresAt(Date + .from(new Date() + .toInstant() + .plusSeconds(Long.parseLong(this.environment.getProperty("conf_email.expiration_time_seconds"))) + ) + ); + confirmationEmail.setUserId(userId); + confirmationEmail.setIsConfirmed(false); + confirmationEmail.setToken(UUID.randomUUID()); + confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail); + sentConfirmationEmail(confirmationEmail, mailService); + } + + @Override + public CompletableFuture sentConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService) { + return CompletableFuture.runAsync(() -> { + SimpleMail mail = new SimpleMail(); + mail.setSubject(environment.getProperty("conf_email.subject")); + mail.setContent(createContent(confirmationEmail.getToken(), mailService)); + mail.setTo(confirmationEmail.getEmail()); + try { + mailService.sendSimpleMail(mail); + } catch (Exception ex) { + logger.error(ex.getMessage(), ex); + } + }); + } + + private String createContent(UUID confirmationToken, MailService mailService) { + String content = mailService.getMailTemplateContent(this.environment.getProperty("email.confirmation")); + content = content.replace("{confirmationToken}", confirmationToken.toString()); + content = content.replace("{expiration_time}", secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds")))); + content = content.replace("{host}", this.environment.getProperty("dmp.domain")); + + return content; + } + + @Override + public CompletableFuture sentMergeConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService, String userName) { + return CompletableFuture.runAsync(() -> { + SimpleMail mail = new SimpleMail(); + mail.setSubject(environment.getProperty("conf_email.subject")); + mail.setContent(createMergeContent(confirmationEmail.getToken(), mailService, userName)); + mail.setTo(confirmationEmail.getEmail()); + try { + mailService.sendSimpleMail(mail); + } catch (Exception ex) { + logger.error(ex.getMessage(), ex); + } + }); + } + + @Override + public CompletableFuture sentUnlinkConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService) { + String email = null; + try { + Map map = new ObjectMapper().readValue(confirmationEmail.getData(), new TypeReference>() {}); + email = (String) map.get("email"); + } + catch (JsonProcessingException e){ + logger.error(e.getMessage(), e); + } + String finalEmail = email; + return CompletableFuture.runAsync(() -> { + SimpleMail mail = new SimpleMail(); + mail.setSubject(environment.getProperty("conf_email.subject")); + mail.setContent(createUnlinkContent(confirmationEmail.getToken(), mailService, finalEmail)); + mail.setTo(confirmationEmail.getEmail()); + try { + mailService.sendSimpleMail(mail); + } catch (Exception ex) { + logger.error(ex.getMessage(), ex); + } + }); + } + + private String createMergeContent(UUID confirmationToken, MailService mailService, String userName) { + String content = mailService.getMailTemplateContent(this.environment.getProperty("email.merge")); + content = content.replace("{userName}", userName); + content = content.replace("{confirmationToken}", confirmationToken.toString()); + content = content.replace("{expiration_time}", secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds")))); + content = content.replace("{host}", this.environment.getProperty("dmp.domain")); + + return content; + } + + private String createUnlinkContent(UUID confirmationToken, MailService mailService, String email) { + String content = mailService.getMailTemplateContent(this.environment.getProperty("email.unlink")); + content = content.replace("{confirmationToken}", confirmationToken.toString()); + content = content.replace("{expiration_time}", secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds")))); + content = content.replace("{host}", this.environment.getProperty("dmp.domain")); + content = content.replace("{email}", email); + + return content; + } + + private String secondsToTime(int seconds) { + int sec = seconds % 60; + int hour = seconds / 60; + int min = hour % 60; + hour = hour / 60; + return (hour + ":" + min + ":" + sec); + } + + @Override + public void createMergeConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, + String email, UUID userId, Principal principal, Integer provider) { + EmailConfirmation confirmationEmail = new EmailConfirmation(); + confirmationEmail.setEmail(email); + confirmationEmail.setExpiresAt(Date + .from(new Date() + .toInstant() + .plusSeconds(Long.parseLong(this.environment.getProperty("conf_email.expiration_time_seconds"))) + ) + ); + confirmationEmail.setUserId(userId); + try { + Map map = new HashMap<>(); + map.put("userId", principal.getId()); + map.put("provider", provider.toString()); + confirmationEmail.setData(new ObjectMapper().writeValueAsString(map)); + } catch (JsonProcessingException e) { + logger.error(e.getMessage(), e); + } + confirmationEmail.setIsConfirmed(false); + confirmationEmail.setToken(UUID.randomUUID()); + confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail); + sentMergeConfirmationEmail(confirmationEmail, mailService, principal.getName()); + + } + + @Override + public void createUnlinkConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, + String email, UUID userId, Principal principal, Integer provider) { + EmailConfirmation confirmationEmail = new EmailConfirmation(); + confirmationEmail.setEmail(principal.getEmail()); + confirmationEmail.setExpiresAt(Date + .from(new Date() + .toInstant() + .plusSeconds(Long.parseLong(this.environment.getProperty("conf_email.expiration_time_seconds"))) + ) + ); + confirmationEmail.setUserId(userId); + try { + Map map = new HashMap<>(); + map.put("email", email); + map.put("provider", provider.toString()); + confirmationEmail.setData(new ObjectMapper().writeValueAsString(map)); + } catch (JsonProcessingException e) { + logger.error(e.getMessage(), e); + } + confirmationEmail.setIsConfirmed(false); + confirmationEmail.setToken(UUID.randomUUID()); + confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail); + sentUnlinkConfirmationEmail(confirmationEmail, mailService); + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/InvitationService.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/InvitationService.java new file mode 100644 index 000000000..1f69aa480 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/InvitationService.java @@ -0,0 +1,24 @@ +package eu.eudat.old.logic.services.utilities; + + +import eu.eudat.old.data.dao.entities.InvitationDao; +import eu.eudat.old.data.dao.entities.DMPDao; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.Invitation; +import eu.eudat.old.data.entities.UserDMP; +import eu.eudat.old.data.entities.UserInfo; + +import javax.mail.MessagingException; +import java.util.List; +import java.util.concurrent.CompletableFuture; + + +public interface InvitationService { + void assignToDmp(DMPDao dmpDao, List users, DMP dmp); + + void assignToDmp(DMPDao dmpDao, UserDMP user, DMP dmp); + + void createInvitations(InvitationDao invitationDao, MailService mailService, List users, DMP dmp, Integer role, UserInfo creator) throws MessagingException; + + CompletableFuture sendInvitationAsync(DMP dmp, Invitation invitation, String recipient, MailService mailService, Integer role) throws MessagingException; +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/InvitationServiceImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/InvitationServiceImpl.java new file mode 100644 index 000000000..cbfc1c899 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/InvitationServiceImpl.java @@ -0,0 +1,108 @@ +package eu.eudat.old.logic.services.utilities; + + +import eu.eudat.old.data.dao.entities.DMPDao; +import eu.eudat.old.data.dao.entities.InvitationDao; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.Invitation; +import eu.eudat.old.data.entities.UserDMP; +import eu.eudat.old.data.entities.UserInfo; +import eu.eudat.old.models.data.invitation.Properties; +import eu.eudat.old.models.data.mail.SimpleMail; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import javax.mail.MessagingException; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import java.io.StringWriter; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; + + +@Service("invitationService") +public class InvitationServiceImpl implements InvitationService { + private static final Logger logger = LoggerFactory.getLogger(InvitationServiceImpl.class); + private Environment environment; + + @Autowired + public InvitationServiceImpl(Environment environment) { + this.environment = environment; + } + + @Override + public void assignToDmp(DMPDao dmpDao, List users, DMP dmp) { + for (UserDMP user : users) { + dmp.getUsers().add(user); + } + dmpDao.createOrUpdate(dmp); + } + + @Override + public void assignToDmp(DMPDao dmpDao, 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); + } + } + + @Override + public void createInvitations(InvitationDao invitationDao, MailService mailService, List users, DMP dmp, Integer role, UserInfo creator) throws MessagingException { + for (UserInfo userInfo : users) { + Invitation invitation = new Invitation(); + invitation.setDmp(dmp); + invitation.setInvitationEmail(userInfo.getEmail()); + invitation.setUser(creator); + invitation.setToken(UUID.randomUUID()); + invitation.setAcceptedInvitation(false); + Properties properties = new Properties(); + properties.setRole(role); + try { + JAXBContext context = JAXBContext.newInstance(Properties.class); + Marshaller marshaller = context.createMarshaller(); + StringWriter propertyWriter = new StringWriter(); + marshaller.marshal(properties, propertyWriter); + invitation.setProperties(propertyWriter.toString()); + }catch (Exception e) { + logger.error(e.getMessage(), e); + } + invitationDao.createOrUpdate(invitation); + sendInvitationAsync(dmp, invitation, userInfo.getName(), mailService, role); + } + } + + @Override + public CompletableFuture sendInvitationAsync(DMP dmp, Invitation invitation, String recipient, MailService mailService, Integer role) { + return CompletableFuture.runAsync(() -> { + SimpleMail mail = new SimpleMail(); + mail.setSubject(createSubject(dmp, mailService.getMailTemplateSubject())); + mail.setContent(createContent(invitation.getId(), dmp, recipient, mailService.getMailTemplateContent(this.environment.getProperty("email.invite")), role)); + mail.setTo(invitation.getInvitationEmail()); + try { + mailService.sendSimpleMail(mail); + } catch (Exception ex) { + logger.error(ex.getMessage(), ex); + } + }); + } + + private String createSubject(DMP dmp, String templateSubject) { + String subject = templateSubject.replace("{dmpname}", dmp.getLabel()); + return subject; + } + + private String createContent(UUID invitationID, DMP dmp, String recipient, String templateContent, Integer role) { + String content = templateContent.replace("{dmpname}", dmp.getLabel()); + content = content.replace("{invitationID}", invitationID.toString()); + content = content.replace("{recipient}", recipient); + content = content.replace("{host}", this.environment.getProperty("dmp.domain")); + content = content.replace("{dmprole}", UserDMP.UserDMPRoles.fromInteger(role).name()); + + return content; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/MailService.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/MailService.java new file mode 100644 index 000000000..2935f75b3 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/MailService.java @@ -0,0 +1,14 @@ +package eu.eudat.old.logic.services.utilities; + +import eu.eudat.old.models.data.mail.SimpleMail; + +import javax.mail.MessagingException; + + +public interface MailService { + void sendSimpleMail(SimpleMail mail) throws MessagingException; + + String getMailTemplateContent(String resourceTemplate); + + String getMailTemplateSubject(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/MailServiceImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/MailServiceImpl.java new file mode 100644 index 000000000..326679e23 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/MailServiceImpl.java @@ -0,0 +1,139 @@ +package eu.eudat.old.logic.services.utilities; + +import eu.eudat.old.models.data.mail.SimpleMail; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.core.env.Environment; +import org.springframework.core.io.Resource; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.stereotype.Service; + +import javax.mail.BodyPart; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + + +@Service("mailService") +public class MailServiceImpl implements MailService { + private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class); + + private Environment env; + + private JavaMailSender emailSender; + + private ApplicationContext applicationContext; + + @Autowired + public MailServiceImpl(Environment env, JavaMailSender emailSender, ApplicationContext applicationContext) { + this.env = env; + this.emailSender = emailSender; + this.applicationContext = applicationContext; + } + + @Override + public void sendSimpleMail(SimpleMail mail) throws MessagingException { + List imageSources = parseImages(mail.getContent()); + List cids = new ArrayList<>(); + if (!imageSources.isEmpty()) { + for (int i = 0; i < imageSources.size(); i++) { + cids.add(UUID.randomUUID().toString()); + } + mail.setContent(replaceImageSources(mail.getContent(), cids)); + } + MimeMultipart content = new MimeMultipart("related"); + BodyPart messageBodyPart = new MimeBodyPart(); + messageBodyPart.setContent(mail.getContent(), "text/html; charset=UTF-8"); + content.addBodyPart(messageBodyPart); + if (!imageSources.isEmpty()) { + for (int i =0; i < imageSources.size(); i++) { + MimeBodyPart imagePart = new MimeBodyPart(); + try { + imagePart.attachFile(applicationContext.getResource(imageSources.get(i)).getFile()); + imagePart.setContentID("<" + cids.get(i) + ">"); + imagePart.setDisposition(MimeBodyPart.INLINE); + content.addBodyPart(imagePart); + } catch (IOException | MessagingException e) { + logger.error(e.getMessage(), e); + } + } + } + MimeMessage message = this.emailSender.createMimeMessage(); + message.setSubject(mail.getSubject()); + message.setContent(content); + message.addRecipients(Message.RecipientType.TO, mail.getTo()); + message.setFrom(env.getProperty("mail.from")); + this.emailSender.send(message); + } + + public Environment getEnv() { + return env; + } + + @Override + public String getMailTemplateContent(String resourceTemplate) { + Resource resource = applicationContext.getResource(resourceTemplate); + try { + InputStream inputStream = resource.getInputStream(); + StringWriter writer = new StringWriter(); + IOUtils.copy(inputStream, writer, "UTF-8"); + inputStream.close(); + return writer.toString(); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + return ""; + } + + @Override + public String getMailTemplateSubject() { + return env.getProperty("mail.subject"); + } + + private List parseImages(String content) { + List imagePaths = new ArrayList<>(); + + int lastIndex = 0; + + while (lastIndex != -1) { + lastIndex = content.indexOf("img src=\"", lastIndex); + + if (lastIndex != -1) { + String imagePath = content.substring(lastIndex + 9, content.indexOf("\"", lastIndex + 9)); + if (!imagePath.contains("data:image/png;base64")) { + imagePaths.add(imagePath); + } + lastIndex++; + } + } + + return imagePaths; + } + + private String replaceImageSources(String content, List cids) { + + int lastIndex = 0; + int cidIndex = 0; + + while (lastIndex != -1) { + lastIndex = content.indexOf("img src=\"", lastIndex); + + if (lastIndex != -1) { + content = content.replace(content.substring(lastIndex + 9, content.indexOf("\"", lastIndex + 9)), "cid:" + cids.get(cidIndex)); + lastIndex ++; + cidIndex ++; + } + } + + return content; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/UtilitiesService.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/UtilitiesService.java new file mode 100644 index 000000000..65ddcdd91 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/UtilitiesService.java @@ -0,0 +1,13 @@ +package eu.eudat.old.logic.services.utilities; + +/** + * Created by ikalyvas on 3/1/2018. + */ +public interface UtilitiesService { + + InvitationService getInvitationService(); + + MailService getMailService(); + + ConfirmationEmailService getConfirmationEmailService(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/UtilitiesServiceImpl.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/UtilitiesServiceImpl.java new file mode 100644 index 000000000..53f2b1268 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/services/utilities/UtilitiesServiceImpl.java @@ -0,0 +1,37 @@ +package eu.eudat.old.logic.services.utilities; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * Created by ikalyvas on 3/1/2018. + */ +@Service("utilitiesService") +public class UtilitiesServiceImpl implements UtilitiesService { + + private InvitationService invitationService; + private MailService mailService; + private ConfirmationEmailService confirmationEmailService; + + @Autowired + public UtilitiesServiceImpl(InvitationService invitationService, MailService mailService, ConfirmationEmailService confirmationEmailService) { + this.invitationService = invitationService; + this.mailService = mailService; + this.confirmationEmailService = confirmationEmailService; + } + + @Override + public ConfirmationEmailService getConfirmationEmailService() { + return confirmationEmailService; + } + + @Override + public InvitationService getInvitationService() { + return invitationService; + } + + @Override + public MailService getMailService() { + return mailService; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/builders/ModelBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/builders/ModelBuilder.java new file mode 100644 index 000000000..15d46f735 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/builders/ModelBuilder.java @@ -0,0 +1,155 @@ +package eu.eudat.old.logic.utilities.builders; + +import eu.eudat.old.logic.utilities.interfaces.ViewStyleDefinition; +import eu.eudat.old.models.data.components.commons.datafield.*; +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.DatabaseViewStyleDefinition; +import eu.eudat.old.models.data.entities.xmlmodels.modeldefinition.DatabaseModelDefinition; +import eu.eudat.old.logic.utilities.interfaces.ModelDefinition; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Element; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public class ModelBuilder { + private static final Logger logger = LoggerFactory.getLogger(ModelBuilder.class); + public , T extends DatabaseModelDefinition> List toModelDefinition(List items, Class clazz) { + List list = new LinkedList(); + for (U item : items) { + try { + list.add(item.toDatabaseDefinition(clazz.newInstance())); + } catch (InstantiationException e) { + logger.error(e.getMessage(), e); + } catch (IllegalAccessException e) { + logger.error(e.getMessage(), e); + } + } + return list; + } + + public , T extends DatabaseViewStyleDefinition> List toViewStyleDefinition(List items, Class clazz) { + List list = new LinkedList(); + for (U item : items) { + try { + list.add(item.toDatabaseDefinition(clazz.newInstance())); + } catch (InstantiationException e) { + logger.error(e.getMessage(), e); + } catch (IllegalAccessException e) { + logger.error(e.getMessage(), e); + } + } + return list; + } + + public , T extends DatabaseViewStyleDefinition> List fromViewStyleDefinition(List items, Class clazz) { + List list = new LinkedList(); + for (T item : items) { + try { + U modelItem = clazz.newInstance(); + modelItem.fromDatabaseDefinition(item); + list.add(modelItem); + } catch (InstantiationException e) { + logger.error(e.getMessage(), e); + } catch (IllegalAccessException e) { + logger.error(e.getMessage(), e); + } + } + return list; + } + + public FieldData toFieldData(Object data, String type, Element dataElement) { + if (type.equals("combobox")) { + if (dataElement != null) { + if (dataElement.getAttribute("type").equals("autocomplete")) { + return (FieldData) new AutoCompleteData().fromData(data); + } else if (dataElement.getAttribute("type").equals("wordlist")) + return (FieldData) new WordListData().fromData(data); + } + } + if (type.equals("internalDmpEntities")) { + if (dataElement != null) { + if (dataElement.getAttribute("type").equals("researchers")) { + return (FieldData) new ResearchersAutoCompleteData().fromData(data); + } + else if (dataElement.getAttribute("type").equals("datasets")) + return (FieldData) new DatasetsAutoCompleteData().fromData(data); + else if (dataElement.getAttribute("type").equals("dmps")) + return (FieldData) new DMPsAutoCompleteData().fromData(data); + } + } + if (type.equals("booleanDecision")) return (FieldData) new BooleanDecisionData().fromData(data); + if (type.equals("radiobox")) return (FieldData) new RadioBoxData().fromData(data); + if (type.equals("checkBox")) return (FieldData) new CheckBoxData().fromData(data); + if (type.equals("freetext")) return (FieldData) new FreeTextData().fromData(data); + if (type.equals("textarea")) return (FieldData) new TextAreaData().fromData(data); + if (type.equals("richTextarea")) return (FieldData) new RichTextAreaData().fromData(data); + if (type.equals("upload")) return (FieldData) new UploadData().fromData(data); +// if (type.equals("table")) return (FieldData) new TableData().fromData(data); + if (type.equals("datePicker")) return (FieldData) new DatePickerData().fromData(data); + if (type.equals("externalDatasets")) return (FieldData) new ExternalDatasetsData().fromData(data); + if (type.equals("dataRepositories")) return (FieldData) new DataRepositoriesData().fromData(data); + if (type.equals("pubRepositories")) return (FieldData) new DataRepositoriesData().fromData(data); + if (type.equals("journalRepositories")) return (FieldData) new DataRepositoriesData().fromData(data); + if (type.equals("taxonomies")) return (FieldData) new TaxonomiesData().fromData(data); + if (type.equals("licenses")) return (FieldData) new LicensesData().fromData(data); + if (type.equals("publications")) return (FieldData) new PublicationsData().fromData(data); + if (type.equals("registries")) return (FieldData) new RegistriesData().fromData(data); + if (type.equals("services")) return (FieldData) new ServicesData().fromData(data); + if (type.equals("tags")) return (FieldData) new TagsData().fromData(data); + if (type.equals("researchers")) return (FieldData) new ResearcherData().fromData(data); + if (type.equals("organizations")) return (FieldData) new OrganizationsData().fromData(data); + if (type.equals("datasetIdentifier")) return (FieldData) new DatasetIdentifierData().fromData(data); + if (type.equals("currency")) return (FieldData) new CurrencyData().fromData(data); + if (type.equals("validation")) return (FieldData) new ValidationData().fromData(data); + return null; + } + + public FieldData toFieldData(Object data, String type) { + if (type.equals("combobox")) { + String comboboxType = (String) ((Map) data).get("type"); + if (comboboxType.equals("autocomplete")) { + return (FieldData) new AutoCompleteData().fromData(data); + } else if (comboboxType.equals("wordlist")) + return (FieldData) new WordListData().fromData(data); + } + if (type.equals("internalDmpEntities")) { + String internalDmpEntitiesType = (String) ((Map) data).get("type"); + if (internalDmpEntitiesType.equals("researchers")) { + return (FieldData) new ResearchersAutoCompleteData().fromData(data); + } + else if (internalDmpEntitiesType.equals("datasets")) { + return (FieldData) new DatasetsAutoCompleteData().fromData(data); + } + else if (internalDmpEntitiesType.equals("dmps")) { + return (FieldData) new DMPsAutoCompleteData().fromData(data); + } + } + if (type.equals("booleanDecision")) return (FieldData) new BooleanDecisionData().fromData(data); + if (type.equals("radiobox")) return (FieldData) new RadioBoxData().fromData(data); + if (type.equals("checkBox")) return (FieldData) new CheckBoxData().fromData(data); + if (type.equals("freetext")) return (FieldData) new FreeTextData().fromData(data); + if (type.equals("textarea")) return (FieldData) new TextAreaData().fromData(data); + if (type.equals("richTextarea")) return (FieldData) new RichTextAreaData().fromData(data); + if (type.equals("upload")) return (FieldData) new UploadData().fromData(data); +// if (type.equals("table")) return (FieldData) new TableData().fromData(data); + if (type.equals("datePicker")) return (FieldData) new DatePickerData().fromData(data); + if (type.equals("externalDatasets")) return (FieldData) new ExternalDatasetsData().fromData(data); + if (type.equals("dataRepositories")) return (FieldData) new DataRepositoriesData().fromData(data); + if (type.equals("pubRepositories")) return (FieldData) new DataRepositoriesData().fromData(data); + if (type.equals("journalRepositories")) return (FieldData) new DataRepositoriesData().fromData(data); + if (type.equals("taxonomies")) return (FieldData) new TaxonomiesData().fromData(data); + if (type.equals("licenses")) return (FieldData) new LicensesData().fromData(data); + if (type.equals("publications")) return (FieldData) new PublicationsData().fromData(data); + if (type.equals("registries")) return (FieldData) new RegistriesData().fromData(data); + if (type.equals("services")) return (FieldData) new ServicesData().fromData(data); + if (type.equals("tags")) return (FieldData) new TagsData().fromData(data); + if (type.equals("researchers")) return (FieldData) new ResearcherData().fromData(data); + if (type.equals("organizations")) return (FieldData) new OrganizationsData().fromData(data); + if (type.equals("datasetIdentifier")) return (FieldData) new DatasetIdentifierData().fromData(data); + if (type.equals("currency")) return (FieldData) new CurrencyData().fromData(data); + if (type.equals("validation")) return (FieldData) new ValidationData().fromData(data); + return null; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/builders/XmlBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/builders/XmlBuilder.java new file mode 100644 index 000000000..6408ca64e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/builders/XmlBuilder.java @@ -0,0 +1,92 @@ +package eu.eudat.old.logic.utilities.builders; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; + + +public class XmlBuilder { + private static final Logger logger = LoggerFactory.getLogger(XmlBuilder.class); + + public static Document getDocument() { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder; + try { + docBuilder = docFactory.newDocumentBuilder(); + Document doc = docBuilder.newDocument(); + return doc; + } catch (ParserConfigurationException e) { + // TODO Auto-generated catch block + logger.error(e.getMessage(), e); + return null; + } + } + + public static String generateXml(Document doc) { + TransformerFactory tFact = TransformerFactory.newInstance(); + Transformer trans; + try { + trans = tFact.newTransformer(); + StringWriter writer = new StringWriter(); + StreamResult result = new StreamResult(writer); + DOMSource source = new DOMSource(doc); + trans.setOutputProperty(OutputKeys.INDENT, "yes"); + trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + trans.transform(source, result); + return writer.toString(); + } catch (TransformerException e) { + // TODO Auto-generated catch block + logger.error(e.getMessage(), e); + return null; + } + } + + public static Document fromXml(String xml) { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder; + try { + docBuilder = docFactory.newDocumentBuilder(); + InputSource inputStream = new InputSource(new StringReader(xml)); + Document doc = docBuilder.parse(inputStream); + return doc; + } catch (ParserConfigurationException | SAXException | IOException e) { + // TODO Auto-generated catch block + logger.error(e.getMessage(), e); + return null; + } + } + + public static String getItemValueAsString(String xml,String name){ + Document doc = fromXml(xml); + Element root = doc.getDocumentElement(); + return root.getElementsByTagName(name).item(0).getNodeValue(); + } + + public static Element getNodeFromListByTagName(NodeList list, String tagName) { + for (int temp = 0; temp < list.getLength(); temp++) { + Node element = list.item(temp); + if (element.getNodeType() == Node.ELEMENT_NODE) { + if (element.getNodeName().equals(tagName)) return (Element) element; + } + } + return null; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/helpers/FileEnvelope.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/helpers/FileEnvelope.java new file mode 100644 index 000000000..e18e75390 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/helpers/FileEnvelope.java @@ -0,0 +1,27 @@ +package eu.eudat.old.logic.utilities.documents.helpers; + +import java.io.File; + +/** + * Created by ikalyvas on 3/6/2018. + */ +public class FileEnvelope { + private String filename; + private File file; + + public String getFilename() { + return filename; + } + + public void setFilename(String filename) { + this.filename = filename; + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/pdf/PDFUtils.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/pdf/PDFUtils.java new file mode 100644 index 000000000..a0f2931e0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/pdf/PDFUtils.java @@ -0,0 +1,45 @@ +package eu.eudat.old.logic.utilities.documents.pdf; + +import eu.eudat.old.logic.utilities.documents.helpers.FileEnvelope; +import org.apache.commons.io.IOUtils; +import org.springframework.core.env.Environment; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.web.client.RestTemplate; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.util.UUID; + +public class PDFUtils { + + public static File convertToPDF(FileEnvelope file, Environment environment) throws IOException { + LinkedMultiValueMap map = new LinkedMultiValueMap<>(); + String uuid = UUID.randomUUID().toString(); + map.add("files", new FileSystemResource(file.getFile())); + map.add("filename", uuid + ".pdf"); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + headers.add("Content-disposition", "attachment; filename=" + uuid + ".pdf"); + headers.add("Content-type", "application/pdf"); + + HttpEntity> requestEntity = new HttpEntity>( + map, headers); + + byte[] queueResult = new RestTemplate().postForObject(environment.getProperty("pdf.converter.url") + "forms/libreoffice/convert" + , requestEntity, byte[].class); + + File resultPdf = new File(environment.getProperty("temp.temp") + uuid + ".pdf"); + FileOutputStream output = new FileOutputStream(resultPdf); + IOUtils.write(queueResult, output); + output.close(); + Files.deleteIfExists(file.getFile().toPath()); + + return resultPdf; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/types/ParagraphStyle.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/types/ParagraphStyle.java new file mode 100644 index 000000000..714b987b6 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/types/ParagraphStyle.java @@ -0,0 +1,49 @@ +package eu.eudat.old.logic.utilities.documents.types; + +/** + * Created by ikalyvas on 2/26/2018. + */ +public enum ParagraphStyle { + TEXT(0), HEADER1(1), HEADER2(2), HEADER3(3), HEADER4(4), TITLE(5), FOOTER(6), COMMENT(7), HEADER5(8), HEADER6(9), HTML(10), IMAGE(11); + + private Integer value; + + private ParagraphStyle(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + public static ParagraphStyle fromInteger(Integer value) { + switch (value) { + case 0: + return TEXT; + case 1: + return HEADER1; + case 2: + return HEADER2; + case 3: + return HEADER3; + case 4: + return HEADER4; + case 5: + return TITLE; + case 6: + return FOOTER; + case 7: + return COMMENT; + case 8: + return HEADER5; + case 9: + return HEADER6; + case 10: + return HTML; + case 11: + return IMAGE; + default: + throw new RuntimeException("Unsupported ParagraphStyle Code"); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/types/TextStyle.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/types/TextStyle.java new file mode 100644 index 000000000..82e5e3a0a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/types/TextStyle.java @@ -0,0 +1,31 @@ +package eu.eudat.old.logic.utilities.documents.types; + +/** + * Created by ikalyvas on 2/27/2018. + */ +public enum TextStyle { + ITALIC(0), BOLD(1), CAPS(2); + + private Integer value; + + private TextStyle(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + public static TextStyle fromInteger(Integer value) { + switch (value) { + case 0: + return ITALIC; + case 1: + return BOLD; + case 2: + return CAPS; + default: + throw new RuntimeException("Unsupported TextStyle Code"); + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/HtmlToWorldBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/HtmlToWorldBuilder.java new file mode 100644 index 000000000..7a62a482d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/HtmlToWorldBuilder.java @@ -0,0 +1,289 @@ +package eu.eudat.old.logic.utilities.documents.word; + +import org.apache.poi.xwpf.usermodel.*; +import org.apache.xmlbeans.XmlCursor; +import org.jsoup.nodes.Document; +import org.jsoup.nodes.Node; +import org.jsoup.nodes.TextNode; +import org.jsoup.select.NodeTraversor; +import org.jsoup.select.NodeVisitor; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; + +import java.math.BigInteger; +import java.util.*; + +public class HtmlToWorldBuilder implements NodeVisitor { + + private final Map properties = new LinkedHashMap<>(); + private XWPFParagraph paragraph; + private XWPFRun run; + private Boolean dumpRun; + private final float indentation; + private Boolean isIdentationUsed; + private XWPFNumbering numbering; + private Queue abstractNumId; + private BigInteger numberingLevel; + private XmlCursor cursor; + + public static HtmlToWorldBuilder convertInTable(XWPFTableCell document, Document htmlDocument, float indentation) { + XWPFParagraph paragraph = document.addParagraph(); + paragraph.setIndentFromLeft(Math.round(400 * indentation)); + HtmlToWorldBuilder htmlToWorldBuilder = new HtmlToWorldBuilder(paragraph, indentation, null); + NodeTraversor.traverse(htmlToWorldBuilder, htmlDocument); + return htmlToWorldBuilder; + } + + public static HtmlToWorldBuilder convert(XWPFDocument document, Document htmlDocument, float indentation) { + XWPFParagraph paragraph = document.createParagraph(); + paragraph.setIndentFromLeft(Math.round(400 * indentation)); + HtmlToWorldBuilder htmlToWorldBuilder = new HtmlToWorldBuilder(paragraph, indentation, null); + NodeTraversor.traverse(htmlToWorldBuilder, htmlDocument); + return htmlToWorldBuilder; + } + + public HtmlToWorldBuilder(XWPFParagraph paragraph, float indentation, XmlCursor cursor) { + this.paragraph = paragraph; + this.run = this.paragraph.createRun(); + this.dumpRun = false; + this.indentation = indentation; + this.isIdentationUsed = false; + this.run.setFontSize(11); + this.abstractNumId = new ArrayDeque<>(); + this.numberingLevel = BigInteger.valueOf(-1); + this.setDefaultIndentation(); + this.cursor = cursor; + } + + @Override + public void head(Node node, int i) { + String name = node.nodeName(); + if (name.equals("#text")) { + String text = ((TextNode)node).text(); + this.run.setText(text); + this.dumpRun = true; + } else { + properties.put(name, true); + } + if (dumpRun) { + this.run = this.paragraph.createRun(); + this.run.setFontSize(11); + this.dumpRun = false; + } + parseProperties(node); + properties.clear(); + } + + private void parseProperties(Node node) { + properties.entrySet().forEach(stringBooleanEntry -> { + switch (stringBooleanEntry.getKey()) { + case "i" : + case "em": + this.run.setItalic(stringBooleanEntry.getValue()); + break; + case "b": + case "strong": + this.run.setBold(stringBooleanEntry.getValue()); + break; + case "u": + case "ins": + this.run.setUnderline(stringBooleanEntry.getValue() ? UnderlinePatterns.SINGLE : UnderlinePatterns.NONE); + break; + case "small": + this.run.setFontSize(stringBooleanEntry.getValue() ? 8 : 11); + break; + case "del": + case "strike": + case "strikethrough": + case "s": + this.run.setStrikeThrough(stringBooleanEntry.getValue()); + break; + case "mark": + this.run.setTextHighlightColor(stringBooleanEntry.getValue() ? STHighlightColor.YELLOW.toString() : STHighlightColor.NONE.toString()); + break; + case "sub": + this.run.setSubscript(stringBooleanEntry.getValue() ? VerticalAlign.SUBSCRIPT : VerticalAlign.BASELINE); + break; + case "sup": + this.run.setSubscript(stringBooleanEntry.getValue() ? VerticalAlign.SUPERSCRIPT : VerticalAlign.BASELINE); + break; + case "div": + case "p": + if(this.cursor != null) { + this.paragraph = this.paragraph.getDocument().insertNewParagraph(this.cursor); + this.cursor = this.paragraph.getCTP().newCursor(); + this.cursor.toNextSibling(); + } else { + this.paragraph = this.paragraph.getDocument().createParagraph(); + } + this.run = this.paragraph.createRun(); + this.isIdentationUsed = false; + this.setDefaultIndentation(); + if (stringBooleanEntry.getValue()) { + if (node.hasAttr("align")) { + String alignment = node.attr("align"); + this.paragraph.setAlignment(ParagraphAlignment.valueOf(alignment.toUpperCase(Locale.ROOT))); + } + } + break; + case "blockquote": + if(this.cursor != null) { + this.paragraph = this.paragraph.getDocument().insertNewParagraph(this.cursor); + this.cursor = this.paragraph.getCTP().newCursor(); + } else { + this.paragraph = this.paragraph.getDocument().createParagraph(); + } + this.run = this.paragraph.createRun(); + if (stringBooleanEntry.getValue()) { + this.paragraph.setIndentationLeft(400); + } else { + this.isIdentationUsed = false; + this.setDefaultIndentation(); + } + break; + case "ul": + if (stringBooleanEntry.getValue()) { + createNumbering(STNumberFormat.BULLET); + } else { + if(this.cursor != null) { + this.paragraph = this.paragraph.getDocument().insertNewParagraph(this.cursor); + this.cursor = this.paragraph.getCTP().newCursor(); + } else { + this.paragraph = this.paragraph.getDocument().createParagraph(); + } + this.run = this.paragraph.createRun(); + this.isIdentationUsed = false; + this.setDefaultIndentation(); + this.numberingLevel = this.numberingLevel.subtract(BigInteger.ONE); + ((ArrayDeque)this.abstractNumId).removeLast(); + } + break; + case "ol": + if (stringBooleanEntry.getValue()) { + createNumbering(STNumberFormat.DECIMAL); + } else { + if(this.cursor != null) { + this.paragraph = this.paragraph.getDocument().insertNewParagraph(this.cursor); + this.cursor = this.paragraph.getCTP().newCursor(); + } else { + this.paragraph = this.paragraph.getDocument().createParagraph(); + } + this.run = this.paragraph.createRun(); + this.isIdentationUsed = false; + this.setDefaultIndentation(); + this.numberingLevel = this.numberingLevel.subtract(BigInteger.ONE); + ((ArrayDeque)this.abstractNumId).removeLast(); + } + break; + case "li": + if (stringBooleanEntry.getValue()) { + if(this.cursor != null) { + this.paragraph = this.paragraph.getDocument().insertNewParagraph(this.cursor); + this.cursor = this.paragraph.getCTP().newCursor(); + } else { + this.paragraph = this.paragraph.getDocument().createParagraph(); + } + // this.paragraph.setIndentationLeft(Math.round(indentation * 720) * (numberingLevel.intValue() + 1)); + this.paragraph.setIndentFromLeft(Math.round(numberingLevel.intValue() * 400 + this.indentation*400)); + this.run = this.paragraph.createRun(); + this.paragraph.setNumID(((ArrayDeque)abstractNumId).getLast()); + } + break; + case "font": + if (stringBooleanEntry.getValue()) { + if (node.hasAttr("color")) { + this.run.setColor(node.attr("color").substring(1)); + } + } else { + this.run.setColor("000000"); + } + break; + case "a": + if (stringBooleanEntry.getValue()) { + if (node.hasAttr("href")) { + this.run = createHyperLinkRun(node.attr("href")); + this.run.setColor("0000FF"); + this.run.setUnderline(UnderlinePatterns.SINGLE); + } + } else { + this.run = paragraph.createRun(); + } + break; + case "br": + if (stringBooleanEntry.getValue()) { + this.run.addBreak(); + } + break; + } + }); + } + + @Override + public void tail(Node node, int i) { + String name = node.nodeName(); + properties.put(name, false); + parseProperties(node); + properties.clear(); + } + + //GK: This function creates one numbering.xml for the word document and adds a specific format. + //It imitates the numbering.xml that is usually generated by word editors like LibreOffice + private void createNumbering(STNumberFormat.Enum format) { + CTAbstractNum ctAbstractNum = CTAbstractNum.Factory.newInstance(); + if (this.numbering == null) this.numbering = this.paragraph.getDocument().createNumbering(); + BigInteger tempNumId = BigInteger.ONE; + boolean found = false; + while (!found) { + Object o = numbering.getAbstractNum(tempNumId); + found = (o == null); + if (!found) tempNumId = tempNumId.add(BigInteger.ONE); + } + ctAbstractNum.setAbstractNumId(tempNumId); + CTLvl ctLvl = ctAbstractNum.addNewLvl(); + this.numberingLevel = numberingLevel.add(BigInteger.ONE); + ctLvl.setIlvl(numberingLevel); + ctLvl.addNewNumFmt().setVal(format); + ctLvl.addNewStart().setVal(BigInteger.ONE); + if (format == STNumberFormat.BULLET) { + ctLvl.addNewLvlJc().setVal(STJc.LEFT); + ctLvl.addNewLvlText().setVal("\u2022"); + ctLvl.addNewRPr(); //Set the Symbol font + CTFonts f = ctLvl.getRPr().addNewRFonts(); + f.setAscii("Symbol"); + f.setHAnsi("Symbol"); + f.setCs("Symbol"); + f.setHint(STHint.DEFAULT); + } else { + ctLvl.addNewLvlText().setVal("%1."); + } + XWPFAbstractNum xwpfAbstractNum = new XWPFAbstractNum(ctAbstractNum); + + this.abstractNumId.add(this.numbering.addAbstractNum(xwpfAbstractNum)); + this.numbering.addNum(((ArrayDeque)abstractNumId).getLast()); + } + + private XWPFHyperlinkRun createHyperLinkRun(String uri) { + String rId = this.paragraph.getDocument().getPackagePart().addExternalRelationship(uri, XWPFRelation.HYPERLINK.getRelation()).getId(); + + CTHyperlink cthyperLink=paragraph.getCTP().addNewHyperlink(); + cthyperLink.setId(rId); + cthyperLink.addNewR(); + + return new XWPFHyperlinkRun( + cthyperLink, + cthyperLink.getRArray(0), + paragraph + ); + } + + private void setDefaultIndentation() { + if (!isIdentationUsed) { +// this.paragraph.setIndentationLeft(Math.round(indentation * 720.0F)); + this.paragraph.setIndentFromLeft(Math.round(indentation * 400)); + this.isIdentationUsed = true; + } + } + + public XWPFParagraph getParagraph() { + return paragraph; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/WordBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/WordBuilder.java new file mode 100644 index 000000000..2d4ae5b0e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/WordBuilder.java @@ -0,0 +1,1160 @@ +package eu.eudat.old.logic.utilities.documents.word; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.logic.proxy.config.configloaders.ConfigLoader; +import eu.eudat.old.logic.services.forms.VisibilityRuleService; +import eu.eudat.old.logic.utilities.json.JavaToJson; +import eu.eudat.old.models.data.components.commons.datafield.*; +import eu.eudat.old.models.data.user.components.datasetprofile.FieldSet; +import eu.eudat.old.models.data.user.composite.DatasetProfilePage; +import eu.eudat.old.data.entities.DMP; +import eu.eudat.old.data.entities.Dataset; +import eu.eudat.old.data.entities.Organisation; +import eu.eudat.old.data.entities.Researcher; +import eu.eudat.old.logic.utilities.documents.types.ParagraphStyle; +import eu.eudat.old.logic.utilities.interfaces.ApplierWithValue; +import eu.eudat.old.models.data.pid.PidLink; +import eu.eudat.old.models.data.user.components.datasetprofile.Field; +import eu.eudat.old.models.data.user.components.datasetprofile.Section; +import eu.eudat.old.models.data.user.composite.PagedDatasetProfile; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.util.Units; +import org.apache.poi.xwpf.usermodel.*; +import org.apache.xmlbeans.XmlCursor; +import org.json.JSONArray; +import org.json.JSONException; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.select.NodeTraversor; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; + +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.ImageInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.apache.poi.xwpf.usermodel.Document.*; + +public class WordBuilder { + private static final Logger logger = LoggerFactory.getLogger(WordBuilder.class); + private static final Map IMAGE_TYPE_MAP = Stream.of(new Object[][] { + {"image/jpeg", PICTURE_TYPE_JPEG}, + {"image/png", PICTURE_TYPE_PNG}, + {"image/gif", PICTURE_TYPE_GIF}, + {"image/tiff", PICTURE_TYPE_TIFF}, + {"image/bmp", PICTURE_TYPE_BMP}, + {"image/wmf", PICTURE_TYPE_WMF} + } + ).collect(Collectors.toMap(objects -> (String)objects[0], o -> (Integer)o[1])); + + private Map> options = new HashMap<>(); + private Map> optionsInTable = new HashMap<>(); + private CTAbstractNum cTAbstractNum; + private BigInteger numId; + private Integer indent; + private final ObjectMapper mapper; + private Integer imageCount; + private ConfigLoader configLoader; + + public WordBuilder(Environment environment, ConfigLoader configLoader) { + this.cTAbstractNum = CTAbstractNum.Factory.newInstance(); + this.cTAbstractNum.setAbstractNumId(BigInteger.valueOf(1)); + this.indent = 0; + this.imageCount = 0; + this.mapper = new ObjectMapper(); + this.buildOptions(environment); + this.buildOptionsInTable(environment); + this.configLoader = configLoader; + } + + private void buildOptionsInTable(Environment environment) { + this.optionsInTable.put(ParagraphStyle.TEXT, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.addParagraph(); + XWPFRun run = paragraph.createRun(); + if (item != null) + run.setText("" + item); + run.setFontSize(11); + return paragraph; + }); + this.optionsInTable.put(ParagraphStyle.HTML, (mainDocumentPart, item) -> { + Document htmlDoc = Jsoup.parse(((String)item).replaceAll("\n", "
")); + HtmlToWorldBuilder htmlToWorldBuilder = HtmlToWorldBuilder.convertInTable(mainDocumentPart, htmlDoc, 0); + return htmlToWorldBuilder.getParagraph(); + }); + this.optionsInTable.put(ParagraphStyle.TITLE, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.addParagraph(); + paragraph.setStyle("Title"); + paragraph.setAlignment(ParagraphAlignment.CENTER); + XWPFRun run = paragraph.createRun(); + run.setText((String)item); + run.setBold(true); + run.setFontSize(14); + return paragraph; + }); + this.optionsInTable.put(ParagraphStyle.IMAGE, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.addParagraph(); + XWPFRun run = paragraph.createRun(); + if (item != null) + run.setText(((Map)item).get("name")); + run.setFontSize(11); + run.setItalic(true); + return paragraph; + }); + } + + private void buildOptions(Environment environment) { + this.options.put(ParagraphStyle.TEXT, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + XWPFRun run = paragraph.createRun(); + if (item != null) + run.setText("" + item); + run.setFontSize(11); + return paragraph; + }); + this.options.put(ParagraphStyle.HTML, (mainDocumentPart, item) -> { + Document htmlDoc = Jsoup.parse(((String)item).replaceAll("\n", "
")); + HtmlToWorldBuilder htmlToWorldBuilder = HtmlToWorldBuilder.convert(mainDocumentPart, htmlDoc, this.indent); + return htmlToWorldBuilder.getParagraph(); + }); + this.options.put(ParagraphStyle.TITLE, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Title"); + paragraph.setAlignment(ParagraphAlignment.CENTER); + XWPFRun run = paragraph.createRun(); + run.setText((String)item); + run.setBold(true); + run.setFontSize(14); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER1, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading1"); + XWPFRun run = paragraph.createRun(); + run.setText((String)item); +// run.setBold(true); +// run.setFontSize(12); +// run.setStyle("0"); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER2, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading2"); + XWPFRun run = paragraph.createRun(); + run.setText("" + item); +// run.setBold(true); +// run.setFontSize(12); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER3, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading3"); + XWPFRun run = paragraph.createRun(); + run.setText("" + item); +// run.setBold(true); +// run.setFontSize(11); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER4, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading4"); + XWPFRun run = paragraph.createRun(); + run.setText((String)item); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER5, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading5"); + XWPFRun run = paragraph.createRun(); + run.setText("" + item); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER6, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading6"); + XWPFRun run = paragraph.createRun(); + run.setText("" + item); + return paragraph; + }); + this.options.put(ParagraphStyle.FOOTER, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + XWPFRun run = paragraph.createRun(); + run.setText((String)item); + return paragraph; + }); + this.options.put(ParagraphStyle.COMMENT, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + XWPFRun run = paragraph.createRun(); + run.setText("" + item); + run.setItalic(true); + return paragraph; + }); + this.options.put(ParagraphStyle.IMAGE, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setPageBreak(true); + paragraph.setSpacingAfter(0); + paragraph.setAlignment(ParagraphAlignment.CENTER); //GK: Center the image if it is too small + XWPFRun run = paragraph.createRun(); + String imageId = ((Map)item).get("id"); + String fileName = ((Map)item).get("name"); + String fileType = ((Map)item).get("type"); + int format; + format = IMAGE_TYPE_MAP.getOrDefault(fileType, 0); + try { + FileInputStream image = new FileInputStream(environment.getProperty("file.storage") + imageId); + ImageInputStream iis = ImageIO.createImageInputStream(new File(environment.getProperty("file.storage") + imageId)); + Iterator readers = ImageIO.getImageReaders(iis); + if (readers.hasNext()) { + ImageReader reader = readers.next(); + reader.setInput(iis); + + int initialImageWidth = reader.getWidth(0); + int initialImageHeight = reader.getHeight(0); + + float ratio = initialImageHeight / (float)initialImageWidth; + + int marginLeftInDXA = mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getLeft().intValue(); + int marginRightInDXA = mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getRight().intValue(); + int pageWidthInDXA = mainDocumentPart.getDocument().getBody().getSectPr().getPgSz().getW().intValue(); + int pageWidth = Math.round((pageWidthInDXA - marginLeftInDXA - marginRightInDXA) / (float)20); // /20 converts dxa to points + + int imageWidth = Math.round(initialImageWidth*(float)0.75); // *0.75 converts pixels to points + int width = Math.min(imageWidth, pageWidth); + + int marginTopInDXA = mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getTop().intValue(); + int marginBottomInDXA = mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getBottom().intValue(); + int pageHeightInDXA = mainDocumentPart.getDocument().getBody().getSectPr().getPgSz().getH().intValue(); + int pageHeight = Math.round((pageHeightInDXA - marginTopInDXA - marginBottomInDXA) / (float)20); // /20 converts dxa to points + + int imageHeight = Math.round(initialImageHeight * ((float)0.75)); // *0.75 converts pixels to points + + int height = Math.round(width*ratio); + if(height > pageHeight) { + // height calculated with ratio is too large. Image may have Portrait (vertical) orientation. Recalculate image dimensions. + height = Math.min(imageHeight, pageHeight); + width = Math.round(height/ratio); + } + + XWPFPicture picture = run.addPicture(image, format, fileName, Units.toEMU(width), Units.toEMU(height)); + paragraph.setPageBreak(false); + imageCount++; + XWPFParagraph captionParagraph = mainDocumentPart.createParagraph(); + captionParagraph.setAlignment(ParagraphAlignment.CENTER); + captionParagraph.setSpacingBefore(0); + captionParagraph.setStyle("Caption"); + XWPFRun captionRun = captionParagraph.createRun(); + captionRun.setText("Image " + imageCount); + + } + } catch (IOException | InvalidFormatException e){ + logger.error(e.getMessage(), e); + } + return paragraph; + }); + } + + public XWPFDocument build(XWPFDocument document, PagedDatasetProfile pagedDatasetProfile, VisibilityRuleService visibilityRuleService) throws IOException { +// createPages(pagedDatasetProfile.getPages(), document, true, visibilityRuleService); +// XWPFNumbering numbering = document.createNumbering(); +// BigInteger tempNumId = BigInteger.ONE; +// boolean found = false; +// while (!found) { +// Object o = numbering.getAbstractNum(tempNumId); +// found = (o == null); +// if (!found) tempNumId = tempNumId.add(BigInteger.ONE); +// } +// cTAbstractNum.setAbstractNumId(tempNumId); +// XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum); +// BigInteger abstractNumID = numbering.addAbstractNum(abstractNum); +// this.numId = numbering.addNum(abstractNumID); + + createPages(pagedDatasetProfile.getPages(), document, false, visibilityRuleService); + return document; + } + + private void createPages(List datasetProfilePages, XWPFDocument mainDocumentPart, Boolean createListing, VisibilityRuleService visibilityRuleService) { + datasetProfilePages.forEach(item -> { + try { + createSections(item.getSections(), mainDocumentPart, ParagraphStyle.HEADER5, 0, createListing, visibilityRuleService, item.getOrdinal() + 1, null); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }); + } + + private void createSections(List
sections, XWPFDocument mainDocumentPart, ParagraphStyle style, Integer indent, Boolean createListing, VisibilityRuleService visibilityRuleService, Integer page, String sectionString) { + if (createListing) this.addListing(mainDocumentPart, indent, false, true); + boolean hasValue = false; + for (Section section: sections) { + int paragraphPos = -1; + String tempSectionString = sectionString != null ? sectionString + "." + (section.getOrdinal() + 1) : "" + (section.getOrdinal() + 1); + if (visibilityRuleService.isElementVisible(section.getId())) { + if (!createListing) { + XWPFParagraph paragraph = addParagraphContent(page + "." + tempSectionString + " " + section.getTitle(), mainDocumentPart, style, numId, indent); +// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); +// number.setVal(BigInteger.valueOf(indent)); + paragraphPos = mainDocumentPart.getPosOfParagraph(paragraph); + } + createSections(section.getSections(), mainDocumentPart, ParagraphStyle.HEADER5, indent+1, createListing, visibilityRuleService, page, tempSectionString); + hasValue = createCompositeFields(section.getCompositeFields(), mainDocumentPart, indent+1, createListing, visibilityRuleService, page, tempSectionString); + + if (!hasValue && paragraphPos > -1) { + mainDocumentPart.removeBodyElement(paragraphPos); + } + } + } + } + + private Boolean createCompositeFields(List
compositeFields, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing, VisibilityRuleService visibilityRuleService, Integer page, String section) { + if (createListing) this.addListing(mainDocumentPart, indent, true, true); + boolean hasValue = false; + boolean returnedValue = false; + + for (FieldSet compositeField: compositeFields) { + if (visibilityRuleService.isElementVisible(compositeField.getId()) && hasVisibleFields(compositeField, visibilityRuleService)) { + char c = 'a'; + int multiplicityItems = 0; + boolean hasMultiplicityItems = false; + int paragraphPos = -1; + int paragraphPosInner = -1; + if (compositeField.getTitle() != null && !compositeField.getTitle().isEmpty() && !createListing) { + XWPFParagraph paragraph = addParagraphContent(page + "." + section + "." + (compositeField.getOrdinal() +1) + " " + compositeField.getTitle(), mainDocumentPart, ParagraphStyle.HEADER6, numId, indent); +// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); +// number.setVal(BigInteger.valueOf(indent)); + paragraphPos = mainDocumentPart.getPosOfParagraph(paragraph); + if(!compositeField.getMultiplicity().getTableView() && compositeField.getMultiplicityItems() != null && !compositeField.getMultiplicityItems().isEmpty()){ + XWPFParagraph paragraphInner = addParagraphContent(c + ". ", mainDocumentPart, ParagraphStyle.TEXT, numId, indent); + paragraphPosInner = mainDocumentPart.getPosOfParagraph(paragraphInner); + hasMultiplicityItems = true; + multiplicityItems++; + } + } + XWPFTable tbl = null; + XWPFTableRow row = null; + int numOfRows = 0; + if(compositeField.getMultiplicity().getTableView()) { + tbl = mainDocumentPart.createTable(); + tbl.setTableAlignment(TableRowAlign.CENTER); + mainDocumentPart.createParagraph(); + createHeadersInTable(compositeField.getFields(), tbl, visibilityRuleService); + numOfRows = tbl.getRows().size(); + row = tbl.createRow(); + } + if(compositeField.getMultiplicity().getTableView()) { + hasValue = createFieldsInTable(compositeField.getFields(), row, indent, createListing, visibilityRuleService, hasMultiplicityItems, numOfRows); + numOfRows++; + } else { + hasValue = createFields(compositeField.getFields(), mainDocumentPart, indent, createListing, visibilityRuleService, hasMultiplicityItems); + } + if(hasValue){ + returnedValue = true; + } else if(paragraphPosInner > -1){ + mainDocumentPart.removeBodyElement(paragraphPosInner); + c--; + multiplicityItems--; + } + if (compositeField.getMultiplicityItems() != null && !compositeField.getMultiplicityItems().isEmpty()) { + List
list = compositeField.getMultiplicityItems().stream().sorted(Comparator.comparingInt(FieldSet::getOrdinal)).collect(Collectors.toList()); + for (FieldSet multiplicityFieldset : list) { + paragraphPosInner = -1; + if(!compositeField.getMultiplicity().getTableView() && !createListing){ + c++; +// addParagraphContent(c + ". ", mainDocumentPart, ParagraphStyle.HEADER6, numId); + XWPFParagraph paragraphInner = addParagraphContent(c + ". ", mainDocumentPart, ParagraphStyle.TEXT, numId, indent); + paragraphPosInner = mainDocumentPart.getPosOfParagraph(paragraphInner); + hasMultiplicityItems = true; + multiplicityItems++; + } +// hasValue = createFields(multiplicityFieldset.getFields(), mainDocumentPart, 3, createListing, visibilityRuleService, hasMultiplicityItems); + boolean hasValueInner = false; + if(compositeField.getMultiplicity().getTableView()) { + row = tbl.createRow(); + hasValueInner = createFieldsInTable(multiplicityFieldset.getFields(), row, indent, createListing, visibilityRuleService, hasMultiplicityItems, numOfRows); + numOfRows++; + } else { + hasValueInner = createFields(multiplicityFieldset.getFields(), mainDocumentPart, indent, createListing, visibilityRuleService, hasMultiplicityItems); + } +// if(hasValue){ + if(hasValueInner){ + hasValue = true; + returnedValue = true; + } else if(paragraphPosInner > -1){ + mainDocumentPart.removeBodyElement(paragraphPosInner); + c--; + multiplicityItems--; + } + } + if(multiplicityItems == 1) { + String text = mainDocumentPart.getLastParagraph().getRuns().get(0).getText(0); + if(text.equals("a. ")) { + mainDocumentPart.getLastParagraph().removeRun(0); + } + } + } + if (hasValue && compositeField.getHasCommentField() && compositeField.getCommentFieldValue() != null && !compositeField.getCommentFieldValue().isEmpty() && !createListing) { + XWPFParagraph paragraph = addParagraphContent("Comment:\n"+compositeField.getCommentFieldValue(), mainDocumentPart, ParagraphStyle.HTML, numId, indent); +// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); +// number.setVal(BigInteger.valueOf(indent)); + } + if (!hasValue && paragraphPos > -1) { + mainDocumentPart.removeBodyElement(paragraphPos); + } + } + } + + return returnedValue; + } + + private void createHeadersInTable(List fields, XWPFTable table, VisibilityRuleService visibilityRuleService) { + boolean atLeastOneHeader = false; + List tempFields = fields.stream().sorted(Comparator.comparingInt(Field::getOrdinal)).collect(Collectors.toList()); + int index = 0; + XWPFTableRow row = table.getRow(0); + for (Field field: tempFields) { + if (visibilityRuleService.isElementVisible(field.getId()) && field.getExport()) { + XWPFTableCell cell; + if(index == 0) { + cell = row.getCell(0); + } else { + cell = row.createCell(); + } + cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.valueOf("CENTER")); + String label = ((FieldData) field.getData()).getLabel(); + if(label != null && label != "") { + XWPFParagraph paragraph = cell.getParagraphs().get(0); + paragraph.setIndentationFirstLine(50); + XWPFRun run = paragraph.createRun(); + run.setText(label); + run.setBold(true); + run.setFontSize(12); + paragraph.setAlignment(ParagraphAlignment.CENTER); + paragraph.setSpacingBefore(100); + + atLeastOneHeader = true; + } + } + index++; + } + + if(!atLeastOneHeader) { + table.removeRow(0); + } + } + + private Boolean createFieldsInTable(List fields, XWPFTableRow mainDocumentPart, Integer indent, Boolean createListing, VisibilityRuleService visibilityRuleService, boolean hasMultiplicityItems, int numOfRows) { + int numOfCells = 0; + boolean hasValue = false; + List tempFields = fields.stream().sorted(Comparator.comparingInt(Field::getOrdinal)).collect(Collectors.toList()); + for (Field field: tempFields) { + if (visibilityRuleService.isElementVisible(field.getId()) && field.getExport()) { + if (!createListing) { + try { + if(field.getViewStyle().getRenderStyle().equals("upload")){ + boolean isImage = false; + for(UploadData.Option type: ((UploadData)field.getData()).getTypes()){ + String fileFormat = type.getValue(); + if(IMAGE_TYPE_MAP.containsKey(fileFormat)){ + isImage = true; + break; + } + } + if(isImage){ + if (field.getValue() != null && !field.getValue().toString().isEmpty()) { + XWPFParagraph paragraph = addCellContent(mapper.convertValue(field.getValue(), Map.class), mainDocumentPart, ParagraphStyle.IMAGE, numId, 0, numOfRows, numOfCells, 0); + if (paragraph != null) { + hasValue = true; + } + if(hasMultiplicityItems){ + hasMultiplicityItems = false; + } + } + } + } + else if (field.getValue() != null && !field.getValue().toString().isEmpty()) { + this.indent = indent; + String format = this.formatter(field); + if (field.getViewStyle().getRenderStyle().equals("tags")) { + format = getCommaSeparatedFormatsFromJson(format, "name"); + } else if (field.getViewStyle().getRenderStyle().equals("combobox") && field.getData() instanceof AutoCompleteData) { + format = getCommaSeparatedFormatsFromJson(format, "label"); + } + boolean isResearcher = field.getViewStyle().getRenderStyle().equals("researchers"); + if(format != null && !format.isEmpty()){ + Object hasMultiAutoComplete = mapper.convertValue(field.getData(), Map.class).get("multiAutoComplete"); + boolean isMultiAutoComplete = hasMultiAutoComplete != null && (boolean)hasMultiAutoComplete; + boolean arrayStringFormat = format.charAt(0) == '['; + if(arrayStringFormat || isMultiAutoComplete){ + List values = (arrayStringFormat) ? Arrays.asList(format.substring(1, format.length() - 1).split(",[ ]*")) : Arrays.asList(format.split(",[ ]*")); + if(values.size() > 1) { + boolean orcidResearcher; + int numOfValuesInCell = 0; + for (String val : values) { + orcidResearcher = false; + String orcId = null; + if(isResearcher && val.contains("orcid:")){ + orcId = val.substring(val.indexOf(':') + 1, val.indexOf(')')); + val = val.substring(0, val.indexOf(':') + 1) + " "; + orcidResearcher = true; + } + format = "• " + val; + if(hasMultiplicityItems){ + XWPFParagraph paragraph = mainDocumentPart.getCell(mainDocumentPart.getTableCells().size()).addParagraph(); + paragraph.createRun().setText(format); + if(orcidResearcher){ + XWPFHyperlinkRun run = paragraph.createHyperlinkRun("https://orcid.org/" + orcId); + run.setText(orcId); + run.setUnderline(UnderlinePatterns.SINGLE); + run.setColor("0000FF"); + paragraph.createRun().setText(")"); + } + hasMultiplicityItems = false; + } + else{ + XWPFParagraph paragraph = addCellContent(format, mainDocumentPart, field.getViewStyle().getRenderStyle().equals("richTextarea") ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent, numOfRows, numOfCells, numOfValuesInCell); + numOfValuesInCell++; + if(orcidResearcher){ + XWPFHyperlinkRun run = paragraph.createHyperlinkRun("https://orcid.org/" + orcId); + run.setText(orcId); + run.setUnderline(UnderlinePatterns.SINGLE); + run.setColor("0000FF"); + paragraph.createRun().setText(")"); + } + if (paragraph != null) { + hasValue = true; + } + } + format = null; + } + } + else if(values.size() == 1){ + format = values.get(0); + } + } + } + if(hasMultiplicityItems && format != null){ + XWPFParagraph paragraph = mainDocumentPart.getCell(mainDocumentPart.getTableCells().size()).addParagraph(); + paragraph.createRun().setText(format); + hasMultiplicityItems = false; + hasValue = true; + } + else{ + XWPFParagraph paragraph = addCellContent(format, mainDocumentPart, field.getViewStyle().getRenderStyle().equals("richTextarea") ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent, numOfRows, numOfCells, 0); + if (paragraph != null) { + hasValue = true; + } + } + } + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + } + numOfCells++; + } + } + return hasValue; + } + + private void createHypeLink(XWPFDocument mainDocumentPart, String format, String pidType, String pid, boolean hasMultiplicityItems, boolean isMultiAutoComplete){ + PidLink pidLink = this.configLoader.getPidLinks().getPidLinks().stream().filter(pl -> pl.getPid().equals(pidType)).findFirst().orElse(null); + if (pidLink != null) { + if (!hasMultiplicityItems) { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setIndentFromLeft(400 * indent); + if (numId != null) { + paragraph.setNumID(numId); + } + } + if (isMultiAutoComplete) { + XWPFRun r = mainDocumentPart.getLastParagraph().createRun(); + r.setText("• "); + } + XWPFHyperlinkRun run = mainDocumentPart.getLastParagraph().createHyperlinkRun(pidLink.getLink().replace("{pid}", pid)); + run.setText(format); + run.setUnderline(UnderlinePatterns.SINGLE); + run.setColor("0000FF"); + run.setFontSize(11); + } + else { + String newFormat = (isMultiAutoComplete) ? "• " + format : format; + if (hasMultiplicityItems) { + mainDocumentPart.getLastParagraph().createRun().setText(newFormat); + } + else { + addParagraphContent(newFormat, mainDocumentPart, ParagraphStyle.TEXT, numId, indent); + } + } + } + + private Boolean createFields(List fields, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing, VisibilityRuleService visibilityRuleService, boolean hasMultiplicityItems) { + if (createListing) this.addListing(mainDocumentPart, indent, false, false); + boolean hasValue = false; + List tempFields = fields.stream().sorted(Comparator.comparingInt(Field::getOrdinal)).collect(Collectors.toList()); + for (Field field: tempFields) { + if (visibilityRuleService.isElementVisible(field.getId()) && field.getExport()) { + if (!createListing) { + try { + if(field.getViewStyle().getRenderStyle().equals("upload")){ + boolean isImage = false; + for(UploadData.Option type: ((UploadData)field.getData()).getTypes()){ + String fileFormat = type.getValue(); + if(IMAGE_TYPE_MAP.containsKey(fileFormat)){ + isImage = true; + break; + } + } + if(isImage){ + if (field.getValue() != null && !field.getValue().toString().isEmpty()) { + XWPFParagraph paragraph = addParagraphContent(mapper.convertValue(field.getValue(), Map.class), mainDocumentPart, ParagraphStyle.IMAGE, numId, 0); + if (paragraph != null) { +// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); +// number.setVal(BigInteger.valueOf(indent)); + hasValue = true; + } + if(hasMultiplicityItems){ + hasMultiplicityItems = false; + } + } + } + } + else if (field.getValue() != null && !field.getValue().toString().isEmpty()) { + this.indent = indent; + String format = this.formatter(field); + if (field.getViewStyle().getRenderStyle().equals("tags")) { + format = getCommaSeparatedFormatsFromJson(format, "name"); + } else if (field.getViewStyle().getRenderStyle().equals("combobox") && field.getData() instanceof AutoCompleteData) { + format = getCommaSeparatedFormatsFromJson(format, "label"); + } + switch (field.getViewStyle().getRenderStyle()) { + case "organizations": + case "externalDatasets": + case "publications": + if(format != null && !format.isEmpty()){ + Object hasMultiAutoComplete = mapper.convertValue(field.getData(), Map.class).get("multiAutoComplete"); + boolean isMultiAutoComplete = hasMultiAutoComplete != null && (boolean)hasMultiAutoComplete; + if(!isMultiAutoComplete){ + Map value = mapper.readValue((String)field.getValue(), Map.class); + if(hasMultiplicityItems){ + createHypeLink(mainDocumentPart, format, value.get("pidTypeField"), value.get("pid"), true, false); + hasMultiplicityItems = false; + } + else{ + createHypeLink(mainDocumentPart, format, value.get("pidTypeField"), value.get("pid"), false, false); + } + } + else{ + mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + List> values = new ArrayList<>(); + try { + values = Arrays.asList(mapper.readValue(field.getValue().toString(), HashMap[].class)); + } + catch (Exception e) { + Map map = new HashMap<>(); + map.put("label", field.getValue()); + values.add(map); + } + if (values.size() > 1) { + for (Map value : values) { + if(hasMultiplicityItems){ + createHypeLink(mainDocumentPart, (String) value.get("name"), (String) value.get("pidTypeField"), (String) value.get("pid"), true, true); + hasMultiplicityItems = false; + } + else{ + createHypeLink(mainDocumentPart, (String) value.get("name"), (String) value.get("pidTypeField"), (String) value.get("pid"), false, true); + } + } + } + else if(values.size() == 1){ + if(hasMultiplicityItems){ + createHypeLink(mainDocumentPart, format, (String) values.get(0).get("pidTypeField"), (String) values.get(0).get("pid"), true, false); + hasMultiplicityItems = false; + } + else{ + createHypeLink(mainDocumentPart, format, (String) values.get(0).get("pidTypeField"), (String) values.get(0).get("pid"), false, false); + } + } + } + hasValue = true; + } + break; + default: + boolean isResearcher = field.getViewStyle().getRenderStyle().equals("researchers"); + if(format != null && !format.isEmpty()){ + Object hasMultiAutoComplete = mapper.convertValue(field.getData(), Map.class).get("multiAutoComplete"); + boolean isMultiAutoComplete = hasMultiAutoComplete != null && (boolean)hasMultiAutoComplete; + boolean arrayStringFormat = format.charAt(0) == '['; + if(arrayStringFormat || isMultiAutoComplete){ + List values = (arrayStringFormat) ? Arrays.asList(format.substring(1, format.length() - 1).split(",[ ]*")) : Arrays.asList(format.split(",[ ]*")); + if(values.size() > 1) { + boolean orcidResearcher; + for (String val : values) { + orcidResearcher = false; + String orcId = null; + if(isResearcher && val.contains("orcid:")){ + orcId = val.substring(val.indexOf(':') + 1, val.indexOf(')')); + val = val.substring(0, val.indexOf(':') + 1) + " "; + orcidResearcher = true; + } + format = "• " + val; + if(hasMultiplicityItems){ + mainDocumentPart.getLastParagraph().createRun().setText(format); + if(orcidResearcher){ + XWPFHyperlinkRun run = mainDocumentPart.getLastParagraph().createHyperlinkRun("https://orcid.org/" + orcId); + run.setText(orcId); + run.setUnderline(UnderlinePatterns.SINGLE); + run.setColor("0000FF"); + mainDocumentPart.getLastParagraph().createRun().setText(")"); + } + hasMultiplicityItems = false; + } + else{ + XWPFParagraph paragraph = addParagraphContent(format, mainDocumentPart, field.getViewStyle().getRenderStyle().equals("richTextarea") ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent); + if(orcidResearcher){ + XWPFHyperlinkRun run = paragraph.createHyperlinkRun("https://orcid.org/" + orcId); + run.setText(orcId); + run.setUnderline(UnderlinePatterns.SINGLE); + run.setColor("0000FF"); + paragraph.createRun().setText(")"); + } + if (paragraph != null) { +// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); +// number.setVal(BigInteger.valueOf(indent)); + hasValue = true; + } + } + format = null; + } + } + else if(values.size() == 1){ + format = values.get(0); + } + } + } + if (format != null) { + if (hasMultiplicityItems) { + mainDocumentPart.getLastParagraph().createRun().setText(format); + hasMultiplicityItems = false; + hasValue = true; + } + else { + XWPFParagraph paragraph = addParagraphContent(format, mainDocumentPart, field.getViewStyle().getRenderStyle().equals("richTextarea") ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent); + if (paragraph != null) { +// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); +// number.setVal(BigInteger.valueOf(indent)); + hasValue = true; + } + } + } + } + } + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + } + } + } + return hasValue; + } + + private String getCommaSeparatedFormatsFromJson(String format, String attribute){ + if((format == null || format.isEmpty()) || (attribute == null || attribute.isEmpty())){ + return null; + } + try { + JSONArray array = new JSONArray(JavaToJson.objectStringToJson(format)); + StringBuilder multipleFormats = new StringBuilder(); + for (int i = 0; i < array.length(); i++) { + multipleFormats.append(array.getJSONObject(i).getString(attribute)).append(", "); + } + if (multipleFormats.length() > 0) { + multipleFormats.setLength(multipleFormats.length() - 2); + } + return multipleFormats.toString(); + } catch (JSONException e) { + return format; + } + } + + public XWPFParagraph addCellContent(Object content, XWPFTableRow mainDocumentPart, ParagraphStyle style, BigInteger numId, int indent, int numOfRows, int numOfCells, int numOfValuesInCell) { + if (content != null) { + if (content instanceof String && ((String)content).isEmpty()) { + return null; + } + this.indent = indent; + XWPFTableCell cell; + if(numOfRows > 0 || numOfValuesInCell > 0) { + cell = mainDocumentPart.getCell(numOfCells); + } else { + cell = mainDocumentPart.createCell(); + } + cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.valueOf("CENTER")); + if(numOfValuesInCell == 0) { + cell.removeParagraph(0); + } + + XWPFParagraph paragraph = this.optionsInTable.get(style).apply(cell, content); + if (paragraph != null) { + paragraph.setAlignment(ParagraphAlignment.CENTER); + paragraph.setSpacingBefore(100); + if (numId != null) { + paragraph.setNumID(numId); + } + return paragraph; + } + } + return null; + } + + public XWPFParagraph addParagraphContent(Object content, XWPFDocument mainDocumentPart, ParagraphStyle style, BigInteger numId, int indent) { +// this.indent = 0; + if (content != null) { + if (content instanceof String && ((String)content).isEmpty()) { + return null; + } + this.indent = indent; + XWPFParagraph paragraph = this.options.get(style).apply(mainDocumentPart, content); + if (paragraph != null) { + paragraph.setIndentFromLeft(400*indent); + if (numId != null) { + paragraph.setNumID(numId); + } + return paragraph; + } + } + return null; + } + + private void addListing(XWPFDocument document, int indent, Boolean question, Boolean hasIndication) { + CTLvl cTLvl = this.cTAbstractNum.addNewLvl(); + + String textLevel = ""; + for (int i = 0; i <= indent; i++) { + textLevel += "%" + (i + 1) + "."; + } + + if (question) { + cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL); +// cTLvl.addNewLvlText().setVal(""); + cTLvl.setIlvl(BigInteger.valueOf(indent)); + } else if (!question && hasIndication) { + cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL); +// cTLvl.addNewLvlText().setVal(""); + cTLvl.setIlvl(BigInteger.valueOf(indent)); + } + if (!question && !hasIndication) { + cTLvl.addNewNumFmt().setVal(STNumberFormat.NONE); +// cTLvl.addNewLvlText().setVal(""); + cTLvl.setIlvl(BigInteger.valueOf(indent)); + } + } + + private String formatter(Field field) throws IOException { + String comboboxType = null; + if (field.getValue() == null) { + return null; + } + switch (field.getViewStyle().getRenderStyle()) { + case "researchers": + case "projects": + case "organizations": + case "externalDatasets": + case "dataRepositories": + case "pubRepositories": + case "journalRepositories": + case "taxonomies": + case "licenses": + case "publications": + case "registries": + case "services": + case "tags": + case "currency": + comboboxType = "autocomplete"; + case "combobox": { + if (comboboxType == null) { + comboboxType = ((ComboBoxData) field.getData()).getType(); + } + if (comboboxType.equals("autocomplete")) { + mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + if (field.getValue() == null) return null; + List> mapList = new ArrayList<>(); + if (!field.getValue().equals("") && field.getValue().toString() != null) { + try { + mapList = Arrays.asList(mapper.readValue(field.getValue().toString(), HashMap[].class)); + }catch (Exception e) { + // logger.warn(e.getMessage(), e); + // logger.info("Moving to fallback parsing"); + Map map = new HashMap<>(); + map.put("label", field.getValue().toString()); + mapList.add(map); + } + } + StringBuilder sb = new StringBuilder(); + int index = 0; + for (Map map: mapList) { + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() != null && (entry.getKey().equals("label") || entry.getKey().equals("description") || entry.getKey().equals("name"))) { + sb.append(entry.getValue()); + break; + } + } + if (index != mapList.size() - 1) sb.append(", "); + index++; + } + return sb.toString(); + } else if (comboboxType.equals("wordlist")) { + WordListData wordListData = (WordListData) field.getData(); + if (field.getValue() != null){ + ComboBoxData.Option selectedOption = null; + if (!wordListData.getOptions().isEmpty()) { + for (ComboBoxData.Option option : wordListData.getOptions()) { + if (option.getValue().equals(field.getValue())) { + selectedOption = option; + } + } + } + return selectedOption != null ? selectedOption.getLabel() : field.getValue().toString(); + } + return ""; + } + } + case "booleanDecision": + if (field.getValue() != null && field.getValue().equals("true")) return "Yes"; + if (field.getValue() != null && field.getValue().equals("false")) return "No"; + return null; + case "radiobox": + return field.getValue() != null ? field.getValue().toString() : null; + case "checkBox": + CheckBoxData data = (CheckBoxData) field.getData(); + if (field.getValue() == null || field.getValue().equals("false")) return null; + return data.getLabel(); + case "datepicker": + case "datePicker":{ + Instant instant; + if (!((String)field.getValue()).isEmpty()) { + try { + instant = Instant.parse((String) field.getValue()); + } catch (DateTimeParseException ex) { + instant = LocalDate.parse((String) field.getValue()).atStartOfDay().toInstant(ZoneOffset.UTC); + } + return field.getValue() != null ? DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()).format(instant) : ""; + } + return (String) field.getValue(); + } + case "freetext": + case "textarea": + case "richTextarea": + return field.getValue() != null ? field.getValue().toString(): ""; + case "datasetIdentifier": + case "validation": + if (field.getValue() != null && !field.getValue().toString().isEmpty()) { + Map identifierData; + try { + identifierData = mapper.readValue(field.getValue().toString(), HashMap.class); + } catch (Exception ex) { + // logger.warn(ex.getLocalizedMessage(), ex); + // logger.info("Reverting to custom parsing"); + identifierData = customParse(field.getValue().toString()); + } + return "id: " + identifierData.get("identifier") + ", Type: " + identifierData.get("type"); + } + return ""; + } + return null; + } + + private boolean hasVisibleFields(FieldSet compositeFields, VisibilityRuleService visibilityRuleService) { + return compositeFields.getFields().stream().anyMatch(field -> visibilityRuleService.isElementVisible(field.getId()) && field.getExport()); + } + + private Map customParse(String value) { + Map result = new LinkedHashMap<>(); + String parsedValue = value.replaceAll("[^a-zA-Z0-9\\s:=,]", ""); + StringTokenizer commaTokens = new StringTokenizer(parsedValue, ", "); + String delimeter = parsedValue.contains("=") ? "=" : ":"; + while (commaTokens.hasMoreTokens()) { + String token = commaTokens.nextToken(); + StringTokenizer delimiterTokens = new StringTokenizer(token, delimeter); + result.put(delimiterTokens.nextToken(), delimiterTokens.nextToken()); + } + return result; + } + + public int findPosOfPoweredBy(XWPFDocument document) { + for (XWPFParagraph p : document.getParagraphs()) { + List runs = p.getRuns(); + if (runs != null) { + for (XWPFRun r : runs) { + String text = r.getText(0); + if (text != null) { + if (text.equals("Powered by")) { + return document.getPosOfParagraph(p) - 1; + } + } + } + } + } + return -1; + } + + public void fillFirstPage(DMP dmpEntity, Dataset datasetEntity, XWPFDocument document, boolean isDataset) { + int parPos = 0; + int descrParPos = -1; + XWPFParagraph descrPar = null; + for(XWPFParagraph p: document.getParagraphs()){ + List runs = p.getRuns(); + if(runs != null){ + for(XWPFRun r : runs){ + String text = r.getText(0); + if(text != null){ + if(text.contains("{ARGOS.DMP.TITLE}")) { + text = text.replace("{ARGOS.DMP.TITLE}", dmpEntity.getLabel()); + r.setText(text, 0); + } else if(text.contains("{ARGOS.DMP.VERSION}")) { + text = text.replace("{ARGOS.DMP.VERSION}", "Version " + dmpEntity.getVersion()); + r.setText(text, 0); + } else if(datasetEntity != null && text.contains("{ARGOS.DATASET.TITLE}")) { + text = text.replace("{ARGOS.DATASET.TITLE}", datasetEntity.getLabel()); + r.setText(text, 0); +// } else if(text.equals("Description") && ((!isDataset && (dmpEntity == null || dmpEntity.getDescription() != null)) || (isDataset && (datasetEntity == null || datasetEntity.getDescription() == null)))) { +// r.setText("", 0); + } else if((dmpEntity != null && text.contains("{ARGOS.DMP.DESCRIPTION}") && !isDataset) || (datasetEntity != null && text.contains("{ARGOS.DATASET.DESCRIPTION}") && isDataset)) { + descrParPos = parPos; + descrPar = p; + if(dmpEntity != null && !isDataset) { + text = text.replace("{ARGOS.DMP.DESCRIPTION}", ""); + } else if(datasetEntity != null && isDataset) { + text = text.replace("{ARGOS.DATASET.DESCRIPTION}", ""); + } + r.setText(text, 0); + } else if(text.equals("{ARGOS.DMP.RESEARCHERS}")) { + String researchersNames = ""; + Set researchers = dmpEntity.getResearchers(); + int i = 0; + for(Researcher researcher : researchers){ + i++; + researchersNames += researcher.getLabel() + (i < researchers.size() ? ", " : ""); + } + text = text.replace("{ARGOS.DMP.RESEARCHERS}", researchersNames); + r.setText(text, 0); + r.setFontSize(17); + } else if(text.equals("{ARGOS.DMP.ORGANIZATIONS}")) { + String organisationsNames = ""; + Set organisations = dmpEntity.getOrganisations(); + int i = 0; + for(Organisation organisation : organisations){ + i++; + organisationsNames += organisation.getLabel() + (i < organisations.size() ? ", " : ""); + } + text = text.replace("{ARGOS.DMP.ORGANIZATIONS}", organisationsNames); + r.setText(text, 0); + r.setFontSize(17); + } + } + } + } + parPos++; + } + + if((descrParPos != -1) && (dmpEntity!=null) && (dmpEntity.getDescription() != null) && !isDataset) { + XmlCursor cursor = descrPar.getCTP().newCursor(); + cursor.toNextSibling(); + Document htmlDoc = Jsoup.parse(((String)dmpEntity.getDescription()).replaceAll("\n", "
")); + HtmlToWorldBuilder htmlToWorldBuilder = new HtmlToWorldBuilder(descrPar, 0, cursor); + NodeTraversor.traverse(htmlToWorldBuilder, htmlDoc); + } + if((descrParPos != -1) && (datasetEntity != null) && (datasetEntity.getDescription() != null) && isDataset) { + XmlCursor cursor = descrPar.getCTP().newCursor(); + cursor.toNextSibling(); + Document htmlDoc = Jsoup.parse(((String)datasetEntity.getDescription()).replaceAll("\n", "
")); + HtmlToWorldBuilder htmlToWorldBuilder = new HtmlToWorldBuilder(descrPar, 0, cursor); + NodeTraversor.traverse(htmlToWorldBuilder, htmlDoc); + } + + + XWPFTable tbl = document.getTables().get(0); + Iterator it = tbl.getRows().iterator(); + it.next(); // skip first row + if(it.hasNext() && dmpEntity.getGrant() != null){ + XWPFParagraph p = it.next().getCell(0).getParagraphs().get(0); + XWPFRun run = p.createRun(); + run.setText(dmpEntity.getGrant().getFunder().getLabel()); + run.setFontSize(17); + p.setAlignment(ParagraphAlignment.CENTER); + } + it = tbl.getRows().iterator(); + it.next(); + if(it.hasNext() && dmpEntity.getGrant() != null){ + XWPFParagraph p = it.next().getCell(1).getParagraphs().get(0); + XWPFRun run = p.createRun(); + String text = dmpEntity.getGrant().getLabel(); + String reference = dmpEntity.getGrant().getReference(); + if(reference != null) { + String[] parts = reference.split("::"); + text += parts.length > 1 ? "/ No "+parts[parts.length - 1] : ""; + } + run.setText(text); + run.setFontSize(17); + p.setAlignment(ParagraphAlignment.CENTER); + } + } + + public void fillFooter(DMP dmpEntity, Dataset datasetEntity, XWPFDocument document, boolean isDataset) { + document.getFooterList().forEach(xwpfFooter -> { + List runs = xwpfFooter.getParagraphs().get(0).getRuns(); + if(runs != null){ + for(XWPFRun r : runs){ + String text = r.getText(0); + if(text != null){ + if(text.contains("{ARGOS.DMP.TITLE}")){ + text = text.replace("{ARGOS.DMP.TITLE}", dmpEntity.getLabel()); + r.setText(text, 0); + } + if(text.contains("{ARGOS.DATASET.TITLE}") && datasetEntity != null){ + text = text.replace("{ARGOS.DATASET.TITLE}", datasetEntity.getLabel()); + r.setText(text, 0); + } + if(text.contains("{ARGOS.DMP.LICENSE}")){ + try{ + Map license = ((Map) mapper.readValue(dmpEntity.getExtraProperties(), Map.class).get("license")); + text = text.replace("{ARGOS.DMP.LICENSE}", license.get("pid")); + } + catch (JsonProcessingException | NullPointerException e){ + text = text.replace("{ARGOS.DMP.LICENSE}", "License: -"); + } + r.setText(text, 0); + } + if(text.contains("{ARGOS.DMP.DOI}")){ + if(dmpEntity.getDois() != null && !dmpEntity.getDois().isEmpty()) + text = text.replace("{ARGOS.DMP.DOI}", dmpEntity.getDois().iterator().next().getDoi()); + else + text = text.replace("{ARGOS.DMP.DOI}", "-"); + r.setText(text, 0); + } + if(text.contains("{ARGOS.DMP.LAST_MODIFIED}")){ + DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); + text = text.replace("{ARGOS.DMP.LAST_MODIFIED}", formatter.format(dmpEntity.getModified())); + r.setText(text, 0); + } + } + } + } + }); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/XWPFHtmlDocument.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/XWPFHtmlDocument.java new file mode 100644 index 000000000..983aab752 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/XWPFHtmlDocument.java @@ -0,0 +1,63 @@ +package eu.eudat.old.logic.utilities.documents.word; + +import org.apache.poi.ooxml.POIXMLDocumentPart; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.openxml4j.opc.PackagePart; +import org.apache.poi.openxml4j.opc.PackagePartName; +import org.apache.poi.openxml4j.opc.PackagingURIHelper; +import org.apache.poi.xwpf.usermodel.XWPFDocument; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.UUID; + +public class XWPFHtmlDocument extends POIXMLDocumentPart { + + private String html; + private String id; + + public XWPFHtmlDocument(PackagePart pkg, String id) { + super(pkg); + this.html = "HTML import

"; + this.id = id; + } + + public String getHtml() { + return html; + } + + public void setHtml(String html) { + this.html = this.html.replace("

", html); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + protected void commit() throws IOException { + PackagePart packagePart = getPackagePart(); + OutputStream outputStream = packagePart.getOutputStream(); + Writer writer = new OutputStreamWriter(outputStream, "UTF-8"); + writer.write(html); + writer.close(); + outputStream.close(); + } + + public static XWPFHtmlDocument addHtmlDocument(XWPFDocument document) throws InvalidFormatException { + OPCPackage oPCPackage = document.getPackage(); + String id = UUID.randomUUID().toString(); + PackagePartName partName = PackagingURIHelper.createPartName("/word/" + id + ".html"); + PackagePart part = oPCPackage.createPart(partName, "text/html"); + XWPFHtmlDocument xWPFHtmlDocument = new XWPFHtmlDocument(part, id); + document.addRelation(xWPFHtmlDocument.getId(), new XWPFHtmlRelation(), xWPFHtmlDocument); + return xWPFHtmlDocument; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/XWPFHtmlRelation.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/XWPFHtmlRelation.java new file mode 100644 index 000000000..019c87d98 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/word/XWPFHtmlRelation.java @@ -0,0 +1,11 @@ +package eu.eudat.old.logic.utilities.documents.word; + +import org.apache.poi.ooxml.POIXMLRelation; + +public class XWPFHtmlRelation extends POIXMLRelation { + public XWPFHtmlRelation() { + super("text/html", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk", + "/word/htmlDoc#.html"); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/ExportXmlBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/ExportXmlBuilder.java new file mode 100644 index 000000000..b305cef16 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/ExportXmlBuilder.java @@ -0,0 +1,152 @@ +package eu.eudat.old.logic.utilities.documents.xml; + +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.old.logic.services.forms.VisibilityRuleService; +import eu.eudat.old.logic.utilities.builders.XmlBuilder; +import eu.eudat.old.models.data.components.commons.datafield.ExternalDatasetsData; +import eu.eudat.old.models.data.user.components.datasetprofile.Field; +import eu.eudat.old.models.data.user.components.datasetprofile.FieldSet; +import eu.eudat.old.models.data.user.components.datasetprofile.Section; +import eu.eudat.old.models.data.user.composite.DatasetProfilePage; +import eu.eudat.old.models.data.user.composite.PagedDatasetProfile; +import org.springframework.core.env.Environment; +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.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public class ExportXmlBuilder { + + public File build(PagedDatasetProfile pagedDatasetProfile, UUID datasetProfileId, VisibilityRuleService visibilityRuleService, Environment environment) throws IOException { + + File xmlFile = new File(environment.getProperty("temp.temp") + 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); + writer.write(xml); + writer.close(); + return xmlFile; + } + + public Element createPages(List datasetProfilePages, VisibilityRuleService visibilityRuleService, Document element) { + Element pages = element.createElement("pages"); + datasetProfilePages.forEach(item -> { + Element page = element.createElement("page"); + page.appendChild(createSections(item.getSections(), visibilityRuleService, element)); + pages.appendChild(page); + }); + return pages; + } + + private Element createSections(List
sections, VisibilityRuleService visibilityRuleService, Document element) { + Element elementSections = element.createElement("sections"); + sections.forEach(section -> { + Element elementSection = element.createElement("section"); + if (visibilityRuleService.isElementVisible(section.getId())) { + elementSection.appendChild(createSections(section.getSections(), visibilityRuleService, element)); + elementSection.appendChild(createCompositeFields(section.getCompositeFields(), visibilityRuleService, element)); + elementSections.appendChild(elementSection); + } + }); + return elementSections; + } + + private Element createCompositeFields(List
compositeFields, VisibilityRuleService visibilityRuleService, Document element) { + Element elementComposites = element.createElement("composite-fields"); + compositeFields.forEach(compositeField -> { + 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()) { + Element title = element.createElement("title"); + title.setTextContent(compositeField.getTitle()); + composite.appendChild(title); + } + if (compositeField.getDescription() != null && !compositeField.getDescription().isEmpty()) { + Element title = element.createElement("description"); + title.setTextContent(compositeField.getDescription()); + composite.appendChild(title); + } + composite.appendChild(createFields(compositeField.getFields(), visibilityRuleService, element)); + if(compositeField.getHasCommentField()){ + Element comment = element.createElement("comment"); + comment.setTextContent(compositeField.getCommentFieldValue()); + composite.appendChild(comment); + } + elementComposites.appendChild(composite); + + } + }); + return elementComposites; + } + + private Element createFields(List fields, VisibilityRuleService visibilityRuleService, Document element) { + Element elementFields = element.createElement("fields"); + fields.forEach(field -> { + if (visibilityRuleService.isElementVisible(field.getId())) { + Element elementField = element.createElement("field"); + elementField.setAttribute("id", field.getId()); + if (field.getViewStyle().getRenderStyle().equals("externalDatasets")) { + elementField.setAttribute("type", ((ExternalDatasetsData)field.getData()).getType()); + } + if (field.getValue() != null) { + Element valueField = element.createElement("value"); + ObjectMapper mapper = new ObjectMapper(); + try { + + List> jsonArray = mapper.readValue(field.getValue().toString(), List.class); +// JSONArray jsonArray = new JSONArray(field.getValue().toString()); + StringBuilder sb = new StringBuilder(); + boolean firstTime = true; + for (Map jsonElement: jsonArray) { + if (!firstTime) { + sb.append(", "); + } + sb.append(jsonElement.get("label") != null ? jsonElement.get("label") : jsonElement.get("name")); + firstTime = false; + + } + /*for (int i = 0; i < jsonArray.length(); i++) { + sb.append(jsonArray.getJSONObject(i).get("label").toString()); + if (i != jsonArray.length() - 1) sb.append(", "); + }*/ + valueField.setTextContent(sb.toString()); + } catch (IOException ex) { + try { + Map jsonElement = mapper.readValue(field.getValue().toString(), Map.class); + valueField.setTextContent((jsonElement.get("label") != null ? jsonElement.get("label").toString() : jsonElement.get("name") != null ? jsonElement.get("name").toString() : "")); + } catch (IOException e) { + try { + valueField.setTextContent(DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()).format(Instant.parse(field.getValue().toString()))); + } catch (Exception exc) { + valueField.setTextContent(field.getValue().toString()); + } + } + } + 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())); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/ExportXmlBuilderDatasetProfile.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/ExportXmlBuilderDatasetProfile.java new file mode 100644 index 000000000..4ea927576 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/ExportXmlBuilderDatasetProfile.java @@ -0,0 +1,375 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml; + + +import eu.eudat.old.logic.utilities.builders.XmlBuilder; +import eu.eudat.old.models.data.admin.components.datasetprofile.Page; +import eu.eudat.old.models.data.components.commons.ViewStyle; +import eu.eudat.old.models.data.components.commons.datafield.*; +import eu.eudat.old.models.data.user.components.datasetprofile.Field; +import eu.eudat.old.models.data.user.components.datasetprofile.FieldSet; +import eu.eudat.old.models.data.user.composite.DatasetProfile; +import eu.eudat.old.models.data.user.components.datasetprofile.Section; + +import org.springframework.core.env.Environment; +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(DatasetProfile datasetProfile, Environment environment) throws IOException { + + File xmlFile = new File(environment.getProperty("temp.temp") + 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)); + Element pages = (Element)xmlDoc.getFirstChild(); + pages.setAttribute("description", datasetProfile.getDescription()); + pages.setAttribute("language", datasetProfile.getLanguage()); + pages.setAttribute("type", datasetProfile.getType()); + pages.setAttribute("enablePrefilling", String.valueOf(datasetProfile.isEnablePrefilling())); + String xml = XmlBuilder.generateXml(xmlDoc); + writer.write(xml); + writer.close(); + return xmlFile; + } + + public Element createPages(List datasetProfilePages, List
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, 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()); + multiplicity.setAttribute("placeholder", field.getMultiplicity().getPlaceholder()); + multiplicity.setAttribute("tableView", String.valueOf(field.getMultiplicity().getTableView())); + 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 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.getSchematics() != null) { + Element schematics = element.createElement("schematics"); + field.getSchematics().forEach(schematic -> { + Element schematicChild = element.createElement("schematic"); + schematicChild.setTextContent(schematic); + schematics.appendChild(schematicChild); + }); + elementField.appendChild(schematics); + } + 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"); + ViewStyle.Type viewStyleType = ViewStyle.Type.fromName(field.getViewStyle().getRenderStyle()); + switch (viewStyleType) { + case COMBO_BOX: + 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()); + dataOut.setAttribute("multiList", wordListDataObject.getMultiList().toString()); + 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("multiAutoComplete", autoCompleteDataObject.getMultiAutoComplete().toString()); + for (AutoCompleteData.AutoCompleteSingleData singleData: autoCompleteDataObject.getAutoCompleteSingleDataList()) { + Element singleItem = element.createElement("autocompleteSingle"); + singleItem.setAttribute("optionsRoot", singleData.getOptionsRoot()); + singleItem.setAttribute("url", singleData.getUrl()); + singleItem.setAttribute("autoCompleteType", Integer.toString(singleData.getAutocompleteType())); + if (singleData.getAutoCompleteOptions() != null) { + Element optionChild = element.createElement("option"); + optionChild.setAttribute("label", singleData.getAutoCompleteOptions().getLabel()); + optionChild.setAttribute("value", singleData.getAutoCompleteOptions().getValue()); + singleItem.appendChild(optionChild); + } + dataOut.appendChild(singleItem); + } + } + break; + case UPLOAD: + UploadData uploadDataObject = (UploadData) field.getData(); + dataOut.setAttribute("label", uploadDataObject.getLabel()); + dataOut.setAttribute("maxFileSizeInMB", String.valueOf(uploadDataObject.getMaxFileSizeInMB())); + Element types = element.createElement("types"); + uploadDataObject.getTypes().forEach(type -> { + Element optionChild = element.createElement("option"); + optionChild.setAttribute("label", type.getLabel()); + optionChild.setAttribute("value", type.getValue()); + types.appendChild(optionChild); + }); + dataOut.appendChild(types); + break; + case BOOLEAN_DECISION: + BooleanDecisionData booleanDecisionDataObject = (BooleanDecisionData) field.getData(); + dataOut.setAttribute("label", booleanDecisionDataObject.getLabel()); + break; + case RADIO_BOX: + 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); + break; + case CHECK_BOX: + case FREE_TEXT: + case TEXT_AREA: + case RICH_TEXT_AREA: + case DATE_PICKER: + case DATASET_IDENTIFIER: + case CURRENCY: + case TAGS: + FieldData fieldDataObject = (FieldData) field.getData(); + dataOut.setAttribute("label", fieldDataObject.getLabel()); + break; + case INTERNAL_DMP_ENTRIES: + InternalDmpEntitiesData internalDmpEntitiesData = (InternalDmpEntitiesData) field.getData(); + dataOut.setAttribute("label", internalDmpEntitiesData.getLabel()); + dataOut.setAttribute("type", internalDmpEntitiesData.getType()); + switch (internalDmpEntitiesData.getType()) { + case "researchers": + ResearchersAutoCompleteData researchersAutoCompleteData = (ResearchersAutoCompleteData) internalDmpEntitiesData; + dataOut.setAttribute("multiAutocomplete", researchersAutoCompleteData.getMultiAutoComplete().toString()); + break; + case "datasets": + DatasetsAutoCompleteData datasetsAutoCompleteData = (DatasetsAutoCompleteData) internalDmpEntitiesData; + dataOut.setAttribute("multiAutocomplete", datasetsAutoCompleteData.getMultiAutoComplete().toString()); + break; + case "dmps": + DMPsAutoCompleteData dmPsAutoCompleteData = (DMPsAutoCompleteData) internalDmpEntitiesData; + dataOut.setAttribute("multiAutocomplete", dmPsAutoCompleteData.getMultiAutoComplete().toString()); + break; + } + break; + case EXTERNAL_DATASETS: + ExternalDatasetsData externalDatasetsData = (ExternalDatasetsData) field.getData(); + dataOut.setAttribute("label", externalDatasetsData.getLabel()); + dataOut.setAttribute("multiAutocomplete", externalDatasetsData.getMultiAutoComplete().toString()); + dataOut.setAttribute("type", externalDatasetsData.getType()); + break; + case DATA_REPOSITORIES: + case JOURNAL_REPOSITORIES: + case PUB_REPOSITORIES: + DataRepositoriesData dataRepositoriesData = (DataRepositoriesData) field.getData(); + dataOut.setAttribute("label", dataRepositoriesData.getLabel()); + dataOut.setAttribute("multiAutocomplete", dataRepositoriesData.getMultiAutoComplete().toString()); + break; + case TAXONOMIES: + TaxonomiesData taxonomiesData = (TaxonomiesData) field.getData(); + dataOut.setAttribute("label", taxonomiesData.getLabel()); + dataOut.setAttribute("multiAutocomplete", taxonomiesData.getMultiAutoComplete().toString()); + break; + case LICENSES: + LicensesData licensesData = (LicensesData) field.getData(); + dataOut.setAttribute("label", licensesData.getLabel()); + dataOut.setAttribute("multiAutocomplete", licensesData.getMultiAutoComplete().toString()); + break; + case PUBLICATIONS: + PublicationsData publicationsData = (PublicationsData) field.getData(); + dataOut.setAttribute("label", publicationsData.getLabel()); + dataOut.setAttribute("multiAutocomplete", publicationsData.getMultiAutoComplete().toString()); + break; + case ORGANIZATIONS: + OrganizationsData organizationsData = (OrganizationsData) field.getData(); + dataOut.setAttribute("label", organizationsData.getLabel()); + dataOut.setAttribute("multiAutocomplete", organizationsData.getMultiAutoComplete().toString()); + break; + case RESEARCHERS: + ResearcherData researcherData = (ResearcherData) field.getData(); + dataOut.setAttribute("label", researcherData.getLabel()); + dataOut.setAttribute("multiAutocomplete", researcherData.getMultiAutoComplete().toString()); + break; + case REGISTRIES: + RegistriesData registriesData = (RegistriesData) field.getData(); + dataOut.setAttribute("label", registriesData.getLabel()); + dataOut.setAttribute("multiAutocomplete", registriesData.getMultiAutoComplete().toString()); + break; + case SERVICES: + ServicesData servicesData = (ServicesData) field.getData(); + dataOut.setAttribute("label", servicesData.getLabel()); + dataOut.setAttribute("multiAutocomplete", servicesData.getMultiAutoComplete().toString()); + break; + + } + elementField.appendChild(dataOut); + } + + elementFields.appendChild(elementField); + }); + return elementFields; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/ImportXmlBuilderDatasetProfile.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/ImportXmlBuilderDatasetProfile.java new file mode 100644 index 000000000..9eddd9136 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/ImportXmlBuilderDatasetProfile.java @@ -0,0 +1,29 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml; +import eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.DatasetProfile; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.*; + +public class ImportXmlBuilderDatasetProfile { + private static final Logger logger = LoggerFactory.getLogger(ImportXmlBuilderDatasetProfile.class); + + 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) { + logger.error(e.getMessage(), e); + } + + return datasetProfile; + } + + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/DatasetProfile.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/DatasetProfile.java new file mode 100644 index 000000000..9e7fa5d13 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/DatasetProfile.java @@ -0,0 +1,89 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel; + + +import eu.eudat.old.data.entities.DescriptionTemplate; +import eu.eudat.old.models.data.admin.components.datasetprofile.Section; + +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 = "pages") +public class DatasetProfile { + + private String description; + private String language; + private String type; + private boolean enablePrefilling; + + private List page; + + @XmlElement(name = "page") + public List getPage() { + return page; + } + + public void setPage(List page) { + this.page = page; + } + + @XmlAttribute(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @XmlAttribute(name = "language") + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + @XmlAttribute(name = "type") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + @XmlAttribute(name = "enablePrefilling") + public boolean isEnablePrefilling() { + return enablePrefilling; + } + + public void setEnablePrefilling(boolean enablePrefilling) { + this.enablePrefilling = enablePrefilling; + } + + public eu.eudat.old.models.data.admin.composite.DatasetProfile toAdminCompositeModel(String label){ + eu.eudat.old.models.data.admin.composite.DatasetProfile newDatasetEntityProfile = new eu.eudat.old.models.data.admin.composite.DatasetProfile(); + newDatasetEntityProfile.setLabel(label); + newDatasetEntityProfile.setStatus(DescriptionTemplate.Status.SAVED.getValue()); + newDatasetEntityProfile.setDescription(description); + newDatasetEntityProfile.setLanguage(language); + newDatasetEntityProfile.setType(type); + newDatasetEntityProfile.setEnablePrefilling(enablePrefilling); + List pagesDatasetEntity = new LinkedList<>(); + List
sectionDatasetEntity = new LinkedList<>(); + for (Page xmlPage: page) { + pagesDatasetEntity.add(xmlPage.toAdminCompositeModelPage()); + for (int i = 0; i < xmlPage.getSections().size(); i++) { + sectionDatasetEntity.add(xmlPage.toAdminCompositeModelSection(i)); + } + } + newDatasetEntityProfile.setPages(pagesDatasetEntity); + newDatasetEntityProfile.setSections(sectionDatasetEntity); + + return newDatasetEntityProfile; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/FieldSet.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/FieldSet.java new file mode 100644 index 000000000..5259b57b2 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/FieldSet.java @@ -0,0 +1,127 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel; + +import eu.eudat.old.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.old.models.data.admin.components.datasetprofile.FieldSet toAdminCompositeModelSection() { + eu.eudat.old.models.data.admin.components.datasetprofile.FieldSet fieldSet1Entity = new eu.eudat.old.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; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/FieldSets.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/FieldSets.java new file mode 100644 index 000000000..42a227377 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/FieldSets.java @@ -0,0 +1,30 @@ +package eu.eudat.old.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; + + @XmlElement(name = "field-Set") + public List
getFieldSet() { + return fieldSet; + } + + public void setFieldSet(List
fieldSet) { + this.fieldSet = fieldSet; + } + + public List toAdminCompositeModelSection(){ + List fieldSetEntity = new LinkedList<>(); + if(this.fieldSet!=null) + for (FieldSet xmlFieldSet:this.fieldSet){ + fieldSetEntity.add(xmlFieldSet.toAdminCompositeModelSection()); + } + return fieldSetEntity; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/DefaultValue.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/DefaultValue.java new file mode 100644 index 000000000..9dfdd742c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/DefaultValue.java @@ -0,0 +1,36 @@ +package eu.eudat.old.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.old.models.data.components.commons.DefaultValue toAdminCompositeModelSection(){ + eu.eudat.old.models.data.components.commons.DefaultValue defaultValueEntity =new eu.eudat.old.models.data.components.commons.DefaultValue(); + defaultValueEntity.setValue(value); + defaultValueEntity.setType(type); + return defaultValueEntity; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Field.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Field.java new file mode 100644 index 000000000..148c3237c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Field.java @@ -0,0 +1,143 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields; + +import eu.eudat.old.logic.utilities.builders.ModelBuilder; +import eu.eudat.old.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; + + private DefaultValue defaultValue; + + private Visible visible; + + private ViewStyle viewStyle; + + private Object data; + + private Schematics schematics; + + @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 getValidations() { + return validations; + } + + public void setValidations(List 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; + } + + @XmlElement(name = "schematics") + public Schematics getSchematics() { + return schematics; + } + + public void setSchematics(Schematics schematics) { + this.schematics = schematics; + } + + public eu.eudat.old.models.data.admin.components.datasetprofile.Field toAdminCompositeModelSection() { + eu.eudat.old.models.data.admin.components.datasetprofile.Field fieldEntity =new eu.eudat.old.models.data.admin.components.datasetprofile.Field(); + fieldEntity.setId(this.id); + fieldEntity.setOrdinal(this.ordinal); + List 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)); + if (data != null) { + fieldEntity.setData(data.toMap((Element) this.data)); + } + List schematicsList = new LinkedList<>(); + if (this.schematics != null && this.schematics.getSchematics() != null) { + for (Schematic schematic : this.schematics.getSchematics()) { + if (schematic != null && schematic.getSchematic() != null && !schematic.getSchematic().isEmpty()) + schematicsList.add(schematic.getSchematic()); + } + } + fieldEntity.setSchematics(schematicsList); + return fieldEntity; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Fields.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Fields.java new file mode 100644 index 000000000..6698735a7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Fields.java @@ -0,0 +1,38 @@ +package eu.eudat.old.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; + + @XmlElement(name = "field") + public List getField() { + return field; + } + + public void setField(List field) { + this.field = field; + } + + public List toAdminCompositeModelSection() { + List fieldsEntity = new LinkedList<>(); + if (this.field != null) + for (Field xmlField : this.field) { + fieldsEntity.add(xmlField.toAdminCompositeModelSection()); + } + return fieldsEntity; + } + +} + + + + + + + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Rule.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Rule.java new file mode 100644 index 000000000..9d34157f1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Rule.java @@ -0,0 +1,57 @@ +package eu.eudat.old.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.old.models.data.components.commons.Rule toAdminCompositeModelSection(){ + eu.eudat.old.models.data.components.commons.Rule ruleEntity = new eu.eudat.old.models.data.components.commons.Rule(); + ruleEntity.setRuleStyle(ruleStyle); + ruleEntity.setTarget(target); + ruleEntity.setRuleType(type); + ruleEntity.setValueType(value.getType()); + ruleEntity.setValue(value.getValue()); + return ruleEntity; + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Schematic.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Schematic.java new file mode 100644 index 000000000..c073b3e19 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Schematic.java @@ -0,0 +1,19 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields; + +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlValue; + +@XmlRootElement(name = "schematic") +public class Schematic { + + private String schematic; + + @XmlValue + public String getSchematic() { + return schematic; + } + public void setSchematic(String schematic) { + this.schematic = schematic; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Schematics.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Schematics.java new file mode 100644 index 000000000..7829ae69e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Schematics.java @@ -0,0 +1,20 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "schematics") +public class Schematics { + + private List schematics; + + @XmlElement(name = "schematic") + public List getSchematics() { + return schematics; + } + + public void setSchematics(List schematics) { + this.schematics = schematics; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Validation.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Validation.java new file mode 100644 index 000000000..a4eee8979 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Validation.java @@ -0,0 +1,19 @@ +package eu.eudat.old.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; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Value.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Value.java new file mode 100644 index 000000000..94be0325d --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Value.java @@ -0,0 +1,30 @@ +package eu.eudat.old.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; + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/ViewStyle.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/ViewStyle.java new file mode 100644 index 000000000..1fba335bc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/ViewStyle.java @@ -0,0 +1,36 @@ +package eu.eudat.old.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.old.models.data.components.commons.ViewStyle toAdminCompositeModelSection(){ + eu.eudat.old.models.data.components.commons.ViewStyle viewStyleEntity = new eu.eudat.old.models.data.components.commons.ViewStyle(); + viewStyleEntity.setCssClass(this.cssClass); + viewStyleEntity.setRenderStyle(this.renderStyle); + return viewStyleEntity; + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Visible.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Visible.java new file mode 100644 index 000000000..b80ab6dd0 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/Visible.java @@ -0,0 +1,46 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields; + +import eu.eudat.old.models.data.components.commons.Visibility; + +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 = "visible") +public class Visible { + + private String style; + private List rule; + + @XmlAttribute(name = "style") + public String getStyle() { + return style; + } + + public void setStyle(String style) { + this.style = style; + } + @XmlElement(name = "rule") + public List getRule() { + return rule; + } + + public void setRule(List rule) { + this.rule = rule; + } + + public Visibility toAdminCompositeModelSection(){ + Visibility visibilityEntity = new Visibility(); + visibilityEntity.setStyle(this.style); + if(this.rule!=null) { + List ruleListEntity = new LinkedList<>(); + for (Rule xmlRule : this.rule) { + ruleListEntity.add(xmlRule.toAdminCompositeModelSection()); + } + visibilityEntity.setRules(ruleListEntity); + } + return visibilityEntity; + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/validations.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/validations.java new file mode 100644 index 000000000..eb0c8e0d9 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Fields/validations.java @@ -0,0 +1,25 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel.Fields; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "validations") +public class validations { + + Validation validation; + + @XmlElement(name = "validation") + public Validation getValidation() { + return validation; + } + + public void setValidation(Validation validation) { + this.validation = validation; + } + + public int toAdminCompositeModelSection() { + return validation.getType(); + } +} + + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Multiplicity.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Multiplicity.java new file mode 100644 index 000000000..baee3ee37 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Multiplicity.java @@ -0,0 +1,58 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + + +@XmlRootElement(name = "multiplicity") +public class Multiplicity { + private int max; + private int min; + private String placeholder; + private boolean tableView; + + @XmlAttribute(name = "max") + public int getMax() { + return max; + } + + public void setMax(int max) { + this.max = max; + } + + @XmlAttribute(name = "min") + public int getMin() { + return min; + } + + public void setMin(int min) { + this.min = min; + } + + @XmlAttribute(name = "placeholder") + public String getPlaceholder() { + return placeholder; + } + + public void setPlaceholder(String placeholder) { + this.placeholder = placeholder; + } + + @XmlAttribute(name = "tableView") + public boolean getTableView() { + return tableView; + } + + public void setTableView(boolean tableView) { + this.tableView = tableView; + } + + public eu.eudat.old.models.data.components.commons.Multiplicity toAdminCompositeModelSection() { + eu.eudat.old.models.data.components.commons.Multiplicity multiplicityEntity = new eu.eudat.old.models.data.components.commons.Multiplicity(); + multiplicityEntity.setMax(max); + multiplicityEntity.setMin(min); + multiplicityEntity.setPlaceholder(placeholder); + multiplicityEntity.setTableView(tableView); + return multiplicityEntity; + } +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Page.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Page.java new file mode 100644 index 000000000..1e4c25b2b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Page.java @@ -0,0 +1,76 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel; + +import eu.eudat.old.models.data.admin.components.datasetprofile.Section; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "page") +public class Page { + private String id; + private int ordinal; + private String title; + private List sections; + + @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; + } + + @XmlAttribute(name = "title") + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + @XmlElement(name = "sections") + public List getSections() { + return sections; + } + + public void setSections(List sections) { + this.sections = sections; + } + + public eu.eudat.old.models.data.admin.components.datasetprofile.Page toAdminCompositeModelPage(){ + eu.eudat.old.models.data.admin.components.datasetprofile.Page pageEntity = new eu.eudat.old.models.data.admin.components.datasetprofile.Page(); + pageEntity.setId(this.id); + pageEntity.setOrdinal(this.ordinal); + pageEntity.setTitle(this.title); + return pageEntity; + } + + public Section toAdminCompositeModelSection(int i){ + /* eu.eudat.models.data.admin.components.datasetprofile.Section sectionEntity =new eu.eudat.models.data.admin.components.datasetprofile.Section(); +// List sectionsListEntity = new LinkedList<>(); +// for (Section xmlsection:this.sections.section) { +// sectionsListEntity.add(xmlsection.toAdminCompositeModelSection()); +// } + if(this.sections.section!=null) + sectionEntity.setSections(this.sections.toAdminCompositeModelSection()); + if(this.sections.fieldSets.fieldSet!=null) + sectionEntity.setFieldSets(this.sections.toAdminCompositeModelSectionFieldSets()); + sectionEntity.setId(this.id); + sectionEntity.setOrdinal(this.ordinal); + sectionEntity.setTitle(this.title);*/ + return sections.get(i).toAdminCompositeModelSection(); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Section.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Section.java new file mode 100644 index 000000000..433e40e55 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Section.java @@ -0,0 +1,147 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel; + +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 = "section") +public class Section { + private String id; + private int ordinal; + private String page; + private Boolean defaultVisibility; + private FieldSets fieldSets; + private String numbering; + private String description; + private String extendedDescription; + private String title; + private List
section; + private Boolean multiplicity; + + @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; + } + + @XmlAttribute(name = "page") + public String getPage() { + return page; + } + + public void setPage(String page) { + this.page = page; + } + + @XmlAttribute(name = "defaultVisibility") + public Boolean getDefaultVisibility() { + return defaultVisibility; + } + + public void setDefaultVisibility(Boolean defaultVisibility) { + this.defaultVisibility = defaultVisibility; + } + + @XmlElement(name = "field-Sets") + public FieldSets getFieldSets() { + return fieldSets; + } + + public void setFieldSets(FieldSets fieldSets) { + this.fieldSets = fieldSets; + } + + @XmlElement(name = "numbering") + public String getNumbering() { + return numbering; + } + + public void setNumbering(String numbering) { + this.numbering = numbering; + } + + @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 = "title") + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public eu.eudat.old.models.data.admin.components.datasetprofile.Section toAdminCompositeModelSection() { + eu.eudat.old.models.data.admin.components.datasetprofile.Section sectionEntity = new eu.eudat.old.models.data.admin.components.datasetprofile.Section(); + List sectionsListEntity = new LinkedList<>(); + + if (this.section != null) { + for (Section xmlsection : this.section) { + sectionsListEntity.add(xmlsection.toAdminCompositeModelSection()); + } + } + sectionEntity.setId(this.id); + sectionEntity.setOrdinal(this.ordinal); + sectionEntity.setTitle(this.title); + sectionEntity.setPage(this.page); + sectionEntity.setDescription(this.description); +// List fieldSetsEntity =new LinkedList<>(); +// +// for (FieldSets xmpFieldSets: this.fieldSets) { +// fieldSetsEntity.add(xmpFieldSets.toAdminCompositeModelSection()); +// } + sectionEntity.setFieldSets(this.fieldSets.toAdminCompositeModelSection()); + + sectionEntity.setSections(sectionsListEntity); + sectionEntity.setDefaultVisibility(this.defaultVisibility); + return sectionEntity; + } + + @XmlElement(name = "section") + public List
getSection() { + return section; + } + + public void setSection(List
section) { + this.section = section; + } + + @XmlAttribute(name = "multiplicity") + public Boolean getMultiplicity() { + return multiplicity; + } + + public void setMultiplicity(Boolean multiplicity) { + this.multiplicity = multiplicity; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Sections.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Sections.java new file mode 100644 index 000000000..6d53ebdb7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/datasetProfileXml/datasetProfileModel/Sections.java @@ -0,0 +1,144 @@ +package eu.eudat.old.logic.utilities.documents.xml.datasetProfileXml.datasetProfileModel; + + +import eu.eudat.old.models.data.admin.components.datasetprofile.FieldSet; + +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 = "sections") +public class Sections { + private String id; + private int ordinal; + private String page; + private Boolean defaultVisibility; + private String numbering; + private String description; + private String title; + private List
section; + private FieldSets fieldSets; + private Boolean multiplicity; + + @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; + } + + @XmlAttribute(name = "page") + public String getPage() { + return page; + } + + public void setPage(String page) { + this.page = page; + } + + @XmlAttribute(name = "defaultVisibility") + public Boolean getDefaultVisibility() { + return defaultVisibility; + } + + public void setDefaultVisibility(Boolean defaultVisibility) { + this.defaultVisibility = defaultVisibility; + } + + @XmlElement(name = "numbering") + public String getNumbering() { + return numbering; + } + + public void setNumbering(String numbering) { + this.numbering = numbering; + } + + @XmlElement(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @XmlElement(name = "title") + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + @XmlElement(name = "section") + public List
getSection() { + return section; + } + + public void setSection(List
section) { + this.section = section; + } + + @XmlElement(name = "field-Sets") + public FieldSets getFieldSets() { + return fieldSets; + } + + public void setFieldSets(FieldSets fieldSets) { + this.fieldSets = fieldSets; + } + + @XmlAttribute(name = "multiplicity") + public Boolean getMultiplicity() { + return multiplicity; + } + + public void setMultiplicity(Boolean multiplicity) { + this.multiplicity = multiplicity; + } + + public eu.eudat.old.models.data.admin.components.datasetprofile.Section toAdminCompositeModelSection() { + eu.eudat.old.models.data.admin.components.datasetprofile.Section sectionEntity = new eu.eudat.old.models.data.admin.components.datasetprofile.Section(); + List sectionsListEntity = new LinkedList<>(); + + if (this.section != null) { + for (Section xmlsection : this.section) { + sectionsListEntity.add(xmlsection.toAdminCompositeModelSection()); + } + } /*else { + sectionsListEntity.add(new eu.eudat.models.data.admin.components.datasetprofile.Section()); + }*/ + sectionEntity.setId(this.id); + sectionEntity.setOrdinal(this.ordinal); + sectionEntity.setTitle(this.title); + sectionEntity.setDefaultVisibility(this.defaultVisibility); + sectionEntity.setDescription(description); + sectionEntity.setPage(this.page); + sectionEntity.setFieldSets(toAdminCompositeModelSectionFieldSets()); + sectionEntity.setMultiplicity(this.multiplicity); + + + sectionEntity.setSections(sectionsListEntity); + return sectionEntity; + } + + public List
toAdminCompositeModelSectionFieldSets() { + return fieldSets.toAdminCompositeModelSection(); + } +} + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/ExportXmlBuilderDmpBlueprint.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/ExportXmlBuilderDmpBlueprint.java new file mode 100644 index 000000000..c86e0bbba --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/ExportXmlBuilderDmpBlueprint.java @@ -0,0 +1,46 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml; + +import eu.eudat.old.logic.utilities.builders.XmlBuilder; + +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.DataManagementPlanBlueprint; +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.Section; +import eu.eudat.old.models.data.listingmodels.DataManagementPlanBlueprintListingModel; +import org.springframework.core.env.Environment; +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.UUID; + +public class ExportXmlBuilderDmpBlueprint { + + + public File build(DataManagementPlanBlueprintListingModel dmpProfile, Environment environment) throws IOException { + + File xmlFile = new File(environment.getProperty("temp.temp") + UUID.randomUUID() + ".xml"); + BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile, true)); + Document xmlDoc = XmlBuilder.getDocument(); + Element root = xmlDoc.createElement("root"); + Element definition = xmlDoc.createElement("definition"); +// Element root = xmlDoc.createElement(dmpProfile.getLabel()); + definition.appendChild(createDefinition(dmpProfile.getDefinition(), xmlDoc)); + root.appendChild(definition); + xmlDoc.appendChild(root); + String xml = XmlBuilder.generateXml(xmlDoc); + writer.write(xml); + writer.close(); + return xmlFile; + } + + public Element createDefinition(DataManagementPlanBlueprint dmpDefinition, Document doc) { + Element sections = doc.createElement("sections"); + for (Section section : dmpDefinition.getSections()) { + sections.appendChild(section.toXml(doc)); + } + return sections; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/ImportXmlBuilderDmpBlueprint.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/ImportXmlBuilderDmpBlueprint.java new file mode 100644 index 000000000..3009e20aa --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/ImportXmlBuilderDmpBlueprint.java @@ -0,0 +1,30 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml; + +import eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel.DmpBlueprint; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.File; +import java.io.IOException; + +public class ImportXmlBuilderDmpBlueprint { + private static final Logger logger = LoggerFactory.getLogger(ImportXmlBuilderDmpBlueprint.class); + + public DmpBlueprint build(File xmlFile) throws IOException { + DmpBlueprint dmpProfile = new DmpBlueprint(); + JAXBContext jaxbContext = null; + try { + jaxbContext = JAXBContext.newInstance(DmpBlueprint.class); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + dmpProfile = (DmpBlueprint) unmarshaller.unmarshal(xmlFile); + } catch (JAXBException e) { + logger.error(e.getMessage(), e); + } + + return dmpProfile; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DescriptionTemplate.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DescriptionTemplate.java new file mode 100644 index 000000000..555adfddb --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DescriptionTemplate.java @@ -0,0 +1,71 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.UUID; + +@XmlRootElement(name = "descriptionTemplate") +public class DescriptionTemplate { + + private String id; + private String descriptionTemplateId; + private String label; + private Integer minMultiplicity; + private Integer maxMultiplicity; + + @XmlAttribute(name = "id") + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @XmlAttribute(name = "descriptionTemplateId") + public String getDescriptionTemplateId() { + return descriptionTemplateId; + } + + public void setDescriptionTemplateId(String descriptionTemplateId) { + this.descriptionTemplateId = descriptionTemplateId; + } + + @XmlAttribute(name = "label") + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + @XmlAttribute(name = "minMultiplicity") + public Integer getMinMultiplicity() { + return minMultiplicity; + } + + public void setMinMultiplicity(Integer minMultiplicity) { + this.minMultiplicity = minMultiplicity; + } + + @XmlAttribute(name = "maxMultiplicity") + public Integer getMaxMultiplicity() { + return maxMultiplicity; + } + + public void setMaxMultiplicity(Integer maxMultiplicity) { + this.maxMultiplicity = maxMultiplicity; + } + + public eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.DescriptionTemplate toDmpBlueprintCompositeModel() { + eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.DescriptionTemplate descriptionTemplate = new eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.DescriptionTemplate(); + descriptionTemplate.setId(UUID.fromString(this.id)); + descriptionTemplate.setDescriptionTemplateId(UUID.fromString(this.descriptionTemplateId)); + descriptionTemplate.setLabel(this.label); + descriptionTemplate.setMinMultiplicity(this.minMultiplicity); + descriptionTemplate.setMaxMultiplicity(this.maxMultiplicity); + return descriptionTemplate; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DescriptionTemplates.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DescriptionTemplates.java new file mode 100644 index 000000000..eac8ce1b4 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DescriptionTemplates.java @@ -0,0 +1,20 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "descriptionTemplates") +public class DescriptionTemplates { + + private List descriptionTemplates; + + @XmlElement(name = "descriptionTemplate") + public List getDescriptionTemplates() { + return descriptionTemplates; + } + public void setDescriptionTemplates(List descriptionTemplates) { + this.descriptionTemplates = descriptionTemplates; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DmpBlueprint.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DmpBlueprint.java new file mode 100644 index 000000000..6675a4263 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DmpBlueprint.java @@ -0,0 +1,36 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel; + +import eu.eudat.old.data.entities.DMPProfile; +import eu.eudat.old.models.data.listingmodels.DataManagementPlanBlueprintListingModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.Date; + +@XmlRootElement(name = "root") +public class DmpBlueprint { + + private DmpBlueprintDefinition dmpBlueprintDefinition; + + @XmlElement(name = "definition") + public DmpBlueprintDefinition getDmpBlueprintDefinition() { + return dmpBlueprintDefinition; + } + + public void setDmpBlueprintDefinition(DmpBlueprintDefinition dmpBlueprintDefinition) { + this.dmpBlueprintDefinition = dmpBlueprintDefinition; + } + + public DataManagementPlanBlueprintListingModel toDmpProfileCompositeModel(String label) { + DataManagementPlanBlueprintListingModel dmpProfileModel = new DataManagementPlanBlueprintListingModel(); + dmpProfileModel.setLabel(label); + dmpProfileModel.setStatus(DMPProfile.Status.SAVED.getValue()); + dmpProfileModel.setCreated(new Date()); + dmpProfileModel.setModified(new Date()); + if (this.dmpBlueprintDefinition != null) { + dmpProfileModel.setDefinition(this.dmpBlueprintDefinition.toDmpBlueprintCompositeModel()); + } + return dmpProfileModel; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DmpBlueprintDefinition.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DmpBlueprintDefinition.java new file mode 100644 index 000000000..7cde06ded --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/DmpBlueprintDefinition.java @@ -0,0 +1,36 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel; + +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.DataManagementPlanBlueprint; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.LinkedList; +import java.util.List; + +@XmlRootElement(name = "definition") +public class DmpBlueprintDefinition { + + private Sections sections; + + @XmlElement(name = "sections") + public Sections getSections() { + return sections; + } + public void setSections(Sections sections) { + this.sections = sections; + } + + + public DataManagementPlanBlueprint toDmpBlueprintCompositeModel() { + DataManagementPlanBlueprint dmpBlueprint = new DataManagementPlanBlueprint(); + List dmpBlueprintSections = new LinkedList<>(); + if (this.sections != null && this.sections.getSections() != null) { + for (Section section : this.sections.getSections()) { + dmpBlueprintSections.add(section.toDmpBlueprintCompositeModel()); + } + } + dmpBlueprint.setSections(dmpBlueprintSections); + return dmpBlueprint; + } + +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/ExtraField.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/ExtraField.java new file mode 100644 index 000000000..fe74c02dc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/ExtraField.java @@ -0,0 +1,97 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel; + +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.FieldModel; +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.types.FieldCategory; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.UUID; + +@XmlRootElement(name = "extraField") +public class ExtraField { + + private String id; + private int type; + private String label; + private String placeholder; + private String description; + private int ordinal; + private boolean required; + + @XmlAttribute(name = "id") + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @XmlAttribute(name = "type") + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + @XmlAttribute(name = "label") + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + @XmlAttribute(name = "placeholder") + public String getPlaceholder() { + return placeholder; + } + + public void setPlaceholder(String placeholder) { + this.placeholder = placeholder; + } + + @XmlAttribute(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @XmlAttribute(name = "ordinal") + public int getOrdinal() { + return ordinal; + } + + public void setOrdinal(int ordinal) { + this.ordinal = ordinal; + } + + @XmlAttribute(name = "required") + public boolean isRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } + + public FieldModel toDmpBlueprintCompositeModel() { + FieldModel systemField = new FieldModel(); + systemField.setId(UUID.fromString(this.id)); + systemField.setCategory(FieldCategory.EXTRA); + systemField.setType(this.type); + systemField.setLabel(this.label); + systemField.setPlaceholder(this.placeholder); + systemField.setDescription(this.description); + systemField.setOrdinal(this.ordinal); + systemField.setRequired(this.required); + return systemField; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/ExtraFields.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/ExtraFields.java new file mode 100644 index 000000000..51a117d11 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/ExtraFields.java @@ -0,0 +1,20 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "extraFields") +public class ExtraFields { + + private List extraFields; + + @XmlElement(name = "extraField") + public List getExtraFields() { + return extraFields; + } + public void setExtraFields(List extraFields) { + this.extraFields = extraFields; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/Section.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/Section.java new file mode 100644 index 000000000..1346d7394 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/Section.java @@ -0,0 +1,125 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel; + +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.FieldModel; + +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; +import java.util.UUID; + +@XmlRootElement(name = "section") +public class Section { + + private String id; + private String label; + private String description; + private int ordinal; + private SystemFields systemFields; + private ExtraFields extraFields; + private boolean hasTemplates; + private DescriptionTemplates descriptionTemplates; + + @XmlAttribute(name = "id") + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @XmlAttribute(name = "label") + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + @XmlAttribute(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @XmlAttribute(name = "ordinal") + public int getOrdinal() { + return ordinal; + } + + public void setOrdinal(int ordinal) { + this.ordinal = ordinal; + } + + @XmlElement(name = "systemFields") + public SystemFields getSystemFields() { + return systemFields; + } + + public void setSystemFields(SystemFields systemFields) { + this.systemFields = systemFields; + } + + @XmlElement(name = "extraFields") + public ExtraFields getExtraFields() { + return extraFields; + } + + public void setExtraFields(ExtraFields extraFields) { + this.extraFields = extraFields; + } + + @XmlAttribute(name = "hasTemplates") + public boolean isHasTemplates() { + return hasTemplates; + } + + public void setHasTemplates(boolean hasTemplates) { + this.hasTemplates = hasTemplates; + } + + @XmlElement(name = "descriptionTemplates") + public DescriptionTemplates getDescriptionTemplates() { + return descriptionTemplates; + } + + public void setDescriptionTemplates(DescriptionTemplates descriptionTemplates) { + this.descriptionTemplates = descriptionTemplates; + } + + public eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.Section toDmpBlueprintCompositeModel() { + eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.Section section = new eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.Section(); + section.setId(UUID.fromString(this.id)); + section.setLabel(this.label); + section.setDescription(this.description); + section.setOrdinal(this.ordinal); + section.setHasTemplates(this.hasTemplates); + List dmpBlueprintFieldModels = new LinkedList<>(); + if (this.systemFields != null && this.systemFields.getSystemFields() != null) { + for (SystemField systemField : this.systemFields.getSystemFields()) { + dmpBlueprintFieldModels.add(systemField.toDmpBlueprintCompositeModel()); + } + } + if (this.extraFields != null&& this.extraFields.getExtraFields() != null) { + for (ExtraField extraField : this.extraFields.getExtraFields()) { + dmpBlueprintFieldModels.add(extraField.toDmpBlueprintCompositeModel()); + } + } + section.setFields(dmpBlueprintFieldModels); + List dmpBlueprintDescriptionTemplates = new LinkedList<>(); + if (this.descriptionTemplates != null && this.descriptionTemplates.getDescriptionTemplates() != null) { + for (DescriptionTemplate descriptionTemplate : this.descriptionTemplates.getDescriptionTemplates()) { + dmpBlueprintDescriptionTemplates.add(descriptionTemplate.toDmpBlueprintCompositeModel()); + } + } + section.setDescriptionTemplates(dmpBlueprintDescriptionTemplates); + return section; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/Sections.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/Sections.java new file mode 100644 index 000000000..0563bd50f --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/Sections.java @@ -0,0 +1,19 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "sections") +public class Sections { + + private List
sections; + + @XmlElement(name = "section") + public List
getSections() { + return sections; + } + public void setSections(List
sections) { + this.sections = sections; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/SystemField.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/SystemField.java new file mode 100644 index 000000000..e5e6f3957 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/SystemField.java @@ -0,0 +1,97 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel; + +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.FieldModel; +import eu.eudat.old.models.data.entities.xmlmodels.dmpprofiledefinition.types.FieldCategory; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.UUID; + +@XmlRootElement(name = "systemField") +public class SystemField { + + private String id; + private int type; + private String label; + private String placeholder; + private String description; + private int ordinal; + private boolean required; + + @XmlAttribute(name = "id") + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @XmlAttribute(name = "type") + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + @XmlAttribute(name = "label") + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + @XmlAttribute(name = "placeholder") + public String getPlaceholder() { + return placeholder; + } + + public void setPlaceholder(String placeholder) { + this.placeholder = placeholder; + } + + @XmlAttribute(name = "description") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @XmlAttribute(name = "ordinal") + public int getOrdinal() { + return ordinal; + } + + public void setOrdinal(int ordinal) { + this.ordinal = ordinal; + } + + @XmlAttribute(name = "required") + public boolean isRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } + + public FieldModel toDmpBlueprintCompositeModel() { + FieldModel systemField = new FieldModel(); + systemField.setId(UUID.fromString(this.id)); + systemField.setCategory(FieldCategory.SYSTEM); + systemField.setType(this.type); + systemField.setLabel(this.label); + systemField.setPlaceholder(this.placeholder); + systemField.setDescription(this.description); + systemField.setOrdinal(this.ordinal); + systemField.setRequired(this.required); + return systemField; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/SystemFields.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/SystemFields.java new file mode 100644 index 000000000..7eadff41a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/documents/xml/dmpXml/dmpBlueprintModel/SystemFields.java @@ -0,0 +1,20 @@ +package eu.eudat.old.logic.utilities.documents.xml.dmpXml.dmpBlueprintModel; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "systemFields") +public class SystemFields { + + private List systemFields; + + @XmlElement(name = "systemField") + public List getSystemFields() { + return systemFields; + } + public void setSystemFields(List systemFields) { + this.systemFields = systemFields; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/LabelBuilder.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/LabelBuilder.java new file mode 100644 index 000000000..e121d79c1 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/LabelBuilder.java @@ -0,0 +1,25 @@ +package eu.eudat.old.logic.utilities.helpers; + +import java.util.List; + + +public class LabelBuilder { + private static String generateLabel(List items) { + String label = ""; + for (T item : items) { + if (items.indexOf(item) == 3) { + label += "..."; + break; + } + if (items.indexOf(item) > 1) { + label += ", "; + } + label += item.generateLabel(); + } + return label; + } + + public static String getLabel(List items) { + return generateLabel(items); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/LabelGenerator.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/LabelGenerator.java new file mode 100644 index 000000000..35f0762ac --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/LabelGenerator.java @@ -0,0 +1,6 @@ +package eu.eudat.old.logic.utilities.helpers; + + +public interface LabelGenerator { + String generateLabel(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/ListHelper.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/ListHelper.java new file mode 100644 index 000000000..a4d202303 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/ListHelper.java @@ -0,0 +1,17 @@ +package eu.eudat.old.logic.utilities.helpers; + +import org.springframework.stereotype.Component; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; + +@Component +public class ListHelper { + + public Predicate distinctByKey(Function keyExtractor) { + Map seen = new ConcurrentHashMap<>(); + return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/ModelBuilderCollector.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/ModelBuilderCollector.java new file mode 100644 index 000000000..8601131f6 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/ModelBuilderCollector.java @@ -0,0 +1,46 @@ +package eu.eudat.old.logic.utilities.helpers; + +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Section; +import eu.eudat.old.models.data.user.components.commons.Rule; + +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +public class ModelBuilderCollector { + + + /** + * @param sections + * @return + */ + public static List collectRules(List
sections) { + List rules = new LinkedList(); + for (Section section : sections) { + if (!section.getSections().isEmpty()) { + rules.addAll(collectRules(section.getSections())); + } + rules.addAll( + section.getFieldSets().stream() + .map(fieldset -> fieldset.getFields()) + .flatMap(List::stream) + .map(field -> getRulesFromField(field.getId(), field.getVisible() + .getRules())) + .flatMap(List::stream) + .collect(Collectors.toList())); + } + + return rules; + } + + private static List getRulesFromField(String id, List rules) { + List modelRules = new LinkedList(); + for (eu.eudat.old.models.data.components.commons.Rule rule : rules) { + Rule modelRule = new Rule().fromDefinitionRule(rule); + modelRule.setSourceField(id); + modelRules.add(modelRule); + } + return modelRules; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/ModelSerializer.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/ModelSerializer.java new file mode 100644 index 000000000..d19faaf52 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/ModelSerializer.java @@ -0,0 +1,9 @@ +package eu.eudat.old.logic.utilities.helpers; + + +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.DatabaseViewStyleDefinition; +import eu.eudat.old.models.data.entities.xmlmodels.modeldefinition.DatabaseModelDefinition; + +public interface ModelSerializer { + void fromDatabaseDefinition(T viewStyle, U model); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/MyStringUtils.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/MyStringUtils.java new file mode 100644 index 000000000..ccf27c971 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/MyStringUtils.java @@ -0,0 +1,21 @@ +package eu.eudat.old.logic.utilities.helpers; + +public class MyStringUtils { + + public static int getFirstDifference(String s1, String s2) { + char[] s1ar = s1.toCharArray(); + char[] s2ar = s2.toCharArray(); + + for(int i = 0; i < s1ar.length; i++) { + if (s2ar.length > i) { + if (s1ar[i] != s2ar[i]) { + return i; + } + } else { + return i; + } + } + + return -1; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/StreamDistinctBy.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/StreamDistinctBy.java new file mode 100644 index 000000000..c46ff67ae --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/helpers/StreamDistinctBy.java @@ -0,0 +1,15 @@ +package eu.eudat.old.logic.utilities.helpers; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; + +public class StreamDistinctBy { + + public static Predicate distinctByKey( + Function keyExtractor) { + Map found = new ConcurrentHashMap<>(); + return t -> found.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/Applier.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/Applier.java new file mode 100644 index 000000000..6ce45bd1e --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/Applier.java @@ -0,0 +1,8 @@ +package eu.eudat.old.logic.utilities.interfaces; + +/** + * Created by ikalyvas on 3/1/2018. + */ +public interface Applier { + void apply(A applier, V value); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ApplierWithValue.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ApplierWithValue.java new file mode 100644 index 000000000..681a05260 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ApplierWithValue.java @@ -0,0 +1,8 @@ +package eu.eudat.old.logic.utilities.interfaces; + +/** + * Created by ikalyvas on 2/27/2018. + */ +public interface ApplierWithValue { + R apply(A applier, V value); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/Cloneable.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/Cloneable.java new file mode 100644 index 000000000..5dcfa1626 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/Cloneable.java @@ -0,0 +1,8 @@ +package eu.eudat.old.logic.utilities.interfaces; + +/** + * Created by ikalyvas on 2/5/2018. + */ +public interface Cloneable { + T clone(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/DatabaseDefinition.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/DatabaseDefinition.java new file mode 100644 index 000000000..b97b87344 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/DatabaseDefinition.java @@ -0,0 +1,5 @@ +package eu.eudat.old.logic.utilities.interfaces; + + +public interface DatabaseDefinition { +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ModelDefinition.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ModelDefinition.java new file mode 100644 index 000000000..44c835ffc --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ModelDefinition.java @@ -0,0 +1,9 @@ +package eu.eudat.old.logic.utilities.interfaces; + +import eu.eudat.old.models.data.entities.xmlmodels.modeldefinition.DatabaseModelDefinition; + +public interface ModelDefinition { + T toDatabaseDefinition(T item); + + void fromDatabaseDefinition(T item); +} \ No newline at end of file diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ModelSerializer.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ModelSerializer.java new file mode 100644 index 000000000..0b1e0b732 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ModelSerializer.java @@ -0,0 +1,9 @@ +package eu.eudat.old.logic.utilities.interfaces; + + +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.DatabaseViewStyleDefinition; +import eu.eudat.old.models.data.entities.xmlmodels.modeldefinition.DatabaseModelDefinition; + +public interface ModelSerializer { + void fromDatabaseDefinition(T viewStyle, U model); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ViewStyleDefinition.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ViewStyleDefinition.java new file mode 100644 index 000000000..f5287cd7c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/ViewStyleDefinition.java @@ -0,0 +1,11 @@ +package eu.eudat.old.logic.utilities.interfaces; + + +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.DatabaseViewStyleDefinition; + +public interface ViewStyleDefinition { + T toDatabaseDefinition(T item); + + void fromDatabaseDefinition(T item); + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/XmlSerializable.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/XmlSerializable.java new file mode 100644 index 000000000..24334e719 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/interfaces/XmlSerializable.java @@ -0,0 +1,11 @@ +package eu.eudat.old.logic.utilities.interfaces; + + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public interface XmlSerializable { + Element toXml(Document doc); + + T fromXml(Element item); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/json/JavaToJson.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/json/JavaToJson.java new file mode 100644 index 000000000..016770f64 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/json/JavaToJson.java @@ -0,0 +1,13 @@ +package eu.eudat.old.logic.utilities.json; + +public class JavaToJson { + + public static String objectStringToJson(String object) { + String result = object.replaceAll("=", "\":\"") + .replaceAll("\\{", "{\"") + .replaceAll(", ", "\", \"") + .replaceAll("}", "\"}" ) + .replaceAll("}\", \"\\{", "}, {"); + return result; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/json/JsonSearcher.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/json/JsonSearcher.java new file mode 100644 index 000000000..2002b69ab --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/json/JsonSearcher.java @@ -0,0 +1,81 @@ +package eu.eudat.old.logic.utilities.json; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +public class JsonSearcher { + + public static List findNodes(JsonNode root, String key, String value) { + return findNodes(root, key, value, false); + } + + public static List findNodes(JsonNode root, String key, String value, boolean parent) { + List nodes = new ArrayList<>(); + for (Iterator it = root.elements(); it.hasNext(); ) { + JsonNode node = it.next(); + int found = 0; + for (Iterator iter = node.fieldNames(); iter.hasNext(); ) { + String fieldName = iter.next(); + if (fieldName.equals(key)) { + if (node.get(fieldName).asText().equals(value) || node.get(fieldName).asText().startsWith(value)) { + if (parent) { + nodes.add(root); + } else { + nodes.add(node); + } + found++; + } + else if(node.get(fieldName).isArray()){ + for(JsonNode item: node.get(fieldName)){ + if(item.asText().equals(value) || item.asText().startsWith(value)){ + if (parent) { + nodes.add(root); + } else { + nodes.add(node); + } + found++; + } + } + } + } + + } + if (found == 0) { + nodes.addAll(findNodes(node, key, value, parent)); + } + } + return nodes; + } + + public static List getParentValues(JsonNode root, String childValue, String key) { + List values = new LinkedList<>(); + + for (Iterator it = root.elements(); it.hasNext(); ) { + JsonNode node = it.next(); + int found = 0; + for (Iterator iter = node.fieldNames(); iter.hasNext(); ) { + String fieldName = iter.next(); + if (fieldName.equals(key)) { + if (node.get(fieldName).asText().equals(childValue) || node.get(fieldName).asText().startsWith(childValue)) { + values.add(childValue); + found++; + } + } + + } + if (found == 0) { + values.addAll(getParentValues(node, childValue, key)); + if (!values.isEmpty() && node.has(key)) { + values.add(node.get(key).asText()); + values.remove(childValue); + } + } + } + + return values; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/json/MultiDateDeserializer.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/json/MultiDateDeserializer.java new file mode 100644 index 000000000..4af002c0a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/json/MultiDateDeserializer.java @@ -0,0 +1,41 @@ +package eu.eudat.old.logic.utilities.json; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; + +import java.io.IOException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +public class MultiDateDeserializer extends StdDeserializer { + + private static final List DATE_FORMATS = Arrays.asList("yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ss.S"); + + + public MultiDateDeserializer() { + super(Date.class); + } + + protected MultiDateDeserializer(Class vc) { + super(vc); + } + + @Override + public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { + String text = p.getText(); + + for (String dateFormat: DATE_FORMATS) { + try { + return new SimpleDateFormat(dateFormat).parse(text); + } catch (ParseException ignored) { + } + } + throw new JsonParseException(p, "No supported Date format"); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/schedule/notification/NotificationScheduleJob.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/schedule/notification/NotificationScheduleJob.java new file mode 100644 index 000000000..285f26450 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/logic/utilities/schedule/notification/NotificationScheduleJob.java @@ -0,0 +1,57 @@ +package eu.eudat.old.logic.utilities.schedule.notification; + +import eu.eudat.old.data.enumeration.notification.NotifyState; +import eu.eudat.old.data.entities.Notification; +import eu.eudat.old.data.enumeration.notification.ActiveStatus; +import eu.eudat.old.logic.managers.NotificationManager; +import eu.eudat.old.logic.services.ApiContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import javax.transaction.Transactional; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +@Component +public class NotificationScheduleJob { + private static final Logger logger = LoggerFactory.getLogger(NotificationScheduleJob.class); + + private ApiContext apiContext; + private NotificationManager notificationManager; + + @Autowired + public NotificationScheduleJob(ApiContext apiContext, NotificationManager notificationManager) { + this.apiContext = apiContext; + this.notificationManager = notificationManager; + } + + @Transactional + @Scheduled(fixedRateString = "${notification.rateInterval}") + public void sendNotifications() { + List> futures = new LinkedList<>(); + this.apiContext.getOperationsContext().getDatabaseRepository().getNotificationDao().asQueryable().where(((builder, root) -> + builder.and( + builder.or( + builder.equal(root.get("notifyState"), NotifyState.PENDING), builder.equal(root.get("notifyState"), NotifyState.ERROR)) + , builder.equal(root.get("isActive"), ActiveStatus.ACTIVE)))).toListAsync().thenApplyAsync((notifications) -> { + if (!notifications.isEmpty()) { + notifications.forEach(notification -> { + try { + this.notificationManager.sendNotification(notification); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }); + } + return notifications; + }).thenApplyAsync((notifications) -> { + notifications.forEach((notification) -> futures.add(this.apiContext.getOperationsContext().getDatabaseRepository().getNotificationDao().createOrUpdateAsync(notification))); + return futures; + }).join(); + + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/DataModel.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/DataModel.java new file mode 100644 index 000000000..646e60305 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/DataModel.java @@ -0,0 +1,12 @@ +package eu.eudat.old.models; + + +import eu.eudat.old.queryable.queryableentity.DataEntity; + +public interface DataModel { + M fromDataModel(T entity); + + T toDataModel() throws Exception; + + String getHint(); +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/HintedModelFactory.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/HintedModelFactory.java new file mode 100644 index 000000000..55c671937 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/HintedModelFactory.java @@ -0,0 +1,21 @@ +package eu.eudat.old.models; + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HintedModelFactory { + private static final Logger logger = LoggerFactory.getLogger(HintedModelFactory.class); + + public static String getHint(Class clazz) { + try { + return clazz.newInstance().getHint(); + } catch (InstantiationException e) { + logger.error(e.getMessage(), e); + return null; + } catch (IllegalAccessException e) { + logger.error(e.getMessage(), e); + return null; + } + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/ContactEmail/ContactEmailModel.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/ContactEmail/ContactEmailModel.java new file mode 100644 index 000000000..3188da5ad --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/ContactEmail/ContactEmailModel.java @@ -0,0 +1,21 @@ +package eu.eudat.old.models.data.ContactEmail; + +public class ContactEmailModel { + + private String subject; + private String description; + + public String getSubject() { + return subject; + } + public void setSubject(String subject) { + this.subject = subject; + } + + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/ContactEmail/PublicContactEmailModel.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/ContactEmail/PublicContactEmailModel.java new file mode 100644 index 000000000..a7fa1a1c2 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/ContactEmail/PublicContactEmailModel.java @@ -0,0 +1,41 @@ +package eu.eudat.old.models.data.ContactEmail; + +public class PublicContactEmailModel { + + private String fullName; + private String email; + private String affiliation; + private String message; + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getAffiliation() { + return affiliation; + } + + public void setAffiliation(String affiliation) { + this.affiliation = affiliation; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/Field.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/Field.java new file mode 100644 index 000000000..2d368b9ba --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/Field.java @@ -0,0 +1,179 @@ +package eu.eudat.old.models.data.admin.components.datasetprofile; + +import eu.eudat.old.models.data.components.commons.Visibility; +import eu.eudat.old.models.data.components.commons.DefaultValue; +import eu.eudat.old.models.data.components.commons.ViewStyle; +import eu.eudat.old.logic.utilities.interfaces.ViewStyleDefinition; +import eu.eudat.old.logic.utilities.builders.ModelBuilder; +import org.apache.commons.lang3.RandomStringUtils; + +import java.util.List; +import java.util.stream.Collectors; + +public class Field implements ViewStyleDefinition, Comparable { + + public enum ValidationType { + NONE((short) 0), REQUIRED((short) 1), URL((short) 2); + private short value; + + private ValidationType(short value) { + this.value = value; + } + + public short getValue() { + return value; + } + + public static ValidationType fromInteger(int value) { + switch (value) { + case 0: + return NONE; + case 1: + return REQUIRED; + case 2: + return URL; + default: + return NONE; + + } + } + + public static List fromIntegers(List values) { + return values.stream().map(ValidationType::fromInteger).collect(Collectors.toList()); + } + } + + private String id; + private Integer ordinal; + private List schematics; + private String value; + private ViewStyle viewStyle; + private String datatype; + private int page; + private DefaultValue defaultValue; + private Object data; + private Visibility visible; + private List validations; + private Boolean export; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + public int getOrdinal() { + return ordinal; + } + public void setOrdinal(int ordinal) { + this.ordinal = ordinal; + } + + + public List getSchematics() { + return schematics; + } + public void setSchematics(List schematics) { + this.schematics = schematics; + } + + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + + public ViewStyle getViewStyle() { + return viewStyle; + } + public void setViewStyle(ViewStyle viewStyle) { + this.viewStyle = viewStyle; + } + + public int getPage() { + return page; + } + public void setPage(int page) { + this.page = page; + } + + public DefaultValue getDefaultValue() { + return defaultValue; + } + public void setDefaultValue(DefaultValue defaultValue) { + this.defaultValue = defaultValue; + } + + public String getDatatype() { + return datatype; + } + public void setDatatype(String datatype) { + this.datatype = datatype; + } + + public Object getData() { + return data; + } + public void setData(Object data) { + this.data = data; + } + + public Visibility getVisible() { + return visible; + } + public void setVisible(Visibility visible) { + this.visible = visible; + } + + public List getValidations() { + return this.validations.stream().map(item -> (int) item.getValue()).collect(Collectors.toList()); + } + public void setValidations(List validations) { + this.validations = ValidationType.fromIntegers(validations); + } + + public Boolean getExport() { + return export; + } + + public void setExport(Boolean export) { + this.export = export; + } + + @Override + public eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Field toDatabaseDefinition(eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Field field) { + if (this.id == null || this.id.isEmpty()) this.id = "field_" + RandomStringUtils.random(5, true, true); + + field.setId(this.id); + field.setOrdinal(this.ordinal); + field.setViewStyle(this.viewStyle); + field.setData(new ModelBuilder().toFieldData(data, this.viewStyle.getRenderStyle())); + field.setVisible(this.visible); + field.setDefaultValue(this.defaultValue); + field.setValidations(this.validations); + field.setSchematics(this.schematics); + field.setExport(this.export); + return field; + } + + @Override + public void fromDatabaseDefinition(eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Field item) { + this.id = item.getId(); + this.ordinal = item.getOrdinal(); + this.viewStyle = item.getViewStyle(); + this.data = item.getData(); + this.visible = item.getVisible(); + this.defaultValue = item.getDefaultValue(); + this.validations = item.getValidations(); + this.schematics = item.getSchematics(); + this.export = item.getExport(); + } + + @Override + public int compareTo(Object o) { + return this.ordinal.compareTo(((Field) o).ordinal); + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/FieldSet.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/FieldSet.java new file mode 100644 index 000000000..df5c8dce3 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/FieldSet.java @@ -0,0 +1,140 @@ +package eu.eudat.old.models.data.admin.components.datasetprofile; + +import eu.eudat.old.logic.utilities.builders.ModelBuilder; +import eu.eudat.old.logic.utilities.interfaces.ViewStyleDefinition; +import eu.eudat.old.models.data.components.commons.Multiplicity; +import org.apache.commons.lang3.RandomStringUtils; + +import java.util.Collections; +import java.util.List; + +public class FieldSet implements Comparable, ViewStyleDefinition { + private String id; + private Integer ordinal; + private Multiplicity multiplicity; + private String title; + private String description; + private String extendedDescription; + private String additionalInformation; + private boolean hasCommentField; + private List fields; + + public List getFields() { + return fields; + } + public void setFields(List fields) { + this.fields = fields; + } + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + public Integer getOrdinal() { + return ordinal; + } + public void setOrdinal(int ordinal) { + this.ordinal = ordinal; + } + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } + + public Multiplicity getMultiplicity() { + return multiplicity; + } + public void setMultiplicity(Multiplicity multiplicity) { + this.multiplicity = multiplicity; + } + + public String getTitle() { + return title; + } + public void setTitle(String title) { + this.title = title; + } + + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + + public String getExtendedDescription() { + return extendedDescription; + } + public void setExtendedDescription(String extendedDescription) { + this.extendedDescription = extendedDescription; + } + + public boolean getHasCommentField() { + return hasCommentField; + } + public void setHasCommentField(boolean hasCommentField) { + this.hasCommentField = hasCommentField; + } + + public String getAdditionalInformation() { + return additionalInformation; + } + public void setAdditionalInformation(String additionalInformation) { + this.additionalInformation = additionalInformation; + } + + @Override + public eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.FieldSet toDatabaseDefinition(eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.FieldSet item) { + if (this.id == null || this.id.isEmpty()) this.id = "fieldSet_" + RandomStringUtils.random(5, true, true); + List viewStyleFields = new ModelBuilder().toViewStyleDefinition(this.fields, eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Field.class); + item.setFields(viewStyleFields); + item.setId(this.id); + item.setDescription(this.description); + item.setTitle(this.title); + item.setExtendedDescription(this.extendedDescription); + item.setAdditionalInformation(this.additionalInformation); + item.setOrdinal(this.ordinal); + item.setMultiplicity(this.multiplicity); + item.setHasCommentField(this.hasCommentField); + + return item; + } + + @Override + public void fromDatabaseDefinition(eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.FieldSet item) { + this.fields = new ModelBuilder().fromViewStyleDefinition(item.getFields(), Field.class); + this.id = item.getId(); + this.ordinal = item.getOrdinal(); + this.description = item.getDescription(); + this.extendedDescription = item.getExtendedDescription(); + this.additionalInformation=item.getAdditionalInformation(); + this.title = item.getTitle(); + this.multiplicity = item.getMultiplicity(); + this.hasCommentField = item.getHasCommentField(); + } + + @Override + public int compareTo(Object o) { + return this.ordinal.compareTo(((FieldSet) o).ordinal); + } + + + public FieldSet toShort() { + FieldSet shortenFieldSet = new FieldSet(); + shortenFieldSet.setId(this.id); + shortenFieldSet.setMultiplicity(this.multiplicity); + shortenFieldSet.setTitle(this.title); + shortenFieldSet.setDescription(this.description); + shortenFieldSet.setExtendedDescription(this.extendedDescription); + shortenFieldSet.setAdditionalInformation(this.additionalInformation); + shortenFieldSet.setHasCommentField(this.hasCommentField); + + List fieldToShort = this.fields; + Collections.sort(fieldToShort); + shortenFieldSet.setFields(fieldToShort); + return shortenFieldSet; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/Page.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/Page.java new file mode 100644 index 000000000..508b5dd04 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/Page.java @@ -0,0 +1,53 @@ +package eu.eudat.old.models.data.admin.components.datasetprofile; + +import eu.eudat.old.logic.utilities.interfaces.ViewStyleDefinition; + +public class Page implements Comparable, ViewStyleDefinition { + private String id; + private Integer ordinal; + private String title; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getOrdinal() { + return ordinal; + } + + public void setOrdinal(int ordinal) { + this.ordinal = ordinal; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + @Override + public eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Page toDatabaseDefinition(eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Page item) { + item.setId(this.id); + item.setOrdinal(this.ordinal); + item.setTitle(this.title); + return item; + } + + @Override + public void fromDatabaseDefinition(eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Page item) { + this.title = item.getTitle(); + this.ordinal = item.getOrdinal(); + this.id = item.getId(); + } + + @Override + public int compareTo(Object o) { + return this.ordinal.compareTo((Integer) o); + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/Section.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/Section.java new file mode 100644 index 000000000..61b322159 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/components/datasetprofile/Section.java @@ -0,0 +1,152 @@ +package eu.eudat.old.models.data.admin.components.datasetprofile; + +import eu.eudat.old.logic.utilities.interfaces.ViewStyleDefinition; +import eu.eudat.old.logic.utilities.builders.ModelBuilder; +import org.apache.commons.lang3.RandomStringUtils; + +import java.util.Collections; +import java.util.List; + +public class Section implements Comparable, ViewStyleDefinition { + private List
sections; + private List
fieldSets; + private Boolean defaultVisibility; + private String page; + private Integer ordinal; + private String id; + private String title; + private String description; + private Boolean multiplicity; + + public List
getSections() { + return sections; + } + + public void setSections(List
sections) { + this.sections = sections; + } + + public List
getFieldSets() { + return fieldSets; + } + + public void setFieldSets(List
fieldSets) { + this.fieldSets = fieldSets; + } + + public Boolean getDefaultVisibility() { + return defaultVisibility; + } + + public void setDefaultVisibility(Boolean defaultVisibility) { + this.defaultVisibility = defaultVisibility; + } + + public String getPage() { + return page; + } + + public void setPage(String page) { + this.page = page; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public int getOrdinal() { + return ordinal; + } + + public void setOrdinal(int ordinal) { + this.ordinal = ordinal; + } + + public Boolean getMultiplicity() { + return multiplicity; + } + + public void setMultiplicity(Boolean multiplicity) { + this.multiplicity = multiplicity; + } + + @Override + public eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Section toDatabaseDefinition(eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Section item) { + if (this.id == null || this.id.isEmpty()) this.id = "section_" + RandomStringUtils.random(5, true, true); + item.setDefaultVisibility(this.defaultVisibility); + item.setDescription(this.description); + item.setMultiplicity(this.multiplicity); + if (this.fieldSets != null) + item.setFieldSets(new ModelBuilder().toViewStyleDefinition(this.fieldSets, eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.FieldSet.class)); + item.setId(this.id); + item.setOrdinal(this.ordinal); + item.setPage(this.page); + if (this.sections != null) + item.setSections(new ModelBuilder().toViewStyleDefinition(this.sections, eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Section.class)); + item.setTitle(this.title); + return item; + } + + @Override + public void fromDatabaseDefinition(eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.Section item) { + + this.defaultVisibility = item.isDefaultVisibility(); + this.description = item.getDescription(); + this.fieldSets = new ModelBuilder().fromViewStyleDefinition(item.getFieldSets(), FieldSet.class); + this.id = item.getId(); + this.ordinal = item.getOrdinal(); + this.page = item.getPage(); + this.sections = new ModelBuilder().fromViewStyleDefinition(item.getSections(), Section.class); + this.title = item.getTitle(); + this.multiplicity = item.getMultiplicity(); + } + + @Override + public int compareTo(Object o) { + return this.ordinal.compareTo(((Section) o).getOrdinal()); + } + + public Section toShort(){ + Section shortenSection = new Section(); + + List
toShortsections = this.sections; + List
toShortFieldSets = this.fieldSets; + Collections.sort(toShortsections); + Collections.sort(toShortFieldSets); + for (Section shortsections : toShortsections ) { shortsections.toShort(); } + for (FieldSet shortFieldSets : toShortFieldSets ) { shortFieldSets.toShort(); } + + shortenSection.setSections(toShortsections); + shortenSection.setFieldSets(toShortFieldSets); + + shortenSection.setDefaultVisibility(this.defaultVisibility); + shortenSection.setPage(this.page); + shortenSection.setOrdinal(this.ordinal); + shortenSection.setId(this.id); + shortenSection.setTitle(this.title); + shortenSection.setDescription(this.description); + shortenSection.setMultiplicity(this.multiplicity); + return shortenSection; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/composite/DatasetProfile.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/composite/DatasetProfile.java new file mode 100644 index 000000000..f7fbce8f7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/admin/composite/DatasetProfile.java @@ -0,0 +1,116 @@ +package eu.eudat.old.models.data.admin.composite; + +import eu.eudat.old.logic.utilities.builders.ModelBuilder; +import eu.eudat.old.models.data.admin.components.datasetprofile.Section; +import eu.eudat.old.models.data.entities.xmlmodels.datasetprofiledefinition.ViewStyleModel; +import eu.eudat.old.models.data.admin.components.datasetprofile.Page; +import eu.eudat.old.models.data.listingmodels.UserInfoListingModel; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +public class DatasetProfile { + private String label; + private String description; + private String type; + private boolean enablePrefilling; + private List pages; + private List
sections; + private Short status; + private Short version; + private String language; + private List users; + + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + public boolean isEnablePrefilling() { + return enablePrefilling; + } + public void setEnablePrefilling(boolean enablePrefilling) { + this.enablePrefilling = enablePrefilling; + } + + public List getPages() { + return pages; + } + public void setPages(List pages) { + this.pages = pages; + } + + public List
getSections() { + return sections; + } + public void setSections(List
sections) { this.sections = sections; } + + public Short getStatus() { + return status; + } + public void setStatus(Short status) { + this.status = status; + } + + public Short getVersion() { return version; } + public void setVersion(Short version) { this.version = version; } + + public String getLanguage() { + return language; + } + public void setLanguage(String language) { + this.language = language; + } + + public List getUsers() { + return users; + } + public void setUsers(List users) { + this.users = users; + } + + public void buildProfile(ViewStyleModel viewStyle) { + this.enablePrefilling = viewStyle.isEnablePrefilling(); + this.sections = new ModelBuilder().fromViewStyleDefinition(viewStyle.getSections(), Section.class); + this.pages = new ModelBuilder().fromViewStyleDefinition(viewStyle.getPages(), Page.class); + } + + public DatasetProfile toShort() { + DatasetProfile shortProfile = new DatasetProfile(); + shortProfile.setLabel(this.label); + shortProfile.setDescription(this.description); + shortProfile.setType(this.type); + shortProfile.setEnablePrefilling(this.enablePrefilling); + List
shortSection = new LinkedList<>(); + for (Section toshortSection : this.getSections()) { + shortSection.add(toshortSection.toShort()); + } + Collections.sort(shortSection); + shortProfile.setSections(shortSection); + shortProfile.setPages(this.pages); + shortProfile.setStatus(this.status); + shortProfile.setVersion(this.version); + shortProfile.setLanguage(this.language); + shortProfile.setUsers(new ArrayList<>()); + return shortProfile; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/DefaultValue.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/DefaultValue.java new file mode 100644 index 000000000..299d8494b --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/DefaultValue.java @@ -0,0 +1,24 @@ +package eu.eudat.old.models.data.components.commons; + +public class DefaultValue { + private String type; + private String value; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/Multiplicity.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/Multiplicity.java new file mode 100644 index 000000000..40c4f4beb --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/Multiplicity.java @@ -0,0 +1,41 @@ +package eu.eudat.old.models.data.components.commons; + +public class Multiplicity { + + private int min; + private int max; + private String placeholder; + private boolean tableView; + + public int getMin() { + return min; + } + + public void setMin(int min) { + this.min = min; + } + + public int getMax() { + return max; + } + + public void setMax(int max) { + this.max = max; + } + + public String getPlaceholder() { + return placeholder; + } + + public void setPlaceholder(String placeholder) { + this.placeholder = placeholder; + } + + public boolean getTableView() { + return tableView; + } + + public void setTableView(boolean tableView) { + this.tableView = tableView; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/Rule.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/Rule.java new file mode 100644 index 000000000..bf4f558d7 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/Rule.java @@ -0,0 +1,86 @@ +package eu.eudat.old.models.data.components.commons; + +import eu.eudat.old.logic.utilities.interfaces.XmlSerializable; +import eu.eudat.old.models.data.entities.xmlmodels.modeldefinition.DatabaseModelDefinition; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class Rule implements XmlSerializable, DatabaseModelDefinition { + private String ruleType; + private String target; + private String ruleStyle; + private String value; + private String valueType; + + public String getRuleType() { + return ruleType; + } + + public void setRuleType(String ruleType) { + this.ruleType = ruleType; + } + + public String getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + public String getRuleStyle() { + return ruleStyle; + } + + public void setRuleStyle(String ruleStyle) { + this.ruleStyle = ruleStyle; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getValueType() { + return valueType; + } + + public void setValueType(String valueType) { + this.valueType = valueType; + } + + @Override + public Element toXml(Document doc) { + Element rule = doc.createElement("rule"); + rule.setAttribute("type", this.ruleType); + rule.setAttribute("target", this.target); + rule.setAttribute("ruleStyle", this.ruleStyle); + + Element value = doc.createElement("value"); + value.setAttribute("type", this.valueType); + value.setTextContent(this.value); + + rule.appendChild(value); + return rule; + } + + @Override + public Rule fromXml(Element item) { + this.ruleType = item.getAttribute("type"); + this.target = item.getAttribute("target"); + this.ruleStyle = item.getAttribute("ruleStyle"); + + Element value = (Element) item.getElementsByTagName("value").item(0); + if (value != null) { + this.valueType = value.getAttribute("type"); + this.value = value.getTextContent(); + } + + return this; + } + + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/ViewStyle.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/ViewStyle.java new file mode 100644 index 000000000..3bd9b1774 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/ViewStyle.java @@ -0,0 +1,71 @@ +package eu.eudat.old.models.data.components.commons; + +public class ViewStyle { + private String renderStyle; + private String cssClass; + + public String getRenderStyle() { + return renderStyle; + } + + public void setRenderStyle(String renderStyle) { + this.renderStyle = renderStyle; + } + + public String getCssClass() { + return cssClass; + } + + public void setCssClass(String cssClass) { + this.cssClass = cssClass; + } + + public enum Type { + COMBO_BOX("combobox"), + BOOLEAN_DECISION("booleanDecision"), + RADIO_BOX("radiobox"), + INTERNAL_DMP_ENTRIES("internalDmpEntities"), + CHECK_BOX("checkBox"), + FREE_TEXT("freetext"), + TEXT_AREA("textarea"), + RICH_TEXT_AREA("richTextarea"), + UPLOAD("upload"), +// TABLE("table"), + DATE_PICKER("datePicker"), + EXTERNAL_DATASETS("externalDatasets"), + DATA_REPOSITORIES("dataRepositories"), + JOURNAL_REPOSITORIES("journalRepositories"), + PUB_REPOSITORIES("pubRepositories"), + LICENSES("licenses"), + TAXONOMIES("taxonomies"), + PUBLICATIONS("publications"), + REGISTRIES("registries"), + SERVICES("services"), + TAGS("tags"), + RESEARCHERS("researchers"), + ORGANIZATIONS("organizations"), + DATASET_IDENTIFIER("datasetIdentifier"), + CURRENCY("currency"), + VALIDATION("validation"); + + private final String name; + + Type(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public static Type fromName(String name) { + for (Type type: Type.values()) { + if (name.equals(type.getName())) { + return type; + } + } + throw new IllegalArgumentException("View Style Type [" + name + "] is not valid"); + } + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/Visibility.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/Visibility.java new file mode 100644 index 000000000..dc589157a --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/Visibility.java @@ -0,0 +1,57 @@ +package eu.eudat.old.models.data.components.commons; + +import eu.eudat.old.logic.utilities.interfaces.XmlSerializable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import java.util.LinkedList; +import java.util.List; + +public class Visibility implements XmlSerializable { + private List rules; + private String style; + + public List getRules() { + return rules; + } + + public void setRules(List rules) { + this.rules = rules; + } + + public String getStyle() { + return style; + } + + public void setStyle(String style) { + this.style = style; + } + + @Override + public Element toXml(Document doc) { + Element root = doc.createElement("visible"); + root.setAttribute("style", this.style); + if (rules != null && !rules.isEmpty()) { + for (Rule rule : rules) { + root.appendChild(rule.toXml(doc)); + } + } + return root; + } + + @Override + public Visibility fromXml(Element item) { + this.style = item.getAttribute("style"); + this.rules = new LinkedList(); + NodeList rulesElements = item.getChildNodes(); + for (int temp = 0; temp < rulesElements.getLength(); temp++) { + Node ruleElement = rulesElements.item(temp); + if (ruleElement.getNodeType() == Node.ELEMENT_NODE) { + this.rules.add(new Rule().fromXml((Element) ruleElement)); + } + } + return this; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/AutoCompleteData.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/AutoCompleteData.java new file mode 100644 index 000000000..b212138b5 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/AutoCompleteData.java @@ -0,0 +1,381 @@ +package eu.eudat.old.models.data.components.commons.datafield; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AutoCompleteData extends ComboBoxData { + + public static class AuthAutoCompleteData { + private String url; + private String method; + private String body; + private String path; + private String type; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + } + public static class AutoCompleteSingleData { + private int autocompleteType; + private String url; + private ComboBoxData.Option autoCompleteOptions; + private String optionsRoot; + private Boolean hasAuth; + private AuthAutoCompleteData auth; + private String method; + + public int getAutocompleteType() { + return autocompleteType; + } + + public void setAutocompleteType(int autocompleteType) { + this.autocompleteType = autocompleteType; + } + + public String getOptionsRoot() { + return optionsRoot; + } + public void setOptionsRoot(String optionsRoot) { + this.optionsRoot = optionsRoot; + } + + public String getUrl() { + return url; + } + public void setUrl(String url) { + this.url = url; + } + + public Boolean getHasAuth() { + return hasAuth; + } + + public void setHasAuth(Boolean hasAuth) { + this.hasAuth = hasAuth; + } + + public AuthAutoCompleteData getAuth() { + return auth; + } + + public void setAuth(AuthAutoCompleteData auth) { + this.auth = auth; + } + + public ComboBoxData.Option getAutoCompleteOptions() { + return autoCompleteOptions; + } + public void setAutoCompleteOptions(ComboBoxData.Option autoCompleteOptions) { + this.autoCompleteOptions = autoCompleteOptions; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + } + + private Boolean multiAutoComplete; + private List autoCompleteSingleDataList; + + public Boolean getMultiAutoComplete() { return multiAutoComplete; } + public void setMultiAutoComplete(Boolean multiAutoComplete) { this.multiAutoComplete = multiAutoComplete; } + + public List getAutoCompleteSingleDataList() { + return autoCompleteSingleDataList; + } + + public void setAutoCompleteSingleDataList(List autoCompleteSingleDataList) { + this.autoCompleteSingleDataList = autoCompleteSingleDataList; + } + + @Override + public Element toXml(Document doc) { + Element root = super.toXml(doc); + if (this.multiAutoComplete != null) + root.setAttribute("multiAutoComplete", this.multiAutoComplete.toString()); + for (AutoCompleteSingleData singleData: this.autoCompleteSingleDataList) { + Element parent = doc.createElement("autocompleteSingle"); + parent.setAttribute("url", singleData.url); + parent.setAttribute("optionsRoot", singleData.optionsRoot); + parent.setAttribute("autoCompleteType", Integer.toString(singleData.autocompleteType)); + parent.setAttribute("hasAuth", Boolean.toString(singleData.hasAuth)); + parent.setAttribute("method", singleData.method); + Element element = doc.createElement("option"); + element.setAttribute("label", singleData.autoCompleteOptions.getLabel()); + element.setAttribute("value", singleData.autoCompleteOptions.getValue()); + element.setAttribute("source", singleData.autoCompleteOptions.getSource()); + parent.appendChild(element); + if (singleData.hasAuth) { + Element authElement = doc.createElement("auth"); + authElement.setAttribute("url", singleData.auth.url); + authElement.setAttribute("method", singleData.auth.method); + authElement.setAttribute("body", singleData.auth.body); + authElement.setAttribute("path", singleData.auth.path); + authElement.setAttribute("type", singleData.auth.type); + parent.appendChild(authElement); + } + root.appendChild(parent); + } + return root; + } + + @Override + public AutoCompleteData fromXml(Element item) { + super.fromXml(item); + this.autoCompleteSingleDataList = new ArrayList<>(); + NodeList items = item.getElementsByTagName("autocompleteSingle"); + if (items != null && items.getLength() > 0) { + for (int i = 0; i < items.getLength(); i++) { + this.autoCompleteSingleDataList.add(new AutoCompleteSingleData()); + Element single = (Element) items.item(i); + this.mapFromXml(single, this.autoCompleteSingleDataList.get(i)); + } + } else { + this.autoCompleteSingleDataList.add(new AutoCompleteSingleData()); + this.mapFromXml(item, this.autoCompleteSingleDataList.get(0)); + } + this.multiAutoComplete = Boolean.parseBoolean(item.getAttribute("multiAutoComplete")); + return this; + } + + private void mapFromXml(Element item, AutoCompleteSingleData singleData) { + singleData.url = item.getAttribute("url"); + singleData.optionsRoot = item.getAttribute("optionsRoot"); + this.multiAutoComplete = Boolean.parseBoolean(item.getAttribute("multiAutoComplete")); + if (item.getAttribute("autoCompleteType") == null || item.getAttribute("autoCompleteType").equals("") ) { + singleData.autocompleteType = AutocompleteType.UNCACHED.getValue(); + } else { + singleData.autocompleteType = AutocompleteType.fromValue(Integer.parseInt(item.getAttribute("autoCompleteType"))).getValue(); + } + singleData.hasAuth = Boolean.parseBoolean(item.getAttribute("hasAuth")); + singleData.method = item.hasAttribute("method") ? item.getAttribute("method") : "GET"; + Element optionElement = (Element) item.getElementsByTagName("option").item(0); + if (optionElement != null) { + singleData.autoCompleteOptions = new Option(); + singleData.autoCompleteOptions.setLabel(optionElement.getAttribute("label")); + singleData.autoCompleteOptions.setValue(optionElement.getAttribute("value")); + singleData.autoCompleteOptions.setSource(optionElement.getAttribute("source")); + singleData.autoCompleteOptions.setUri(optionElement.getAttribute("uri")); + } + if (singleData.hasAuth) { + Element authElement = (Element) item.getElementsByTagName("auth").item(0); + if (authElement != null) { + singleData.auth = new AuthAutoCompleteData(); + singleData.auth.setUrl(authElement.getAttribute("url")); + singleData.auth.setMethod(authElement.getAttribute("method")); + singleData.auth.setBody(authElement.getAttribute("body")); + singleData.auth.setPath(authElement.getAttribute("path")); + singleData.auth.setType(authElement.getAttribute("type")); + } + } + } + + @Override + public AutoCompleteData fromData(Object data) { + super.fromData(data); + this.autoCompleteSingleDataList = new ArrayList<>(); + + + + if (data != null) { + this.multiAutoComplete = (Boolean) ((Map) data).get("multiAutoComplete"); + + List> dataList = (List>) ((Map) data).get("autocompleteSingle"); + if (dataList == null) { + dataList = (List>) ((Map) data).get("autoCompleteSingleDataList"); + } + + this.autoCompleteSingleDataList = new ArrayList<>(); + + int i = 0; + for (Map singleData: dataList) { + this.autoCompleteSingleDataList.add(new AutoCompleteSingleData()); + this.autoCompleteSingleDataList.get(i).autoCompleteOptions = new Option(); + this.autoCompleteSingleDataList.get(i).url = (String) singleData.get("url"); + this.autoCompleteSingleDataList.get(i).optionsRoot = (String) singleData.get("optionsRoot"); + this.autoCompleteSingleDataList.get(i).hasAuth = (Boolean) singleData.get("hasAuth"); + this.autoCompleteSingleDataList.get(i).method = singleData.containsKey("method") ? (String) singleData.get("method") : "GET"; + + if (singleData.get("autoCompleteType") == null) { + this.autoCompleteSingleDataList.get(i).autocompleteType = AutocompleteType.UNCACHED.getValue(); + } else { + this.autoCompleteSingleDataList.get(i).autocompleteType = AutocompleteType.fromValue((Integer) singleData.get("autoCompleteType")).getValue(); + } + Map options = (Map) singleData.get("autoCompleteOptions"); + if (options != null) { + this.autoCompleteSingleDataList.get(i).autoCompleteOptions.setLabel(options.get("label")); + this.autoCompleteSingleDataList.get(i).autoCompleteOptions.setValue(options.get("value")); + this.autoCompleteSingleDataList.get(i).autoCompleteOptions.setSource(options.get("source")); + this.autoCompleteSingleDataList.get(i).autoCompleteOptions.setUri(options.get("uri")); + } + if (this.autoCompleteSingleDataList.get(i).hasAuth) { + Map auth = (Map) singleData.get("auth"); + if (auth != null) { + this.autoCompleteSingleDataList.get(i).auth = new AuthAutoCompleteData(); + this.autoCompleteSingleDataList.get(i).auth.setUrl(auth.get("url")); + this.autoCompleteSingleDataList.get(i).auth.setType(auth.get("type")); + this.autoCompleteSingleDataList.get(i).auth.setPath(auth.get("path")); + this.autoCompleteSingleDataList.get(i).auth.setBody(auth.get("body")); + this.autoCompleteSingleDataList.get(i).auth.setMethod(auth.get("method")); + } + } + i++; + } + } + + return this; + } + + @Override + public Object toData() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map toMap(Element item) { + HashMap dataMap = new HashMap(); + dataMap.put("label", item != null ? item.getAttribute("label") : ""); + //dataMap.put("url", item != null ? item.getAttribute("url") : ""); + dataMap.put("type", item != null ? item.getAttribute("type") : "autocomplete"); + dataMap.put("multiAutoComplete", item != null ? Boolean.valueOf(item.getAttribute("multiAutoComplete")) : false); + List> autoCompletes = new ArrayList<>(); + NodeList autoCompleteSingles = item.getChildNodes(); + for (int i = 0; i < autoCompleteSingles.getLength(); i++) { + if (autoCompleteSingles.item(i) instanceof Element) { + if (!((Element) autoCompleteSingles.item(i)).getTagName().equals("option")) { + Element node = (Element) autoCompleteSingles.item(i); + if (!node.hasChildNodes()) { + node.appendChild(node); + } + + autoCompletes.add(singleToMap(node)); + } else { + Element node = item.getOwnerDocument().createElement("autocompleteSingle"); + node.appendChild(autoCompleteSingles.item(i)); + node.setAttribute("url", item.getAttribute("url")); + node.setAttribute("optionsRoot", item.getAttribute("optionsRoot")); + node.setAttribute("hasAuth", item.getAttribute("hasAuth")); + node.setAttribute("method", item.hasAttribute("method") ? item.getAttribute("method") : "GET"); + autoCompletes.add(singleToMap(node)); + } + } + } + dataMap.put("autocompleteSingle", autoCompletes); + //dataMap.put("optionsRoot", item != null ? item.getAttribute("optionsRoot") : ""); + //Element optionElement = (Element) item.getElementsByTagName("option").item(0); +// if (optionElement != null) { +// this.autoCompleteOptions = new Option(); +// this.autoCompleteOptions.setLabel(optionElement.getAttribute("label")); +// this.autoCompleteOptions.setValue(optionElement.getAttribute("value")); +// } + // dataMap.put("autoCompleteOptions", item != null ? optionToMap(optionElement) : null); + return dataMap; + } + + private Map optionToMap(Element item){ + HashMap dataMap = new HashMap(); + dataMap.put("label", item != null ? item.getAttribute("label") : ""); + dataMap.put("value", item != null ? item.getAttribute("value") : ""); + dataMap.put("source", item != null ? item.getAttribute("source") : ""); + return dataMap; + } + + private Map authToMap(Element item){ + HashMap dataMap = new HashMap(); + dataMap.put("url", item != null ? item.getAttribute("url") : ""); + dataMap.put("method", item != null ? item.getAttribute("method") : ""); + dataMap.put("body", item != null ? item.getAttribute("body") : ""); + dataMap.put("path", item != null ? item.getAttribute("path") : ""); + dataMap.put("type", item != null ? item.getAttribute("type") : ""); + return dataMap; + } + + private Map singleToMap(Element item) { + Map dataMap = new HashMap<>(); + if (!item.getAttribute("autoCompleteType").isEmpty()) { + dataMap.put("autoCompleteType", Integer.parseInt(item.getAttribute("autoCompleteType"))); + } + dataMap.put("optionsRoot", item != null ? item.getAttribute("optionsRoot") : ""); + dataMap.put("url", item != null ? item.getAttribute("url") : ""); + dataMap.put("hasAuth", item != null ? item.getAttribute("hasAuth") : "false"); + Element optionElement = (Element) item.getElementsByTagName("option").item(0); + dataMap.put("autoCompleteOptions", item != null ? optionToMap(optionElement) : null); + Element authElement = (Element) item.getElementsByTagName("auth").item(0); + dataMap.put("auth", item != null ? authToMap(authElement) : null); + dataMap.put("method", item != null && item.hasAttribute("method") ? item.getAttribute("method") : "GET"); + return dataMap; + } + + public enum AutocompleteType { + UNCACHED(0), CACHED(1); + + int value; + + AutocompleteType(int value) { + this.value = value; + } + + public int getValue() { + return this.value; + } + + public static AutocompleteType fromValue(int value) { + for (AutocompleteType type: AutocompleteType.values()) { + if (type.getValue() == value) { + return type; + } + } + return UNCACHED; + } + } +} + + diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/BooleanDecisionData.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/BooleanDecisionData.java new file mode 100644 index 000000000..5ff78af2c --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/BooleanDecisionData.java @@ -0,0 +1,44 @@ +package eu.eudat.old.models.data.components.commons.datafield; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import java.util.HashMap; +import java.util.Map; + +public class BooleanDecisionData extends FieldData { + + @Override + public BooleanDecisionData fromData(Object data) { + if (data != null) { + this.setLabel((String) ((Map) data).get("label")); + } + return this; + } + + @Override + public Object toData() { + return null; + } + + @Override + public Element toXml(Document doc) { + Element element = doc.createElement("data"); + element.setAttribute("label", this.getLabel()); + return element; + } + + @Override + public BooleanDecisionData fromXml(Element item) { + this.setLabel(item.getAttribute("label")); + return this; + } + + @Override + public Map toMap(Element item) { + HashMap dataMap = new HashMap(); + dataMap.put("label", item != null ? item.getAttribute("label") : ""); + return dataMap; + } + +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/CheckBoxData.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/CheckBoxData.java new file mode 100644 index 000000000..f7e5fee52 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/CheckBoxData.java @@ -0,0 +1,44 @@ +package eu.eudat.old.models.data.components.commons.datafield; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import java.util.HashMap; +import java.util.Map; + +public class CheckBoxData extends FieldData { + + @Override + public Element toXml(Document doc) { + Element root = doc.createElement("data"); + root.setAttribute("label", this.getLabel()); + return root; + } + + @Override + public CheckBoxData fromXml(Element item) { + this.setLabel(item != null ? item.getAttribute("label") : ""); + return this; + } + + @Override + public CheckBoxData fromData(Object data) { + if (data != null) { + this.setLabel((String) ((Map) data).get("label")); + } + return this; + } + + @Override + public Object toData() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map toMap(Element item) { + HashMap dataMap = new HashMap(); + dataMap.put("label", item != null ? item.getAttribute("label") : ""); + return dataMap; + } +} diff --git a/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/ComboBoxData.java b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/ComboBoxData.java new file mode 100644 index 000000000..5f8ec4690 --- /dev/null +++ b/dmp-migration-tool/web/src/main/java/eu/eudat/old/models/data/components/commons/datafield/ComboBoxData.java @@ -0,0 +1,116 @@ +package eu.eudat.old.models.data.components.commons.datafield; + +import eu.eudat.old.logic.utilities.interfaces.XmlSerializable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import java.util.HashMap; +import java.util.Map; + +public abstract class ComboBoxData extends FieldData { + public static class Option implements XmlSerializable