diff --git a/.gitignore b/.gitignore index efd255a32..163f4068e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,32 +1,32 @@ dmp-frontend/dist.7z .idea/ *.iml -dmp-backend/src/main/ui-resources/static/vendor.bundle.js.map -dmp-backend/src/main/ui-resources/static/vendor.bundle.js -dmp-backend/src/main/ui-resources/static/unauthorized.module.chunk.js.map -dmp-backend/src/main/ui-resources/static/unauthorized.module.chunk.js -dmp-backend/src/main/ui-resources/static/styles.bundle.js.map -dmp-backend/src/main/ui-resources/static/styles.bundle.js -dmp-backend/src/main/ui-resources/static/polyfills.bundle.js.map -dmp-backend/src/main/ui-resources/static/polyfills.bundle.js -dmp-backend/src/main/ui-resources/static/main.bundle.js.map -dmp-backend/src/main/ui-resources/static/main.bundle.js -dmp-backend/src/main/ui-resources/static/lang/en.json -dmp-backend/src/main/ui-resources/static/inline.bundle.js.map -dmp-backend/src/main/ui-resources/static/inline.bundle.js -dmp-backend/src/main/ui-resources/static/index.html -dmp-backend/src/main/ui-resources/static/favicon.ico -dmp-backend/src/main/ui-resources/static/assets/lang/en.json +backend/src/main/ui-resources/static/vendor.bundle.js.map +backend/src/main/ui-resources/static/vendor.bundle.js +backend/src/main/ui-resources/static/unauthorized.module.chunk.js.map +backend/src/main/ui-resources/static/unauthorized.module.chunk.js +backend/src/main/ui-resources/static/styles.bundle.js.map +backend/src/main/ui-resources/static/styles.bundle.js +backend/src/main/ui-resources/static/polyfills.bundle.js.map +backend/src/main/ui-resources/static/polyfills.bundle.js +backend/src/main/ui-resources/static/main.bundle.js.map +backend/src/main/ui-resources/static/main.bundle.js +backend/src/main/ui-resources/static/lang/en.json +backend/src/main/ui-resources/static/inline.bundle.js.map +backend/src/main/ui-resources/static/inline.bundle.js +backend/src/main/ui-resources/static/index.html +backend/src/main/ui-resources/static/favicon.ico +backend/src/main/ui-resources/static/assets/lang/en.json dmp-frontend/new 3.xml -dmp-backend/src/main/ui-resources/static/ -dmp-backend/web/target/ +backend/src/main/ui-resources/static/ +backend/web/target/ *.class -dmp-backend/web/src/main/ui-resources/static/ -dmp-backend/data/target/data-1.0-SNAPSHOT.jar -dmp-backend/data/target/ -dmp-backend/queryable/target/ -dmp-backend/elastic/target/ -dmp-backend/queryengine/target/ +backend/web/src/main/ui-resources/static/ +backend/data/target/data-1.0-SNAPSHOT.jar +backend/data/target/ +backend/queryable/target/ +backend/elastic/target/ +backend/queryengine/target/ *.tar *.gz final/ @@ -38,7 +38,7 @@ dmp-frontend/.vscode/ dmp-frontend/package-lock.json -dmp-backend/logging/target/ +backend/logging/target/ ELK.Docker/shared/data-elk/ # Eclipse @@ -47,12 +47,12 @@ ELK.Docker/shared/data-elk/ bin/ *.classpath .run -openDMP/dmp-backend/uploads/ -openDMP/dmp-backend/tmp/ +openDMP/backend/uploads/ +openDMP/backend/tmp/ logs/ -dmp-backend/web/src/main/resources/certificates/ +backend/web/src/main/resources/certificates/ /storage/ -dmp-backend/target/classes/ -dmp-backend/core/target/maven-archiver/ -dmp-backend/node_modules/.yarn-integrity +backend/target/classes/ +backend/core/target/maven-archiver/ +backend/node_modules/.yarn-integrity dmp-frontend/.nx/ diff --git a/dmp-backend/Dockerfile b/backend/Dockerfile similarity index 100% rename from dmp-backend/Dockerfile rename to backend/Dockerfile diff --git a/dmp-backend/Dockerfile.Sonar b/backend/Dockerfile.Sonar similarity index 100% rename from dmp-backend/Dockerfile.Sonar rename to backend/Dockerfile.Sonar diff --git a/backend/core/pom.xml b/backend/core/pom.xml new file mode 100644 index 000000000..afe6aa264 --- /dev/null +++ b/backend/core/pom.xml @@ -0,0 +1,109 @@ + + + 4.0.0 + + core + ${revision} + + + org.opencdmp + opencdmp-backend + ${revision} + ../pom.xml + + + + 21 + 21 + 21 + 21 + UTF-8 + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-validation + + + org.apache.commons + commons-csv + 1.10.0 + + + commons-validator + commons-validator + 1.8.0 + + + gr.cite + validation + 3.0.3 + + + gr.cite + oidc-authz + 2.1.0 + + + gr.cite.opendmp + repositorydepositbase + 2.0.7 + + + gr.cite.opendmp + common-models + 0.0.10 + + + gr.cite.opendmp + file-transformer-base + 0.0.14 + + + gr.cite + elastic + 2.1.2 + + + gr.cite + queue-inbox + 2.1.1 + + + gr.cite + queue-outbox + 2.1.1 + + + + gr.cite + oidc-authn + 2.2.2 + + + + gr.cite + keycloak-api + 2.3.0 + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 21 + 21 + + + + + + \ No newline at end of file diff --git a/backend/core/src/main/java/org/opencdmp/audit/AuditableAction.java b/backend/core/src/main/java/org/opencdmp/audit/AuditableAction.java new file mode 100644 index 000000000..2b8ad850c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/audit/AuditableAction.java @@ -0,0 +1,173 @@ +package org.opencdmp.audit; + +import gr.cite.tools.logging.EventId; + +public class AuditableAction { + + public static final EventId DescriptionTemplateType_Query = new EventId(1000, "DescriptionTemplateType_Query"); + public static final EventId DescriptionTemplateType_Lookup = new EventId(1001, "DescriptionTemplateType_Lookup"); + public static final EventId DescriptionTemplateType_Persist = new EventId(1002, "DescriptionTemplateType_Persist"); + public static final EventId DescriptionTemplateType_Delete = new EventId(1003, "DescriptionTemplateType_Delete"); + + public static final EventId EntityDoi_Query = new EventId(2000, "EntityDoi_Query"); + public static final EventId EntityDoi_Lookup = new EventId(2001, "EntityDoi_Lookup"); + public static final EventId EntityDoi_Persist = new EventId(2002, "EntityDoi_Persist"); + public static final EventId EntityDoi_Delete = new EventId(2003, "EntityDoi_Delete"); + + public static final EventId DmpBlueprint_Query = new EventId(3000, "DmpBlueprint_Query"); + public static final EventId DmpBlueprint_Lookup = new EventId(3001, "DmpBlueprint_Lookup"); + public static final EventId DmpBlueprint_Persist = new EventId(3002, "DmpBlueprint_Persist"); + public static final EventId DmpBlueprint_Delete = new EventId(3003, "DmpBlueprint_Delete"); + public static final EventId DmpBlueprint_Clone = new EventId(3004, "DmpBlueprint_Clone"); + + public static final EventId DmpBlueprint_PersistNewVersion = new EventId(3005, "DmpBlueprint_PersistNewVersion"); + public static final EventId DmpBlueprint_GetXml = new EventId(3006, "DmpBlueprint_GetXml"); + public static final EventId DmpBlueprint_Import = new EventId(3007, "DmpBlueprint_Import"); + + public static final EventId User_Settings_Query = new EventId(4000, "User_Settings_Query"); + public static final EventId User_Settings_Lookup = new EventId(4001, "User_Settings_Lookup"); + public static final EventId User_Settings_Persist = new EventId(4002, "User_Settings_Persist"); + public static final EventId User_Settings_Delete = new EventId(4003, "User_Settings_Delete"); + + public static final EventId Dmp_Query = new EventId(5000, "Dmp_Query"); + public static final EventId Dmp_Lookup = new EventId(5001, "Dmp_Lookup"); + public static final EventId Dmp_Persist = new EventId(5002, "Dmp_Persist"); + public static final EventId Dmp_Delete = new EventId(5003, "Dmp_Delete"); + public static final EventId Dmp_Clone = new EventId(5004, "Dmp_Clone"); + public static final EventId Dmp_PersistNewVersion = new EventId(5005, "Dmp_PersistNewVersion"); + public static final EventId Dmp_Assign_Users = new EventId(5006, "Dmp_Assign_Users"); + public static final EventId Dmp_RemoveUser = new EventId(5007, "Dmp_RemoveUser"); + public static final EventId Dmp_Invite_Users = new EventId(5008, "Dmp_Invite_Users"); + public static final EventId Dmp_Invite_Accept = new EventId(5009, "Dmp_Invite_Accept"); + public static final EventId Dmp_PublicQuery = new EventId(5010, "Dmp_PublicQuery"); + public static final EventId Dmp_Export = new EventId(5011, "Dmp_Export"); + public static final EventId Dmp_PublicLookup = new EventId(5012, "Dmp_PublicLookup"); + public static final EventId Dmp_Finalize = new EventId(5013, "Dmp_Finalize"); + public static final EventId Dmp_Undo_Finalize = new EventId(5014, "Dmp_Undo_Finalize"); + public static final EventId Dmp_Validate = new EventId(5015, "Dmp_Validate"); + + + public static final EventId Description_Query = new EventId(6000, "Description_Query"); + public static final EventId Description_Lookup = new EventId(6001, "Description_Lookup"); + public static final EventId Description_Persist = new EventId(6002, "Description_Persist"); + public static final EventId Description_Delete = new EventId(6003, "Description_Delete"); + public static final EventId Description_PublicQuery = new EventId(6004, "Description_PublicQuery"); + public static final EventId Description_PublicLookup = new EventId(6005, "Description_PublicLookup"); + public static final EventId Description_PersistStatus = new EventId(6006, "Description_PersistStatus"); + public static final EventId Description_UploadFieldFiles = new EventId(6007, "Description_UploadFieldFiles"); + public static final EventId Description_GetFieldFile = new EventId(6008, "Description_GetFieldFile"); + public static final EventId Description_Validate = new EventId(6009, "Description_Validate"); + public static final EventId Description_GetDescriptionSectionPermissions = new EventId(6010, "Description_GetDescriptionSectionPermissions"); + public static final EventId Description_UpdateDescriptionTemplate = new EventId(6011, "Description_UpdateDescriptionTemplate"); + + + public static final EventId Reference_Query = new EventId(7000, "Reference_Query"); + public static final EventId Reference_Lookup = new EventId(7001, "Reference_Lookup"); + public static final EventId Reference_Persist = new EventId(7002, "Reference_Persist"); + public static final EventId Reference_Delete = new EventId(7003, "Reference_Delete"); + public static final EventId Reference_Search = new EventId(7004, "Reference_Search"); + + public static final EventId DescriptionTemplate_Query = new EventId(8000, "DescriptionTemplate_Query"); + public static final EventId DescriptionTemplate_Lookup = new EventId(8001, "DescriptionTemplate_Lookup"); + public static final EventId DescriptionTemplate_Persist = new EventId(8002, "DescriptionTemplate_Persist"); + public static final EventId DescriptionTemplate_Delete = new EventId(8003, "DescriptionTemplate_Delete"); + public static final EventId DescriptionTemplate_Clone = new EventId(8004, "DescriptionTemplate_Clone"); + public static final EventId DescriptionTemplate_PersistNewVersion = new EventId(8005, "DescriptionTemplate_PersistNewVersion"); + public static final EventId DescriptionTemplate_GetXml = new EventId(8006, "DescriptionTemplate_GetXml"); + public static final EventId DescriptionTemplate_Import = new EventId(8007, "DescriptionTemplate_Import"); + + public static final EventId SupportiveMaterial_Query = new EventId(9000, "SupportiveMaterial_Query"); + public static final EventId SupportiveMaterial_Lookup = new EventId(9001, "SupportiveMaterial_Lookup"); + public static final EventId SupportiveMaterial_Persist = new EventId(9002, "SupportiveMaterial_Persist"); + public static final EventId SupportiveMaterial_Delete = new EventId(9003, "SupportiveMaterial_Delete"); + + public static final EventId ReferenceType_Query = new EventId(10000, "ReferenceType_Query"); + public static final EventId ReferenceType_Lookup = new EventId(10001, "ReferenceType_Lookup"); + public static final EventId ReferenceType_Persist = new EventId(10002, "ReferenceType_Persist"); + public static final EventId ReferenceType_Delete = new EventId(10003, "ReferenceType_Delete"); + + public static final EventId User_Query = new EventId(11000, "User_Query"); + public static final EventId User_Lookup = new EventId(11001, "User_Lookup"); + public static final EventId User_Persist = new EventId(11002, "User_Persist"); + public static final EventId User_Delete = new EventId(11003, "User_Delete"); + public static final EventId User_LookupByEmail = new EventId(11004, "User_LookupByEmail"); + public static final EventId User_ExportCsv = new EventId(11005, "User_ExportCsv"); + public static final EventId User_PersistRoles = new EventId(11006, "User_PersistRoles"); + public static final EventId User_LanguageMine = new EventId(11007, "User_LanguageMine"); + public static final EventId User_TimezoneMine = new EventId(11008, "User_TimezoneMine"); + public static final EventId User_CultureMine = new EventId(11009, "User_CultureMine"); + public static final EventId User_MergeRequest = new EventId(11010, "User_MergeRequest"); + public static final EventId User_MergeConfirm = new EventId(11011, "User_MergeConfirm"); + public static final EventId User_RemoveCredentialRequest = new EventId(11012, "User_RemoveCredentialRequest"); + public static final EventId User_RemoveCredentialConfirm = new EventId(11013, "User_RemoveCredentialConfirm"); + public static final EventId User_DmpAssociatedQuery = new EventId(11014, "User_DmpAssociatedQuery"); + + public static final EventId Tenant_Query = new EventId(12000, "Tenant_Query"); + public static final EventId Tenant_Lookup = new EventId(12001, "Tenant_Lookup"); + public static final EventId Tenant_Persist = new EventId(12002, "Tenant_Persist"); + public static final EventId Tenant_Delete = new EventId(12003, "Tenant_Delete"); + + public static final EventId Language_Query = new EventId(13000, "Language_Query"); + public static final EventId Language_Lookup = new EventId(13001, "Language_Lookup"); + public static final EventId Language_Persist = new EventId(13002, "Language_Persist"); + public static final EventId Language_Delete = new EventId(13003, "Language_Delete"); + + public static final EventId StorageFile_Download = new EventId(14000, "StorageFile_Download"); + public static final EventId StorageFile_Upload = new EventId(14001, "StorageFile_Upload"); + public static final EventId StorageFile_Query = new EventId(14002, "StorageFile_Query"); + + public static final EventId Dashboard_MyRecentActivityItems = new EventId(15000, "Dashboard_MyRecentActivityItems"); + public static final EventId Dashboard_MyDashboardStatistics = new EventId(15001, "Dashboard_MyDashboardStatistics"); + public static final EventId Dashboard_PublicDashboardStatistics = new EventId(15002, "Dashboard_PublicDashboardStatistics"); + + public static final EventId Notification_Persist = new EventId(16000, "Notification_Persist"); + + public static final EventId Lock_Query = new EventId(17000, "Lock_Query"); + public static final EventId Lock_Lookup = new EventId(17001, "Lock_Lookup"); + public static final EventId Lock_Persist = new EventId(17002, "Lock_Persist"); + public static final EventId Lock_Delete = new EventId(17003, "Lock_Delete"); + public static final EventId Lock_IsLocked = new EventId(17004, "Lock_IsLocked"); + public static final EventId Lock_UnLocked = new EventId(17005, "Lock_UnLocked"); + public static final EventId Lock_Touched = new EventId(17006, "Lock_Touched"); + public static final EventId Lock_Locked = new EventId(17007, "Lock_Locked"); + + public static final EventId Deposit_GetAvailableRepositories = new EventId(18000, "Deposit_GetAvailableRepositories"); + public static final EventId Deposit_GetAccessToken = new EventId(18001, "Deposit_GetAccessToken"); + public static final EventId Deposit_Deposit = new EventId(18002, "Deposit_Deposit"); + public static final EventId Deposit_GetLogo = new EventId(18003, "Deposit_GetLogo"); + + public static final EventId Tag_Query = new EventId(19000, "Tag_Query"); + public static final EventId Tag_Lookup = new EventId(19001, "Tag_Lookup"); + public static final EventId Tag_Persist = new EventId(19002, "Tag_Persist"); + public static final EventId Tag_Delete = new EventId(19003, "Tag_Delete"); + + public static final EventId FileTransformer_GetAvailableConfigurations = new EventId(20000, "FileTransformer_GetAvailableConfigurations"); + + public static final EventId ContactSupport_Sent = new EventId(210000, "ContactSupport_Sent"); + public static final EventId ContactSupport_PublicSent = new EventId(210001, "ContactSupport_PublicSent"); + + public static final EventId Maintenance_GenerateElastic = new EventId(220000, "Maintenance_GenerateElastic"); + public static final EventId Maintenance_ClearElastic = new EventId(230000, "Maintenance_ClearElastic"); + public static final EventId Maintenance_SendUserTouchEvents = new EventId(230001, "Maintenance_SendUserTouchEvents"); + public static final EventId Maintenance_SendTenantTouchEvents = new EventId(230002, "Maintenance_SendTenantTouchEvents"); + + public static final EventId Principal_Lookup = new EventId(240000, "Principal_Lookup"); + public static final EventId Principal_MyTenants = new EventId(240001, "Principal_MyTenants"); + + public static final EventId GetSemantics = new EventId(250000, "GetSemantics"); + + public static final EventId PrefillingSource_Query = new EventId(260000, "PrefillingSource_Query"); + public static final EventId PrefillingSource_Lookup = new EventId(260001, "PrefillingSource_Lookup"); + public static final EventId PrefillingSource_Persist = new EventId(260002, "PrefillingSource_Persist"); + public static final EventId PrefillingSource_Delete = new EventId(260003, "PrefillingSource_Delete"); + public static final EventId PrefillingSource_Generate = new EventId(260004, "PrefillingSource_Generate"); + + public static final EventId TenantConfiguration_Query = new EventId(270000, "TenantConfiguration_Query"); + public static final EventId TenantConfiguration_Lookup = new EventId(270001, "TenantConfiguration_Lookup"); + public static final EventId TenantConfiguration_Persist = new EventId(270002, "TenantConfiguration_Persist"); + public static final EventId TenantConfiguration_Delete = new EventId(270003, "TenantConfiguration_Delete"); + public static final EventId TenantConfiguration_LookupByType = new EventId(270004, "TenantConfiguration_LookupByType"); + + + +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/AffiliatedAuthorizationRequirement.java b/backend/core/src/main/java/org/opencdmp/authorization/AffiliatedAuthorizationRequirement.java new file mode 100644 index 000000000..c5450f0f4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/AffiliatedAuthorizationRequirement.java @@ -0,0 +1,40 @@ +package org.opencdmp.authorization; + +import gr.cite.commons.web.authz.policy.AuthorizationRequirement; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class AffiliatedAuthorizationRequirement implements AuthorizationRequirement { + private final Set requiredPermissions; + private final boolean matchAll; + + public AffiliatedAuthorizationRequirement(Set requiredPermissions) { + this(false, requiredPermissions); + } + + public AffiliatedAuthorizationRequirement(String... requiredPermissions) { + this(false, requiredPermissions); + + } + + public AffiliatedAuthorizationRequirement(boolean matchAll, Set requiredPermissions) { + this.matchAll = matchAll; + this.requiredPermissions = requiredPermissions; + } + + public AffiliatedAuthorizationRequirement(boolean matchAll, String... requiredPermissions) { + this.requiredPermissions = new HashSet<>(); + this.matchAll = matchAll; + this.requiredPermissions.addAll(Arrays.stream(requiredPermissions).distinct().toList()); + } + + public Set getRequiredPermissions() { + return requiredPermissions; + } + + public boolean getMatchAll() { + return matchAll; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/AffiliatedResource.java b/backend/core/src/main/java/org/opencdmp/authorization/AffiliatedResource.java new file mode 100644 index 000000000..f6c469e92 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/AffiliatedResource.java @@ -0,0 +1,31 @@ +package org.opencdmp.authorization; + +import org.opencdmp.commons.enums.DmpUserRole; +import gr.cite.commons.web.authz.policy.AuthorizationResource; + +import java.util.HashSet; +import java.util.List; + +public class AffiliatedResource extends AuthorizationResource { + private HashSet dmpUserRoles; + + public AffiliatedResource() { + dmpUserRoles = new HashSet<>(); + } + + public AffiliatedResource(DmpUserRole dmpUserRole) { + this(List.of(dmpUserRole)); + } + + public AffiliatedResource(List dmpUserRoles) { + this.dmpUserRoles = new HashSet<>(dmpUserRoles); + } + + public HashSet getDmpUserRoles() { + return dmpUserRoles; + } + + public void setDmpUserRoles(HashSet dmpUserRoles) { + this.dmpUserRoles = dmpUserRoles; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/AuthorizationConfiguration.java b/backend/core/src/main/java/org/opencdmp/authorization/AuthorizationConfiguration.java new file mode 100644 index 000000000..9cf23acee --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/AuthorizationConfiguration.java @@ -0,0 +1,9 @@ +package org.opencdmp.authorization; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration("AppAuthorizationConfiguration") +@EnableConfigurationProperties(AuthorizationProperties.class) +public class AuthorizationConfiguration { +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/AuthorizationFlags.java b/backend/core/src/main/java/org/opencdmp/authorization/AuthorizationFlags.java new file mode 100644 index 000000000..516749ca3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/AuthorizationFlags.java @@ -0,0 +1,8 @@ +package org.opencdmp.authorization; + +import java.util.EnumSet; + +public enum AuthorizationFlags { + None, Permission, DmpAssociated, Public, Owner; + public static final EnumSet OwnerOrDmpAssociatedOrPermission = EnumSet.of(DmpAssociated, Permission, Owner); +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/AuthorizationProperties.java b/backend/core/src/main/java/org/opencdmp/authorization/AuthorizationProperties.java new file mode 100644 index 000000000..ef9670d7e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/AuthorizationProperties.java @@ -0,0 +1,50 @@ +package org.opencdmp.authorization; + + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.HashSet; +import java.util.List; + +@ConfigurationProperties(prefix = "authorization") +public class AuthorizationProperties { + + private String globalAdminRole; + + public String getGlobalAdminRole() { + return globalAdminRole; + } + + public void setGlobalAdminRole(String globalAdminRole) { + this.globalAdminRole = globalAdminRole; + } + private Boolean autoAssignGlobalAdminToNewTenants; + + public Boolean getAutoAssignGlobalAdminToNewTenants() { + return autoAssignGlobalAdminToNewTenants; + } + + public void setAutoAssignGlobalAdminToNewTenants(Boolean autoAssignGlobalAdminToNewTenants) { + this.autoAssignGlobalAdminToNewTenants = autoAssignGlobalAdminToNewTenants; + } + + private List allowedTenantRoles; + + public List getAllowedTenantRoles() { + return allowedTenantRoles; + } + + public void setAllowedTenantRoles(List allowedTenantRoles) { + this.allowedTenantRoles = allowedTenantRoles; + } + + private List allowedGlobalRoles; + + public List getAllowedGlobalRoles() { + return allowedGlobalRoles; + } + + public void setAllowedGlobalRoles(List allowedGlobalRoles) { + this.allowedGlobalRoles = allowedGlobalRoles; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/ClaimNames.java b/backend/core/src/main/java/org/opencdmp/authorization/ClaimNames.java new file mode 100644 index 000000000..c893b6ac8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/ClaimNames.java @@ -0,0 +1,9 @@ +package org.opencdmp.authorization; + +public class ClaimNames { + public static final String ExternalProviderName = "ExternalProviderName"; + public static final String TenantCodesClaimName = "TenantCodes"; + public static final String TenantClaimName = "x-tenant"; + public static final String GlobalRolesClaimName = "GlobalRoles"; + public static final String TenantRolesClaimName = "TenantRoles"; +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/OwnedAuthorizationRequirement.java b/backend/core/src/main/java/org/opencdmp/authorization/OwnedAuthorizationRequirement.java new file mode 100644 index 000000000..19ccdafcf --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/OwnedAuthorizationRequirement.java @@ -0,0 +1,6 @@ +package org.opencdmp.authorization; + +import gr.cite.commons.web.authz.policy.AuthorizationRequirement; + +public class OwnedAuthorizationRequirement implements AuthorizationRequirement { +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/OwnedResource.java b/backend/core/src/main/java/org/opencdmp/authorization/OwnedResource.java new file mode 100644 index 000000000..f0b7cc6f4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/OwnedResource.java @@ -0,0 +1,26 @@ +package org.opencdmp.authorization; + +import gr.cite.commons.web.authz.policy.AuthorizationResource; + +import java.util.List; +import java.util.UUID; + +public class OwnedResource extends AuthorizationResource { + private List userIds; + + public OwnedResource(UUID userId) { + this(List.of(userId)); + } + + public OwnedResource(List userIds) { + this.userIds = userIds; + } + + public List getUserIds() { + return userIds; + } + + public void setUserIds(List userIds) { + this.userIds = userIds; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/Permission.java b/backend/core/src/main/java/org/opencdmp/authorization/Permission.java new file mode 100644 index 000000000..23498eccf --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/Permission.java @@ -0,0 +1,222 @@ +package org.opencdmp.authorization; + +public final class Permission { + ///// + public static String DeferredAffiliation = "DeferredAffiliation"; + + //Public + public static String PublicBrowseDescription = "PublicBrowseDescription"; + public static String PublicBrowseDescriptionTemplate = "PublicBrowseDescriptionTemplate"; + public static String PublicBrowseDmp = "PublicBrowseDmp"; + public static String PublicBrowseDmpReference = "PublicBrowseDmpReference"; + public static String PublicBrowseDmpUser = "PublicBrowseDmpUser"; + public static String PublicBrowseReference = "PublicBrowseReference"; + public static String PublicBrowseUser = "PublicBrowseUser"; + public static String PublicBrowseDashboardStatistics = "PublicBrowseDashboardStatistics"; + public static String PublicSendContactSupport = "PublicSendContactSupport"; + public static String PublicBrowseReferenceType = "PublicBrowseReferenceType"; + //Elastic + public static String ManageElastic = "ManageElastic"; + //Queue Events + public static String ManageQueueEvents = "ManageQueueEvents"; + + + //Deposit + public static String BrowseDeposit = "BrowseDeposit"; + public static String EditDeposit = "BrowseDeposit"; + + + //Language + public static String BrowseLanguage = "BrowseLanguage"; + public static String EditLanguage = "EditLanguage"; + public static String DeleteLanguage = "DeleteLanguage"; + + + //NotificationTemplate + public static String BrowseNotificationTemplate = "BrowseNotificationTemplate"; + public static String EditNotificationTemplate = "EditNotificationTemplate"; + public static String DeleteNotificationTemplate = "DeleteNotificationTemplate"; + + //Language + public static String BrowseStatistics = "BrowseStatistics"; + public static String BrowsePublicStatistics = "BrowsePublicStatistics"; + + //DescriptionTemplate + public static String BrowseDescriptionTemplate = "BrowseDescriptionTemplate"; + public static String EditDescriptionTemplate = "EditDescriptionTemplate"; + public static String DeleteDescriptionTemplate = "DeleteDescriptionTemplate"; + public static String CloneDescriptionTemplate = "CloneDescriptionTemplate"; + public static String CreateNewVersionDescriptionTemplate = "CreateNewVersionDescriptionTemplate"; + public static String ImportDescriptionTemplate = "ImportDescriptionTemplate"; + public static String ExportDescriptionTemplate = "ExportDescriptionTemplate"; + + + + //User + public static String BrowseUser = "BrowseUser"; + public static String EditUser = "EditUser"; + public static String DeleteUser = "DeleteUser"; + public static String ExportUsers = "ExportUsers"; + public static String BrowseDmpAssociatedUser = "BrowseDmpAssociatedUser"; + + + //StorageFile + public static String BrowseStorageFile = "BrowseStorageFile"; + public static String EditStorageFile = "EditStorageFile"; + public static String DeleteStorageFile = "DeleteStorageFile"; + + //DescriptionTemplateType + public static String BrowseDescriptionTemplateType = "BrowseDescriptionTemplateType"; + public static String EditDescriptionTemplateType = "EditDescriptionTemplateType"; + public static String DeleteDescriptionTemplateType = "DeleteDescriptionTemplateType"; + + //Dmp + public static String BrowseDmp = "BrowseDmp"; + public static String EditDmp = "EditDmp"; + public static String NewDmp = "NewDmp"; + public static String DepositDmp = "DepositDmp"; + public static String DeleteDmp = "DeleteDmp"; + public static String CloneDmp = "CloneDmp"; + public static String ExportDmp = "ExportDmp"; + public static String CreateNewVersionDmp = "CreateNewVersionDmp"; + public static String FinalizeDmp = "FinalizeDmp"; + public static String UndoFinalizeDmp = "UndoFinalizeDmp"; + public static String AssignDmpUsers = "AssignDmpUsers"; + public static String InviteDmpUsers = "InviteDmpUsers"; + + //DmpBlueprint + public static String BrowseDmpBlueprint = "BrowseDmpBlueprint"; + public static String EditDmpBlueprint = "EditDmpBlueprint"; + public static String DeleteDmpBlueprint = "DeleteDmpBlueprint"; + public static String CloneDmpBlueprint = "CloneDmpBlueprint"; + public static String CreateNewVersionDmpBlueprint = "CreateNewVersionDmpBlueprint"; + public static String ExportDmpBlueprint = "ExportDmpBlueprint"; + public static String ImportDmpBlueprint = "ImportDmpBlueprint"; + + //DmpDescriptionTemplate + public static String BrowseDmpDescriptionTemplate = "BrowseDmpDescriptionTemplate"; + public static String EditDmpDescriptionTemplate = "EditDmpDescriptionTemplate"; + public static String DeleteDmpDescriptionTemplate = "DeleteDmpDescriptionTemplate"; + + //DmpUser + public static String BrowseDmpUser = "BrowseDmpUser"; + public static String EditDmpUser = "EditDmpUser"; + public static String DeleteDmpUser = "DeleteDmpUser"; + + //Description + public static String BrowseDescription = "BrowseDescription"; + public static String EditDescription = "EditDescription"; + public static String FinalizeDescription = "FinalizeDescription"; + public static String DeleteDescription = "DeleteDescription"; + public static String CloneDescription = "CloneDescription"; + + //DescriptionTag + public static String BrowseDescriptionTag = "BrowseDescriptionTag"; + public static String EditDescriptionTag = "EditDescriptionTag"; + public static String DeleteDescriptionTag = "DeleteDescriptionTag"; + + //DescriptionTemplateType + public static String BrowseEntityDoi = "BrowseEntityDoi"; + public static String EditEntityDoi = "EditEntityDoi"; + public static String DeleteEntityDoi = "DeleteEntityDoi"; + + //UserSettings + public static String BrowseUserSettings = "BrowseUserSettings"; + public static String EditUserSettings = "EditUserSettings"; + public static String DeleteUserSettings = "DeleteUserSettings"; + + + + //Reference + public static String BrowseReference = "BrowseReference"; + public static String EditReference = "EditReference"; + public static String DeleteReference = "DeleteReference"; + + //Tag + public static String BrowseTag = "BrowseTag"; + public static String EditTag = "EditTag"; + public static String DeleteTag = "DeleteTag"; + + //DmpReference + public static String BrowseDmpReference = "BrowseDmpReference"; + public static String EditDmpReference = "EditDmpReference"; + public static String DeleteDmpReference = "DeleteDmpReference"; + + //DescriptionReference + public static String BrowseDescriptionReference = "BrowseDescriptionReference"; + public static String EditDescriptionReference = "EditDescriptionReference"; + public static String DeleteDescriptionReference = "DeleteDescriptionReference"; + + //SupportiveMaterial + public static String BrowseSupportiveMaterial = "BrowseSupportiveMaterial"; + public static String EditSupportiveMaterial= "EditSupportiveMaterial"; + public static String DeleteSupportiveMaterial = "DeleteSupportiveMaterial"; + + //ReferenceType + public static String BrowseReferenceType = "BrowseReferenceType"; + public static String EditReferenceType= "EditReferenceType"; + public static String DeleteReferenceType = "DeleteReferenceType"; + + //Tenant + public static String BrowseTenant = "BrowseTenant"; + public static String EditTenant= "EditTenant"; + public static String DeleteTenant = "DeleteTenant"; + public static String AllowNoTenant = "AllowNoTenant"; + + //TenantConfiguration + public static String BrowseTenantConfiguration = "BrowseTenantConfiguration"; + public static String EditTenantConfiguration = "EditTenantConfiguration"; + public static String DeleteTenantConfiguration = "DeleteTenantConfiguration"; + + //TenantUser + public static String BrowseTenantUser = "BrowseTenantUser"; + public static String EditTenantUser = "EditTenantUser"; + public static String DeleteTenantUser = "DeleteTenantUser"; + + //Prefilling + public static String BrowsePrefilling = "BrowsePrefilling"; + + + //Lock + public static String BrowseLock = "BrowseLock"; + public static String EditLock = "EditLock"; + public static String DeleteLock = "DeleteLock"; + + //ContactSupport + public static String SendContactSupport = "SendContactSupport"; + + //ActionConfirmation + public static String BrowseActionConfirmation = "BrowseActionConfirmation"; + public static String EditActionConfirmation = "EditActionConfirmation"; + public static String DeleteActionConfirmation = "DeleteActionConfirmation"; + + //PrefillingSource + public static String BrowsePrefillingSource = "BrowsePrefillingSource"; + public static String EditPrefillingSource= "EditPrefillingSource"; + public static String DeletePrefillingSource = "DeletePrefillingSource"; + + + // UI Pages + public static String ViewDescriptionTemplateTypePage = "ViewDescriptionTemplateTypePage"; + public static String ViewMaintenancePage = "ViewMaintenancePage"; + public static String ViewNotificationPage = "ViewNotificationPage"; + public static String ViewNotificationTemplatePage = "ViewNotificationTemplatePage"; + public static String ViewSupportiveMaterialPage = "ViewSupportiveMaterialPage"; + public static String ViewLanguagePage = "ViewLanguagePage"; + public static String ViewUserPage = "ViewUserPage"; + public static String ViewTenantPage = "ViewTenantPage"; + public static String ViewPrefillingSourcePage = "ViewPrefillingSourcePage"; + public static String ViewReferenceTypePage = "ViewReferenceTypePage"; + public static String ViewReferencePage = "ViewReferencePage"; + public static String ViewEntityLockPage = "ViewEntityLockPage"; + public static String ViewDescriptionTemplatePage = "ViewDescriptionTemplatePage"; + public static String ViewDmpBlueprintPage = "ViewDmpBlueprintPage"; + public static String ViewPublicDescriptionPage = "ViewPublicDescriptionPage"; + public static String ViewPublicDmpPage = "ViewPublicDmpPage"; + public static String ViewMyDescriptionPage = "ViewMyDescriptionPage"; + public static String ViewMyDmpPage = "ViewMyDmpPage"; + public static String ViewHomePage = "ViewHomePage"; + public static String ViewMineInAppNotificationPage = "ViewMineInAppNotificationPage"; + public static String ViewTenantConfigurationPage = "ViewTenantConfigurationPage"; + +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/PermissionNameProvider.java b/backend/core/src/main/java/org/opencdmp/authorization/PermissionNameProvider.java new file mode 100644 index 000000000..0e84f5234 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/PermissionNameProvider.java @@ -0,0 +1,40 @@ +package org.opencdmp.authorization; + +import org.opencdmp.convention.ConventionService; +import org.opencdmp.service.deposit.DepositServiceImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Service; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) +public class PermissionNameProvider { + private static final Logger logger = LoggerFactory.getLogger(PermissionNameProvider.class); + private final List permissions; + + public PermissionNameProvider(ConventionService conventionService) { + this.permissions = new ArrayList<>(); + Class clazz = Permission.class; + for (Field f : clazz.getDeclaredFields()) { + if (Modifier.isStatic(f.getModifiers())) { + try { + Object value = f.get(null); + if (value != null && !conventionService.isNullOrEmpty((String)value)) this.permissions.add((String)value); + } catch (Exception e) { + logger.error("Can not load permission " + f.getName() + " " + e.getMessage()); + } + } + } + } + + public List getPermissions() { + return permissions; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AffiliationCacheOptions.java b/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AffiliationCacheOptions.java new file mode 100644 index 000000000..9bde2a0e2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AffiliationCacheOptions.java @@ -0,0 +1,10 @@ +package org.opencdmp.authorization.authorizationcontentresolver; + +import gr.cite.tools.cache.CacheOptions; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "cache.affiliation") +public class AffiliationCacheOptions extends CacheOptions { +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AffiliationCacheService.java b/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AffiliationCacheService.java new file mode 100644 index 000000000..5870f1e87 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AffiliationCacheService.java @@ -0,0 +1,108 @@ +package org.opencdmp.authorization.authorizationcontentresolver; + +import org.opencdmp.authorization.AffiliatedResource; +import org.opencdmp.convention.ConventionService; +import gr.cite.tools.cache.CacheService; +import gr.cite.tools.exception.MyApplicationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.UUID; + +@Service +public class AffiliationCacheService extends CacheService { + + public static class AffiliationCacheValue { + + public AffiliationCacheValue() { + } + + public AffiliationCacheValue(UUID tenantId, UUID userId, UUID entityId, String entityType, AffiliatedResource affiliatedResource) { + this.userId = userId; + this.tenantId = tenantId; + this.entityId = entityId; + this.entityType = entityType; + this.affiliatedResource = affiliatedResource; + } + + private UUID userId; + private UUID tenantId; + private UUID entityId; + private String entityType; + private AffiliatedResource affiliatedResource; + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } + + public UUID getEntityId() { + return entityId; + } + + public void setEntityId(UUID entityId) { + this.entityId = entityId; + } + + public String getEntityType() { + return entityType; + } + + public void setEntityType(String entityType) { + this.entityType = entityType; + } + + public AffiliatedResource getAffiliatedResource() { + return affiliatedResource; + } + + public void setAffiliatedResource(AffiliatedResource affiliatedResource) { + this.affiliatedResource = affiliatedResource; + } + } + + private final ConventionService conventionService; + @Autowired + public AffiliationCacheService(AffiliationCacheOptions options, ConventionService conventionService) { + super(options); + this.conventionService = conventionService; + } + + @Override + protected Class valueClass() { + return AffiliationCacheValue.class; + } + + @Override + public String keyOf(AffiliationCacheValue value) { + return this.buildKey(value.getTenantId(), value.getUserId(), value.getEntityId(), value.getEntityType()); + } + + + public String buildKey(UUID tenantId, UUID userId, UUID entityId, String entityType) { + if (userId == null) throw new IllegalArgumentException("userId id is required"); + if (entityId == null) throw new IllegalArgumentException("entityId id is required"); + if (this.conventionService.isNullOrEmpty(entityType)) throw new IllegalArgumentException("entityType id is required"); + + HashMap keyParts = new HashMap<>(); + keyParts.put("$user$", userId.toString().replace("-", "").toLowerCase(Locale.ROOT)); + keyParts.put("$tenant$", tenantId == null ? "" : userId.toString().replace("-", "").toLowerCase(Locale.ROOT)); + keyParts.put("$entity$", entityId.toString().replace("-", "").toLowerCase(Locale.ROOT)); + keyParts.put("$type$", entityType); + return this.generateKey(keyParts); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AuthorizationContentResolver.java b/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AuthorizationContentResolver.java new file mode 100644 index 000000000..a8793f40a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AuthorizationContentResolver.java @@ -0,0 +1,23 @@ +package org.opencdmp.authorization.authorizationcontentresolver; + +import org.opencdmp.authorization.AffiliatedResource; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public interface AuthorizationContentResolver { + List getPermissionNames(); + + AffiliatedResource dmpAffiliation(UUID id); + + Map dmpsAffiliation(List ids); + + AffiliatedResource descriptionAffiliation(UUID id); + + Map descriptionsAffiliation(List ids); + + AffiliatedResource descriptionsAffiliationBySection(UUID dmpId, UUID sectionId); + + Map descriptionsAffiliationBySections(UUID dmpId, List sectionIds); +} diff --git a/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AuthorizationContentResolverImpl.java b/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AuthorizationContentResolverImpl.java new file mode 100644 index 000000000..7f28686f9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/authorization/authorizationcontentresolver/AuthorizationContentResolverImpl.java @@ -0,0 +1,174 @@ +package org.opencdmp.authorization.authorizationcontentresolver; + +import org.opencdmp.authorization.AffiliatedResource; +import org.opencdmp.authorization.PermissionNameProvider; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.scope.user.UserScope; +import org.opencdmp.data.DescriptionEntity; +import org.opencdmp.data.DmpDescriptionTemplateEntity; +import org.opencdmp.data.DmpEntity; +import org.opencdmp.data.DmpUserEntity; +import org.opencdmp.model.Description; +import org.opencdmp.model.DmpDescriptionTemplate; +import org.opencdmp.model.DmpUser; +import org.opencdmp.query.DescriptionQuery; +import org.opencdmp.query.DmpDescriptionTemplateQuery; +import org.opencdmp.query.DmpUserQuery; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.fieldset.BaseFieldSet; +import org.springframework.stereotype.Service; +import org.springframework.web.context.annotation.RequestScope; + +import javax.management.InvalidApplicationException; +import java.util.*; +import java.util.stream.Collectors; + +@Service +@RequestScope +public class AuthorizationContentResolverImpl implements AuthorizationContentResolver { + private final QueryFactory queryFactory; + private final UserScope userScope; + private final TenantScope tenantScope; + private final AffiliationCacheService affiliationCacheService; + private final PermissionNameProvider permissionNameProvider; + public AuthorizationContentResolverImpl(QueryFactory queryFactory, UserScope userScope, TenantScope tenantScope, AffiliationCacheService affiliationCacheService, PermissionNameProvider permissionNameProvider) { + this.queryFactory = queryFactory; + this.userScope = userScope; + this.tenantScope = tenantScope; + this.affiliationCacheService = affiliationCacheService; + this.permissionNameProvider = permissionNameProvider; + } + + @Override + public List getPermissionNames() { + return permissionNameProvider.getPermissions(); + } + + @Override + public AffiliatedResource dmpAffiliation(UUID id) { + return this.dmpsAffiliation(List.of(id)).getOrDefault(id, new AffiliatedResource()); + } + @Override + public Map dmpsAffiliation(List ids){ + UUID userId = this.userScope.getUserIdSafe(); + Map affiliatedResources = new HashMap<>(); + for (UUID id : ids){ + affiliatedResources.put(id, new AffiliatedResource()); + } + if (userId == null || !userScope.isSet()) return affiliatedResources; + + List idsToResolve = this.getAffiliatedFromCache(ids, userId, affiliatedResources, DmpEntity.class.getSimpleName()); + if (idsToResolve.isEmpty()) return affiliatedResources; + + List dmpUsers = this.queryFactory.query(DmpUserQuery.class).dmpIds(ids).sectionIsEmpty(true).userIds(userId).isActives(IsActive.Active).collectAs(new BaseFieldSet().ensure(DmpUser._role).ensure(DmpUser._dmp)); + + for (DmpUserEntity dmpUser : dmpUsers){ + affiliatedResources.get(dmpUser.getDmpId()).getDmpUserRoles().add(dmpUser.getRole()); + } + + this.ensureAffiliatedInCache(idsToResolve, userId, affiliatedResources, DmpEntity.class.getSimpleName()); + return affiliatedResources; + } + + @Override + public AffiliatedResource descriptionAffiliation(UUID id) { + return this.descriptionsAffiliation(List.of(id)).getOrDefault(id, new AffiliatedResource()); + } + @Override + public Map descriptionsAffiliation(List ids){ + UUID userId = this.userScope.getUserIdSafe(); + Map affiliatedResources = new HashMap<>(); + for (UUID id : ids){ + affiliatedResources.put(id, new AffiliatedResource()); + } + if (userId == null || !userScope.isSet()) return affiliatedResources; + + List idsToResolve = this.getAffiliatedFromCache(ids, userId, affiliatedResources, DescriptionEntity.class.getSimpleName()); + if (idsToResolve.isEmpty()) return affiliatedResources; + + List descriptionEntities = this.queryFactory.query(DescriptionQuery.class).ids(ids).collectAs(new BaseFieldSet().ensure(Description._id).ensure(Description._dmpDescriptionTemplate).ensure(Description._dmp)); + List dmpDescriptionTemplateEntities = this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(descriptionEntities.stream().map(DescriptionEntity::getDmpDescriptionTemplateId).distinct().toList()).collectAs(new BaseFieldSet().ensure(DmpDescriptionTemplate._id).ensure(DmpDescriptionTemplate._sectionId)); + Map dmpDescriptionTemplateEntityMap = dmpDescriptionTemplateEntities == null ? new HashMap<>() : dmpDescriptionTemplateEntities.stream().collect(Collectors.toMap(DmpDescriptionTemplateEntity::getId, x-> x)); + + List dmpUsers = this.queryFactory.query(DmpUserQuery.class).descriptionIds(ids).userIds(userId).isActives(IsActive.Active).collectAs(new BaseFieldSet().ensure(DmpUser._role).ensure(DmpUser._sectionId).ensure(DmpUser._dmp)); + Map> dmpUsersMap = dmpUsers.stream().collect(Collectors.groupingBy(DmpUserEntity::getDmpId)); + + for (DescriptionEntity description : descriptionEntities){ + List dmpDescriptionUsers = dmpUsersMap.getOrDefault(description.getDmpId(), new ArrayList<>()); + for (DmpUserEntity dmpUser : dmpDescriptionUsers) { + if (dmpUser.getSectionId() == null) affiliatedResources.get(description.getId()).getDmpUserRoles().add(dmpUser.getRole()); + else { + DmpDescriptionTemplateEntity dmpDescriptionTemplateEntity = dmpDescriptionTemplateEntityMap.getOrDefault(description.getDmpDescriptionTemplateId(), null); + if (dmpDescriptionTemplateEntity != null && dmpUser.getSectionId().equals(dmpDescriptionTemplateEntity.getSectionId())){ + affiliatedResources.get(description.getId()).getDmpUserRoles().add(dmpUser.getRole()); + } + } + } + } + + this.ensureAffiliatedInCache(idsToResolve, userId, affiliatedResources, DescriptionEntity.class.getSimpleName()); + return affiliatedResources; + } + + @Override + public AffiliatedResource descriptionsAffiliationBySection(UUID dmpId, UUID sectionId){ + return this.descriptionsAffiliationBySections(dmpId, List.of(sectionId)).getOrDefault(sectionId, new AffiliatedResource()); + } + + @Override + public Map descriptionsAffiliationBySections(UUID dmpId, List sectionIds){ + UUID userId = this.userScope.getUserIdSafe(); + Map affiliatedResources = new HashMap<>(); + for (UUID id : sectionIds){ + affiliatedResources.put(id, new AffiliatedResource()); + } + if (userId == null || !userScope.isSet()) return affiliatedResources; + + List dmpUsers = this.queryFactory.query(DmpUserQuery.class).dmpIds(dmpId).userIds(userId).isActives(IsActive.Active).collectAs(new BaseFieldSet().ensure(DmpUser._role).ensure(DmpUser._sectionId).ensure(DmpUser._dmp)); + + for (UUID sectionId : sectionIds.stream().distinct().toList()){ + List dmpSectionUsers = dmpUsers.stream().filter(x-> x.getSectionId() == null || x.getSectionId().equals(sectionId)).toList(); + for (DmpUserEntity dmpUser : dmpSectionUsers) { + if (dmpUser.getSectionId() == null) affiliatedResources.get(sectionId).getDmpUserRoles().add(dmpUser.getRole()); + else { + if (dmpUser.getSectionId().equals(sectionId)){ + affiliatedResources.get(sectionId).getDmpUserRoles().add(dmpUser.getRole()); + } + } + } + } + + return affiliatedResources; + } + + private List getAffiliatedFromCache(List ids, UUID userId, Map affiliatedResources, String entityType) { + List idsToResolve = new ArrayList<>(); + for (UUID id : ids){ + AffiliationCacheService.AffiliationCacheValue cacheValue = null; + try { + cacheValue = this.affiliationCacheService.lookup(this.affiliationCacheService.buildKey(this.tenantScope.isSet() ? this.tenantScope.getTenant(): null, userId, id, entityType)); + } catch (InvalidApplicationException e) { + throw new RuntimeException(e); + } + if (cacheValue != null) affiliatedResources.put(id, cacheValue.getAffiliatedResource()); + else idsToResolve.add(id); + } + return idsToResolve; + } + + private void ensureAffiliatedInCache(List idsToResolve, UUID userId, Map affiliatedResources, String entityType) { + for (UUID id : idsToResolve){ + AffiliatedResource affiliatedResource = affiliatedResources.getOrDefault(id, null); + if (affiliatedResource != null) { + AffiliationCacheService.AffiliationCacheValue cacheValue = null; + try { + cacheValue = new AffiliationCacheService.AffiliationCacheValue(this.tenantScope.isSet() ? this.tenantScope.getTenant(): null, userId, id, entityType, affiliatedResource); + } catch (InvalidApplicationException e) { + throw new RuntimeException(e); + } + this.affiliationCacheService.put(cacheValue); + } + } + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/JsonHandlingService.java b/backend/core/src/main/java/org/opencdmp/commons/JsonHandlingService.java new file mode 100644 index 000000000..38c92f799 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/JsonHandlingService.java @@ -0,0 +1,56 @@ +package org.opencdmp.commons; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) +public class JsonHandlingService { + private final ObjectMapper objectMapper; + + public JsonHandlingService() { + this.objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + } + + public String toJson(Object item) throws JsonProcessingException { + if (item == null) return null; + return objectMapper.writeValueAsString(item); + } + + public String toJsonSafe(Object item) { + if (item == null) return null; + try { + return objectMapper.writeValueAsString(item); + } catch (Exception ex) { + return null; + } + } + + public T fromJson(Class type, String json) throws JsonProcessingException { + if (json == null) return null; + return objectMapper.readValue(json, type); + } + + public HashMap mapFromJson(String json) throws JsonProcessingException { + ObjectReader reader = objectMapper.readerFor(Map.class); + return reader.readValue(json); + } + + public T fromJsonSafe(Class type, String json) { + if (json == null) return null; + try { + return objectMapper.readValue(json, type); + } catch (Exception ex) { + return null; + } + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/XmlHandlingService.java b/backend/core/src/main/java/org/opencdmp/commons/XmlHandlingService.java new file mode 100644 index 000000000..d5c00a32b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/XmlHandlingService.java @@ -0,0 +1,103 @@ +package org.opencdmp.commons; + +import com.fasterxml.jackson.core.JsonProcessingException; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import javax.management.InvalidApplicationException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) +public class XmlHandlingService { + + public String generateXml(Document doc) throws TransformerException { + TransformerFactory tFact = TransformerFactory.newInstance(); + Transformer 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(); + } + + public String toXml(Object item) throws JAXBException { + + + JAXBContext context = JAXBContext.newInstance(item.getClass()); + Marshaller marshaller = context.createMarshaller(); + StringWriter out = new StringWriter(); + marshaller.marshal(item, out); + return out.toString(); + } + + public String toXmlSafe(Object item) { + if (item == null) return null; + try { + return this.toXml(item); + } catch (Exception ex) { + return null; + } + } + + public T fromXml(Class type, String xmlString) throws JAXBException, InstantiationException, IllegalAccessException, ParserConfigurationException, IOException, SAXException { + JAXBContext jaxbContext = JAXBContext.newInstance(type); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + + return (T) jaxbUnmarshaller.unmarshal(new StringReader(xmlString)); + } + + public T fromXmlSafe(Class type, String xmlString) { + if (xmlString == null) return null; + try { + return this.fromXml(type, xmlString); + } catch (Exception ex) { + return null; + } + } + +// public > T xmlSerializableFromXml(Class type, String xmlString) throws JAXBException, InstantiationException, IllegalAccessException, ParserConfigurationException, IOException, SAXException { +// T object = type.newInstance(); +// return (T) object.fromXml(this.getDocument(xmlString).getDocumentElement()); +// } +// +// public > T xmlSerializableFromXmlSafe(Class type, String xmlString) { +// if (xmlString == null) return null; +// try { +// return this.xmlSerializableFromXml(type, xmlString); +// } catch (Exception ex) { +// return null; +// } +// } + + public Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + InputSource inputStream = new InputSource(new StringReader(xml)); + return docBuilder.parse(inputStream); + } + + public Document getDocument() throws ParserConfigurationException { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + return docBuilder.newDocument(); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/ActionConfirmationStatus.java b/backend/core/src/main/java/org/opencdmp/commons/enums/ActionConfirmationStatus.java new file mode 100644 index 000000000..3268aba00 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/ActionConfirmationStatus.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum ActionConfirmationStatus implements DatabaseEnum { + + Requested((short) 0), + Accepted((short) 1); + + private final Short value; + + ActionConfirmationStatus(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(ActionConfirmationStatus.class); + + public static ActionConfirmationStatus of(Short i) { + return map.get(i); + } + + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/ActionConfirmationType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/ActionConfirmationType.java new file mode 100644 index 000000000..15eed455e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/ActionConfirmationType.java @@ -0,0 +1,33 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum ActionConfirmationType implements DatabaseEnum { + + MergeAccount((short) 0), + RemoveCredential((short) 1), + DmpInvitation((short) 2); + + private final Short value; + + ActionConfirmationType(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(ActionConfirmationType.class); + + public static ActionConfirmationType of(Short i) { + return map.get(i); + } + + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/ContactInfoType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/ContactInfoType.java new file mode 100644 index 000000000..93e4685a0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/ContactInfoType.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum ContactInfoType implements DatabaseEnum { + + Email((short) 0); + + private final Short value; + + ContactInfoType(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(ContactInfoType.class); + + public static ContactInfoType of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionStatus.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionStatus.java new file mode 100644 index 000000000..fa07e7708 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionStatus.java @@ -0,0 +1,31 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DescriptionStatus implements DatabaseEnum { + + Draft((short) 0), + Finalized((short) 1), + Canceled((short) 2); + + private final Short value; + + DescriptionStatus(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DescriptionStatus.class); + + public static DescriptionStatus of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionTemplateStatus.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionTemplateStatus.java new file mode 100644 index 000000000..c7dc5b8d8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionTemplateStatus.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DescriptionTemplateStatus implements DatabaseEnum { + + Draft((short) 0), + Finalized((short) 1); + + private final Short value; + + DescriptionTemplateStatus(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DescriptionTemplateStatus.class); + + public static DescriptionTemplateStatus of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionTemplateTypeStatus.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionTemplateTypeStatus.java new file mode 100644 index 000000000..ceade7c51 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionTemplateTypeStatus.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DescriptionTemplateTypeStatus implements DatabaseEnum { + + Draft((short) 0), + Finalized((short) 1); + + private final Short value; + + DescriptionTemplateTypeStatus(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DescriptionTemplateTypeStatus.class); + + public static DescriptionTemplateTypeStatus of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionTemplateVersionStatus.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionTemplateVersionStatus.java new file mode 100644 index 000000000..ca779106d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionTemplateVersionStatus.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DescriptionTemplateVersionStatus implements DatabaseEnum { + + Current((short) 0), + Previous((short) 1), + NotFinalized((short) 2); + + private final Short value; + + DescriptionTemplateVersionStatus(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DescriptionTemplateVersionStatus.class); + + public static DescriptionTemplateVersionStatus of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionValidationOutput.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionValidationOutput.java new file mode 100644 index 000000000..509b4dfcd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DescriptionValidationOutput.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DescriptionValidationOutput implements DatabaseEnum { + + Valid((short) 1), + Invalid((short) 2); + + private final Short value; + + DescriptionValidationOutput(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DescriptionValidationOutput.class); + + public static DescriptionValidationOutput of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DmpAccessType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpAccessType.java new file mode 100644 index 000000000..9418774db --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpAccessType.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DmpAccessType implements DatabaseEnum { + + Public((short) 0), Restricted((short) 1); + + private final Short value; + + DmpAccessType(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DmpAccessType.class); + + public static DmpAccessType of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintExtraFieldDataType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintExtraFieldDataType.java new file mode 100644 index 000000000..a22be8ee5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintExtraFieldDataType.java @@ -0,0 +1,33 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DmpBlueprintExtraFieldDataType implements DatabaseEnum { + + Text((short) 0), + RichTex((short) 1), + Date((short) 2), + Number((short) 3), + ; + + private final Short value; + + DmpBlueprintExtraFieldDataType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DmpBlueprintExtraFieldDataType.class); + + public static DmpBlueprintExtraFieldDataType of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintFieldCategory.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintFieldCategory.java new file mode 100644 index 000000000..2db7c80b2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintFieldCategory.java @@ -0,0 +1,35 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DmpBlueprintFieldCategory implements DatabaseEnum { + System((short) 0), + Extra((short) 1), + ReferenceType((short) 2); + + public static class Names { + public static final String System = "system"; + public static final String Extra = "extra"; + public static final String ReferenceType = "referenceType"; + } + + private final Short value; + + DmpBlueprintFieldCategory(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DmpBlueprintFieldCategory.class); + + public static DmpBlueprintFieldCategory of(Short i) { + return map.get(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintStatus.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintStatus.java new file mode 100644 index 000000000..d82f48001 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintStatus.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DmpBlueprintStatus implements DatabaseEnum { + + Draft((short) 0), + Finalized((short) 1); + + private final Short value; + + DmpBlueprintStatus(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DmpBlueprintStatus.class); + + public static DmpBlueprintStatus of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintSystemFieldType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintSystemFieldType.java new file mode 100644 index 000000000..a04509453 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintSystemFieldType.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DmpBlueprintSystemFieldType implements DatabaseEnum { + + Title((short)0), + Description((short)1), + Language((short)2), + Contact((short)3), + AccessRights((short)4), + User((short)5); + private final Short value; + + DmpBlueprintSystemFieldType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DmpBlueprintSystemFieldType.class); + + public static DmpBlueprintSystemFieldType of(Short i) { + return map.get(i); + } +} \ No newline at end of file diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintVersionStatus.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintVersionStatus.java new file mode 100644 index 000000000..80fa6c976 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpBlueprintVersionStatus.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DmpBlueprintVersionStatus implements DatabaseEnum { + + Current((short) 0), + Previous((short) 1), + NotFinalized((short) 2); + + private final Short value; + + DmpBlueprintVersionStatus(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DmpBlueprintVersionStatus.class); + + public static DmpBlueprintVersionStatus of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DmpStatus.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpStatus.java new file mode 100644 index 000000000..0cb33f250 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpStatus.java @@ -0,0 +1,31 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DmpStatus implements DatabaseEnum { + + Draft((short) 0), Finalized((short) 1); + + private final Short value; + + DmpStatus(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DmpStatus.class); + + public static DmpStatus of(Short i) { + return map.get(i); + } + + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DmpUserRole.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpUserRole.java new file mode 100644 index 000000000..b641e64d5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpUserRole.java @@ -0,0 +1,33 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DmpUserRole implements DatabaseEnum { + + Owner((short) 0), + User((short) 1), + DescriptionContributor((short) 2), + Reviewer((short) 3); + + private final Short value; + + DmpUserRole(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DmpUserRole.class); + + public static DmpUserRole of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DmpValidationOutput.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpValidationOutput.java new file mode 100644 index 000000000..2245df5b6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpValidationOutput.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DmpValidationOutput implements DatabaseEnum { + + Valid((short) 1), + Invalid((short) 2); + + private final Short value; + + DmpValidationOutput(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DmpValidationOutput.class); + + public static DmpValidationOutput of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/DmpVersionStatus.java b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpVersionStatus.java new file mode 100644 index 000000000..af6601322 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/DmpVersionStatus.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum DmpVersionStatus implements DatabaseEnum { + + Current((short) 0), + Previous((short) 1), + NotFinalized((short) 2); + + private final Short value; + + DmpVersionStatus(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(DmpVersionStatus.class); + + public static DmpVersionStatus of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/EntityType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/EntityType.java new file mode 100644 index 000000000..15ae70af4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/EntityType.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum EntityType implements DatabaseEnum { + + DMP((short) 0); + + private final Short value; + + EntityType(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(EntityType.class); + + public static EntityType of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/EnumUtils.java b/backend/core/src/main/java/org/opencdmp/commons/enums/EnumUtils.java new file mode 100644 index 000000000..074e11c6c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/EnumUtils.java @@ -0,0 +1,16 @@ +package org.opencdmp.commons.enums; + +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.HashMap; +import java.util.Map; + +public class EnumUtils { + public static & DatabaseEnum, EnumValue> Map getEnumValueMap(Class enumType){ + HashMap map = new HashMap<>(); + for (EnumType v : enumType.getEnumConstants()) { + map.put(v.getValue(), v); + } + return map; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/ExternalFetcherApiHTTPMethodType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/ExternalFetcherApiHTTPMethodType.java new file mode 100644 index 000000000..40741ed29 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/ExternalFetcherApiHTTPMethodType.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; +import jakarta.xml.bind.annotation.XmlEnumValue; + +import java.util.Map; + +public enum ExternalFetcherApiHTTPMethodType implements DatabaseEnum { + @XmlEnumValue(value = "0") + GET((short) 0), + @XmlEnumValue(value = "1") + POST((short) 1); + private final Short value; + + ExternalFetcherApiHTTPMethodType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(ExternalFetcherApiHTTPMethodType.class); + + public static ExternalFetcherApiHTTPMethodType of(Short i) { + return map.get(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/ExternalFetcherSourceType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/ExternalFetcherSourceType.java new file mode 100644 index 000000000..d2b27aceb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/ExternalFetcherSourceType.java @@ -0,0 +1,35 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; +import jakarta.xml.bind.annotation.XmlEnumValue; + +import java.util.Map; + +public enum ExternalFetcherSourceType implements DatabaseEnum { + @XmlEnumValue(value = "0") + API((short) 0), + @XmlEnumValue(value = "1") + STATIC((short) 1); + private final Short value; + + public static class Names { + public static final String API = "api"; + public static final String STATIC = "static"; + } + + ExternalFetcherSourceType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(ExternalFetcherSourceType.class); + + public static ExternalFetcherSourceType of(Short i) { + return map.get(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/FieldType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/FieldType.java new file mode 100644 index 000000000..9046c5e3a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/FieldType.java @@ -0,0 +1,82 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum FieldType implements DatabaseEnum { + SELECT(Names.Select), + BOOLEAN_DECISION(Names.BooleanDecision), + RADIO_BOX(Names.RadioBox), + INTERNAL_ENTRIES_DMPS(Names.InternalEntitiesDmps), + INTERNAL_ENTRIES_DESCRIPTIONS(Names.InternalEntitiesDescriptions), + CHECK_BOX(Names.CheckBox), + FREE_TEXT(Names.FreeText), + TEXT_AREA(Names.TextArea), + RICH_TEXT_AREA(Names.RichTextarea), + UPLOAD(Names.Upload), + DATE_PICKER(Names.DatePicker), + TAGS(Names.Tags), + REFERENCE_TYPES(Names.ReferenceTypes), + DATASET_IDENTIFIER(Names.DatasetIdentifier), + VALIDATION(Names.Validation); + private final String value; + + public static class Names { + public static final String Select = "select"; + public static final String BooleanDecision = "booleanDecision"; + public static final String RadioBox = "radiobox"; + public static final String InternalEntitiesDmps = "internalEntitiesDmps"; + public static final String InternalEntitiesDescriptions = "internalEntitiesDescriptions"; + public static final String CheckBox = "checkBox"; + public static final String FreeText = "freetext"; + public static final String TextArea = "textarea"; + public static final String RichTextarea = "richTextarea"; + public static final String Upload = "upload"; + public static final String DatePicker = "datePicker"; + public static final String Tags = "tags"; + public static final String DatasetIdentifier = "datasetIdentifier"; + public static final String Validation = "validation"; + public static final String ReferenceTypes = "referenceTypes"; + } + + FieldType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(FieldType.class); + + public static FieldType of(String i) { + return map.get(i); + } + + + public static boolean isReferenceType(FieldType fieldType){ + return fieldType.equals(FieldType.REFERENCE_TYPES); + } + + public static boolean isTextType(FieldType fieldType){ + return fieldType.equals(FieldType.FREE_TEXT) || fieldType.equals(FieldType.CHECK_BOX) || fieldType.equals(FieldType.TEXT_AREA) || + fieldType.equals(FieldType.RICH_TEXT_AREA) || fieldType.equals(FieldType.UPLOAD) || fieldType.equals(FieldType.BOOLEAN_DECISION) || + fieldType.equals(FieldType.RADIO_BOX); + } + + public static boolean isTextListType(FieldType fieldType){ + return fieldType.equals(FieldType.SELECT) || fieldType.equals(FieldType.TAGS) || fieldType.equals(FieldType.INTERNAL_ENTRIES_DMPS) || + fieldType.equals(FieldType.INTERNAL_ENTRIES_DESCRIPTIONS); + } + + public static boolean isDateType(FieldType fieldType){ + return fieldType.equals(FieldType.DATE_PICKER); + } + + public static boolean isExternalIdentifierType(FieldType fieldType){ + return fieldType.equals(FieldType.VALIDATION) || fieldType.equals(FieldType.DATASET_IDENTIFIER) ; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/FieldValidationType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/FieldValidationType.java new file mode 100644 index 000000000..abc2f5302 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/FieldValidationType.java @@ -0,0 +1,33 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public enum FieldValidationType implements DatabaseEnum { + + None((short) 0), + Required((short) 1), + Url((short) 2); + + private final Short value; + + FieldValidationType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(FieldValidationType.class); + + public static FieldValidationType of(Short i) { + return map.get(i); + } + +} \ No newline at end of file diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/IsActive.java b/backend/core/src/main/java/org/opencdmp/commons/enums/IsActive.java new file mode 100644 index 000000000..c329cc87c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/IsActive.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum IsActive implements DatabaseEnum { + + Inactive((short) 0), + Active((short) 1); + + private final Short value; + + IsActive(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(IsActive.class); + + public static IsActive of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/LockTargetType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/LockTargetType.java new file mode 100644 index 000000000..56b27b270 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/LockTargetType.java @@ -0,0 +1,29 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum LockTargetType implements DatabaseEnum { + Dmp((short) 0), + Description((short) 1), + DmpBlueprint((short) 2), + DescriptionTemplate((short) 3); + private final Short value; + + LockTargetType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(LockTargetType.class); + + public static LockTargetType of(Short i) { + return map.get(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/ProviderType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/ProviderType.java new file mode 100644 index 000000000..bc6c36d32 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/ProviderType.java @@ -0,0 +1,36 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.HashMap; +import java.util.Map; + +public enum ProviderType implements DatabaseEnum { + + Google (1), + Facebook ( 2), + Twitter ( 3), + LinkedIn (4), + NativeLogin ( 5), + B2Access ( 6), + ORCID (7), + OpenAire ( 8), + Configurable ( 9), + Zenodo (10), + Keycloack ( 128); + + private final Integer value; + + ProviderType(Integer value) { + this.value = value; + } + + @JsonValue + public Integer getValue() { return this.value; } + + private static final Map map = EnumUtils.getEnumValueMap(ProviderType.class); + public static ProviderType of(Integer i) { + return map.get(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/RecentActivityItemType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/RecentActivityItemType.java new file mode 100644 index 000000000..e752e2c85 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/RecentActivityItemType.java @@ -0,0 +1,31 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum RecentActivityItemType implements DatabaseEnum { + + Dmp((short) 0), + Description((short) 1); + + private final Short value; + + RecentActivityItemType(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(RecentActivityItemType.class); + + public static RecentActivityItemType of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/RecentActivityOrder.java b/backend/core/src/main/java/org/opencdmp/commons/enums/RecentActivityOrder.java new file mode 100644 index 000000000..f115e9efe --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/RecentActivityOrder.java @@ -0,0 +1,31 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum RecentActivityOrder implements DatabaseEnum { + UpdatedAt((short) 0), + Label((short) 1), + Status((short) 2); + + private final Short value; + + RecentActivityOrder(Short value) { + this.value = value; + } + + @Override + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(RecentActivityOrder.class); + + public static RecentActivityOrder of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/ReferenceFieldDataType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/ReferenceFieldDataType.java new file mode 100644 index 000000000..93dd9b555 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/ReferenceFieldDataType.java @@ -0,0 +1,27 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum ReferenceFieldDataType implements DatabaseEnum { + Text((short) 0), + Date((short) 1); + private final Short value; + + ReferenceFieldDataType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(ReferenceFieldDataType.class); + + public static ReferenceFieldDataType of(Short i) { + return map.get(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/ReferenceSourceType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/ReferenceSourceType.java new file mode 100644 index 000000000..08a34b1ec --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/ReferenceSourceType.java @@ -0,0 +1,28 @@ +package org.opencdmp.commons.enums; + +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum ReferenceSourceType implements DatabaseEnum { + + Internal((short) 0), + External((short) 1); + + private final Short value; + + ReferenceSourceType(Short value) { + this.value = value; + } + + @Override + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(ReferenceSourceType.class); + + public static ReferenceSourceType of(Short i) { + return map.get(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/StorageFilePermission.java b/backend/core/src/main/java/org/opencdmp/commons/enums/StorageFilePermission.java new file mode 100644 index 000000000..04095a214 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/StorageFilePermission.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum StorageFilePermission implements DatabaseEnum { + + Read((short) 0), + Write((short) 1); + + private final Short value; + + StorageFilePermission(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(StorageFilePermission.class); + + public static StorageFilePermission of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/StorageType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/StorageType.java new file mode 100644 index 000000000..b0644f0ea --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/StorageType.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum StorageType implements DatabaseEnum { + + Temp((short) 0), + Main((short) 1), + Transformer((short)2), + Deposit((short)3); + + private final Short value; + + StorageType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(StorageType.class); + + public static StorageType of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/SupportiveMaterialFieldType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/SupportiveMaterialFieldType.java new file mode 100644 index 000000000..0a34bc2c6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/SupportiveMaterialFieldType.java @@ -0,0 +1,31 @@ +package org.opencdmp.commons.enums; + +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum SupportiveMaterialFieldType implements DatabaseEnum { + + Faq((short) 0), + About((short) 1), + Glossary((short) 2), + TermsOfService((short) 3), + UserGuide((short) 4); + + private final Short value; + + SupportiveMaterialFieldType(Short value) { + this.value = value; + } + + @Override + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(SupportiveMaterialFieldType.class); + + public static SupportiveMaterialFieldType of(Short i) { + return map.get(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/TenantConfigurationType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/TenantConfigurationType.java new file mode 100644 index 000000000..1bfa0dfff --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/TenantConfigurationType.java @@ -0,0 +1,33 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum TenantConfigurationType implements DatabaseEnum { + + DepositPlugins((short) 0), + FileTransformerPlugins((short) 1), + DefaultUserLocale((short) 2), + Logo((short) 3), + CssColors((short) 4); + + private final Short value; + + TenantConfigurationType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(TenantConfigurationType.class); + + public static TenantConfigurationType of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/UserDescriptionTemplateRole.java b/backend/core/src/main/java/org/opencdmp/commons/enums/UserDescriptionTemplateRole.java new file mode 100644 index 000000000..fc75dca7d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/UserDescriptionTemplateRole.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum UserDescriptionTemplateRole implements DatabaseEnum { + + Owner((short) 0), + Member((short) 1); + + private final Short value; + + UserDescriptionTemplateRole(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(UserDescriptionTemplateRole.class); + + public static UserDescriptionTemplateRole of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/UserSettingsType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/UserSettingsType.java new file mode 100644 index 000000000..0a60f575f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/UserSettingsType.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum UserSettingsType implements DatabaseEnum { + + Settings((short) 0), + Config((short) 1); + + private final Short value; + + UserSettingsType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(UserSettingsType.class); + + public static UserSettingsType of(Short i) { + return map.get(i); + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/commons/enums/notification/NotificationContactType.java b/backend/core/src/main/java/org/opencdmp/commons/enums/notification/NotificationContactType.java new file mode 100644 index 000000000..af180f8be --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/enums/notification/NotificationContactType.java @@ -0,0 +1,33 @@ +package org.opencdmp.commons.enums.notification; + +import com.fasterxml.jackson.annotation.JsonValue; +import org.opencdmp.commons.enums.EnumUtils; +import org.opencdmp.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum NotificationContactType implements DatabaseEnum { + + EMAIL((short) 0), + SLACK_BROADCAST((short) 1), + SMS((short) 2), + IN_APP((short) 3); + + private final Short value; + + NotificationContactType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(NotificationContactType.class); + + public static NotificationContactType of(Short i) { + return map.get(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/fake/FakeRequestAttributes.java b/backend/core/src/main/java/org/opencdmp/commons/fake/FakeRequestAttributes.java new file mode 100644 index 000000000..a258f23de --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/fake/FakeRequestAttributes.java @@ -0,0 +1,126 @@ +package org.opencdmp.commons.fake; + +import org.jetbrains.annotations.NotNull; +import org.springframework.util.Assert; +import org.springframework.web.context.request.RequestAttributes; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +public class FakeRequestAttributes implements RequestAttributes { + private final Map requestAttributeMap = new HashMap<>(); + private final Map requestDestructionCallbacks = new LinkedHashMap<>(8); + private volatile boolean requestActive = true; + + @Override + public Object getAttribute(@NotNull String name, int scope) { + if (scope == RequestAttributes.SCOPE_REQUEST) { + if (!isRequestActive()) { + throw new IllegalStateException("Cannot ask for request attribute - request is not active anymore!"); + } + return this.requestAttributeMap.get(name); + } else { + throw new IllegalStateException("Only " + RequestAttributes.SCOPE_REQUEST + " allowed for " + FakeRequestAttributes.class.getSimpleName()); + } + } + + @Override + public void setAttribute(@NotNull String name, @NotNull Object value, int scope) { + if (scope == RequestAttributes.SCOPE_REQUEST) { + if (!isRequestActive()) { + throw new IllegalStateException("Cannot set request attribute - request is not active anymore!"); + } + this.requestAttributeMap.put(name, value); + } else { + throw new IllegalStateException("Only " + RequestAttributes.SCOPE_REQUEST + " allowed for " + FakeRequestAttributes.class.getSimpleName()); + } + } + + @Override + public void removeAttribute(@NotNull String name, int scope) { + if (scope == RequestAttributes.SCOPE_REQUEST) { + if (isRequestActive()) { + removeRequestDestructionCallback(name); + this.requestAttributeMap.remove(name); + } + } else { + throw new IllegalStateException("Only " + RequestAttributes.SCOPE_REQUEST + " allowed for " + FakeRequestAttributes.class.getSimpleName()); + } + } + + @Override + public String @NotNull [] getAttributeNames(int scope) { + if (scope == RequestAttributes.SCOPE_REQUEST) { + if (!isRequestActive()) { + throw new IllegalStateException("Cannot ask for request attributes - request is not active anymore!"); + } + return this.requestAttributeMap.keySet().toArray(new String[0]); + } else { + throw new IllegalStateException("Only " + RequestAttributes.SCOPE_REQUEST + " allowed for " + FakeRequestAttributes.class.getSimpleName()); + } + //return new String[0]; + } + + @Override + public void registerDestructionCallback(@NotNull String name, @NotNull Runnable callback, int scope) { + if (scope == SCOPE_REQUEST) { + registerRequestDestructionCallback(name, callback); + } else { + throw new IllegalStateException("Only " + RequestAttributes.SCOPE_REQUEST + " allowed for " + FakeRequestAttributes.class.getSimpleName()); + } + } + + protected final void registerRequestDestructionCallback(String name, Runnable callback) { + Assert.notNull(name, "Name must not be null"); + Assert.notNull(callback, "Callback must not be null"); + synchronized (this.requestDestructionCallbacks) { + this.requestDestructionCallbacks.put(name, callback); + } + } + + @Override + public Object resolveReference(@NotNull String key) { + // Not supported + return null; + } + + @Override + public @NotNull String getSessionId() { + return ""; + } + + @Override + public @NotNull Object getSessionMutex() { + return new Object(); + } + + public void requestCompleted() { + executeRequestDestructionCallbacks(); + for (String name : getAttributeNames(RequestAttributes.SCOPE_REQUEST)) { + this.removeAttribute(name, RequestAttributes.SCOPE_REQUEST); + } + this.requestActive = false; + } + + private boolean isRequestActive() { + return this.requestActive; + } + + + private void removeRequestDestructionCallback(String name) { + Assert.notNull(name, "Name must not be null"); + synchronized (this.requestDestructionCallbacks) { + this.requestDestructionCallbacks.remove(name); + } + } + + private void executeRequestDestructionCallbacks() { + synchronized (this.requestDestructionCallbacks) { + for (Runnable runnable : this.requestDestructionCallbacks.values()) { + runnable.run(); + } + this.requestDestructionCallbacks.clear(); + } + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/fake/FakeRequestScope.java b/backend/core/src/main/java/org/opencdmp/commons/fake/FakeRequestScope.java new file mode 100644 index 000000000..7cfc9ae9c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/fake/FakeRequestScope.java @@ -0,0 +1,44 @@ +package org.opencdmp.commons.fake; + +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; + +import java.io.Closeable; + +public class FakeRequestScope implements Closeable { + private RequestAttributes initialRequestAttributes = null; + private FakeRequestAttributes currentRequestAttributes = null; + boolean isInUse = false; + + public FakeRequestScope() { + this.reset(); + } + + public final void reset() { + this.close(); + this.isInUse = true; + + this.initialRequestAttributes = RequestContextHolder.getRequestAttributes(); + this.currentRequestAttributes = new FakeRequestAttributes(); + RequestContextHolder.setRequestAttributes(this.currentRequestAttributes); + } + + @Override + public void close() { + if (!this.isInUse) + return; + this.isInUse = false; + + if (initialRequestAttributes != null) + RequestContextHolder.setRequestAttributes(initialRequestAttributes); + else + RequestContextHolder.resetRequestAttributes(); + + if (currentRequestAttributes != null) + currentRequestAttributes.requestCompleted(); + + this.initialRequestAttributes = null; + this.currentRequestAttributes = null; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/locale/LocaleConfiguration.java b/backend/core/src/main/java/org/opencdmp/commons/locale/LocaleConfiguration.java new file mode 100644 index 000000000..197a63ea8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/locale/LocaleConfiguration.java @@ -0,0 +1,20 @@ +package org.opencdmp.commons.locale; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties(LocaleProperties.class) +public class LocaleConfiguration { + private final LocaleProperties properties; + + @Autowired + public LocaleConfiguration(LocaleProperties properties) { + this.properties = properties; + } + + public LocaleProperties getProperties() { + return properties; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/locale/LocaleProperties.java b/backend/core/src/main/java/org/opencdmp/commons/locale/LocaleProperties.java new file mode 100644 index 000000000..7ddf7ae04 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/locale/LocaleProperties.java @@ -0,0 +1,34 @@ +package org.opencdmp.commons.locale; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "locale") +public class LocaleProperties { + private String timezone; + private String language; + private String culture; + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getCulture() { + return culture; + } + + public void setCulture(String culture) { + this.culture = culture; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/lock/LockByKeyManager.java b/backend/core/src/main/java/org/opencdmp/commons/lock/LockByKeyManager.java new file mode 100644 index 000000000..c65faec63 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/lock/LockByKeyManager.java @@ -0,0 +1,58 @@ +package org.opencdmp.commons.lock; + +import org.springframework.stereotype.Service; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.ReentrantLock; + +@Service +public class LockByKeyManager { + + private static class LockWrapper { + private final ReentrantLock lock = new ReentrantLock(); + private final AtomicInteger numberOfThreadsInQueue = new AtomicInteger(1); + + private LockWrapper addThreadInQueue() { + numberOfThreadsInQueue.incrementAndGet(); + return this; + } + + private int removeThreadFromQueue() { + return numberOfThreadsInQueue.decrementAndGet(); + } + + } + + private static ConcurrentHashMap locks = new ConcurrentHashMap(); + + public void lock(String key) { + LockWrapper lockWrapper = locks.compute(key, (k, v) -> v == null ? new LockWrapper() : v.addThreadInQueue()); + lockWrapper.lock.lock(); + } + + public boolean tryLock(String key, long timeout, TimeUnit unit) throws InterruptedException { + LockWrapper lockWrapper = null; + try { + lockWrapper = locks.compute(key, (k, v) -> v == null ? new LockWrapper() : v.addThreadInQueue()); + return lockWrapper.lock.tryLock(timeout, unit); + } catch (Exception ex){ + if (lockWrapper != null && lockWrapper.removeThreadFromQueue() == 0) { + // NB : We pass in the specific value to remove to handle the case where another thread would queue right before the removal + locks.remove(key, lockWrapper); + } + throw ex; + } + } + + public void unlock(String key) { + LockWrapper lockWrapper = locks.get(key); + lockWrapper.lock.unlock(); + if (lockWrapper.removeThreadFromQueue() == 0) { + // NB : We pass in the specific value to remove to handle the case where another thread would queue right before the removal + locks.remove(key, lockWrapper); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/metrics/MetricLabels.java b/backend/core/src/main/java/org/opencdmp/commons/metrics/MetricLabels.java new file mode 100644 index 000000000..a09721df1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/metrics/MetricLabels.java @@ -0,0 +1,21 @@ +package org.opencdmp.commons.metrics; + +public class MetricLabels { + + public static final String DRAFT = "draft"; + + public static final String FINALIZED = "finalized"; + + public static final String PUBLISHED = "published"; + + public static final String DOIED = "doied"; + + public static final String ACTIVE = "active"; + + public static final String USED = "used"; + + public static final String LOGGEDIN = "loggedin"; + + public static final String TOTAL = "total"; + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/metrics/MetricNames.java b/backend/core/src/main/java/org/opencdmp/commons/metrics/MetricNames.java new file mode 100644 index 000000000..aa263e1d9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/metrics/MetricNames.java @@ -0,0 +1,28 @@ +package org.opencdmp.commons.metrics; + +public class MetricNames { + + public static final String DATASET_TEMPLATE = "argos_dmp_templates"; + + public static final String INSTALLATIONS = "installations"; + + public static final String USERS = "argos_users"; + + public static final String DMP = "argos_managed_dmps"; + + public static final String DATASET = "argos_managed_dataset_descriptions"; + + public static final String RESEARCHERS = "argos_researchers"; + + public static final String PROJECTS = "argos_projects"; + + public static final String FUNDERS = "argos_funders"; + + public static final String GRANTS = "argos_grants"; + + public static final String LANGUAGES = "argos_languages"; + + public static final String DMP_WITH_GRANT = "argos_managed_dmps_with_grantid"; + + public static final String NEXUS_PREFIX = "nexus_"; +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/notification/NotificationConfiguration.java b/backend/core/src/main/java/org/opencdmp/commons/notification/NotificationConfiguration.java new file mode 100644 index 000000000..990f602f5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/notification/NotificationConfiguration.java @@ -0,0 +1,20 @@ +package org.opencdmp.commons.notification; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties(NotificationProperties.class) +public class NotificationConfiguration { + private final NotificationProperties properties; + + @Autowired + public NotificationConfiguration(NotificationProperties properties) { + this.properties = properties; + } + + public NotificationProperties getProperties() { + return properties; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/notification/NotificationProperties.java b/backend/core/src/main/java/org/opencdmp/commons/notification/NotificationProperties.java new file mode 100644 index 000000000..4da201dcf --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/notification/NotificationProperties.java @@ -0,0 +1,136 @@ +package org.opencdmp.commons.notification; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.UUID; + +@ConfigurationProperties(prefix = "notification") +public class NotificationProperties { + + private UUID dmpInvitationExternalUserType; + private UUID dmpInvitationExistingUserType; + private UUID dmpModifiedType; + private UUID dmpFinalisedType; + private UUID descriptionModifiedType; + private UUID descriptionFinalisedType; + private UUID mergeAccountConfirmationType; + private UUID removeCredentialConfirmationType; + private UUID dmpDepositType; + private UUID descriptionTemplateInvitationType; + private UUID contactSupportType; + private UUID publicContactSupportType; + private int emailExpirationTimeSeconds; + private String contactSupportEmail; + + public UUID getDmpInvitationExternalUserType() { + return dmpInvitationExternalUserType; + } + + public void setDmpInvitationExternalUserType(UUID dmpInvitationExternalUserType) { + this.dmpInvitationExternalUserType = dmpInvitationExternalUserType; + } + + public UUID getDmpInvitationExistingUserType() { + return dmpInvitationExistingUserType; + } + + public void setDmpInvitationExistingUserType(UUID dmpInvitationExistingUserType) { + this.dmpInvitationExistingUserType = dmpInvitationExistingUserType; + } + + public UUID getDmpModifiedType() { + return dmpModifiedType; + } + + public void setDmpModifiedType(UUID dmpModifiedType) { + this.dmpModifiedType = dmpModifiedType; + } + + public UUID getDmpFinalisedType() { + return dmpFinalisedType; + } + + public void setDmpFinalisedType(UUID dmpFinalisedType) { + this.dmpFinalisedType = dmpFinalisedType; + } + + public UUID getDescriptionModifiedType() { + return descriptionModifiedType; + } + + public void setDescriptionModifiedType(UUID descriptionModifiedType) { + this.descriptionModifiedType = descriptionModifiedType; + } + + public UUID getDescriptionFinalisedType() { + return descriptionFinalisedType; + } + + public void setDescriptionFinalisedType(UUID descriptionFinalisedType) { + this.descriptionFinalisedType = descriptionFinalisedType; + } + + public UUID getMergeAccountConfirmationType() { + return mergeAccountConfirmationType; + } + + public void setMergeAccountConfirmationType(UUID mergeAccountConfirmationType) { + this.mergeAccountConfirmationType = mergeAccountConfirmationType; + } + + public UUID getRemoveCredentialConfirmationType() { + return removeCredentialConfirmationType; + } + + public void setRemoveCredentialConfirmationType(UUID removeCredentialConfirmationType) { + this.removeCredentialConfirmationType = removeCredentialConfirmationType; + } + + public UUID getDmpDepositType() { + return dmpDepositType; + } + + public void setDmpDepositType(UUID dmpDepositType) { + this.dmpDepositType = dmpDepositType; + } + + public UUID getDescriptionTemplateInvitationType() { + return descriptionTemplateInvitationType; + } + + public void setDescriptionTemplateInvitationType(UUID descriptionTemplateInvitationType) { + this.descriptionTemplateInvitationType = descriptionTemplateInvitationType; + } + + public int getEmailExpirationTimeSeconds() { + return emailExpirationTimeSeconds; + } + + public void setEmailExpirationTimeSeconds(int emailExpirationTimeSeconds) { + this.emailExpirationTimeSeconds = emailExpirationTimeSeconds; + } + + public UUID getContactSupportType() { + return contactSupportType; + } + + public void setContactSupportType(UUID contactSupportType) { + this.contactSupportType = contactSupportType; + } + + public UUID getPublicContactSupportType() { + return publicContactSupportType; + } + + public void setPublicContactSupportType(UUID publicContactSupportType) { + this.publicContactSupportType = publicContactSupportType; + } + + public String getContactSupportEmail() { + return contactSupportEmail; + } + + public void setContactSupportEmail(String contactSupportEmail) { + this.contactSupportEmail = contactSupportEmail; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/MultitenancyConfiguration.java b/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/MultitenancyConfiguration.java new file mode 100644 index 000000000..dd7c17666 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/MultitenancyConfiguration.java @@ -0,0 +1,9 @@ +package org.opencdmp.commons.scope.tenant; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties(MultitenancyProperties.class) +public class MultitenancyConfiguration { +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/MultitenancyProperties.java b/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/MultitenancyProperties.java new file mode 100644 index 000000000..ce18b6c6c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/MultitenancyProperties.java @@ -0,0 +1,25 @@ +package org.opencdmp.commons.scope.tenant; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "tenant.multitenancy") +public class MultitenancyProperties { + private boolean isMultitenant; + private String defaultTenantCode; + + public boolean isMultitenant() { + return isMultitenant; + } + + public void setIsMultitenant(boolean multitenant) { + isMultitenant = multitenant; + } + + public String getDefaultTenantCode() { + return defaultTenantCode; + } + + public void setDefaultTenantCode(String defaultTenantCode) { + this.defaultTenantCode = defaultTenantCode; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/TenantScope.java b/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/TenantScope.java new file mode 100644 index 000000000..a70cb1470 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/TenantScope.java @@ -0,0 +1,126 @@ +package org.opencdmp.commons.scope.tenant; + +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.EntityManager; +import org.hibernate.Session; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.context.annotation.RequestScope; + +import javax.management.InvalidApplicationException; + +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; + +@Component +@RequestScope +public class TenantScope { + public static final String TenantReplaceParameter = "::TenantCode::"; + private final MultitenancyProperties multitenancy; + private final AtomicReference tenant = new AtomicReference<>(); + private final AtomicReference tenantCode = new AtomicReference<>(); + private final AtomicReference initialTenant = new AtomicReference<>(); + private final AtomicReference initialTenantCode = new AtomicReference<>(); + + @Autowired + public TenantScope(MultitenancyProperties multitenancy) { + this.multitenancy = multitenancy; + } + + public Boolean isMultitenant() { + return multitenancy.isMultitenant(); + } + + public String getDefaultTenantCode() { + return multitenancy.getDefaultTenantCode(); + } + + public Boolean isSet() { + if (!this.isMultitenant()) + return Boolean.TRUE; + return this.tenant.get() != null || this.isDefaultTenant(); + } + + public Boolean isDefaultTenant() { + if (!this.isMultitenant()) + return Boolean.TRUE; + return this.multitenancy.getDefaultTenantCode().equalsIgnoreCase(this.tenantCode.get()); + } + + public UUID getTenant() throws InvalidApplicationException { + if (!this.isMultitenant()) + return null; + if (this.tenant.get() == null && !this.isDefaultTenant()) + throw new InvalidApplicationException("tenant not set"); + return this.isDefaultTenant() ? null : this.tenant.get(); + } + + public String getTenantCode() throws InvalidApplicationException { + if (!this.isMultitenant()) + return null; + if (this.tenantCode.get() == null) + throw new InvalidApplicationException("tenant not set"); + return this.tenantCode.get(); + } + + public void setTempTenant(EntityManager entityManager, UUID tenant, String tenantCode) { + this.tenant.set(tenant); + this.tenantCode.set(tenantCode); + + entityManager + .unwrap(Session.class) + .disableFilter(TenantScopedBaseEntity.TENANT_FILTER); + + entityManager + .unwrap(Session.class) + .disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); + if (this.tenant.get() != null || this.isDefaultTenant()) { + if(!this.isDefaultTenant()) { + entityManager + .unwrap(Session.class) + .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) + .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenant.get().toString()); + } else { + entityManager + .unwrap(Session.class) + .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); + } + } + } + + public void removeTempTenant(EntityManager entityManager) { + this.tenant.set(this.initialTenant.get()); + this.tenantCode.set(this.initialTenantCode.get()); + + + entityManager + .unwrap(Session.class) + .disableFilter(TenantScopedBaseEntity.TENANT_FILTER); + + entityManager + .unwrap(Session.class) + .disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); + if (this.initialTenant.get() != null || this.isDefaultTenant()) { + if(!this.isDefaultTenant()) { + entityManager + .unwrap(Session.class) + .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) + .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenant.get().toString()); + } else { + entityManager + .unwrap(Session.class) + .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); + } + } + } + + public void setTenant(UUID tenant, String tenantCode) { + if (this.isMultitenant()) { + this.tenant.set(tenant); + this.initialTenant.set(tenant); + this.tenantCode.set(tenantCode); + this.initialTenantCode.set(tenantCode); + } + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/TenantScoped.java b/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/TenantScoped.java new file mode 100644 index 000000000..7735776b6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/scope/tenant/TenantScoped.java @@ -0,0 +1,9 @@ +package org.opencdmp.commons.scope.tenant; + +import java.beans.Transient; +import java.util.UUID; + +public interface TenantScoped { + void setTenantId(UUID tenantId); + UUID getTenantId(); +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/scope/user/UserScope.java b/backend/core/src/main/java/org/opencdmp/commons/scope/user/UserScope.java new file mode 100644 index 000000000..5de65380f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/scope/user/UserScope.java @@ -0,0 +1,35 @@ +package org.opencdmp.commons.scope.user; + +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.context.annotation.RequestScope; + +import javax.management.InvalidApplicationException; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; + +@Component +@RequestScope +public class UserScope { + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserScope.class)); + private final AtomicReference userId = new AtomicReference<>(); + + public Boolean isSet() { + return this.userId.get() != null; + } + + public UUID getUserId() throws InvalidApplicationException { + if (this.userId.get() == null) throw new InvalidApplicationException("user not set"); + return this.userId.get(); + } + + public UUID getUserIdSafe() { + return this.userId.get(); + } + + public void setUserId(UUID userId) { + this.userId.set(userId); + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/actionconfirmation/DmpInvitationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/actionconfirmation/DmpInvitationEntity.java new file mode 100644 index 000000000..e01d2ccc6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/actionconfirmation/DmpInvitationEntity.java @@ -0,0 +1,44 @@ +package org.opencdmp.commons.types.actionconfirmation; + +import org.opencdmp.commons.enums.DmpUserRole; +import jakarta.xml.bind.annotation.*; + +import java.util.UUID; + +@XmlRootElement(name = "dmp-invitation") +@XmlAccessorType(XmlAccessType.FIELD) +public class DmpInvitationEntity { + + @XmlAttribute(name = "email") + private String email; + + @XmlAttribute(name = "dmp") + private UUID dmpId; + + @XmlAttribute(name = "dmp-role") + private DmpUserRole role; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public UUID getDmpId() { + return dmpId; + } + + public void setDmpId(UUID dmpId) { + this.dmpId = dmpId; + } + + public DmpUserRole getRole() { + return role; + } + + public void setRole(DmpUserRole role) { + this.role = role; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/actionconfirmation/MergeAccountConfirmationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/actionconfirmation/MergeAccountConfirmationEntity.java new file mode 100644 index 000000000..4af63df6e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/actionconfirmation/MergeAccountConfirmationEntity.java @@ -0,0 +1,22 @@ +package org.opencdmp.commons.types.actionconfirmation; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "merge-account-confirmation") +@XmlAccessorType(XmlAccessType.FIELD) +public class MergeAccountConfirmationEntity { + + @XmlAttribute(name = "email") + private String email; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/actionconfirmation/RemoveCredentialRequestEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/actionconfirmation/RemoveCredentialRequestEntity.java new file mode 100644 index 000000000..48d8d39a8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/actionconfirmation/RemoveCredentialRequestEntity.java @@ -0,0 +1,24 @@ +package org.opencdmp.commons.types.actionconfirmation; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlRootElement; + +import java.util.UUID; + +@XmlRootElement(name = "remove-credential-confirmation") +@XmlAccessorType(XmlAccessType.FIELD) +public class RemoveCredentialRequestEntity { + + @XmlAttribute(name = "credential-id") + private UUID credentialId; + + public UUID getCredentialId() { + return credentialId; + } + + public void setCredentialId(UUID credentialId) { + this.credentialId = credentialId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dashborad/RecentActivityItemEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dashborad/RecentActivityItemEntity.java new file mode 100644 index 000000000..8e7b23592 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dashborad/RecentActivityItemEntity.java @@ -0,0 +1,62 @@ +package org.opencdmp.commons.types.dashborad; + +import org.opencdmp.commons.enums.RecentActivityItemType; + +import java.time.Instant; +import java.util.UUID; + +public class RecentActivityItemEntity { + private RecentActivityItemType type; + private UUID id; + private Instant updatedAt; + private String label; + private Short statusValue; + + public RecentActivityItemEntity(RecentActivityItemType type, UUID id, Instant updatedAt, String label, Short statusValue) { + this.type = type; + this.id = id; + this.updatedAt = updatedAt; + this.label = label; + this.statusValue = statusValue; + } + + public RecentActivityItemType getType() { + return type; + } + + public void setType(RecentActivityItemType type) { + this.type = type; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public Short getStatusValue() { + return statusValue; + } + + public void setStatusValue(Short statusValue) { + this.statusValue = statusValue; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/deposit/DepositSourceEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/deposit/DepositSourceEntity.java new file mode 100644 index 000000000..0aef2fe0e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/deposit/DepositSourceEntity.java @@ -0,0 +1,77 @@ +package org.opencdmp.commons.types.deposit; + +public class DepositSourceEntity { + + private String repositoryId; + private String url; + private String issuerUrl; + private String clientId; + private String clientSecret; + private String scope; + private String pdfTransformerId; + private String rdaTransformerId; + + public String getRepositoryId() { + return repositoryId; + } + + public void setRepositoryId(String repositoryId) { + this.repositoryId = repositoryId; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getIssuerUrl() { + return issuerUrl; + } + + public void setIssuerUrl(String issuerUrl) { + this.issuerUrl = issuerUrl; + } + + 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 getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + public String getPdfTransformerId() { + return pdfTransformerId; + } + + public void setPdfTransformerId(String pdfTransformerId) { + this.pdfTransformerId = pdfTransformerId; + } + + public String getRdaTransformerId() { + return rdaTransformerId; + } + + public void setRdaTransformerId(String rdaTransformerId) { + this.rdaTransformerId = rdaTransformerId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/description/ExternalIdentifierEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/description/ExternalIdentifierEntity.java new file mode 100644 index 000000000..2e6d07639 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/description/ExternalIdentifierEntity.java @@ -0,0 +1,25 @@ +package org.opencdmp.commons.types.description; + +public class ExternalIdentifierEntity { + + private String identifier; + + private String type; + + public String getIdentifier() { + return identifier; + } + + public void setIdentifier(String identifier) { + this.identifier = identifier; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/description/FieldEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/description/FieldEntity.java new file mode 100644 index 000000000..969056255 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/description/FieldEntity.java @@ -0,0 +1,44 @@ +package org.opencdmp.commons.types.description; + + +import java.time.Instant; +import java.util.List; + +public class FieldEntity { + private String textValue; + private List textListValue; + private Instant dateValue; + private ExternalIdentifierEntity externalIdentifier; + + public String getTextValue() { + return textValue; + } + + public void setTextValue(String textValue) { + this.textValue = textValue; + } + + public List getTextListValue() { + return textListValue; + } + + public void setTextListValue(List textListValue) { + this.textListValue = textListValue; + } + + public Instant getDateValue() { + return dateValue; + } + + public void setDateValue(Instant dateValue) { + this.dateValue = dateValue; + } + + public ExternalIdentifierEntity getExternalIdentifier() { + return externalIdentifier; + } + + public void setExternalIdentifier(ExternalIdentifierEntity externalIdentifier) { + this.externalIdentifier = externalIdentifier; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/description/PropertyDefinitionEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/description/PropertyDefinitionEntity.java new file mode 100644 index 000000000..561e3df3c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/description/PropertyDefinitionEntity.java @@ -0,0 +1,18 @@ +package org.opencdmp.commons.types.description; + +import java.util.Map; + +public class PropertyDefinitionEntity { + private Map fieldSets; + + public Map getFieldSets() { + return fieldSets; + } + + public void setFieldSets(Map fieldSets) { + this.fieldSets = fieldSets; + } +} + + + diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/description/PropertyDefinitionFieldSetEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/description/PropertyDefinitionFieldSetEntity.java new file mode 100644 index 000000000..b0207e859 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/description/PropertyDefinitionFieldSetEntity.java @@ -0,0 +1,15 @@ +package org.opencdmp.commons.types.description; + +import java.util.List; + +public class PropertyDefinitionFieldSetEntity { + private List items; + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/description/PropertyDefinitionFieldSetItemEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/description/PropertyDefinitionFieldSetItemEntity.java new file mode 100644 index 000000000..c17232466 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/description/PropertyDefinitionFieldSetItemEntity.java @@ -0,0 +1,33 @@ +package org.opencdmp.commons.types.description; + +import java.util.Map; + +public class PropertyDefinitionFieldSetItemEntity { + private Map fields; + private String comment; + private int ordinal; + + public Map getFields() { + return fields; + } + + public void setFields(Map fields) { + this.fields = fields; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public int getOrdinal() { + return ordinal; + } + + public void setOrdinal(int ordinal) { + this.ordinal = ordinal; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptionreference/DescriptionReferenceDataEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptionreference/DescriptionReferenceDataEntity.java new file mode 100644 index 000000000..f897f6785 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptionreference/DescriptionReferenceDataEntity.java @@ -0,0 +1,15 @@ +package org.opencdmp.commons.types.descriptionreference; + +import java.util.UUID; + +public class DescriptionReferenceDataEntity { + private String fieldId; + + public String getFieldId() { + return fieldId; + } + + public void setFieldId(String fieldId) { + this.fieldId = fieldId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/DefinitionEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/DefinitionEntity.java new file mode 100644 index 000000000..334864987 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/DefinitionEntity.java @@ -0,0 +1,50 @@ +package org.opencdmp.commons.types.descriptiontemplate; + +import jakarta.xml.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; + +@XmlRootElement(name = "root") +@XmlAccessorType(XmlAccessType.FIELD) +public class DefinitionEntity { + @XmlElementWrapper(name = "pages") + @XmlElement(name = "page") + private List pages; + + public List getPages() { + return pages; + } + + public void setPages(List pageEntities) { + this.pages = pageEntities; + } + + public List getAllField(){ + List fieldEntities = new ArrayList<>(); + if (this.getPages() != null){ + for (PageEntity sectionEntity: this.getPages()) { + fieldEntities.addAll(sectionEntity.getAllField()); + } + } + return fieldEntities; + } + + public List getAllFieldSets(){ + List fieldSetsEntities = new ArrayList<>(); + if (this.getPages() != null){ + for (PageEntity sectionEntity: this.getPages()) { + fieldSetsEntities.addAll(sectionEntity.getAllFieldSets()); + } + } + return fieldSetsEntities; + } + + public List getFieldSetById(String id) { + return this.getAllFieldSets().stream().filter(x-> id.equals(x.getId())).toList(); + } + + public List getFieldById(String id) { + return this.getAllField().stream().filter(x-> id.equals(x.getId())).toList(); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/ExternalIdentifierEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/ExternalIdentifierEntity.java new file mode 100644 index 000000000..96c1c5a1a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/ExternalIdentifierEntity.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.types.descriptiontemplate; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +@XmlAccessorType(XmlAccessType.FIELD) +public class ExternalIdentifierEntity { + + @XmlAttribute(name="identifier") + private String identifier; + + @XmlAttribute(name="type") + private String type; + + public String getIdentifier() { + return identifier; + } + + public void setIdentifier(String identifier) { + this.identifier = identifier; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/FieldEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/FieldEntity.java new file mode 100644 index 000000000..58b260e87 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/FieldEntity.java @@ -0,0 +1,106 @@ +package org.opencdmp.commons.types.descriptiontemplate; + +import org.opencdmp.commons.enums.FieldValidationType; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.*; +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class FieldEntity { + @XmlAttribute(name="id") + private String id; + @XmlAttribute(name="ordinal") + private int ordinal; + @XmlElementWrapper(name = "schematics") + @XmlElement(name = "schematic") + private List schematics; + @XmlAttribute(name="numbering") + private String numbering; + @XmlAttribute(name="defaultValue") + private String defaultValue; + @XmlElementWrapper(name = "visibilityRules") + @XmlElement(name = "rule") + private List visibilityRules; + + @XmlElements({ + @XmlElement(name = LabelDataEntity.XmlElementName, type = LabelDataEntity.class), + @XmlElement(name = LabelAndMultiplicityDataEntity.XmlElementName, type = LabelAndMultiplicityDataEntity.class), + @XmlElement(name = UploadDataEntity.XmlElementName, type = UploadDataEntity.class), + @XmlElement(name = RadioBoxDataEntity.XmlElementName, type = RadioBoxDataEntity.class), + @XmlElement(name = SelectDataEntity.XmlElementName, type = SelectDataEntity.class), + @XmlElement(name = ReferenceTypeDataEntity.XmlElementName, type = ReferenceTypeDataEntity.class) + }) + private BaseFieldDataEntity data; + @XmlElementWrapper(name = "validations") + @XmlElement(name = "validation") + private List validations; + @XmlAttribute(name="includeInExport") + private Boolean includeInExport; + + 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 BaseFieldDataEntity getData() { + return data; + } + public void setData(BaseFieldDataEntity data) { + this.data = data; + } + + public String getDefaultValue() { + return defaultValue; + } + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + + public List getValidations() { + return validations; + } + public void setValidations(List validations) { + this.validations = validations; + } + + public String getNumbering() { + return numbering; + } + public void setNumbering(String numbering) { + this.numbering = numbering; + } + + public Boolean getIncludeInExport() { + return includeInExport; + } + + public void setIncludeInExport(Boolean includeInExport) { + this.includeInExport = includeInExport; + } + + public List getVisibilityRules() { + return visibilityRules; + } + + public void setVisibilityRules(List visibilityRules) { + this.visibilityRules = visibilityRules; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/FieldSetEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/FieldSetEntity.java new file mode 100644 index 000000000..5ab80101d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/FieldSetEntity.java @@ -0,0 +1,121 @@ +package org.opencdmp.commons.types.descriptiontemplate; + +import jakarta.xml.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class FieldSetEntity { + @XmlAttribute(name="id") + private String id; + @XmlAttribute(name="ordinal") + private int ordinal; + + @XmlElementWrapper(name = "fields") + @XmlElement(name = "field") + private List fields; + @XmlAttribute(name="numbering") + private String numbering; + @XmlAttribute(name="title") + private String title; + @XmlAttribute(name="description") + private String description; + @XmlAttribute(name="extendedDescription") + private String extendedDescription; + @XmlAttribute(name="additionalInformation") + private String additionalInformation; + @XmlElement(name="multiplicity") + private MultiplicityEntity multiplicity; + @XmlAttribute(name="hasMultiplicity") + private boolean hasMultiplicity; + @XmlAttribute(name="hasCommentField") + private boolean hasCommentField; + + public List getFields() { + return fields; + } + public void setFields(List fieldEntities) { + this.fields = fieldEntities; + } + + 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; + } + + 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 MultiplicityEntity getMultiplicity() { + return multiplicity; + } + public void setMultiplicity(MultiplicityEntity multiplicity) { + this.multiplicity = multiplicity; + } + + public boolean getHasCommentField() { + return hasCommentField; + } + public void setHasCommentField(boolean hasCommentField) { + this.hasCommentField = hasCommentField; + } + + public String getNumbering() { + return numbering; + } + public void setNumbering(String numbering) { + this.numbering = numbering; + } + + public String getAdditionalInformation() { + return additionalInformation; + } + public void setAdditionalInformation(String additionalInformation) { + this.additionalInformation = additionalInformation; + } + + + public List getAllField() { + return this.getFields() == null ? new ArrayList<>() : this.getFields(); + } + + public List getFieldById(String id) { + return this.getAllField().stream().filter(x-> id.equals(x.getId())).toList(); + } + + public boolean getHasMultiplicity() { + return hasMultiplicity; + } + + public void setHasMultiplicity(boolean hasMultiplicity) { + this.hasMultiplicity = hasMultiplicity; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/MultiplicityEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/MultiplicityEntity.java new file mode 100644 index 000000000..728d817a9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/MultiplicityEntity.java @@ -0,0 +1,50 @@ +package org.opencdmp.commons.types.descriptiontemplate; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +@XmlAccessorType(XmlAccessType.FIELD) +public class MultiplicityEntity { + + @XmlAttribute(name="min") + private int min; + @XmlAttribute(name="max") + private int max; + @XmlAttribute(name="placeholder") + private String placeholder; + @XmlAttribute(name="tableView") + 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/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/PageEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/PageEntity.java new file mode 100644 index 000000000..0313f713a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/PageEntity.java @@ -0,0 +1,74 @@ +package org.opencdmp.commons.types.descriptiontemplate; + +import jakarta.xml.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; + + +@XmlAccessorType(XmlAccessType.FIELD) +public class PageEntity { + @XmlAttribute(name="id") + private String id; + @XmlAttribute(name="ordinal") + private int ordinal; + @XmlAttribute(name="title") + private String title; + + @XmlElementWrapper(name = "sections") + @XmlElement(name = "section") + private List sections; + + public List getSections() { + return sections; + } + + public void setSections(List sections) { + this.sections = sections; + } + + 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; + } + + + public List getAllField(){ + List fieldEntities = new ArrayList<>(); + if (this.getSections() != null){ + for (SectionEntity sectionEntity: this.getSections()) { + fieldEntities.addAll(sectionEntity.getAllField()); + } + } + return fieldEntities; + } + + public List getAllFieldSets(){ + List fieldSetsEntities = new ArrayList<>(); + if (this.getSections() != null){ + for (SectionEntity sectionEntity: this.getSections()) { + fieldSetsEntities.addAll(sectionEntity.getAllFieldSets()); + } + } + return fieldSetsEntities; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/RuleEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/RuleEntity.java new file mode 100644 index 000000000..cbf0c7ddb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/RuleEntity.java @@ -0,0 +1,64 @@ +package org.opencdmp.commons.types.descriptiontemplate; + +import jakarta.xml.bind.annotation.*; + +import java.time.Instant; +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class RuleEntity { + @XmlAttribute(name="target") + private String target; + @XmlAttribute(name="value") + private String textValue; + + @XmlElementWrapper(name = "textListValues") + @XmlElement(name = "textListValue") + private List textListValue; + + @XmlElement(name = "dateValue") + private Instant dateValue; + @XmlElement(name="externalIdentifier") + private ExternalIdentifierEntity externalIdentifier; + + public String getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + public String getTextValue() { + return textValue; + } + + public void setTextValue(String textValue) { + this.textValue = textValue; + } + + public List getTextListValue() { + return textListValue; + } + + public void setTextListValue(List textListValue) { + this.textListValue = textListValue; + } + + public Instant getDateValue() { + return dateValue; + } + + public void setDateValue(Instant dateValue) { + this.dateValue = dateValue; + } + + public ExternalIdentifierEntity getExternalIdentifier() { + return externalIdentifier; + } + + public void setExternalIdentifier(ExternalIdentifierEntity externalIdentifier) { + this.externalIdentifier = externalIdentifier; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/SectionEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/SectionEntity.java new file mode 100644 index 000000000..87832ad6e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/SectionEntity.java @@ -0,0 +1,131 @@ +package org.opencdmp.commons.types.descriptiontemplate; + +import jakarta.xml.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class SectionEntity{ + @XmlAttribute(name="id") + private String id; + @XmlAttribute(name="ordinal") + private int ordinal; + @XmlAttribute(name="defaultVisibility") + private boolean defaultVisibility; + @XmlAttribute(name="numbering") + private String numbering; + @XmlAttribute(name="title") + private String title; + @XmlAttribute(name="description") + private String description; + @XmlAttribute(name="extendedDescription") + private String extendedDescription; + + @XmlElementWrapper(name = "sections") + @XmlElement(name = "section") + private List sections; + @XmlElementWrapper(name = "fieldSets") + @XmlElement(name = "fieldSet") + private List fieldSets; + + 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 boolean isDefaultVisibility() { + return defaultVisibility; + } + + public void setDefaultVisibility(boolean defaultVisibility) { + this.defaultVisibility = defaultVisibility; + } + + 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 List getSections() { + return sections; + } + + public void setSections(List sections) { + this.sections = sections; + } + + public List getFieldSets() { + return fieldSets; + } + + public void setFieldSets(List fieldSetEntities) { + this.fieldSets = fieldSetEntities; + } + + public String getExtendedDescription() { + return extendedDescription; + } + + public void setExtendedDescription(String extendedDescription) { + this.extendedDescription = extendedDescription; + } + + public String getNumbering() { + return numbering; + } + + public void setNumbering(String numbering) { + this.numbering = numbering; + } + + public List getAllField(){ + List fieldEntities = new ArrayList<>(); + if (this.getFieldSets() != null){ + for (FieldSetEntity fieldSetEntity: this.getFieldSets()) { + fieldEntities.addAll(fieldSetEntity.getAllField()); + } + } + if (this.getSections() != null){ + for (SectionEntity sectionEntity: this.getSections()) { + fieldEntities.addAll(sectionEntity.getAllField()); + } + } + return fieldEntities; + } + + public List getAllFieldSets(){ + List fieldSetEntities = new ArrayList<>(); + if (this.getFieldSets() != null){ + fieldSetEntities.addAll(this.getFieldSets()); + } + if (this.getSections() != null){ + for (SectionEntity sectionEntity: this.getSections()) { + fieldSetEntities.addAll(sectionEntity.getAllFieldSets()); + } + } + return fieldSetEntities; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/BaseFieldDataEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/BaseFieldDataEntity.java new file mode 100644 index 000000000..73b41e33f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/BaseFieldDataEntity.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.types.descriptiontemplate.fielddata; + +import org.opencdmp.commons.enums.FieldType; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + + +@XmlAccessorType(XmlAccessType.FIELD) +public abstract class BaseFieldDataEntity { + + @XmlAttribute(name = "label") + private String label; + @XmlAttribute(name = "fieldType") + private FieldType fieldType; + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public FieldType getFieldType() { + return fieldType; + } + + public void setFieldType(FieldType fieldType) { + this.fieldType = fieldType; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/LabelAndMultiplicityDataEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/LabelAndMultiplicityDataEntity.java new file mode 100644 index 000000000..c419e11af --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/LabelAndMultiplicityDataEntity.java @@ -0,0 +1,21 @@ +package org.opencdmp.commons.types.descriptiontemplate.fielddata; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +@XmlAccessorType(XmlAccessType.FIELD) +public class LabelAndMultiplicityDataEntity extends BaseFieldDataEntity { + public static final String XmlElementName = "labelAndMultiplicityData"; + + @XmlAttribute(name = "multipleSelect") + private Boolean multipleSelect; + + public Boolean getMultipleSelect() { + return multipleSelect; + } + + public void setMultipleSelect(Boolean multipleSelect) { + this.multipleSelect = multipleSelect; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/LabelDataEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/LabelDataEntity.java new file mode 100644 index 000000000..4b3fa23f2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/LabelDataEntity.java @@ -0,0 +1,10 @@ +package org.opencdmp.commons.types.descriptiontemplate.fielddata; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; + + +@XmlAccessorType(XmlAccessType.FIELD) +public class LabelDataEntity extends BaseFieldDataEntity { + public static final String XmlElementName = "labelData"; +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/RadioBoxDataEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/RadioBoxDataEntity.java new file mode 100644 index 000000000..4cbffa500 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/RadioBoxDataEntity.java @@ -0,0 +1,45 @@ +package org.opencdmp.commons.types.descriptiontemplate.fielddata; + +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class RadioBoxDataEntity extends BaseFieldDataEntity { + public static final String XmlElementName = "radioBoxData"; + @XmlAccessorType(XmlAccessType.FIELD) + public static class RadioBoxDataOptionEntity { + @XmlAttribute(name="label") + private String label; + @XmlAttribute(name="value") + private String value; + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } + + @XmlElementWrapper(name = "options") + @XmlElement(name = "option") + private List options; + + public List getOptions() { + return options; + } + + public void setOptions(List options) { + this.options = options; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/ReferenceTypeDataEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/ReferenceTypeDataEntity.java new file mode 100644 index 000000000..b7dd20e5f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/ReferenceTypeDataEntity.java @@ -0,0 +1,33 @@ +package org.opencdmp.commons.types.descriptiontemplate.fielddata; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public class ReferenceTypeDataEntity extends BaseFieldDataEntity { + public static final String XmlElementName = "referenceTypeData"; + + @XmlAttribute(name = "multipleSelect") + private Boolean multipleSelect; + + @XmlAttribute(name = "referenceTypeId") + private UUID referenceTypeId; + public Boolean getMultipleSelect() { + return multipleSelect; + } + + public void setMultipleSelect(Boolean multipleSelect) { + this.multipleSelect = multipleSelect; + } + + public UUID getReferenceTypeId() { + return referenceTypeId; + } + + public void setReferenceTypeId(UUID referenceTypeId) { + this.referenceTypeId = referenceTypeId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/SelectDataEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/SelectDataEntity.java new file mode 100644 index 000000000..39d0d0f84 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/SelectDataEntity.java @@ -0,0 +1,44 @@ +package org.opencdmp.commons.types.descriptiontemplate.fielddata; + +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class SelectDataEntity extends LabelAndMultiplicityDataEntity { + public static final String XmlElementName = "selectData"; + @XmlElementWrapper(name = "options") + @XmlElement(name = "options") + private List options; + + public List getOptions() { + return options; + } + + public void setOptions(List optionEntities) { + this.options = optionEntities; + } + + @XmlAccessorType(XmlAccessType.FIELD) + public static class OptionEntity { + @XmlAttribute(name="label") + private String label; + @XmlAttribute(name="value") + private String value; + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/UploadDataEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/UploadDataEntity.java new file mode 100644 index 000000000..4498c3df7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/fielddata/UploadDataEntity.java @@ -0,0 +1,59 @@ +package org.opencdmp.commons.types.descriptiontemplate.fielddata; + +import jakarta.xml.bind.annotation.*; + +import java.util.List; + + +@XmlAccessorType(XmlAccessType.FIELD) +public class UploadDataEntity extends BaseFieldDataEntity { + public static final String XmlElementName = "uploadData"; + + @XmlAccessorType(XmlAccessType.FIELD) + public static class UploadDataOptionEntity { + @XmlAttribute(name="label") + private String label; + @XmlAttribute(name="value") + private String value; + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } + + @XmlElementWrapper(name = "types") + @XmlElement(name = "type") + private List types; + + @XmlAttribute(name="maxFileSizeInMB") + private Integer maxFileSizeInMB; + + + public List getTypes() { + return types; + } + + public void setTypes(List types) { + this.types = types; + } + + public Integer getMaxFileSizeInMB() { + return maxFileSizeInMB; + } + + public void setMaxFileSizeInMB(Integer maxFileSizeInMB) { + this.maxFileSizeInMB = maxFileSizeInMB; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/DescriptionTemplateImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/DescriptionTemplateImportExport.java new file mode 100644 index 000000000..f6ac730e1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/DescriptionTemplateImportExport.java @@ -0,0 +1,66 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport; + + +import org.opencdmp.commons.enums.DescriptionTemplateStatus; + +import org.opencdmp.model.persist.DescriptionTemplatePersist; +import org.opencdmp.model.persist.NewVersionDescriptionTemplatePersist; +import org.opencdmp.model.persist.descriptiontemplatedefinition.DefinitionPersist; +import org.opencdmp.model.persist.descriptiontemplatedefinition.PagePersist; +import org.opencdmp.model.persist.descriptiontemplatedefinition.SectionPersist; +import org.opencdmp.service.fielddatahelper.FieldDataHelperServiceProvider; +import jakarta.xml.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; + +@XmlRootElement(name = "root") +@XmlAccessorType(XmlAccessType.FIELD) +public class DescriptionTemplateImportExport { + @XmlAttribute(name = "description") + private String description; + @XmlAttribute(name = "language") + private String language; + @XmlAttribute(name = "type") + private UUID type; + @XmlElementWrapper(name = "pages") + @XmlElement(name = "page") + private List pages; + + + public List getPages() { + return pages; + } + + public void setPages(List pages) { + this.pages = pages; + } + + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + + public UUID getType() { + return type; + } + + public void setType(UUID type) { + this.type = type; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/ExternalIdentifierImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/ExternalIdentifierImportExport.java new file mode 100644 index 000000000..e78d8606b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/ExternalIdentifierImportExport.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +@XmlAccessorType(XmlAccessType.FIELD) +public class ExternalIdentifierImportExport { + + @XmlAttribute(name="identifier") + private String identifier; + + @XmlAttribute(name="type") + private String type; + + public String getIdentifier() { + return identifier; + } + + public void setIdentifier(String identifier) { + this.identifier = identifier; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/FieldImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/FieldImportExport.java new file mode 100644 index 000000000..483811a79 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/FieldImportExport.java @@ -0,0 +1,122 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport; + +import org.opencdmp.commons.enums.FieldType; +import org.opencdmp.commons.enums.FieldValidationType; +import org.opencdmp.commons.types.descriptiontemplate.importexport.fielddata.*; +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class FieldImportExport { + + @XmlAttribute(name = "id") + private String id; + + @XmlAttribute(name = "ordinal") + private int ordinal; + + @XmlElement(name = "numbering") + private String numbering; + + @XmlElementWrapper(name = "validations") + @XmlElement(name = "validation") + private List validations; + + @XmlElement(name = "defaultValue") + private String defaultValue; + + @XmlElementWrapper(name = "visibilityRules") + @XmlElement(name = "visibilityRule") + private List visibilityRules; + + @XmlElement(name = "fieldType") + private FieldType fieldType; + + @XmlElements({ + @XmlElement(name = LabelDataImportExport.XmlElementName, type = LabelDataImportExport.class), + @XmlElement(name = LabelAndMultiplicityDataImportExport.XmlElementName, type = LabelAndMultiplicityDataImportExport.class), + @XmlElement(name = UploadDataImportExport.XmlElementName, type = UploadDataImportExport.class), + @XmlElement(name = RadioBoxDataImportExport.XmlElementName, type = RadioBoxDataImportExport.class), + @XmlElement(name = SelectDataImportExport.XmlElementName, type = SelectDataImportExport.class), + @XmlElement(name = ReferenceTypeDataImportExport.XmlElementName, type = ReferenceTypeDataImportExport.class), + }) + private BaseFieldDataImportExport data; + + @XmlElementWrapper(name = "schematics") + @XmlElement(name = "schematic") + private List schematics; + + 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 getNumbering() { + return numbering; + } + + public void setNumbering(String numbering) { + this.numbering = numbering; + } + + public String getDefaultValue() { + return defaultValue; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public FieldType getFieldType() { + return fieldType; + } + + public void setFieldType(FieldType fieldType) { + this.fieldType = fieldType; + } + + public BaseFieldDataImportExport getData() { + return this.data; + } + + public void setData(BaseFieldDataImportExport data) { + this.data = data; + } + + public List getValidations() { + return validations; + } + + public void setValidations(List validations) { + this.validations = validations; + } + + public List getSchematics() { + return schematics; + } + + public void setSchematics(List schematics) { + this.schematics = schematics; + } + + public List getVisibilityRules() { + return visibilityRules; + } + + public void setVisibilityRules(List visibilityRules) { + this.visibilityRules = visibilityRules; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/FieldSetImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/FieldSetImportExport.java new file mode 100644 index 000000000..da8914ed7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/FieldSetImportExport.java @@ -0,0 +1,122 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport; + +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class FieldSetImportExport { + + @XmlAttribute(name="id") + private String id; + @XmlAttribute(name="ordinal") + private int ordinal; + + @XmlElementWrapper(name = "fields") + @XmlElement(name = "field") + private List fields; + @XmlAttribute(name="numbering") + private String numbering; + @XmlAttribute(name="title") + private String title; + @XmlAttribute(name="description") + private String description; + @XmlAttribute(name="extendedDescription") + private String extendedDescription; + @XmlAttribute(name="additionalInformation") + private String additionalInformation; + @XmlElement(name="multiplicity") + private MultiplicityImportExport multiplicity; + + @XmlAttribute(name="hasMultiplicity") + private boolean hasMultiplicity; + @XmlAttribute(name="hasCommentField") + private Boolean hasCommentField; + + 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 getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } + + public String getNumbering() { + return numbering; + } + + public void setNumbering(String numbering) { + this.numbering = numbering; + } + + public Boolean getHasCommentField() { + return hasCommentField; + } + public void setHasCommentField(Boolean hasCommentField) { + this.hasCommentField = hasCommentField; + } + + public MultiplicityImportExport getMultiplicity() { + return multiplicity; + } + + public void setMultiplicity(MultiplicityImportExport multiplicity) { + this.multiplicity = multiplicity; + } + + public String getTitle() { + return 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 String getAdditionalInformation() { + return additionalInformation; + } + + public void setAdditionalInformation(String additionalInformation) { + this.additionalInformation = additionalInformation; + } + + public void setTitle(String title) { + this.title = title; + } + + public boolean getHasMultiplicity() { + return hasMultiplicity; + } + + public void setHasMultiplicity(boolean hasMultiplicity) { + this.hasMultiplicity = hasMultiplicity; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/MultiplicityImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/MultiplicityImportExport.java new file mode 100644 index 000000000..a73e64fde --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/MultiplicityImportExport.java @@ -0,0 +1,51 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + + +@XmlAccessorType(XmlAccessType.FIELD) +public class MultiplicityImportExport { + @XmlAttribute(name="min") + private int min; + @XmlAttribute(name="max") + private int max; + @XmlAttribute(name="placeholder") + private String placeholder; + @XmlAttribute(name="tableView") + 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; + } + +} \ No newline at end of file diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/PageImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/PageImportExport.java new file mode 100644 index 000000000..eecb3fa9c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/PageImportExport.java @@ -0,0 +1,55 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport; + +import org.opencdmp.model.persist.descriptiontemplatedefinition.PagePersist; +import org.opencdmp.model.persist.descriptiontemplatedefinition.SectionPersist; +import org.opencdmp.service.fielddatahelper.FieldDataHelperServiceProvider; +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class PageImportExport { + @XmlAttribute(name = "id") + private String id; + @XmlAttribute(name = "ordinal") + private int ordinal; + + @XmlAttribute(name = "title") + private String title; + @XmlElementWrapper(name = "sections") + @XmlElement(name = "section") + private List sections; + + + 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; + } + + public List getSections() { + return sections; + } + + public void setSections(List sections) { + this.sections = sections; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/RuleImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/RuleImportExport.java new file mode 100644 index 000000000..05125f3d2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/RuleImportExport.java @@ -0,0 +1,64 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport; + +import jakarta.xml.bind.annotation.*; + +import java.time.Instant; +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class RuleImportExport { + + @XmlAttribute(name="target") + private String target; + @XmlAttribute(name="value") + private String textValue; + + @XmlElementWrapper(name = "textListValues") + @XmlElement(name = "textListValue") + private List textListValue; + @XmlElement(name = "dateValue") + private Instant dateValue; + + @XmlElement(name="externalIdentifier") + private ExternalIdentifierImportExport externalIdentifier; + + public String getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + public String getTextValue() { + return textValue; + } + + public void setTextValue(String textValue) { + this.textValue = textValue; + } + + public List getTextListValue() { + return textListValue; + } + + public void setTextListValue(List textListValue) { + this.textListValue = textListValue; + } + + public Instant getDateValue() { + return dateValue; + } + + public void setDateValue(Instant dateValue) { + this.dateValue = dateValue; + } + + public ExternalIdentifierImportExport getExternalIdentifier() { + return externalIdentifier; + } + + public void setExternalIdentifier(ExternalIdentifierImportExport externalIdentifier) { + this.externalIdentifier = externalIdentifier; + } +} \ No newline at end of file diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/SectionImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/SectionImportExport.java new file mode 100644 index 000000000..afcb35924 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/SectionImportExport.java @@ -0,0 +1,102 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport; + +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class SectionImportExport { + @XmlAttribute(name = "id") + private String id; + @XmlAttribute(name = "ordinal") + private int ordinal; + @XmlAttribute(name = "defaultVisibility") + private Boolean defaultVisibility; + @XmlElementWrapper(name = "fieldSets") + @XmlElement(name = "fieldSet") + private List fieldSets; + @XmlElement(name = "numbering") + private String numbering; + @XmlElement(name = "description") + private String description; + @XmlElement(name = "title") + private String title; + @XmlElementWrapper(name = "sections") + @XmlElement(name = "section") + private List sections; + @XmlAttribute(name = "multiplicity") + private Boolean multiplicity; + + 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 Boolean getDefaultVisibility() { + return defaultVisibility; + } + + public void setDefaultVisibility(Boolean defaultVisibility) { + this.defaultVisibility = defaultVisibility; + } + + public List getFieldSets() { + return fieldSets; + } + + public void setFieldSets(List fieldSets) { + this.fieldSets = fieldSets; + } + + public String getNumbering() { + return numbering; + } + + public void setNumbering(String numbering) { + this.numbering = numbering; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getSections() { + return sections; + } + + public void setSections(List sections) { + this.sections = sections; + } + + public Boolean getMultiplicity() { + return multiplicity; + } + + public void setMultiplicity(Boolean multiplicity) { + this.multiplicity = multiplicity; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/BaseFieldDataImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/BaseFieldDataImportExport.java new file mode 100644 index 000000000..281767a9b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/BaseFieldDataImportExport.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport.fielddata; + +import org.opencdmp.commons.enums.FieldType; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +@XmlAccessorType(XmlAccessType.FIELD) +public abstract class BaseFieldDataImportExport { + @XmlAttribute(name = "label") + private String label; + @XmlAttribute(name = "fieldType") + private FieldType fieldType; + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public FieldType getFieldType() { + return fieldType; + } + + public void setFieldType(FieldType fieldType) { + this.fieldType = fieldType; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/LabelAndMultiplicityDataImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/LabelAndMultiplicityDataImportExport.java new file mode 100644 index 000000000..ad4a17fda --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/LabelAndMultiplicityDataImportExport.java @@ -0,0 +1,23 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport.fielddata; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +@XmlAccessorType(XmlAccessType.FIELD) +public class LabelAndMultiplicityDataImportExport extends BaseFieldDataImportExport { + public static final String XmlElementName = "labelAndMultiplicityData"; + + @XmlAttribute(name = "multipleSelect") + private Boolean multipleSelect; + + public Boolean getMultipleSelect() { + return multipleSelect; + } + + public void setMultipleSelect(Boolean multipleSelect) { + this.multipleSelect = multipleSelect; + } + +} + diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/LabelDataImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/LabelDataImportExport.java new file mode 100644 index 000000000..7bee61ddc --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/LabelDataImportExport.java @@ -0,0 +1,10 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport.fielddata; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; + +@XmlAccessorType(XmlAccessType.FIELD) +public class LabelDataImportExport extends BaseFieldDataImportExport { + public static final String XmlElementName = "labelData"; + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/RadioBoxDataImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/RadioBoxDataImportExport.java new file mode 100644 index 000000000..6b1c926ab --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/RadioBoxDataImportExport.java @@ -0,0 +1,47 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport.fielddata; + +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class RadioBoxDataImportExport extends BaseFieldDataImportExport { + public static final String XmlElementName = "radioBoxData"; + + @XmlElementWrapper(name = "options") + @XmlElement(name = "option") + private List options; + + public List getOptions() { + return options; + } + + public void setOptions(List options) { + this.options = options; + } + + @XmlAccessorType(XmlAccessType.FIELD) + public static class RadioBoxOption { + @XmlAttribute(name = "label") + private String label; + @XmlAttribute(name = "value") + private String value; + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/ReferenceTypeDataImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/ReferenceTypeDataImportExport.java new file mode 100644 index 000000000..e3c00cecd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/ReferenceTypeDataImportExport.java @@ -0,0 +1,34 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport.fielddata; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public class ReferenceTypeDataImportExport extends BaseFieldDataImportExport { + public static final String XmlElementName = "labelAndMultiplicityData"; + + @XmlAttribute(name = "multipleSelect") + private Boolean multipleSelect; + + @XmlAttribute(name = "referenceTypeId") + private UUID referenceTypeId; + + public Boolean getMultipleSelect() { + return multipleSelect; + } + + public void setMultipleSelect(Boolean multipleSelect) { + this.multipleSelect = multipleSelect; + } + + public UUID getReferenceTypeId() { + return referenceTypeId; + } + + public void setReferenceTypeId(UUID referenceTypeId) { + this.referenceTypeId = referenceTypeId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/SelectDataImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/SelectDataImportExport.java new file mode 100644 index 000000000..caa009f1e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/SelectDataImportExport.java @@ -0,0 +1,45 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport.fielddata; + +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +public class SelectDataImportExport extends LabelAndMultiplicityDataImportExport { + public static final String XmlElementName = "selectData"; + @XmlElementWrapper(name = "options") + @XmlElement(name = "options") + private List options; + + + public List getOptions() { + return options; + } + + public void setOptions(List options) { + this.options = options; + } + + @XmlAccessorType(XmlAccessType.FIELD) + public static class OptionImportExport { + @XmlAttribute(name = "label") + private String label; + @XmlAttribute(name = "value") + private String value; + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/UploadDataImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/UploadDataImportExport.java new file mode 100644 index 000000000..3b9aef215 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/descriptiontemplate/importexport/fielddata/UploadDataImportExport.java @@ -0,0 +1,58 @@ +package org.opencdmp.commons.types.descriptiontemplate.importexport.fielddata; + +import jakarta.xml.bind.annotation.*; + +import java.util.List; + + +@XmlAccessorType(XmlAccessType.FIELD) +public class UploadDataImportExport extends BaseFieldDataImportExport { + public static final String XmlElementName = "uploadData"; + @XmlElementWrapper(name = "types") + @XmlElement(name = "type") + private List types; + + @XmlAttribute(name = "maxFileSizeInMB") + private Integer maxFileSizeInMB; + + public List getTypes() { + return types; + } + + public void setTypes(List types) { + this.types = types; + } + + public Integer getMaxFileSizeInMB() { + return maxFileSizeInMB; + } + + public void setMaxFileSizeInMB(Integer maxFileSizeInMB) { + this.maxFileSizeInMB = maxFileSizeInMB; + } + + @XmlAccessorType(XmlAccessType.FIELD) + public static class UploadDataOption { + @XmlAttribute(name = "label") + private String label; + @XmlAttribute(name = "value") + private String value; + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmp/DmpBlueprintValueEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmp/DmpBlueprintValueEntity.java new file mode 100644 index 000000000..efe8775d4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmp/DmpBlueprintValueEntity.java @@ -0,0 +1,27 @@ +package org.opencdmp.commons.types.dmp; + +import java.util.UUID; + +public class DmpBlueprintValueEntity { + + private UUID fieldId; + + private String value; + + public UUID getFieldId() { + return fieldId; + } + + public void setFieldId(UUID fieldId) { + this.fieldId = fieldId; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmp/DmpContactEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmp/DmpContactEntity.java new file mode 100644 index 000000000..2d1a66595 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmp/DmpContactEntity.java @@ -0,0 +1,47 @@ +package org.opencdmp.commons.types.dmp; + +import java.util.UUID; + +public class DmpContactEntity { + + private UUID userId; + + private String firstName; + + private String lastName; + + private String email; + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmp/DmpPropertiesEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmp/DmpPropertiesEntity.java new file mode 100644 index 000000000..8d200344c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmp/DmpPropertiesEntity.java @@ -0,0 +1,27 @@ +package org.opencdmp.commons.types.dmp; + +import java.util.List; + +public class DmpPropertiesEntity { + + private List dmpBlueprintValues; + + private List contacts; + + public List getDmpBlueprintValues() { + return dmpBlueprintValues; + } + + public void setDmpBlueprintValues(List dmpBlueprintValues) { + this.dmpBlueprintValues = dmpBlueprintValues; + } + + public List getContacts() { + return contacts; + } + + public void setContacts(List contacts) { + this.contacts = contacts; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/DefinitionEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/DefinitionEntity.java new file mode 100644 index 000000000..df259b2f3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/DefinitionEntity.java @@ -0,0 +1,36 @@ +package org.opencdmp.commons.types.dmpblueprint; + +import jakarta.xml.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@XmlRootElement(name = "root") +@XmlAccessorType(XmlAccessType.FIELD) +public class DefinitionEntity { + @XmlElementWrapper(name = "sections") + @XmlElement(name = "section") + private List sections; + + public List getSections() { + return sections; + } + public void setSections(List sections) { + this.sections = sections; + } + + public List getAllField(){ + List fieldEntities = new ArrayList<>(); + if (this.getSections() != null){ + for (SectionEntity sectionEntity: this.getSections()) { + fieldEntities.addAll(sectionEntity.getAllField()); + } + } + return fieldEntities; + } + + public List getFieldById(UUID id) { + return this.getAllField().stream().filter(x-> id.equals(x.getId())).toList(); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/DescriptionTemplateEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/DescriptionTemplateEntity.java new file mode 100644 index 000000000..dbd7e8e8a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/DescriptionTemplateEntity.java @@ -0,0 +1,50 @@ +package org.opencdmp.commons.types.dmpblueprint; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public class DescriptionTemplateEntity { + + @XmlAttribute(name="descriptionTemplateGroupId") + private UUID descriptionTemplateGroupId; + @XmlAttribute(name="label") + private String label; + @XmlAttribute(name="minMultiplicity") + private Integer minMultiplicity; + @XmlAttribute(name="maxMultiplicity") + private Integer maxMultiplicity; + + public UUID getDescriptionTemplateGroupId() { + return descriptionTemplateGroupId; + } + + public void setDescriptionTemplateGroupId(UUID descriptionTemplateGroupId) { + this.descriptionTemplateGroupId = descriptionTemplateGroupId; + } + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public Integer getMinMultiplicity() { + return minMultiplicity; + } + public void setMinMultiplicity(Integer minMultiplicity) { + this.minMultiplicity = minMultiplicity; + } + + public Integer getMaxMultiplicity() { + return maxMultiplicity; + } + public void setMaxMultiplicity(Integer maxMultiplicity) { + this.maxMultiplicity = maxMultiplicity; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/ExtraFieldEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/ExtraFieldEntity.java new file mode 100644 index 000000000..9196add10 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/ExtraFieldEntity.java @@ -0,0 +1,23 @@ +package org.opencdmp.commons.types.dmpblueprint; + +import org.opencdmp.commons.enums.DmpBlueprintExtraFieldDataType; +import org.opencdmp.commons.enums.DmpBlueprintFieldCategory; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; +import org.w3c.dom.Element; + +@XmlAccessorType(XmlAccessType.FIELD) +public class ExtraFieldEntity extends FieldEntity { + + @XmlAttribute(name="type") + private DmpBlueprintExtraFieldDataType type; + + public DmpBlueprintExtraFieldDataType getType() { + return type; + } + public void setType(DmpBlueprintExtraFieldDataType type) { + this.type = type; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/FieldEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/FieldEntity.java new file mode 100644 index 000000000..d332a0d9e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/FieldEntity.java @@ -0,0 +1,94 @@ +package org.opencdmp.commons.types.dmpblueprint; + +import org.opencdmp.commons.enums.DmpBlueprintFieldCategory; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +import java.util.List; +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public abstract class FieldEntity { + @XmlAttribute(name="id") + private UUID id; + + @XmlAttribute(name="category") + private DmpBlueprintFieldCategory category; + + @XmlAttribute(name="label") + private String label; + + @XmlAttribute(name="placeholder") + private String placeholder; + + @XmlAttribute(name="description") + private String description; + + @XmlAttribute(name="semantics") + private List semantics; + + @XmlAttribute(name="ordinal") + private Integer ordinal; + + @XmlAttribute(name="required") + private boolean required; + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public DmpBlueprintFieldCategory getCategory() { + return category; + } + public void setCategory(DmpBlueprintFieldCategory category) { + this.category = category; + } + + public String getLabel() { + return label; + } + public void setLabel(String label) { + this.label = label; + } + + public String getPlaceholder() { + return placeholder; + } + public void setPlaceholder(String placeholder) { + this.placeholder = placeholder; + } + + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + + public List getSemantics() { + return semantics; + } + + public void setSemantics(List semantics) { + this.semantics = semantics; + } + + public Integer getOrdinal() { + return ordinal; + } + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } + + public boolean isRequired() { + return required; + } + public void setRequired(boolean required) { + this.required = required; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/ReferenceTypeFieldEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/ReferenceTypeFieldEntity.java new file mode 100644 index 000000000..f27d51686 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/ReferenceTypeFieldEntity.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.types.dmpblueprint; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public class ReferenceTypeFieldEntity extends FieldEntity { + + @XmlAttribute(name="referenceTypeId") + private UUID referenceTypeId; + + @XmlAttribute(name = "multipleSelect") + private Boolean multipleSelect; + public UUID getReferenceTypeId() { + return referenceTypeId; + } + + public void setReferenceTypeId(UUID referenceTypeId) { + this.referenceTypeId = referenceTypeId; + } + + public Boolean getMultipleSelect() { + return multipleSelect; + } + + public void setMultipleSelect(Boolean multipleSelect) { + this.multipleSelect = multipleSelect; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/SectionEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/SectionEntity.java new file mode 100644 index 000000000..5128971bb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/SectionEntity.java @@ -0,0 +1,105 @@ +package org.opencdmp.commons.types.dmpblueprint; + +import org.opencdmp.commons.enums.DmpBlueprintFieldCategory; +import jakarta.xml.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public class SectionEntity { + + @XmlAttribute(name="id") + private UUID id; + + @XmlAttribute(name="label") + private String label; + + @XmlAttribute(name="description") + private String description; + + @XmlAttribute(name="ordinal") + private Integer ordinal; + + @XmlElementWrapper(name = "fields") + @XmlElements({ + @XmlElement(name = DmpBlueprintFieldCategory.Names.Extra, type = ExtraFieldEntity.class), + @XmlElement(name = DmpBlueprintFieldCategory.Names.System, type = SystemFieldEntity.class), + @XmlElement(name = DmpBlueprintFieldCategory.Names.ReferenceType, type = ReferenceTypeFieldEntity.class), + }) + private List fields; + + @XmlAttribute(name="hasTemplates") + private Boolean hasTemplates; + + @XmlElementWrapper(name = "descriptionTemplates") + @XmlElement(name = "descriptionTemplate") + private List descriptionTemplates; + + @XmlElementWrapper(name = "prefillingSourcesIds") + @XmlElement(name = "id") + private List prefillingSourcesIds; + + 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 Integer getOrdinal() { + return ordinal; + } + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } + + public List getFields() { + return fields; + } + public void setFields(List fields) { + this.fields = fields; + } + + public Boolean getHasTemplates() { + return hasTemplates; + } + public void setHasTemplates(Boolean hasTemplates) { + this.hasTemplates = hasTemplates; + } + + public List getDescriptionTemplates() { + return descriptionTemplates; + } + public void setDescriptionTemplates(List descriptionTemplates) { + this.descriptionTemplates = descriptionTemplates; + } + + public List getPrefillingSourcesIds() { + return prefillingSourcesIds; + } + + public void setPrefillingSourcesIds(List prefillingSourcesIds) { + this.prefillingSourcesIds = prefillingSourcesIds; + } + + public List getAllField(){ + return this.getFields() != null ? this.getFields() : new ArrayList<>(); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/SystemFieldEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/SystemFieldEntity.java new file mode 100644 index 000000000..efc127159 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/SystemFieldEntity.java @@ -0,0 +1,22 @@ +package org.opencdmp.commons.types.dmpblueprint; + +import org.opencdmp.commons.enums.DmpBlueprintSystemFieldType; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public class SystemFieldEntity extends FieldEntity { + + @XmlAttribute(name="type") + private DmpBlueprintSystemFieldType type; + + public DmpBlueprintSystemFieldType getType() { + return type; + } + public void setType(DmpBlueprintSystemFieldType type) { + this.type = type; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/BlueprintImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/BlueprintImportExport.java new file mode 100644 index 000000000..5c4aeb13c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/BlueprintImportExport.java @@ -0,0 +1,22 @@ +package org.opencdmp.commons.types.dmpblueprint.importexport; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "root") +@XmlAccessorType(XmlAccessType.FIELD) +public class BlueprintImportExport { + + @XmlElement(name = "definition") + private DefinitionImportExport dmpBlueprintDefinition; + + public DefinitionImportExport getDmpBlueprintDefinition() { + return dmpBlueprintDefinition; + } + + public void setDmpBlueprintDefinition(DefinitionImportExport dmpBlueprintDefinition) { + this.dmpBlueprintDefinition = dmpBlueprintDefinition; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/DefinitionImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/DefinitionImportExport.java new file mode 100644 index 000000000..917c209e7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/DefinitionImportExport.java @@ -0,0 +1,22 @@ +package org.opencdmp.commons.types.dmpblueprint.importexport; + +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlRootElement(name = "root") +@XmlAccessorType(XmlAccessType.FIELD) +public class DefinitionImportExport { + + @XmlElementWrapper(name = "sections") + @XmlElement(name = "section") + private List sections; + + public List getSections() { + return sections; + } + + public void setSections(List sections) { + this.sections = sections; + } +} \ No newline at end of file diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/DescriptionTemplateImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/DescriptionTemplateImportExport.java new file mode 100644 index 000000000..5e6865a80 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/DescriptionTemplateImportExport.java @@ -0,0 +1,54 @@ +package org.opencdmp.commons.types.dmpblueprint.importexport; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public class DescriptionTemplateImportExport { + + @XmlAttribute(name = "descriptionTemplateGroupId") + private UUID descriptionTemplateGroupId; + @XmlAttribute(name = "label") + private String label; + @XmlAttribute(name = "minMultiplicity") + private int minMultiplicity; + @XmlAttribute(name = "maxMultiplicity") + private int maxMultiplicity; + + public UUID getDescriptionTemplateGroupId() { + return descriptionTemplateGroupId; + } + + public void setDescriptionTemplateGroupId(UUID descriptionTemplateGroupId) { + this.descriptionTemplateGroupId = descriptionTemplateGroupId; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public int getMinMultiplicity() { + return minMultiplicity; + } + + public void setMinMultiplicity(int minMultiplicity) { + this.minMultiplicity = minMultiplicity; + } + + public int getMaxMultiplicity() { + return maxMultiplicity; + } + + public void setMaxMultiplicity(int maxMultiplicity) { + this.maxMultiplicity = maxMultiplicity; + } + + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/ExtraFieldImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/ExtraFieldImportExport.java new file mode 100644 index 000000000..a3f331fde --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/ExtraFieldImportExport.java @@ -0,0 +1,86 @@ +package org.opencdmp.commons.types.dmpblueprint.importexport; + +import org.opencdmp.commons.enums.DmpBlueprintExtraFieldDataType; +import org.opencdmp.commons.enums.DmpBlueprintSystemFieldType; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public class ExtraFieldImportExport { + + @XmlAttribute(name = "id") + private UUID id; + @XmlAttribute(name = "type") + private DmpBlueprintExtraFieldDataType type; + @XmlAttribute(name = "label") + private String label; + @XmlAttribute(name = "placeholder") + private String placeholder; + @XmlAttribute(name = "description") + private String description; + @XmlAttribute(name = "ordinal") + private int ordinal; + @XmlAttribute(name = "required") + private boolean required; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public DmpBlueprintExtraFieldDataType getType() { + return type; + } + + public void setType(DmpBlueprintExtraFieldDataType type) { + this.type = type; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getPlaceholder() { + return placeholder; + } + + public void setPlaceholder(String placeholder) { + this.placeholder = placeholder; + } + + 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 isRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } + + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/ReferenceTypeFieldImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/ReferenceTypeFieldImportExport.java new file mode 100644 index 000000000..681168178 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/ReferenceTypeFieldImportExport.java @@ -0,0 +1,93 @@ +package org.opencdmp.commons.types.dmpblueprint.importexport; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public class ReferenceTypeFieldImportExport { + + @XmlAttribute(name = "id") + private UUID id; + @XmlAttribute(name = "referenceTypeId") + private UUID referenceTypeId; + @XmlAttribute(name = "label") + private String label; + @XmlAttribute(name = "placeholder") + private String placeholder; + @XmlAttribute(name = "description") + private String description; + @XmlAttribute(name = "ordinal") + private int ordinal; + @XmlAttribute(name = "required") + private boolean required; + + @XmlAttribute(name = "multipleSelect") + private Boolean multipleSelect; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getReferenceTypeId() { + return referenceTypeId; + } + + public void setReferenceTypeId(UUID referenceTypeId) { + this.referenceTypeId = referenceTypeId; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getPlaceholder() { + return placeholder; + } + + public void setPlaceholder(String placeholder) { + this.placeholder = placeholder; + } + + 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 isRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } + + public Boolean getMultipleSelect() { + return multipleSelect; + } + + public void setMultipleSelect(Boolean multipleSelect) { + this.multipleSelect = multipleSelect; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/SectionImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/SectionImportExport.java new file mode 100644 index 000000000..f6bf88a8a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/SectionImportExport.java @@ -0,0 +1,106 @@ +package org.opencdmp.commons.types.dmpblueprint.importexport; + +import jakarta.xml.bind.annotation.*; + +import java.util.List; +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public class SectionImportExport { + + @XmlAttribute(name = "id") + private UUID id; + @XmlAttribute(name = "label") + private String label; + @XmlAttribute(name = "description") + private String description; + @XmlAttribute(name = "ordinal") + private int ordinal; + @XmlElementWrapper(name = "systemFields") + @XmlElement(name = "systemField") + private List systemFields; + @XmlElementWrapper(name = "extraFields") + @XmlElement(name = "extraField") + private List extraFields; + @XmlElementWrapper(name = "referenceFields") + @XmlElement(name = "referenceField") + private List referenceFields; + @XmlAttribute(name = "hasTemplates") + private boolean hasTemplates; + @XmlElementWrapper(name = "descriptionTemplates") + @XmlElement(name = "descriptionTemplate") + private List descriptionTemplates; + + 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 int getOrdinal() { + return ordinal; + } + + public void setOrdinal(int ordinal) { + this.ordinal = ordinal; + } + + public List getSystemFields() { + return systemFields; + } + + public void setSystemFields(List systemFields) { + this.systemFields = systemFields; + } + + public List getExtraFields() { + return extraFields; + } + + public void setExtraFields(List extraFields) { + this.extraFields = extraFields; + } + + public List getReferenceFields() { + return referenceFields; + } + + public void setReferenceFields(List referenceFields) { + this.referenceFields = referenceFields; + } + + public boolean isHasTemplates() { + return hasTemplates; + } + + public void setHasTemplates(boolean hasTemplates) { + this.hasTemplates = hasTemplates; + } + + public List getDescriptionTemplates() { + return descriptionTemplates; + } + + public void setDescriptionTemplates(List descriptionTemplates) { + this.descriptionTemplates = descriptionTemplates; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/SystemFieldImportExport.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/SystemFieldImportExport.java new file mode 100644 index 000000000..dc33cd2dd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpblueprint/importexport/SystemFieldImportExport.java @@ -0,0 +1,83 @@ +package org.opencdmp.commons.types.dmpblueprint.importexport; + +import org.opencdmp.commons.enums.DmpBlueprintSystemFieldType; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; + +import java.util.UUID; + +@XmlAccessorType(XmlAccessType.FIELD) +public class SystemFieldImportExport { + + @XmlAttribute(name = "id") + private UUID id; + @XmlAttribute(name = "type") + private DmpBlueprintSystemFieldType type; + @XmlAttribute(name = "label") + private String label; + @XmlAttribute(name = "placeholder") + private String placeholder; + @XmlAttribute(name = "description") + private String description; + @XmlAttribute(name = "ordinal") + private int ordinal; + @XmlAttribute(name = "required") + private boolean required; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public DmpBlueprintSystemFieldType getType() { + return type; + } + + public void setType(DmpBlueprintSystemFieldType type) { + this.type = type; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getPlaceholder() { + return placeholder; + } + + public void setPlaceholder(String placeholder) { + this.placeholder = placeholder; + } + + 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 isRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/dmpreference/DmpReferenceDataEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/dmpreference/DmpReferenceDataEntity.java new file mode 100644 index 000000000..4ce6979ba --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/dmpreference/DmpReferenceDataEntity.java @@ -0,0 +1,15 @@ +package org.opencdmp.commons.types.dmpreference; + +import java.util.UUID; + +public class DmpReferenceDataEntity { + private UUID blueprintFieldId; + + public UUID getBlueprintFieldId() { + return blueprintFieldId; + } + + public void setBlueprintFieldId(UUID blueprintFieldId) { + this.blueprintFieldId = blueprintFieldId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/AuthenticationConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/AuthenticationConfigurationEntity.java new file mode 100644 index 000000000..72e248842 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/AuthenticationConfigurationEntity.java @@ -0,0 +1,69 @@ +package org.opencdmp.commons.types.externalfetcher; + +import org.opencdmp.commons.enums.ExternalFetcherApiHTTPMethodType; +import org.opencdmp.service.externalfetcher.config.entities.AuthenticationConfiguration; +import jakarta.xml.bind.annotation.XmlElement; + +public class AuthenticationConfigurationEntity implements AuthenticationConfiguration { + + private Boolean enabled; + private String authUrl; + private ExternalFetcherApiHTTPMethodType authMethod; + private String authTokenPath; + private String authRequestBody; + private String type; + + public String getAuthUrl() { + return authUrl; + } + + public Boolean getEnabled() { + return enabled; + } + + @XmlElement(name = "enabled") + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + @XmlElement(name = "authUrl") + public void setAuthUrl(String authUrl) { + this.authUrl = authUrl; + } + + public ExternalFetcherApiHTTPMethodType getAuthMethod() { + return authMethod; + } + + @XmlElement(name = "authUrlMethod") + public void setAuthMethod(ExternalFetcherApiHTTPMethodType authMethod) { + this.authMethod = authMethod; + } + + public String getAuthTokenPath() { + return authTokenPath; + } + + @XmlElement(name = "authTokenPath") + 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/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ExternalFetcherApiSourceConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ExternalFetcherApiSourceConfigurationEntity.java new file mode 100644 index 000000000..6a46b4d3a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ExternalFetcherApiSourceConfigurationEntity.java @@ -0,0 +1,105 @@ +package org.opencdmp.commons.types.externalfetcher; + + +import org.opencdmp.commons.enums.ExternalFetcherApiHTTPMethodType; +import org.opencdmp.service.externalfetcher.config.entities.SourceExternalApiConfiguration; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlElementWrapper; + +import java.util.List; +public class ExternalFetcherApiSourceConfigurationEntity extends ExternalFetcherBaseSourceConfigurationEntity implements SourceExternalApiConfiguration { + + private String url; + private ResultsConfigurationEntity results; + private String paginationPath; + private String contentType; + private String firstPage; + private ExternalFetcherApiHTTPMethodType httpMethod; + private String requestBody = ""; + private String filterType = "remote"; + private AuthenticationConfigurationEntity auth; + + private List queries; + + public String getUrl() { + return url; + } + @XmlElement(name = "url") + public void setUrl(String url) { + this.url = url; + } + + public ResultsConfigurationEntity getResults() { + return results; + } + @XmlElement(name = "results") + public void setResults(ResultsConfigurationEntity results) { + this.results = results; + } + + public String getPaginationPath() { + return paginationPath; + } + @XmlElement(name = "paginationPath") + public void setPaginationPath(String paginationPath) { + this.paginationPath = paginationPath; + } + + + public String getContentType() { + return contentType; + } + @XmlElement(name = "contentType") + public void setContentType(String contentType) { + this.contentType = contentType; + } + + public String getFirstPage() { + return firstPage; + } + @XmlElement(name = "firstPage") + public void setFirstPage(String firstPage) { + this.firstPage = firstPage; + } + + public ExternalFetcherApiHTTPMethodType getHttpMethod() { + return httpMethod; + } + @XmlElement(name = "requestHttpMethod") + public void setHttpMethod(ExternalFetcherApiHTTPMethodType httpMethod) { + this.httpMethod = httpMethod != null ? httpMethod : ExternalFetcherApiHTTPMethodType.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 AuthenticationConfigurationEntity getAuth() { + return auth; + } + + @XmlElement(name="authentication") + public void setAuth(AuthenticationConfigurationEntity auth) { + this.auth = auth; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ExternalFetcherBaseSourceConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ExternalFetcherBaseSourceConfigurationEntity.java new file mode 100644 index 000000000..7b9c9a423 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ExternalFetcherBaseSourceConfigurationEntity.java @@ -0,0 +1,66 @@ +package org.opencdmp.commons.types.externalfetcher; + +import org.opencdmp.commons.enums.ExternalFetcherSourceType; +import org.opencdmp.service.externalfetcher.config.entities.SourceBaseConfiguration; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlElementWrapper; + +import java.util.List; +import java.util.UUID; + +public abstract class ExternalFetcherBaseSourceConfigurationEntity implements SourceBaseConfiguration { + + private String key; + + private String label; + + private Integer ordinal; + private ExternalFetcherSourceType type; + + private List referenceTypeDependencyIds; + public ExternalFetcherSourceType getType() { + return type; + } + + 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 Integer getOrdinal() { + return ordinal; + } + + @XmlElement(name = "ordinal") + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } + + @XmlElement(name = "type") + public void setType(ExternalFetcherSourceType type) { + this.type = type; + } + + public List getReferenceTypeDependencyIds() { + return referenceTypeDependencyIds; + } + + @XmlElementWrapper + @XmlElement(name = "referenceTypeDependencyIds") + public void setReferenceTypeDependencyIds(List referenceTypeDependencyIds) { + this.referenceTypeDependencyIds = referenceTypeDependencyIds; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ExternalFetcherStaticOptionSourceConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ExternalFetcherStaticOptionSourceConfigurationEntity.java new file mode 100644 index 000000000..746c1a6fa --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ExternalFetcherStaticOptionSourceConfigurationEntity.java @@ -0,0 +1,22 @@ +package org.opencdmp.commons.types.externalfetcher; + +import org.opencdmp.service.externalfetcher.config.entities.SourceStaticOptionConfiguration; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlElementWrapper; + +import java.util.List; + +public class ExternalFetcherStaticOptionSourceConfigurationEntity extends ExternalFetcherBaseSourceConfigurationEntity implements SourceStaticOptionConfiguration { + + List items; + + public List getItems() { + return items; + } + + @XmlElementWrapper + @XmlElement(name = "item") + public void setItems(List options) { + this.items = options; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/QueryCaseConfigEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/QueryCaseConfigEntity.java new file mode 100644 index 000000000..18e7fc2b7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/QueryCaseConfigEntity.java @@ -0,0 +1,66 @@ +package org.opencdmp.commons.types.externalfetcher; + +import org.opencdmp.service.externalfetcher.config.entities.QueryCaseConfig; +import jakarta.xml.bind.annotation.XmlElement; + +import java.util.UUID; + +public class QueryCaseConfigEntity implements QueryCaseConfig { + + private UUID referenceTypeId; + private String referenceTypeSourceKey; + private String likePattern; + private String separator; + private String value; + + + @Override + public String getReferenceTypeSourceKey() { + return referenceTypeSourceKey; + } + + @XmlElement(name = "referenceTypeSourceKey") + public void setReferenceTypeSourceKey(String referenceTypeSourceKey) { + this.referenceTypeSourceKey = referenceTypeSourceKey; + } + + @Override + public UUID getReferenceTypeId() { + return referenceTypeId; + } + + @XmlElement(name = "referenceTypeId") + public void setReferenceTypeId(UUID referenceTypeId) { + this.referenceTypeId = referenceTypeId; + } + + @Override + public String getLikePattern() { + return likePattern; + } + + @XmlElement(name = "likePattern") + public void setLikePattern(String likePattern) { + this.likePattern = likePattern; + } + + @Override + public String getSeparator() { + return separator; + } + + @XmlElement(name = "separator") + public void setSeparator(String separator) { + this.separator = separator; + } + + @Override + public String getValue() { + return value; + } + + @XmlElement(name = "value") + public void setValue(String value) { + this.value = value; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/QueryConfigEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/QueryConfigEntity.java new file mode 100644 index 000000000..7c058f88f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/QueryConfigEntity.java @@ -0,0 +1,46 @@ +package org.opencdmp.commons.types.externalfetcher; + +import org.opencdmp.service.externalfetcher.config.entities.QueryConfig; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlElementWrapper; + +import java.util.List; + +public class QueryConfigEntity implements QueryConfig { + + private String name; + private String defaultValue; + List cases; + + @Override + public String getName() { + return name; + } + + @XmlElement(name = "name") + public void setName(String name) { + this.name = name; + } + + @Override + public String getDefaultValue() { + return defaultValue; + } + + @XmlElement(name = "defaultValue") + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + @Override + public List getCases() { + return cases; + } + + @XmlElementWrapper + @XmlElement(name = "case") + public void setCases(List cases) { + this.cases = cases; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ResultFieldsMappingConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ResultFieldsMappingConfigurationEntity.java new file mode 100644 index 000000000..e99cb0837 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ResultFieldsMappingConfigurationEntity.java @@ -0,0 +1,28 @@ +package org.opencdmp.commons.types.externalfetcher; + +import org.opencdmp.service.externalfetcher.config.entities.ResultFieldsMappingConfiguration; +import jakarta.xml.bind.annotation.XmlElement; + +public class ResultFieldsMappingConfigurationEntity implements ResultFieldsMappingConfiguration { + private String code; + private String responsePath; + + public String getCode() { + return code; + } + + @XmlElement(name = "code") + public void setCode(String code) { + this.code = code; + } + + public String getResponsePath() { + return responsePath; + } + + @XmlElement(name = "responsePath") + public void setResponsePath(String responsePath) { + this.responsePath = responsePath; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ResultsConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ResultsConfigurationEntity.java new file mode 100644 index 000000000..c6a470db3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/ResultsConfigurationEntity.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.types.externalfetcher; + +import org.opencdmp.service.externalfetcher.config.entities.ResultsConfiguration; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlElementWrapper; + +import java.util.List; + +public class ResultsConfigurationEntity implements ResultsConfiguration { + private String resultsArrayPath; + private List fieldsMapping; + + public String getResultsArrayPath() { + return resultsArrayPath; + } + + @XmlElement(name = "resultsArrayPath") + public void setResultsArrayPath(String resultsArrayPath) { + this.resultsArrayPath = resultsArrayPath; + } + + public List getFieldsMapping() { + return fieldsMapping; + } + + @XmlElementWrapper + @XmlElement(name = "field") + public void setFieldsMapping(List fieldsMapping) { + this.fieldsMapping = fieldsMapping; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/StaticEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/StaticEntity.java new file mode 100644 index 000000000..75e80701e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/StaticEntity.java @@ -0,0 +1,22 @@ +package org.opencdmp.commons.types.externalfetcher; + +import org.opencdmp.service.externalfetcher.config.entities.Static; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlElementWrapper; + +import java.util.List; + +public class StaticEntity implements Static { + + private List options; + + public List getOptions() { + return options; + } + + @XmlElementWrapper + @XmlElement(name = "option") + public void setOptions(List options) { + this.options = options; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/StaticOptionEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/StaticOptionEntity.java new file mode 100644 index 000000000..9a20cf938 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/externalfetcher/StaticOptionEntity.java @@ -0,0 +1,29 @@ +package org.opencdmp.commons.types.externalfetcher; + +import org.opencdmp.service.externalfetcher.config.entities.StaticOption; +import jakarta.xml.bind.annotation.XmlElement; + +public class StaticOptionEntity implements StaticOption { + + private String code; + + private String value; + + public String getCode() { + return code; + } + + @XmlElement(name = "code") + public void setCode(String code) { + this.code = code; + } + + public String getValue() { + return value; + } + + @XmlElement(name = "value") + public void setValue(String value) { + this.value = value; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/filetransformer/FileTransformerSourceEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/filetransformer/FileTransformerSourceEntity.java new file mode 100644 index 000000000..fa34a4f7d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/filetransformer/FileTransformerSourceEntity.java @@ -0,0 +1,59 @@ +package org.opencdmp.commons.types.filetransformer; + +public class FileTransformerSourceEntity { + + private String url; + private String transformerId; + private String issuerUrl; + private String clientId; + private String clientSecret; + private String scope; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getTransformerId() { + return transformerId; + } + + public void setTransformerId(String transformerId) { + this.transformerId = transformerId; + } + + public String getIssuerUrl() { + return issuerUrl; + } + + public void setIssuerUrl(String issuerUrl) { + this.issuerUrl = issuerUrl; + } + + 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 getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } +} \ No newline at end of file diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/notification/Attachment.java b/backend/core/src/main/java/org/opencdmp/commons/types/notification/Attachment.java new file mode 100644 index 000000000..542ab84c7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/notification/Attachment.java @@ -0,0 +1,36 @@ +package org.opencdmp.commons.types.notification; + +public class Attachment { + + private String fileRef, fileName, mimeType; + + public Attachment(String fileRef, String fileName, String mimeType) { + this.fileRef = fileRef; + this.fileName = fileName; + this.mimeType = mimeType; + } + + public String getFileRef() { + return fileRef; + } + + public void setFileRef(String fileRef) { + this.fileRef = fileRef; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getMimeType() { + return mimeType; + } + + public void setMimeType(String mimeType) { + this.mimeType = mimeType; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/notification/ContactPair.java b/backend/core/src/main/java/org/opencdmp/commons/types/notification/ContactPair.java new file mode 100644 index 000000000..3a5a062c0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/notification/ContactPair.java @@ -0,0 +1,33 @@ +package org.opencdmp.commons.types.notification; + + +import org.opencdmp.commons.enums.ContactInfoType; + +public class ContactPair { + private ContactInfoType type; + private String Contact; + + public ContactPair(ContactInfoType type, String contact) { + this.type = type; + Contact = contact; + } + + public ContactPair() { + } + + public ContactInfoType getType() { + return type; + } + + public void setType(ContactInfoType type) { + this.type = type; + } + + public String getContact() { + return Contact; + } + + public void setContact(String contact) { + Contact = contact; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/notification/DataType.java b/backend/core/src/main/java/org/opencdmp/commons/types/notification/DataType.java new file mode 100644 index 000000000..a9788ee63 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/notification/DataType.java @@ -0,0 +1,42 @@ +package org.opencdmp.commons.types.notification; + +import com.fasterxml.jackson.annotation.JsonValue; + +import java.util.HashMap; +import java.util.Map; + +public enum DataType { + Integer(0), + Decimal(1), + Double(2), + DateTime(3), + TimeSpan(4), + String(5); + private static final Map values = new HashMap<>(); + + private final Integer mappedName; + + //For jackson parsing (used by MVC) + @JsonValue + public Integer getMappedName() { + return mappedName; + } + + static { + for (DataType e : values()) { + values.put(e.asInt(), e); + } + } + + private DataType(int mappedName) { + this.mappedName = mappedName; + } + + public Integer asInt() { + return this.mappedName; + } + + public static DataType fromString(Integer value) { + return values.getOrDefault(value, Integer); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/notification/FieldInfo.java b/backend/core/src/main/java/org/opencdmp/commons/types/notification/FieldInfo.java new file mode 100644 index 000000000..c33336fb0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/notification/FieldInfo.java @@ -0,0 +1,40 @@ +package org.opencdmp.commons.types.notification; + +public class FieldInfo { + private String key; + private DataType type; + private String value; + + public FieldInfo(String key, DataType type, String value) { + this.key = key; + this.type = type; + this.value = value; + } + + public FieldInfo() { + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public DataType getType() { + return type; + } + + public void setType(DataType type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/notification/InAppTrackingData.java b/backend/core/src/main/java/org/opencdmp/commons/types/notification/InAppTrackingData.java new file mode 100644 index 000000000..12ef61e8e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/notification/InAppTrackingData.java @@ -0,0 +1,31 @@ +package org.opencdmp.commons.types.notification; + +import java.util.List; +import java.util.UUID; + +public class InAppTrackingData { + + private UUID inAppNotificationId; + private List traces; + + public InAppTrackingData(UUID inAppNotificationId, List traces) { + this.inAppNotificationId = inAppNotificationId; + this.traces = traces; + } + + public UUID getInAppNotificationId() { + return inAppNotificationId; + } + + public void setInAppNotificationId(UUID inAppNotificationId) { + this.inAppNotificationId = inAppNotificationId; + } + + public List getTraces() { + return traces; + } + + public void setTraces(List traces) { + this.traces = traces; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/notification/NotificationContactData.java b/backend/core/src/main/java/org/opencdmp/commons/types/notification/NotificationContactData.java new file mode 100644 index 000000000..94da73622 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/notification/NotificationContactData.java @@ -0,0 +1,39 @@ +package org.opencdmp.commons.types.notification; + +import java.util.List; + +public class NotificationContactData { + private List contacts; + private List BCC; + private List CC; + + public NotificationContactData(List contacts, List BCC, List CC) { + this.contacts = contacts; + this.BCC = BCC; + this.CC = CC; + } + + public List getContacts() { + return contacts; + } + + public void setContacts(List contacts) { + this.contacts = contacts; + } + + public List getBCC() { + return BCC; + } + + public void setBCC(List BCC) { + this.BCC = BCC; + } + + public List getCC() { + return CC; + } + + public void setCC(List CC) { + this.CC = CC; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/notification/NotificationFieldData.java b/backend/core/src/main/java/org/opencdmp/commons/types/notification/NotificationFieldData.java new file mode 100644 index 000000000..10d608b4a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/notification/NotificationFieldData.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.types.notification; + +import java.util.List; + +public class NotificationFieldData { + private List fields; + private List attachments; + + public NotificationFieldData(List fields, List attachments) { + this.fields = fields; + this.attachments = attachments; + } + + public NotificationFieldData() { + } + + public List getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } + + public List getAttachments() { + return attachments; + } + + public void setAttachments(List attachments) { + this.attachments = attachments; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/notification/RouteTrackingData.java b/backend/core/src/main/java/org/opencdmp/commons/types/notification/RouteTrackingData.java new file mode 100644 index 000000000..40f00e244 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/notification/RouteTrackingData.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.types.notification; + +import java.util.List; + +public class RouteTrackingData { + + private String trackingId; + private List traces; + + public RouteTrackingData(String trackingId, List traces) { + this.trackingId = trackingId; + this.traces = traces; + } + + public String getTrackingId() { + return trackingId; + } + + public void setTrackingId(String trackingId) { + this.trackingId = trackingId; + } + + public List getTraces() { + return traces; + } + + public void setTraces(List traces) { + this.traces = traces; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/notification/TrackingTrace.java b/backend/core/src/main/java/org/opencdmp/commons/types/notification/TrackingTrace.java new file mode 100644 index 000000000..2c4218caf --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/notification/TrackingTrace.java @@ -0,0 +1,30 @@ +package org.opencdmp.commons.types.notification; + +import java.time.Instant; + +public class TrackingTrace { + + private Instant at; + private String data; + + public TrackingTrace(Instant at, String data) { + this.at = at; + this.data = data; + } + + public Instant getAt() { + return at; + } + + public void setAt(Instant at) { + this.at = at; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/prefillingsource/PrefillingSourceDefinitionEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/prefillingsource/PrefillingSourceDefinitionEntity.java new file mode 100644 index 000000000..0d2fa7268 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/prefillingsource/PrefillingSourceDefinitionEntity.java @@ -0,0 +1,53 @@ +package org.opencdmp.commons.types.prefillingsource; + +import org.opencdmp.commons.types.externalfetcher.ExternalFetcherApiSourceConfigurationEntity; +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlRootElement(name = "definition") +@XmlAccessorType(XmlAccessType.FIELD) +public class PrefillingSourceDefinitionEntity { + @XmlElement(name = "searchConfiguration") + private ExternalFetcherApiSourceConfigurationEntity searchConfiguration; + @XmlElement(name = "getConfiguration") + private ExternalFetcherApiSourceConfigurationEntity getConfiguration; + @XmlElementWrapper(name = "fields") + @XmlElement(name = "field") + private List fields; + @XmlElementWrapper(name = "fixedValueFields") + @XmlElement(name = "fixedValueField") + private List fixedValueFields; + + public ExternalFetcherApiSourceConfigurationEntity getSearchConfiguration() { + return searchConfiguration; + } + + public void setSearchConfiguration(ExternalFetcherApiSourceConfigurationEntity searchConfiguration) { + this.searchConfiguration = searchConfiguration; + } + + public ExternalFetcherApiSourceConfigurationEntity getGetConfiguration() { + return getConfiguration; + } + + public void setGetConfiguration(ExternalFetcherApiSourceConfigurationEntity getConfiguration) { + this.getConfiguration = getConfiguration; + } + + public List getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } + + public List getFixedValueFields() { + return fixedValueFields; + } + + public void setFixedValueFields(List fixedValueFields) { + this.fixedValueFields = fixedValueFields; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/prefillingsource/PrefillingSourceDefinitionFieldEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/prefillingsource/PrefillingSourceDefinitionFieldEntity.java new file mode 100644 index 000000000..f052b5c97 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/prefillingsource/PrefillingSourceDefinitionFieldEntity.java @@ -0,0 +1,47 @@ +package org.opencdmp.commons.types.prefillingsource; + +import jakarta.xml.bind.annotation.XmlElement; + +public class PrefillingSourceDefinitionFieldEntity { + private String code; + private String systemFieldTarget; + private String semanticTarget; + private String trimRegex; + + public String getCode() { + return code; + } + + @XmlElement(name = "code") + public void setCode(String code) { + this.code = code; + } + + public String getSystemFieldTarget() { + return systemFieldTarget; + } + + @XmlElement(name = "systemFieldTarget") + public void setSystemFieldTarget(String systemFieldTarget) { + this.systemFieldTarget = systemFieldTarget; + } + + public String getSemanticTarget() { + return semanticTarget; + } + + @XmlElement(name = "semanticTarget") + public void setSemanticTarget(String semanticTarget) { + this.semanticTarget = semanticTarget; + } + + public String getTrimRegex() { + return trimRegex; + } + + @XmlElement(name = "trimRegex") + public void setTrimRegex(String trimRegex) { + this.trimRegex = trimRegex; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/prefillingsource/PrefillingSourceDefinitionFixedValueFieldEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/prefillingsource/PrefillingSourceDefinitionFixedValueFieldEntity.java new file mode 100644 index 000000000..a52b245a9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/prefillingsource/PrefillingSourceDefinitionFixedValueFieldEntity.java @@ -0,0 +1,46 @@ +package org.opencdmp.commons.types.prefillingsource; + +import jakarta.xml.bind.annotation.XmlElement; + +public class PrefillingSourceDefinitionFixedValueFieldEntity { + private String systemFieldTarget; + private String semanticTarget; + private String trimRegex; + private String fixedValue; + + public String getSystemFieldTarget() { + return systemFieldTarget; + } + + @XmlElement(name = "systemFieldTarget") + public void setSystemFieldTarget(String systemFieldTarget) { + this.systemFieldTarget = systemFieldTarget; + } + + public String getSemanticTarget() { + return semanticTarget; + } + + @XmlElement(name = "semanticTarget") + public void setSemanticTarget(String semanticTarget) { + this.semanticTarget = semanticTarget; + } + + public String getTrimRegex() { + return trimRegex; + } + + @XmlElement(name = "trimRegex") + public void setTrimRegex(String trimRegex) { + this.trimRegex = trimRegex; + } + + public String getFixedValue() { + return fixedValue; + } + + @XmlElement(name = "fixedValue") + public void setFixedValue(String fixedValue) { + this.fixedValue = fixedValue; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/reference/DefinitionEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/reference/DefinitionEntity.java new file mode 100644 index 000000000..583b17b55 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/reference/DefinitionEntity.java @@ -0,0 +1,22 @@ +package org.opencdmp.commons.types.reference; + +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlRootElement(name = "definition") +@XmlAccessorType(XmlAccessType.FIELD) +public class DefinitionEntity { + @XmlElementWrapper(name = "fields") + @XmlElement(name = "field") + private List fields; + + public List getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/reference/FieldEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/reference/FieldEntity.java new file mode 100644 index 000000000..f05e2927b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/reference/FieldEntity.java @@ -0,0 +1,47 @@ +package org.opencdmp.commons.types.reference; + +import org.opencdmp.commons.enums.ReferenceFieldDataType; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "field") +@XmlAccessorType(XmlAccessType.FIELD) +public class FieldEntity { + + @XmlAttribute(name = "code") + private String code; + @XmlAttribute(name = "dataType") + private ReferenceFieldDataType dataType; + @XmlAttribute(name = "value") + private String value; + + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + + public ReferenceFieldDataType getDataType() { + return dataType; + } + + public void setDataType(ReferenceFieldDataType dataType) { + this.dataType = dataType; + } + + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/referencetype/ReferenceTypeDefinitionEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/referencetype/ReferenceTypeDefinitionEntity.java new file mode 100644 index 000000000..64e82f799 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/referencetype/ReferenceTypeDefinitionEntity.java @@ -0,0 +1,40 @@ +package org.opencdmp.commons.types.referencetype; + +import org.opencdmp.commons.enums.ExternalFetcherSourceType; +import org.opencdmp.commons.types.externalfetcher.ExternalFetcherBaseSourceConfigurationEntity; +import org.opencdmp.commons.types.externalfetcher.ExternalFetcherApiSourceConfigurationEntity; +import org.opencdmp.commons.types.externalfetcher.ExternalFetcherStaticOptionSourceConfigurationEntity; +import jakarta.xml.bind.annotation.*; + +import java.util.List; + +@XmlRootElement(name = "definition") +@XmlAccessorType(XmlAccessType.FIELD) +public class ReferenceTypeDefinitionEntity { + @XmlElementWrapper(name = "fields") + @XmlElement(name = "field") + private List fields; + + @XmlElementWrapper(name = "sources") + @XmlElements({ + @XmlElement(name = ExternalFetcherSourceType.Names.API, type = ExternalFetcherApiSourceConfigurationEntity.class), + @XmlElement(name = ExternalFetcherSourceType.Names.STATIC, type = ExternalFetcherStaticOptionSourceConfigurationEntity.class), + }) + private List sources; + + public List getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } + + public List getSources() { + return sources; + } + + public void setSources(List sources) { + this.sources = sources; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/referencetype/ReferenceTypeFieldEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/referencetype/ReferenceTypeFieldEntity.java new file mode 100644 index 000000000..c5fd5a8bb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/referencetype/ReferenceTypeFieldEntity.java @@ -0,0 +1,57 @@ +package org.opencdmp.commons.types.referencetype; + +import org.opencdmp.commons.enums.ReferenceFieldDataType; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "field") +@XmlAccessorType(XmlAccessType.FIELD) +public class ReferenceTypeFieldEntity { + + @XmlAttribute(name = "code") + private String code; + + @XmlAttribute(name = "label") + private String label; + + @XmlAttribute(name = "description") + private String description; + @XmlAttribute(name = "dataType") + private ReferenceFieldDataType dataType; + + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + 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 ReferenceFieldDataType getDataType() { + return dataType; + } + + public void setDataType(ReferenceFieldDataType dataType) { + this.dataType = dataType; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/CssColorsTenantConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/CssColorsTenantConfigurationEntity.java new file mode 100644 index 000000000..f54090d26 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/CssColorsTenantConfigurationEntity.java @@ -0,0 +1,40 @@ +package org.opencdmp.commons.types.tenantconfiguration; + +public class CssColorsTenantConfigurationEntity { + private String primaryColor; + private String primaryColor2; + private String primaryColor3; + private String secondaryColor; + + public String getPrimaryColor() { + return primaryColor; + } + + public void setPrimaryColor(String primaryColor) { + this.primaryColor = primaryColor; + } + + public String getPrimaryColor2() { + return primaryColor2; + } + + public void setPrimaryColor2(String primaryColor2) { + this.primaryColor2 = primaryColor2; + } + + public String getPrimaryColor3() { + return primaryColor3; + } + + public void setPrimaryColor3(String primaryColor3) { + this.primaryColor3 = primaryColor3; + } + + public String getSecondaryColor() { + return secondaryColor; + } + + public void setSecondaryColor(String secondaryColor) { + this.secondaryColor = secondaryColor; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/DefaultUserLocaleTenantConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/DefaultUserLocaleTenantConfigurationEntity.java new file mode 100644 index 000000000..224e64b57 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/DefaultUserLocaleTenantConfigurationEntity.java @@ -0,0 +1,32 @@ +package org.opencdmp.commons.types.tenantconfiguration; + +public class DefaultUserLocaleTenantConfigurationEntity { + private String timezone; + private String language; + private String culture; + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getCulture() { + return culture; + } + + public void setCulture(String culture) { + this.culture = culture; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/DepositTenantConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/DepositTenantConfigurationEntity.java new file mode 100644 index 000000000..3a355bf60 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/DepositTenantConfigurationEntity.java @@ -0,0 +1,26 @@ +package org.opencdmp.commons.types.tenantconfiguration; + +import org.opencdmp.commons.types.deposit.DepositSourceEntity; + +import java.util.List; + +public class DepositTenantConfigurationEntity { + private List sources; + private boolean disableSystemSources; + + public List getSources() { + return sources; + } + + public void setSources(List sources) { + this.sources = sources; + } + + public boolean getDisableSystemSources() { + return disableSystemSources; + } + + public void setDisableSystemSources(boolean disableSystemSources) { + this.disableSystemSources = disableSystemSources; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/FileTransformerTenantConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/FileTransformerTenantConfigurationEntity.java new file mode 100644 index 000000000..e726a6c25 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/FileTransformerTenantConfigurationEntity.java @@ -0,0 +1,27 @@ +package org.opencdmp.commons.types.tenantconfiguration; + +import org.opencdmp.commons.types.filetransformer.FileTransformerSourceEntity; + +import java.util.List; + +public class FileTransformerTenantConfigurationEntity { + + private List sources; + private boolean disableSystemSources; + + public List getSources() { + return sources; + } + + public void setSources(List sources) { + this.sources = sources; + } + + public boolean getDisableSystemSources() { + return disableSystemSources; + } + + public void setDisableSystemSources(boolean disableSystemSources) { + this.disableSystemSources = disableSystemSources; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/LogoTenantConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/LogoTenantConfigurationEntity.java new file mode 100644 index 000000000..efb71be07 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/tenantconfiguration/LogoTenantConfigurationEntity.java @@ -0,0 +1,15 @@ +package org.opencdmp.commons.types.tenantconfiguration; + +import java.util.UUID; + +public class LogoTenantConfigurationEntity { + private UUID storageFileId; + + public UUID getStorageFileId() { + return storageFileId; + } + + public void setStorageFileId(UUID storageFileId) { + this.storageFileId = storageFileId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/user/AdditionalInfoEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/user/AdditionalInfoEntity.java new file mode 100644 index 000000000..8c453b1b6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/user/AdditionalInfoEntity.java @@ -0,0 +1,60 @@ +package org.opencdmp.commons.types.user; + +import java.util.UUID; + +public class AdditionalInfoEntity { + private String avatarUrl; + private String timezone; + private String culture; + private String language; + private String roleOrganization; + private UUID organizationId; + + public String getAvatarUrl() { + return avatarUrl; + } + + public void setAvatarUrl(String avatarUrl) { + this.avatarUrl = avatarUrl; + } + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + public String getCulture() { + return culture; + } + + public void setCulture(String culture) { + this.culture = culture; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public UUID getOrganizationId() { + return organizationId; + } + + public void setOrganizationId(UUID organizationId) { + this.organizationId = organizationId; + } + + public String getRoleOrganization() { + return roleOrganization; + } + + public void setRoleOrganization(String roleOrganization) { + this.roleOrganization = roleOrganization; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/types/usercredential/UserCredentialDataEntity.java b/backend/core/src/main/java/org/opencdmp/commons/types/usercredential/UserCredentialDataEntity.java new file mode 100644 index 000000000..197aaac93 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/types/usercredential/UserCredentialDataEntity.java @@ -0,0 +1,24 @@ +package org.opencdmp.commons.types.usercredential; + +import java.util.List; + +public class UserCredentialDataEntity { + private List externalProviderNames; + private String email; + + public List getExternalProviderNames() { + return externalProviderNames; + } + + public void setExternalProviderNames(List externalProviderNames) { + this.externalProviderNames = externalProviderNames; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/commons/validation/BaseValidator.java b/backend/core/src/main/java/org/opencdmp/commons/validation/BaseValidator.java new file mode 100644 index 000000000..52563f444 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/commons/validation/BaseValidator.java @@ -0,0 +1,78 @@ +package org.opencdmp.commons.validation; + +import org.opencdmp.convention.ConventionService; +import org.opencdmp.errorcode.ErrorThesaurusProperties; +import gr.cite.tools.exception.MyValidationException; +import gr.cite.tools.validation.AbstractValidator; +import gr.cite.tools.validation.ValidationResult; +import org.apache.commons.validator.routines.EmailValidator; + +import java.util.*; + +public abstract class BaseValidator extends AbstractValidator { + protected final ConventionService conventionService; + protected final ErrorThesaurusProperties errors; + + protected BaseValidator(ConventionService conventionService, ErrorThesaurusProperties errors) { + this.conventionService = conventionService; + this.errors = errors; + } + + @Override + public void validateForce(Object target) { + this.validate(target); + ValidationResult result = result(); + if (!result.isValid()) { + List>> errorsMap = this.flattenValidationResult(); + throw new MyValidationException(this.errors.getModelValidation().getCode(), errorsMap); + } + } + + protected Boolean isValidGuid(UUID guid) { + return this.conventionService.isValidGuid(guid); + } + protected Boolean isValidEmail(String value) { + return EmailValidator.getInstance().isValid(value); + } + + protected Boolean isValidHash(String hash) { + return this.conventionService.isValidHash(hash); + } + + protected Boolean isEmpty(String value) { + return this.conventionService.isNullOrEmpty(value); + } + protected Boolean isListNullOrEmpty(List value) { + return this.conventionService.isListNullOrEmpty(value); + } + protected Boolean isNull(Object value) { + return value == null; + } + + protected boolean isBoolean(String value) { + return value != null && Arrays.stream(new String[]{"true", "false"}) + .anyMatch(b -> b.equalsIgnoreCase(value)); + } + + protected boolean isUUID(String value) { + try { + UUID.fromString(value); + return true; + } catch (Exception e){ + return false; + } + } + + protected Boolean isNull(Collection value) { + return value == null; + } + + protected Boolean lessEqualLength(String value, int size) { + return value.length() <= size; + } + + protected Boolean lessEqual(Integer value, int target) { + return value <= target; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/convention/ConventionService.java b/backend/core/src/main/java/org/opencdmp/convention/ConventionService.java new file mode 100644 index 000000000..13561f778 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/convention/ConventionService.java @@ -0,0 +1,40 @@ +package org.opencdmp.convention; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; + +public interface ConventionService { + + Boolean isValidId(Integer id); + + Boolean isValidGuid(UUID guid); + + Boolean isValidUUID(String str); + UUID parseUUIDSafe(String str); + + Boolean isValidHash(String hash); + + String hashValue(Object value); + + String limit(String text, int maxLength); + + String truncate(String text, int maxLength); + + UUID getEmptyUUID(); + + boolean isNullOrEmpty(String value); + + boolean isListNullOrEmpty(List value); + + String stringEmpty(); + + String asPrefix(String name); + + String asIndexerPrefix(String part); + + String asIndexer(String... names); + + Map> toDictionaryOfList(List items, Function keySelector); +} diff --git a/backend/core/src/main/java/org/opencdmp/convention/ConventionServiceImpl.java b/backend/core/src/main/java/org/opencdmp/convention/ConventionServiceImpl.java new file mode 100644 index 000000000..052ba92b9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/convention/ConventionServiceImpl.java @@ -0,0 +1,150 @@ +package org.opencdmp.convention; + +import org.opencdmp.errorcode.ErrorThesaurusProperties; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.time.Instant; +import java.util.*; +import java.util.function.Function; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) +public class ConventionServiceImpl implements ConventionService { + private final static Pattern UUID_REGEX_PATTERN = Pattern.compile("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$"); + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ConventionServiceImpl.class)); + private final ErrorThesaurusProperties errors; + + @Autowired + public ConventionServiceImpl(ErrorThesaurusProperties errors) { + this.errors = errors; + } + + @Override + public Boolean isValidId(Integer id) { + return id != null && id > 0; + } + + @Override + public Boolean isValidGuid(UUID guid) { + return guid != null && !guid.equals(this.getEmptyUUID()); + } + + @Override + public Boolean isValidUUID(String str) { + if (this.isNullOrEmpty(str)) { + return false; + } + return UUID_REGEX_PATTERN.matcher(str).matches(); + } + + @Override + public UUID parseUUIDSafe(String str) { + if (!this.isValidUUID(str)) { + return null; + } + try { + return UUID.fromString(str); + } catch (Exception ex){ + logger.warn("invalid uuid" + str, ex); + return null; + } + } + + @Override + public Boolean isValidHash(String hash) { + return !this.isNullOrEmpty(hash); + } + + @Override + public String hashValue(Object value) throws MyApplicationException { + if (value == null) return this.stringEmpty(); + if (value instanceof Instant) return String.format("%ts", (Instant) value); + throw new MyApplicationException(this.errors.getSystemError().getCode(), this.errors.getSystemError().getMessage()); + } + + @Override + public String limit(String text, int maxLength) { + if (this.isNullOrEmpty(text)) return text; + if (text.length() > maxLength) return String.format("%s...", text.substring(0, maxLength)); + else return text; + } + + @Override + public String truncate(String text, int maxLength) { + String truncated = text; + if (text.length() < maxLength) return text; + + truncated = truncated.trim(); + truncated = truncated.replaceAll("\\s+", " ");//remove multiple spaces + if (truncated.length() < maxLength) return truncated; + truncated = truncated.replaceAll("([.!@#$%^&-=':;,<>?*\"/|])+", "");//remove multiple spaces + if (truncated.length() < maxLength) return truncated; + truncated = truncated.replaceAll("([aeiou])+", "");//remove multiple spaces + if (truncated.length() < maxLength) return truncated; + truncated = truncated.replaceAll("([AEIOU])+", "");//remove multiple spaces + if (truncated.length() < maxLength) return truncated; + + if (text.length() > maxLength) return String.format("%s...", text.substring(0, maxLength)); + return text; + + } + + @Override + public UUID getEmptyUUID() { + return new UUID(0L, 0L); + } + + @Override + public boolean isNullOrEmpty(String value) { + return value == null || value.isEmpty(); + } + + @Override + public boolean isListNullOrEmpty(List value) { + if(value == null) return true; + return value.isEmpty(); + } + + @Override + public String stringEmpty() { + return ""; + } + + @Override + public String asPrefix(String name) { + if (name == null) return null; + return name + "."; + } + + @Override + public String asIndexer(String... names) { + if (names == null) return null; + return String.join(".", Arrays.stream(names).filter(x -> !this.isNullOrEmpty(x)).collect(Collectors.toList())); + } + + @Override + public String asIndexerPrefix(String part) { + if (part == null) return null; + return part + "."; + } + + @Override + public Map> toDictionaryOfList(List items, Function keySelector) { + Map> map = new HashMap<>(); + for (V model : items) { + K key = keySelector.apply(model); + if (!map.containsKey(key)) map.put(key, new ArrayList()); + map.get(key).add(model); + } + return map; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/ActionConfirmationEntity.java b/backend/core/src/main/java/org/opencdmp/data/ActionConfirmationEntity.java new file mode 100644 index 000000000..1243a148c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/ActionConfirmationEntity.java @@ -0,0 +1,143 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.ActionConfirmationStatus; +import org.opencdmp.commons.enums.ActionConfirmationType; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.ActionConfirmationStatusConverter; +import org.opencdmp.data.converters.enums.ActionConfirmationTypeConverter; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"ActionConfirmation\"") +public class ActionConfirmationEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "type", nullable = false) + @Convert(converter = ActionConfirmationTypeConverter.class) + private ActionConfirmationType type; + public static final String _type = "type"; + + @Column(name = "status", nullable = false) + @Convert(converter = ActionConfirmationStatusConverter.class) + private ActionConfirmationStatus status; + public static final String _status = "status"; + + @Column(name = "\"token\"", updatable = false, nullable = false) + private String token; + public static final String _token = "token"; + + @Column(name = "\"data\"", nullable = false) + private String data; + public static final String _data = "data"; + + @Column(name = "\"expires_at\"", nullable = false) + private Instant expiresAt; + public static final String _expiresAt = "expiresAt"; + + @Column(name = "created_by", columnDefinition = "uuid", nullable = false) + private UUID createdById; + public static final String _createdById = "createdById"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public ActionConfirmationType getType() { + return type; + } + + public void setType(ActionConfirmationType type) { + this.type = type; + } + + public ActionConfirmationStatus getStatus() { + return status; + } + + public void setStatus(ActionConfirmationStatus status) { + this.status = status; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public Instant getExpiresAt() { + return expiresAt; + } + + public void setExpiresAt(Instant expiresAt) { + this.expiresAt = expiresAt; + } + + public UUID getCreatedById() { + return createdById; + } + + public void setCreatedById(UUID createdById) { + this.createdById = createdById; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/DescriptionEntity.java b/backend/core/src/main/java/org/opencdmp/data/DescriptionEntity.java new file mode 100644 index 000000000..137cddc79 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/DescriptionEntity.java @@ -0,0 +1,192 @@ +package org.opencdmp.data; + + +import org.opencdmp.commons.enums.DescriptionStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.DescriptionStatusConverter; +import org.opencdmp.data.converters.enums.IsActiveConverter; + +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.*; + + +@Entity +@Table(name = "\"Description\"") +public class DescriptionEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + + public static final String _id = "id"; + + @Column(name = "label", length = DescriptionEntity._labelLength, nullable = false) + private String label; + public static final int _labelLength = 250; + + public static final String _label = "label"; + + + @Column(name = "properties") + private String properties; + + public static final String _properties = "properties"; + + @Column(name = "status", nullable = false) + @Convert(converter = DescriptionStatusConverter.class) + private DescriptionStatus status; + public static final String _status = "status"; + + @Column(name = "description") + private String description; + + public static final String _description = "description"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + @Column(name = "\"finalized_at\"") + private Instant finalizedAt; + + public static final String _finalizedAt = "finalizedAt"; + + @Column(name = "created_by", columnDefinition = "uuid", nullable = false) + private UUID createdById; + + public static final String _createdById = "createdById"; + + @Column(name = "dmp_description_template", columnDefinition = "uuid", nullable = false) + private UUID dmpDescriptionTemplateId; + public static final String _dmpDescriptionTemplateId = "dmpDescriptionTemplateId"; + + @Column(name = "dmp", columnDefinition = "uuid", nullable = false) + private UUID dmpId; + public static final String _dmpId = "dmpId"; + + @Column(name = "description_template", columnDefinition = "uuid", nullable = false) + private UUID descriptionTemplateId; + public static final String _descriptionTemplateId = "descriptionTemplateId"; + + + + 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 getProperties() { + return properties; + } + + public void setProperties(String properties) { + this.properties = properties; + } + + public DescriptionStatus getStatus() { + return status; + } + + public void setStatus(DescriptionStatus status) { + this.status = status; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Instant finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public UUID getCreatedById() { + return createdById; + } + + public void setCreatedById(UUID createdById) { + this.createdById = createdById; + } + + public UUID getDmpDescriptionTemplateId() { + return dmpDescriptionTemplateId; + } + + public void setDmpDescriptionTemplateId(UUID dmpDescriptionTemplateId) { + this.dmpDescriptionTemplateId = dmpDescriptionTemplateId; + } + + public UUID getDmpId() { + return dmpId; + } + + public void setDmpId(UUID dmpId) { + this.dmpId = dmpId; + } + + public UUID getDescriptionTemplateId() { + return descriptionTemplateId; + } + + public void setDescriptionTemplateId(UUID descriptionTemplateId) { + this.descriptionTemplateId = descriptionTemplateId; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/data/DescriptionReferenceEntity.java b/backend/core/src/main/java/org/opencdmp/data/DescriptionReferenceEntity.java new file mode 100644 index 000000000..355a182f8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/DescriptionReferenceEntity.java @@ -0,0 +1,107 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"DescriptionReference\"") +public class DescriptionReferenceEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + public static final String _id = "id"; + + @Column(name = "data") + private String data; + + public static final String _data = "data"; + + @Column(name = "description_id", columnDefinition = "uuid", nullable = false) + private UUID descriptionId; + + public static final String _descriptionId = "descriptionId"; + + @Column(name = "reference_id", columnDefinition = "uuid", nullable = false) + private UUID referenceId; + + public static final String _referenceId = "referenceId"; + + @Column(name = "created_at") + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at") + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getDescriptionId() { + return descriptionId; + } + + public void setDescriptionId(UUID descriptionId) { + this.descriptionId = descriptionId; + } + + public UUID getReferenceId() { + return referenceId; + } + + public void setReferenceId(UUID referenceId) { + this.referenceId = referenceId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/DescriptionTagEntity.java b/backend/core/src/main/java/org/opencdmp/data/DescriptionTagEntity.java new file mode 100644 index 000000000..628acdf4a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/DescriptionTagEntity.java @@ -0,0 +1,95 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"DescriptionTag\"") +public class DescriptionTagEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + public static final String _id = "id"; + + @Column(name = "description", columnDefinition = "uuid", nullable = false) + private UUID descriptionId; + + public static final String _descriptionId = "descriptionId"; + + @Column(name = "tag", columnDefinition = "uuid", nullable = false) + private UUID tagId; + + public static final String _tagId = "tagId"; + + @Column(name = "created_at") + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at") + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getDescriptionId() { + return descriptionId; + } + + public void setDescriptionId(UUID descriptionId) { + this.descriptionId = descriptionId; + } + + public UUID getTagId() { + return tagId; + } + + public void setTagId(UUID tagId) { + this.tagId = tagId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/DescriptionTemplateEntity.java b/backend/core/src/main/java/org/opencdmp/data/DescriptionTemplateEntity.java new file mode 100644 index 000000000..e7a4b7de5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/DescriptionTemplateEntity.java @@ -0,0 +1,165 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.DescriptionTemplateStatus; +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.DescriptionTemplateStatusConverter; +import org.opencdmp.data.converters.enums.DescriptionTemplateVersionStatusConverter; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import org.opencdmp.data.types.SQLXMLType; +import jakarta.persistence.*; +import org.hibernate.annotations.Type; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"DescriptionTemplate\"") +public class DescriptionTemplateEntity extends TenantScopedBaseEntity { + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "label", length = DescriptionTemplateEntity._labelLength, nullable = false) + private String label; + public static final String _label = "label"; + public static final int _labelLength = 250; + + @Type(value = SQLXMLType.class) + @Column(name = "definition", nullable = false, columnDefinition = "xml") + private String definition; + public static final String _definition = "definition"; + + @Column(name = "status", nullable = false) + @Convert(converter = DescriptionTemplateStatusConverter.class) + private DescriptionTemplateStatus status; + public static final String _status = "status"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public static final String _isActive = "isActive"; + + + @Column(name = "created_at", nullable = false) + private Instant createdAt = null; + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + @Column(name = "description", nullable = false) + private String description; + public static final String _description = "description"; + + @Column(name = "group_id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID groupId; + public static final String _groupId = "groupId"; + + @Column(name = "version", nullable = false) + private Short version; + public static final String _version = "version"; + + @Column(name = "version_status", nullable = false) + @Convert(converter = DescriptionTemplateVersionStatusConverter.class) + private DescriptionTemplateVersionStatus versionStatus; + public static final String _versionStatus = "versionStatus"; + + @Column(name = "language", nullable = false) + private String language; + public static final String _language = "language"; + + @Column(name = "type", nullable = false) + private UUID typeId; + public static final String _typeId = "typeId"; + + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + + 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 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 DescriptionTemplateStatus getStatus() { + return status; + } + + public void setStatus(DescriptionTemplateStatus status) { + this.status = status; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public UUID getTypeId() { + return typeId; + } + + public void setTypeId(UUID typeId) { + this.typeId = typeId; + } + + public DescriptionTemplateVersionStatus getVersionStatus() { + return versionStatus; + } + + public void setVersionStatus(DescriptionTemplateVersionStatus versionStatus) { + this.versionStatus = versionStatus; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/DescriptionTemplateTypeEntity.java b/backend/core/src/main/java/org/opencdmp/data/DescriptionTemplateTypeEntity.java new file mode 100644 index 000000000..c7ada0082 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/DescriptionTemplateTypeEntity.java @@ -0,0 +1,98 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.DescriptionTemplateTypeStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.DescriptionTemplateTypeStatusConverter; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"DescriptionTemplateType\"") +public class DescriptionTemplateTypeEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + + public static final String _id = "id"; + + @Column(name = "name", length = DescriptionTemplateTypeEntity._nameLength, nullable = false) + private String name; + public static final int _nameLength = 500; + + public static final String _name = "name"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + @Column(name = "status", nullable = false) + @Convert(converter = DescriptionTemplateTypeStatusConverter.class) + private DescriptionTemplateTypeStatus status; + + public static final String _status = "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 Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public DescriptionTemplateTypeStatus getStatus() { + return status; + } + + public void setStatus(DescriptionTemplateTypeStatus status) { + this.status = status; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/DmpBlueprintEntity.java b/backend/core/src/main/java/org/opencdmp/data/DmpBlueprintEntity.java new file mode 100644 index 000000000..bb6fabd6a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/DmpBlueprintEntity.java @@ -0,0 +1,157 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.DmpBlueprintStatus; +import org.opencdmp.commons.enums.DmpBlueprintVersionStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.DmpBlueprintVersionStatusConverter; +import org.opencdmp.data.converters.enums.DmpBlueprintStatusConverter; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import org.opencdmp.data.types.SQLXMLType; +import jakarta.persistence.*; +import org.hibernate.annotations.Type; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"DmpBlueprint\"") +public class DmpBlueprintEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + + public static final String _id = "id"; + + @Column(name = "label", length = DmpBlueprintEntity._labelLength, nullable = false) + private String label; + + public static final String _label = "label"; + + public static final int _labelLength = 250; + + @Type(value = SQLXMLType.class) + @Column(name = "definition", columnDefinition = "xml") + private String definition; + + public static final String _definition = "definition"; + + @Column(name = "status", nullable = false) + @Convert(converter = DmpBlueprintStatusConverter.class) + private DmpBlueprintStatus status; + + public static final String _status = "status"; + + @Column(name = "group_id", columnDefinition = "uuid", nullable = false) + private UUID groupId; + + public static final String _groupId = "groupId"; + + @Column(name = "version", nullable = false) + private Short version; + + public static final String _version = "version"; + + @Column(name = "version_status", nullable = false) + @Convert(converter = DmpBlueprintVersionStatusConverter.class) + private DmpBlueprintVersionStatus versionStatus; + + public static final String _versionStatus = "versionStatus"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt = null; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + 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 DmpBlueprintStatus getStatus() { + return status; + } + + public void setStatus(DmpBlueprintStatus status) { + this.status = status; + } + + 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 DmpBlueprintVersionStatus getVersionStatus() { + return versionStatus; + } + + public void setVersionStatus(DmpBlueprintVersionStatus versionStatus) { + this.versionStatus = versionStatus; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/DmpDescriptionTemplateEntity.java b/backend/core/src/main/java/org/opencdmp/data/DmpDescriptionTemplateEntity.java new file mode 100644 index 000000000..6877cd4ae --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/DmpDescriptionTemplateEntity.java @@ -0,0 +1,107 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"DmpDescriptionTemplate\"") +public class DmpDescriptionTemplateEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + public static final String _id = "id"; + + @Column(name = "dmp", columnDefinition = "uuid", nullable = false) + private UUID dmpId; + + public static final String _dmpId = "dmpId"; + + @Column(name = "description_template_group", columnDefinition = "uuid", nullable = false) + private UUID descriptionTemplateGroupId; + + public static final String _descriptionTemplateGroupId = "descriptionTemplateGroupId"; + + @Column(name = "section_id") + private UUID sectionId; + + public static final String _sectionId = "sectionId"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getDmpId() { + return dmpId; + } + + public void setDmpId(UUID dmpId) { + this.dmpId = dmpId; + } + + public UUID getDescriptionTemplateGroupId() { + return descriptionTemplateGroupId; + } + + public void setDescriptionTemplateGroupId(UUID descriptionTemplateGroupId) { + this.descriptionTemplateGroupId = descriptionTemplateGroupId; + } + + public UUID getSectionId() { + return sectionId; + } + + public void setSectionId(UUID sectionId) { + this.sectionId = sectionId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/DmpEntity.java b/backend/core/src/main/java/org/opencdmp/data/DmpEntity.java new file mode 100644 index 000000000..27646a807 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/DmpEntity.java @@ -0,0 +1,247 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.DmpAccessType; +import org.opencdmp.commons.enums.DmpStatus; +import org.opencdmp.commons.enums.DmpVersionStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.DmpAccessTypeNullableConverter; +import org.opencdmp.data.converters.enums.DmpStatusConverter; +import org.opencdmp.data.converters.enums.DmpVersionStatusConverter; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"Dmp\"") +public class DmpEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + public static final String _id = "id"; + + @Column(name = "label", length = DescriptionEntity._labelLength, nullable = false) + private String label; + + public static final String _label = "label"; + public static final int _labelLength = 250; + + @Column(name = "version", nullable = false) + private Short version; + + public static final String _version = "version"; + + @Column(name = "version_status", nullable = false) + @Convert(converter = DmpVersionStatusConverter.class) + private DmpVersionStatus versionStatus; + + public static final String _versionStatus = "versionStatus"; + + @Column(name = "status", nullable = false) + @Convert(converter = DmpStatusConverter.class) + private DmpStatus status; + + public static final String _status = "status"; + + @Column(name = "properties", nullable = true) + private String properties; + + public static final String _properties = "properties"; + + @Column(name = "group_id", nullable = false) + private UUID groupId; + + public static final String _groupId = "groupId"; + + @Column(name = "description", nullable = true) + private String description; + + public static final String _description = "description"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + @Column(name = "finalized_at") + private Instant finalizedAt; + + public static final String _finalizedAt = "finalizedAt"; + + @Column(name = "creator", nullable = false) + private UUID creatorId; + + public static final String _creatorId = "creatorId"; + + @Column(name = "access_type", nullable = true) + @Convert(converter = DmpAccessTypeNullableConverter.class) + private DmpAccessType accessType; + + public static final String _accessType = "accessType"; + + @Column(name = "blueprint", nullable = false) + private UUID blueprintId; + + public static final String _blueprintId = "blueprintId"; + + @Column(name = "language", nullable = true) + private String language; + + public static final String _language = "language"; + + @Column(name = "public_after", nullable = true) + private Instant publicAfter; + + public static final String _publicAfter = "publicAfter"; + + 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 Short getVersion() { + return version; + } + + public void setVersion(Short version) { + this.version = version; + } + + public DmpStatus getStatus() { + return status; + } + + public void setStatus(DmpStatus status) { + this.status = status; + } + + public String getProperties() { + return properties; + } + + public void setProperties(String properties) { + this.properties = properties; + } + + public UUID getGroupId() { + return groupId; + } + + public void setGroupId(UUID groupId) { + this.groupId = groupId; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Instant finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public UUID getCreatorId() { + return creatorId; + } + + public void setCreatorId(UUID creatorId) { + this.creatorId = creatorId; + } + + public DmpAccessType getAccessType() { + return accessType; + } + + public void setAccessType(DmpAccessType accessType) { + this.accessType = accessType; + } + + public UUID getBlueprintId() { + return blueprintId; + } + + public void setBlueprintId(UUID blueprintId) { + this.blueprintId = blueprintId; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public Instant getPublicAfter() { + return publicAfter; + } + + public void setPublicAfter(Instant publicAfter) { + this.publicAfter = publicAfter; + } + + public DmpVersionStatus getVersionStatus() { + return versionStatus; + } + + public void setVersionStatus(DmpVersionStatus versionStatus) { + this.versionStatus = versionStatus; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/DmpReferenceEntity.java b/backend/core/src/main/java/org/opencdmp/data/DmpReferenceEntity.java new file mode 100644 index 000000000..dd1649a23 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/DmpReferenceEntity.java @@ -0,0 +1,100 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"DmpReference\"") +public class DmpReferenceEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "dmp_id", columnDefinition = "uuid", nullable = false) + private UUID dmpId; + public static final String _dmpId = "dmpId"; + + @Column(name = "reference_id", columnDefinition = "uuid", nullable = false) + private UUID referenceId; + public static final String _referenceId = "referenceId"; + + @Column(name = "data") + private String data; + public static final String _data = "data"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public static final String _isActive = "isActive"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getDmpId() { + return dmpId; + } + + public void setDmpId(UUID dmpId) { + this.dmpId = dmpId; + } + + public UUID getReferenceId() { + return referenceId; + } + + public void setReferenceId(UUID referenceId) { + this.referenceId = referenceId; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/DmpUserEntity.java b/backend/core/src/main/java/org/opencdmp/data/DmpUserEntity.java new file mode 100644 index 000000000..6a1755a94 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/DmpUserEntity.java @@ -0,0 +1,122 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.DmpUserRole; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.DmpUserRoleConverter; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"DmpUser\"") +public class DmpUserEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + public static final String _id = "id"; + + @Column(name = "dmp", columnDefinition = "uuid", nullable = false) + private UUID dmpId; + + public static final String _dmpId = "dmpId"; + + @Column(name = "\"user\"", columnDefinition = "uuid", nullable = false) + private UUID userId; + + public static final String _userId = "userId"; + + @Column(name = "role", nullable = false) + @Convert(converter = DmpUserRoleConverter.class) + private DmpUserRole role; + + public static final String _role = "role"; + + @Column(name = "section_id", columnDefinition = "uuid", nullable = true) + private UUID sectionId; + public static final String _sectionId = "sectionId"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getDmpId() { + return dmpId; + } + + public void setDmpId(UUID dmpId) { + this.dmpId = dmpId; + } + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public DmpUserRole getRole() { + return role; + } + + public void setRole(DmpUserRole role) { + this.role = role; + } + + public UUID getSectionId() { + return sectionId; + } + + public void setSectionId(UUID sectionId) { + this.sectionId = sectionId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/EntityDoiEntity.java b/backend/core/src/main/java/org/opencdmp/data/EntityDoiEntity.java new file mode 100644 index 000000000..883e11227 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/EntityDoiEntity.java @@ -0,0 +1,123 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.EntityType; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.EntityTypeConverter; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"EntityDoi\"") +public class EntityDoiEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)") + private UUID id; + + public static final String _id = "id"; + + @Column(name = "entity_type", nullable = false) + @Convert(converter = EntityTypeConverter.class) + private EntityType entityType; + + public static final String _entityType = "entityType"; + + @Column(name = "repository_id", nullable = false) + private String repositoryId; + + public static final String _repositoryId = "repositoryId"; + + @Column(name = "doi", nullable = false) + private String doi; + + public static final String _doi = "doi"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + @Column(name = "entity_id", nullable = false) + private UUID entityId; + + public static final String _entityId = "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 Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public UUID getEntityId() { + return entityId; + } + + public void setEntityId(UUID entityId) { + this.entityId = entityId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/LanguageEntity.java b/backend/core/src/main/java/org/opencdmp/data/LanguageEntity.java new file mode 100644 index 000000000..8ef95d172 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/LanguageEntity.java @@ -0,0 +1,101 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"Language\"") +public class LanguageEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "code", length = _codeLength, nullable = false) + private String code; + public static final String _code = "code"; + public static final int _codeLength = 20; + + @Column(name = "payload") + private String payload; + public static final String _payload = "payload"; + + @Column(name = "\"created_at\"", nullable = false) + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + @Column(name = "\"updated_at\"", nullable = false) + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public static final String _isActive = "isActive"; + + @Column(name = "ordinal") + private Integer ordinal; + public static final String _ordinal = "ordinal"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getPayload() { + return payload; + } + + public void setPayload(String payload) { + this.payload = payload; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Integer getOrdinal() { + return ordinal; + } + + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/LockEntity.java b/backend/core/src/main/java/org/opencdmp/data/LockEntity.java new file mode 100644 index 000000000..38f667b45 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/LockEntity.java @@ -0,0 +1,90 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.LockTargetType; +import org.opencdmp.data.converters.enums.LockTargetTypeConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"Lock\"") +public class LockEntity extends TenantScopedBaseEntity { + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "target", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID target; + public static final String _target = "target"; + + @Column(name = "target_type", nullable = false) + @Convert(converter = LockTargetTypeConverter.class) + private LockTargetType targetType; + public static final String _targetType = "targetType"; + + + @Column(name = "locked_by", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID lockedBy; + public static final String _lockedBy = "lockedBy"; + + + @Column(name = "locked_at", nullable = false) + private Instant lockedAt = null; + public static final String _lockedAt = "lockedAt"; + + @Column(name = "touched_at", nullable = true) + private Instant touchedAt; + public static final String _touchedAt = "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 LockTargetType getTargetType() { + return targetType; + } + + public void setTargetType(LockTargetType targetType) { + this.targetType = targetType; + } + + public UUID getLockedBy() { + return lockedBy; + } + + public void setLockedBy(UUID lockedBy) { + this.lockedBy = lockedBy; + } + + public Instant getLockedAt() { + return lockedAt; + } + + public void setLockedAt(Instant lockedAt) { + this.lockedAt = lockedAt; + } + + public Instant getTouchedAt() { + return touchedAt; + } + + public void setTouchedAt(Instant touchedAt) { + this.touchedAt = touchedAt; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/PrefillingSourceEntity.java b/backend/core/src/main/java/org/opencdmp/data/PrefillingSourceEntity.java new file mode 100644 index 000000000..cdfb81d69 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/PrefillingSourceEntity.java @@ -0,0 +1,92 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import org.opencdmp.data.types.SQLXMLType; +import jakarta.persistence.*; +import org.hibernate.annotations.Type; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"PrefillingSource\"") +public class PrefillingSourceEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "label", length = _labelLength, nullable = false) + private String label; + public static final String _label = "label"; + public static final int _labelLength = 250; + + @Type(value = SQLXMLType.class) + @Column(name = "definition", nullable = false, columnDefinition = "xml") + private String definition; + public static final String _definition = "definition"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public static final String _isActive = "isActive"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + 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 IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/QueueInboxEntity.java b/backend/core/src/main/java/org/opencdmp/data/QueueInboxEntity.java new file mode 100644 index 000000000..c5753e769 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/QueueInboxEntity.java @@ -0,0 +1,180 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.converters.enums.QueueInboxStatusConverter; +import org.opencdmp.data.types.JsonSQLType; +import gr.cite.queueinbox.entity.QueueInbox; +import gr.cite.queueinbox.entity.QueueInboxStatus; +import jakarta.persistence.*; +import org.hibernate.annotations.Type; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"QueueInbox\"") +public class QueueInboxEntity implements QueueInbox { + @Id + @Column(name = "\"id\"", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public final static String _id = "id"; + + @Column(name = "\"queue\"", nullable = false, length = 200) + private String queue; + public final static String _queue = "queue"; + + @Column(name = "\"exchange\"", nullable = false, length = 200) + private String exchange; + public final static String _exchange = "exchange"; + + @Column(name = "\"route\"", nullable = false, length = 200) + private String route; + public final static String _route = "route"; + + @Column(name = "\"application_id\"", nullable = false, length = 100) + private String applicationId; + public final static String _applicationId = "applicationId"; + + @Column(name = "\"message_id\"", columnDefinition = "uuid", nullable = false) + private UUID messageId; + public final static String _messageId = "messageId"; + + @Type(JsonSQLType.class) + @Column(name = "\"message\"", columnDefinition = "json", nullable = false) + private String message; + public final static String _message = "message"; + + @Column(name = "\"retry_count\"", nullable = true) + private Integer retryCount; + public final static String _retryCount = "retryCount"; + + @Column(name = "\"tenant\"", columnDefinition = "uuid", nullable = true) + private UUID tenantId; + public final static String _tenantId = "tenantId"; + + @Column(name = "\"is_active\"", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public final static String _isActive = "isActive"; + + @Column(name = "\"status\"", nullable = false) + @Convert(converter = QueueInboxStatusConverter.class) + private QueueInboxStatus status; + public final static String _status = "status"; + + @Column(name = "\"created_at\"", nullable = false) + private Instant createdAt; + public final static String _createdAt = "createdAt"; + + @Column(name = "\"updated_at\"", nullable = false) + @Version + private Instant updatedAt; + public final static String _updatedAt = "updatedAt"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getExchange() { + return exchange; + } + + public void setExchange(String exchange) { + this.exchange = exchange; + } + + public String getRoute() { + return route; + } + + public void setRoute(String route) { + this.route = route; + } + + public UUID getMessageId() { + return messageId; + } + + public void setMessageId(UUID messageId) { + this.messageId = messageId; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public String getQueue() { + return queue; + } + + public void setQueue(String queue) { + this.queue = queue; + } + + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + + @Override + public Integer getRetryCount() { + return retryCount; + } + + public void setRetryCount(Integer retryCount) { + this.retryCount = retryCount; + } + + public QueueInboxStatus getStatus() { + return status; + } + + public void setStatus(QueueInboxStatus status) { + this.status = status; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/data/QueueOutboxEntity.java b/backend/core/src/main/java/org/opencdmp/data/QueueOutboxEntity.java new file mode 100644 index 000000000..2f4d01326 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/QueueOutboxEntity.java @@ -0,0 +1,175 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.converters.enums.QueueOutboxNotifyStatusConverter; +import gr.cite.queueoutbox.entity.QueueOutbox; +import gr.cite.queueoutbox.entity.QueueOutboxNotifyStatus; + +import jakarta.persistence.*; +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"QueueOutbox\"") +public class QueueOutboxEntity implements QueueOutbox { + @Id + @Column(name = "\"id\"", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public final static String _id = "id"; + + @Column(name = "\"exchange\"", nullable = false, length = 200) + private String exchange; + public final static String _exchange = "exchange"; + + @Column(name = "\"route\"", length = 200) + private String route; + public final static String _route = "route"; + + @Column(name = "\"message_id\"", columnDefinition = "uuid", nullable = false) + private UUID messageId; + public final static String _messageId = "messageId"; + + @Column(name = "\"message\"", columnDefinition = "json", nullable = false) + private String message; + public final static String _message = "message"; + + @Column(name = "\"notify_status\"", nullable = false) + @Convert(converter = QueueOutboxNotifyStatusConverter.class) + private QueueOutboxNotifyStatus notifyStatus; + public final static String _notifyStatus = "notifyStatus"; + + @Column(name = "\"retry_count\"", nullable = false) + private int retryCount; + public final static String _retryCount = "retryCount"; + + @Column(name = "\"published_at\"", nullable = true) + private Instant publishedAt; + public final static String _publishedAt = "publishedAt"; + + @Column(name = "\"confirmed_at\"", nullable = true) + private Instant confirmedAt; + public final static String _confirmedAt = "confirmedAt"; + + @Column(name = "\"tenant\"", columnDefinition = "uuid", nullable = true) + private UUID tenantId; + public final static String _tenantId = "tenantId"; + + @Column(name = "\"is_active\"", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public final static String _isActive = "isActive"; + + @Column(name = "\"created_at\"", nullable = false) + private Instant createdAt; + public final static String _createdAt = "createdAt"; + + @Column(name = "\"updated_at\"", nullable = false) + private Instant updatedAt; + public final static String _updatedAt = "updatedAt"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getExchange() { + return exchange; + } + + public void setExchange(String exchange) { + this.exchange = exchange; + } + + public String getRoute() { + return route; + } + + public void setRoute(String route) { + this.route = route; + } + + public UUID getMessageId() { + return messageId; + } + + public void setMessageId(UUID messageId) { + this.messageId = messageId; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public QueueOutboxNotifyStatus getNotifyStatus() { + return notifyStatus; + } + + public void setNotifyStatus(QueueOutboxNotifyStatus notifyStatus) { + this.notifyStatus = notifyStatus; + } + + public Integer getRetryCount() { + return retryCount; + } + + public void setRetryCount(Integer retryCount) { + this.retryCount = retryCount; + } + + public Instant getPublishedAt() { + return publishedAt; + } + + public void setPublishedAt(Instant publishedAt) { + this.publishedAt = publishedAt; + } + + public Instant getConfirmedAt() { + return confirmedAt; + } + + public void setConfirmedAt(Instant confirmedAt) { + this.confirmedAt = confirmedAt; + } + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/data/ReferenceEntity.java b/backend/core/src/main/java/org/opencdmp/data/ReferenceEntity.java new file mode 100644 index 000000000..fb0c021e6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/ReferenceEntity.java @@ -0,0 +1,207 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.enums.ReferenceSourceType; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.converters.enums.ReferenceSourceTypeConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"Reference\"") +public class ReferenceEntity extends TenantScopedBaseEntity { + + public static class KnownFields { + public static final String Key = "key"; + public static final String ReferenceId = "reference_id"; + public static final String Abbreviation = "abbreviation"; + public static final String Description = "description"; + public static final String Label = "label"; + public static final String SourceLabel = "tag"; + } + + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + + public static final String _id = "id"; + + @Column(name = "label", length = _labelLength, nullable = false) + private String label; + + public static final String _label = "label"; + + public static final int _labelLength = 1024; + + @Column(name = "type", nullable = false) + private UUID typeId; + + public static final String _typeId = "typeId"; + + @Column(name = "description") + private String description; + + public static final String _description = "description"; + + @Column(name = "definition") + private String definition; + + public static final String _definition = "definition"; + + @Column(name = "reference", length = _referenceLength, nullable = false) + private String reference; + + public static final String _reference = "reference"; + + public static final int _referenceLength = 1024; + + @Column(name = "abbreviation", length = _abbreviationLength) + private String abbreviation; + + public static final String _abbreviation = "abbreviation"; + + public static final int _abbreviationLength = 50; + + @Column(name = "source", length = _sourceLength) + private String source; + + public static final String _source = "source"; + + public static final int _sourceLength = 1024; + + @Column(name = "source_type", nullable = false) + @Convert(converter = ReferenceSourceTypeConverter.class) + private ReferenceSourceType sourceType; + + public static final String _sourceType = "sourceType"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "created_by", columnDefinition = "uuid") + private UUID createdById; + + public static final String _createdById = "createdById"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public UUID getTypeId() { + return typeId; + } + + public void setTypeId(UUID typeId) { + this.typeId = typeId; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDefinition() { + return definition; + } + + public void setDefinition(String definition) { + this.definition = definition; + } + + public String getReference() { + return reference; + } + + public void setReference(String reference) { + this.reference = reference; + } + + public String getAbbreviation() { + return abbreviation; + } + + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public ReferenceSourceType getSourceType() { + return sourceType; + } + + public void setSourceType(ReferenceSourceType referenceSourceType) { + this.sourceType = referenceSourceType; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public UUID getCreatedById() { + return createdById; + } + + public void setCreatedById(UUID createdById) { + this.createdById = createdById; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/ReferenceTypeEntity.java b/backend/core/src/main/java/org/opencdmp/data/ReferenceTypeEntity.java new file mode 100644 index 000000000..ec3a834bd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/ReferenceTypeEntity.java @@ -0,0 +1,111 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"ReferenceType\"") +public class ReferenceTypeEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + + public static final String _id = "id"; + + @Column(name = "name", length = _nameLength, nullable = false) + private String name; + + public static final String _name = "name"; + + public static final int _nameLength = 250; + + @Column(name = "code", length = _codeLength, nullable = false) + private String code; + + public static final String _code = "code"; + + public static final int _codeLength = 100; + + @Column(name = "definition") + private String definition; + + public static final String _definition = "definition"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + public static final String _isActive = "isActive"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + 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 getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getDefinition() { + return definition; + } + + public void setDefinition(String definition) { + this.definition = definition; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/StorageFileEntity.java b/backend/core/src/main/java/org/opencdmp/data/StorageFileEntity.java new file mode 100644 index 000000000..a7d8e8fe2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/StorageFileEntity.java @@ -0,0 +1,142 @@ +package org.opencdmp.data; + + +import org.opencdmp.commons.enums.StorageType; +import org.opencdmp.data.converters.enums.StorageTypeConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"StorageFile\"") +public class StorageFileEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public final static String _id = "id"; + + @Column(name = "file_ref", length = _fileRefLen, nullable = false) + private String fileRef; + public final static String _fileRef = "fileRef"; + public final static int _fileRefLen = 100; + + @Column(name = "name", length = _nameLen, nullable = false) + private String name; + public final static String _name = "name"; + public final static int _nameLen = 250; + + @Column(name = "extension", length = _extensionLen, nullable = false) + private String extension; + public final static String _extension = "extension"; + public final static int _extensionLen = 10; + + @Column(name = "mime_type", length = _mimeTypeLen, nullable = false) + private String mimeType; + public final static String _mimeType = "mimeType"; + public final static int _mimeTypeLen = 200; + + @Column(name = "storage_type", nullable = false) + @Convert(converter = StorageTypeConverter.class) + private StorageType storageType; + public final static String _storageType = "storageType"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + public final static String _createdAt = "createdAt"; + + @Column(name = "purge_at", nullable = true) + private Instant purgeAt; + public final static String _purgeAt = "purgeAt"; + + @Column(name = "purged_at", nullable = true) + private Instant purgedAt; + public final static String _purgedAt = "purgedAt"; + + @Column(name = "owner", nullable = true) + private UUID ownerId; + public final static String _ownerId = "ownerId"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getFileRef() { + return fileRef; + } + + public void setFileRef(String fileRef) { + this.fileRef = fileRef; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public String getMimeType() { + return mimeType; + } + + public void setMimeType(String mimeType) { + this.mimeType = mimeType; + } + + public StorageType getStorageType() { + return storageType; + } + + public void setStorageType(StorageType storageType) { + this.storageType = storageType; + } + + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getPurgeAt() { + return purgeAt; + } + + public void setPurgeAt(Instant purgeAt) { + this.purgeAt = purgeAt; + } + + public Instant getPurgedAt() { + return purgedAt; + } + + public void setPurgedAt(Instant purgedAt) { + this.purgedAt = purgedAt; + } + + public UUID getOwnerId() { + return ownerId; + } + + public void setOwnerId(UUID ownerId) { + this.ownerId = ownerId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/SupportiveMaterialEntity.java b/backend/core/src/main/java/org/opencdmp/data/SupportiveMaterialEntity.java new file mode 100644 index 000000000..efd3a4d19 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/SupportiveMaterialEntity.java @@ -0,0 +1,104 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.enums.SupportiveMaterialFieldType; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.converters.enums.SupportiveMaterialFieldTypeConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"SupportiveMaterial\"") +public class SupportiveMaterialEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "type", nullable = false) + @Convert(converter = SupportiveMaterialFieldTypeConverter.class) + private SupportiveMaterialFieldType type; + public static final String _type = "type"; + + @Column(name = "language_code", length = _languageCodeLength, nullable = false) + private String languageCode; + public static final String _languageCode = "languageCode"; + public static final int _languageCodeLength = 20; + + @Column(name = "payload", nullable = false) + private String payload; + public static final String _payload = "payload"; + + @Column(name = "\"created_at\"", nullable = false) + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + @Column(name = "\"updated_at\"", nullable = false) + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public static final String _isActive = "isActive"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public SupportiveMaterialFieldType getType() { + return type; + } + + public void setType(SupportiveMaterialFieldType type) { + this.type = type; + } + + public String getLanguageCode() { + return languageCode; + } + + public void setLanguageCode(String languageCode) { + this.languageCode = languageCode; + } + + public String getPayload() { + return payload; + } + + public void setPayload(String payload) { + this.payload = payload; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/TagEntity.java b/backend/core/src/main/java/org/opencdmp/data/TagEntity.java new file mode 100644 index 000000000..c6d416a5f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/TagEntity.java @@ -0,0 +1,89 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"Tag\"") +public class TagEntity extends TenantScopedBaseEntity { + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "\"label\"", length = TagEntity._labelLength, nullable = false) + private String label; + public static final String _label = "label"; + public static final int _labelLength = 250; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public static final String _isActive = "isActive"; + + + @Column(name = "\"created_at\"", nullable = false) + private Instant createdAt = null; + public static final String _createdAt = "createdAt"; + + @Column(name = "\"updated_at\"", nullable = false) + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + @Column(name = "\"created_by\"", nullable = false) + private UUID createdById; + public static final String _createdById = "createdById"; + + 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 IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public UUID getCreatedById() { + return createdById; + } + + public void setCreatedById(UUID createdById) { + this.createdById = createdById; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/TenantConfigurationEntity.java b/backend/core/src/main/java/org/opencdmp/data/TenantConfigurationEntity.java new file mode 100644 index 000000000..485688188 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/TenantConfigurationEntity.java @@ -0,0 +1,92 @@ +package org.opencdmp.data; + + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.enums.TenantConfigurationType; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.converters.enums.TenantConfigurationTypeConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"TenantConfiguration\"") +public class TenantConfigurationEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public final static String _id = "id"; + + @Column(name = "value", nullable = false) + private String value; + public final static String _value = "value"; + + @Column(name = "type", nullable = false) + @Convert(converter = TenantConfigurationTypeConverter.class) + private TenantConfigurationType type; + public final static String _type = "type"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public final static String _isActive = "isActive"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + public final static String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + public final static String _updatedAt = "updatedAt"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public TenantConfigurationType getType() { + return type; + } + + public void setType(TenantConfigurationType type) { + this.type = type; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/TenantEntity.java b/backend/core/src/main/java/org/opencdmp/data/TenantEntity.java new file mode 100644 index 000000000..40cceaa6d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/TenantEntity.java @@ -0,0 +1,102 @@ +package org.opencdmp.data; + + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"Tenant\"") +public class TenantEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public final static String _id = "id"; + + @Column(name = "code", length = _codeLength, nullable = false) + private String code; + public final static String _code = "code"; + public final static int _codeLength = 200; + + @Column(name = "name", length = _nameLength, nullable = false) + private String name; + public final static String _name = "name"; + public final static int _nameLength = 500; + + @Column(name = "description", nullable = false) + private String description; + public final static String _description = "description"; + + @Column(name = "is_active", length = 20, nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public final static String _isActive = "isActive"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + public final static String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + public final static String _updatedAt = "updatedAt"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/TenantEntityManager.java b/backend/core/src/main/java/org/opencdmp/data/TenantEntityManager.java new file mode 100644 index 000000000..909f4828d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/TenantEntityManager.java @@ -0,0 +1,121 @@ +package org.opencdmp.data; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.scope.tenant.TenantScoped; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import org.opencdmp.errorcode.ErrorThesaurusProperties; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; +import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractor; +import gr.cite.tools.exception.MyForbiddenException; + +import jakarta.persistence.*; +import org.hibernate.Session; +import org.springframework.stereotype.Service; +import org.springframework.web.context.annotation.RequestScope; + +import javax.management.InvalidApplicationException; + +import java.util.UUID; + +@Service +@RequestScope +public class TenantEntityManager { + @PersistenceContext + private EntityManager entityManager; + private final TenantScope tenantScope; + private final ErrorThesaurusProperties errors; + + public TenantEntityManager(TenantScope tenantScope, ErrorThesaurusProperties errors) { + this.tenantScope = tenantScope; + this.errors = errors; + } + + + public void persist(Object entity) { + this.entityManager.persist(entity); + } + + public T merge(T entity) throws InvalidApplicationException { + if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { + if (!tenantScope.isDefaultTenant()) { + if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + } else if (tenantScopedEntity.getTenantId() != null) { + throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + } + } + return this.entityManager.merge(entity); + } + + public void remove(Object entity) throws InvalidApplicationException { + if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { + if (!tenantScope.isDefaultTenant()) { + if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + } else if (tenantScopedEntity.getTenantId() != null) { + throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + } + } + this.entityManager.remove(entity); + } + + public T find(Class entityClass, Object primaryKey) throws InvalidApplicationException { + T entity = this.entityManager.find(entityClass, primaryKey); + + if (tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { + if (tenantScopedEntity.getTenantId() != null && !tenantScopedEntity.getTenantId().equals(tenantScope.getTenant())) return null; + } + return entity; + } + + public void flush() { + this.entityManager.flush(); + } + + + public void setFlushMode(FlushModeType flushMode) { + this.entityManager.setFlushMode(flushMode); + + } + + public FlushModeType getFlushMode() { + return this.entityManager.getFlushMode(); + } + + public void clear() { + this.entityManager.clear(); + } + + public void enableTenantFilters() throws InvalidApplicationException { + if (!tenantScope.isSet()) return; + if(!tenantScope.isDefaultTenant()) { + this.entityManager + .unwrap(Session.class) + .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) + .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); + } else { + this.entityManager + .unwrap(Session.class) + .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); + } + } + + public void disableTenantFilters(){ + this.entityManager + .unwrap(Session.class) + .disableFilter(TenantScopedBaseEntity.TENANT_FILTER); + + this.entityManager + .unwrap(Session.class) + .disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); + } + + public EntityManager getEntityManager() { + return entityManager; + } + + public void setEntityManager(EntityManager entityManager) { + this.entityManager = entityManager; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/TenantUserEntity.java b/backend/core/src/main/java/org/opencdmp/data/TenantUserEntity.java new file mode 100644 index 000000000..5223ed731 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/TenantUserEntity.java @@ -0,0 +1,86 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"TenantUser\"") +public class TenantUserEntity extends TenantScopedBaseEntity { + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public final static String _id = "id"; + + @Column(name = "user", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID userId; + public final static String _userId = "userId"; + + @Column(name = "tenant", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID tenantId; + public final static String _tenantId = "tenantId"; + + @Column(name = "is_active", length = 20, nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public final static String _isActive = "isActive"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + public final static String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + public final static String _updatedAt = "updatedAt"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/UserContactInfoEntity.java b/backend/core/src/main/java/org/opencdmp/data/UserContactInfoEntity.java new file mode 100644 index 000000000..94f5fe87f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/UserContactInfoEntity.java @@ -0,0 +1,91 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.ContactInfoType; +import org.opencdmp.data.converters.enums.ContactInfoTypeConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"UserContactInfo\"") +public class UserContactInfoEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "\"user\"", nullable = false) + private UUID userId; + public static final String _userId = "userId"; + + @Column(name = "\"ordinal\"", nullable = false) + private Integer ordinal; + public static final String _ordinal = "ordinal"; + + @Column(name = "type", nullable = false) + @Convert(converter = ContactInfoTypeConverter.class) + private ContactInfoType type; + public static final String _type = "type"; + + @Column(name = "value", length = UserContactInfoEntity._valueLength, nullable = false) + private String value; + public static final int _valueLength = 512; + + public static final String _value = "value"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public ContactInfoType getType() { + return type; + } + + public void setType(ContactInfoType type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public Integer getOrdinal() { + return ordinal; + } + + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/UserCredentialEntity.java b/backend/core/src/main/java/org/opencdmp/data/UserCredentialEntity.java new file mode 100644 index 000000000..5a8fa81b0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/UserCredentialEntity.java @@ -0,0 +1,78 @@ +package org.opencdmp.data; + +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"UserCredential\"") +public class UserCredentialEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public final static String _id = "id"; + + @Column(name = "\"user\"", columnDefinition = "uuid", nullable = false) + private UUID userId; + public final static String _userId = "userId"; + + @Column(name = "data", nullable = true) + private String data; + public final static String _data = "data"; + + @Column(name = "\"external_id\"", length = UserCredentialEntity._externalIdLength, nullable = false) + private String externalId; + public final static String _externalId = "externalId"; + public final static int _externalIdLength = 512; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public String getExternalId() { + return externalId; + } + + public void setExternalId(String externalId) { + this.externalId = externalId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/UserDescriptionTemplateEntity.java b/backend/core/src/main/java/org/opencdmp/data/UserDescriptionTemplateEntity.java new file mode 100644 index 000000000..9eff9721b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/UserDescriptionTemplateEntity.java @@ -0,0 +1,103 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.enums.UserDescriptionTemplateRole; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.converters.enums.UserDescriptionTemplateRoleConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"UserDescriptionTemplate\"") +public class UserDescriptionTemplateEntity extends TenantScopedBaseEntity { + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "\"user\"", nullable = false) + private UUID userId; + public static final String _userId = "userId"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public static final String _isActive = "isActive"; + + + @Column(name = "\"created_at\"", nullable = false) + private Instant createdAt = null; + public static final String _createdAt = "createdAt"; + + @Column(name = "\"updated_at\"", nullable = false) + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + @Column(name = "\"description_template\"", nullable = false) + private UUID descriptionTemplateId; + public static final String _descriptionTemplateId = "descriptionTemplateId"; + + @Column(name = "role", nullable = false) + @Convert(converter = UserDescriptionTemplateRoleConverter.class) + private UserDescriptionTemplateRole role; + public static final String _role = "role"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public UUID getDescriptionTemplateId() { + return descriptionTemplateId; + } + + public void setDescriptionTemplateId(UUID descriptionTemplateId) { + this.descriptionTemplateId = descriptionTemplateId; + } + + public UserDescriptionTemplateRole getRole() { + return role; + } + + public void setRole(UserDescriptionTemplateRole role) { + this.role = role; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/UserEntity.java b/backend/core/src/main/java/org/opencdmp/data/UserEntity.java new file mode 100644 index 000000000..188b48120 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/UserEntity.java @@ -0,0 +1,91 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"User\"") +public class UserEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public final static String _id = "id"; + + @Column(name = "name", length = UserEntity._nameLength, nullable = true) + private String name = null; + public final static String _name = "name"; + public final static int _nameLength = 250; + + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + @Column(name = "is_active", nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + public static final String _isActive = "isActive"; + + @Column(name = "additional_info", nullable = true) + private String additionalInfo; + public final static String _additionalInfo = "additionalInfo"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + 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 IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/UserRoleEntity.java b/backend/core/src/main/java/org/opencdmp/data/UserRoleEntity.java new file mode 100644 index 000000000..6f6cde814 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/UserRoleEntity.java @@ -0,0 +1,64 @@ +package org.opencdmp.data; + +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"UserRole\"") +public class UserRoleEntity extends TenantScopedBaseEntity { + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "role", length = UserRoleEntity._roleLength, nullable = false) + private String role; + public static final String _role = "role"; + public static final int _roleLength = 512; + + @Column(name = "\"user\"", nullable = false) + private UUID userId; + public static final String _userId = "userId"; + + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/UserSettingsEntity.java b/backend/core/src/main/java/org/opencdmp/data/UserSettingsEntity.java new file mode 100644 index 000000000..79c756016 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/UserSettingsEntity.java @@ -0,0 +1,112 @@ +package org.opencdmp.data; + +import org.opencdmp.commons.enums.UserSettingsType; +import org.opencdmp.data.converters.enums.UserSettingsTypeConverter; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"UserSettings\"") +public class UserSettingsEntity extends TenantScopedBaseEntity { + + @Id + @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + public static final String _id = "id"; + + @Column(name = "key", length = 500, nullable = false) + private String key; + public static final String _key = "key"; + + @Column(name = "value", nullable = false) + private String value; + public static final String _value = "value"; + + @Column(name = "name", nullable = false) + private String name; + public static final String _name = "name"; + + @Column(name = "entity_id", columnDefinition = "uuid", nullable = true) + private UUID entityId; + public static final String _entityId = "entityId"; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + @Column(name = "updated_at", nullable = false) + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + @Column(name = "type", nullable = false) + @Convert(converter = UserSettingsTypeConverter.class) + private UserSettingsType type; + public static final String _type = "type"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public UUID getEntityId() { + return entityId; + } + + public void setEntityId(UUID entityId) { + this.entityId = entityId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public UserSettingsType getType() { + return type; + } + + public void setType(UserSettingsType type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/DmpBlueprintVersionStatusConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/DmpBlueprintVersionStatusConverter.java new file mode 100644 index 000000000..b09a827fc --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/DmpBlueprintVersionStatusConverter.java @@ -0,0 +1,15 @@ +package org.opencdmp.data.converters; + +import org.opencdmp.commons.enums.DmpBlueprintVersionStatus; +import org.opencdmp.data.converters.enums.DatabaseEnumConverter; +import jakarta.persistence.Converter; + +@Converter +public class DmpBlueprintVersionStatusConverter extends DatabaseEnumConverter { + + @Override + protected DmpBlueprintVersionStatus of(Short i) { + return DmpBlueprintVersionStatus.of(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/ActionConfirmationStatusConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/ActionConfirmationStatusConverter.java new file mode 100644 index 000000000..4effc32df --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/ActionConfirmationStatusConverter.java @@ -0,0 +1,15 @@ +package org.opencdmp.data.converters.enums; + + +import org.opencdmp.commons.enums.ActionConfirmationStatus; +import jakarta.persistence.Converter; + +@Converter +public class ActionConfirmationStatusConverter extends DatabaseEnumConverter { + + @Override + protected ActionConfirmationStatus of(Short i) { + return ActionConfirmationStatus.of(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/ActionConfirmationTypeConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/ActionConfirmationTypeConverter.java new file mode 100644 index 000000000..c7bdad9b8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/ActionConfirmationTypeConverter.java @@ -0,0 +1,15 @@ +package org.opencdmp.data.converters.enums; + + +import org.opencdmp.commons.enums.ActionConfirmationType; +import jakarta.persistence.Converter; + +@Converter +public class ActionConfirmationTypeConverter extends DatabaseEnumConverter { + + @Override + protected ActionConfirmationType of(Short i) { + return ActionConfirmationType.of(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/ContactInfoTypeConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/ContactInfoTypeConverter.java new file mode 100644 index 000000000..273c60704 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/ContactInfoTypeConverter.java @@ -0,0 +1,12 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.ContactInfoType; +import org.opencdmp.commons.enums.DescriptionStatus; +import jakarta.persistence.Converter; + +@Converter +public class ContactInfoTypeConverter extends DatabaseEnumConverter{ + protected ContactInfoType of(Short i) { + return ContactInfoType.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/DatabaseEnum.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DatabaseEnum.java new file mode 100644 index 000000000..48ca7be2d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DatabaseEnum.java @@ -0,0 +1,8 @@ +package org.opencdmp.data.converters.enums; + +import com.fasterxml.jackson.annotation.JsonValue; + +public interface DatabaseEnum { + @JsonValue + T getValue(); +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/DatabaseEnumConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DatabaseEnumConverter.java new file mode 100644 index 000000000..d6a0f303e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DatabaseEnumConverter.java @@ -0,0 +1,21 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.ProviderType; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; + +@Converter +public abstract class DatabaseEnumConverter, T> implements AttributeConverter { + protected abstract EnumType of(T dbData); + + @Override + public T convertToDatabaseColumn(EnumType value) { + if (value == null) throw new IllegalArgumentException("Value could not be null for: " + this.getClass().getSimpleName()); + return value.getValue(); + } + + @Override + public EnumType convertToEntityAttribute(T dbData) { + return this.of(dbData); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionStatusConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionStatusConverter.java new file mode 100644 index 000000000..a4bb057a1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionStatusConverter.java @@ -0,0 +1,11 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.DescriptionStatus; +import jakarta.persistence.Converter; + +@Converter +public class DescriptionStatusConverter extends DatabaseEnumConverter{ + protected DescriptionStatus of(Short i) { + return DescriptionStatus.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionTemplateStatusConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionTemplateStatusConverter.java new file mode 100644 index 000000000..0529906b1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionTemplateStatusConverter.java @@ -0,0 +1,12 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.DescriptionTemplateStatus; +import org.opencdmp.commons.enums.DescriptionTemplateTypeStatus; +import jakarta.persistence.Converter; + +@Converter +public class DescriptionTemplateStatusConverter extends DatabaseEnumConverter { + public DescriptionTemplateStatus of(Short i) { + return DescriptionTemplateStatus.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionTemplateTypeStatusConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionTemplateTypeStatusConverter.java new file mode 100644 index 000000000..7815d89ee --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionTemplateTypeStatusConverter.java @@ -0,0 +1,12 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.DescriptionTemplateTypeStatus; +import org.opencdmp.commons.enums.IsActive; +import jakarta.persistence.Converter; + +@Converter +public class DescriptionTemplateTypeStatusConverter extends DatabaseEnumConverter { + public DescriptionTemplateTypeStatus of(Short i) { + return DescriptionTemplateTypeStatus.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionTemplateVersionStatusConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionTemplateVersionStatusConverter.java new file mode 100644 index 000000000..e01050bcf --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DescriptionTemplateVersionStatusConverter.java @@ -0,0 +1,11 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import jakarta.persistence.Converter; + +@Converter +public class DescriptionTemplateVersionStatusConverter extends DatabaseEnumConverter{ + protected DescriptionTemplateVersionStatus of(Short i) { + return DescriptionTemplateVersionStatus.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpAccessTypeNullableConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpAccessTypeNullableConverter.java new file mode 100644 index 000000000..46df1d1a2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpAccessTypeNullableConverter.java @@ -0,0 +1,25 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.DmpAccessType; +import jakarta.persistence.Converter; + +@Converter +public class DmpAccessTypeNullableConverter extends DatabaseEnumConverter { + + @Override + protected DmpAccessType of(Short i) { + return DmpAccessType.of(i); + } + + + @Override + public Short convertToDatabaseColumn(DmpAccessType value) { + if (value == null) return null; + return value.getValue(); + } + + @Override + public DmpAccessType convertToEntityAttribute(Short dbData) { + return dbData == null ? null : this.of(dbData); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpBlueprintStatusConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpBlueprintStatusConverter.java new file mode 100644 index 000000000..e1a740578 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpBlueprintStatusConverter.java @@ -0,0 +1,12 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.DescriptionTemplateTypeStatus; +import org.opencdmp.commons.enums.DmpBlueprintStatus; +import jakarta.persistence.Converter; + +@Converter +public class DmpBlueprintStatusConverter extends DatabaseEnumConverter { + public DmpBlueprintStatus of(Short i) { + return DmpBlueprintStatus.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpStatusConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpStatusConverter.java new file mode 100644 index 000000000..940a4e197 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpStatusConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.DmpStatus; +import jakarta.persistence.Converter; + +@Converter +public class DmpStatusConverter extends DatabaseEnumConverter { + + @Override + protected DmpStatus of(Short i) { + return DmpStatus.of(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpUserRoleConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpUserRoleConverter.java new file mode 100644 index 000000000..78c6f662f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpUserRoleConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.DmpUserRole; +import jakarta.persistence.Converter; + +@Converter +public class DmpUserRoleConverter extends DatabaseEnumConverter { + + @Override + protected DmpUserRole of(Short i) { + return DmpUserRole.of(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpVersionStatusConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpVersionStatusConverter.java new file mode 100644 index 000000000..16c9a7cdf --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/DmpVersionStatusConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.DmpVersionStatus; +import jakarta.persistence.Converter; + +@Converter +public class DmpVersionStatusConverter extends DatabaseEnumConverter { + + @Override + protected DmpVersionStatus of(Short i) { + return DmpVersionStatus.of(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/EntityTypeConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/EntityTypeConverter.java new file mode 100644 index 000000000..5d31ea3e5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/EntityTypeConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.EntityType; +import jakarta.persistence.Converter; + +@Converter +public class EntityTypeConverter extends DatabaseEnumConverter{ + + @Override + protected EntityType of(Short i) { + return EntityType.of(i); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/IsActiveConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/IsActiveConverter.java new file mode 100644 index 000000000..eea6fcce4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/IsActiveConverter.java @@ -0,0 +1,11 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.IsActive; +import jakarta.persistence.Converter; + +@Converter +public class IsActiveConverter extends DatabaseEnumConverter { + public IsActive of(Short i) { + return IsActive.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/LockTargetTypeConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/LockTargetTypeConverter.java new file mode 100644 index 000000000..7732e2da0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/LockTargetTypeConverter.java @@ -0,0 +1,11 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.LockTargetType; +import jakarta.persistence.Converter; + +@Converter +public class LockTargetTypeConverter extends DatabaseEnumConverter{ + protected LockTargetType of(Short i) { + return LockTargetType.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/ProviderTypeConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/ProviderTypeConverter.java new file mode 100644 index 000000000..06e253ecf --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/ProviderTypeConverter.java @@ -0,0 +1,15 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.ProviderType; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; + +import java.util.HashMap; +import java.util.Map; + +@Converter +public class ProviderTypeConverter extends DatabaseEnumConverter { + public ProviderType of(Integer i) { + return ProviderType.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/QueueInboxStatusConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/QueueInboxStatusConverter.java new file mode 100644 index 000000000..55f0f0efe --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/QueueInboxStatusConverter.java @@ -0,0 +1,19 @@ +package org.opencdmp.data.converters.enums; + +import gr.cite.queueinbox.entity.QueueInboxStatus; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; + +@Converter +public class QueueInboxStatusConverter implements AttributeConverter { + @Override + public Short convertToDatabaseColumn(QueueInboxStatus value) { + if (value == null) throw new IllegalArgumentException("Value could not be null for: " + this.getClass().getSimpleName()); + return value.getValue(); + } + + @Override + public QueueInboxStatus convertToEntityAttribute(Short dbData) { + return QueueInboxStatus.of(dbData); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/QueueOutboxNotifyStatusConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/QueueOutboxNotifyStatusConverter.java new file mode 100644 index 000000000..1f2cac5cc --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/QueueOutboxNotifyStatusConverter.java @@ -0,0 +1,19 @@ +package org.opencdmp.data.converters.enums; + +import gr.cite.queueoutbox.entity.QueueOutboxNotifyStatus; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; + +@Converter +public class QueueOutboxNotifyStatusConverter implements AttributeConverter { + @Override + public Short convertToDatabaseColumn(QueueOutboxNotifyStatus value) { + if (value == null) throw new IllegalArgumentException("Value could not be null for: " + this.getClass().getSimpleName()); + return value.getValue(); + } + + @Override + public QueueOutboxNotifyStatus convertToEntityAttribute(Short dbData) { + return QueueOutboxNotifyStatus.of(dbData); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/ReferenceSourceTypeConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/ReferenceSourceTypeConverter.java new file mode 100644 index 000000000..59f4f0d65 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/ReferenceSourceTypeConverter.java @@ -0,0 +1,11 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.ReferenceSourceType; +import jakarta.persistence.Converter; + +@Converter +public class ReferenceSourceTypeConverter extends DatabaseEnumConverter{ + public ReferenceSourceType of(Short i) { + return ReferenceSourceType.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/StorageTypeConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/StorageTypeConverter.java new file mode 100644 index 000000000..a8aaae989 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/StorageTypeConverter.java @@ -0,0 +1,12 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.enums.StorageType; +import jakarta.persistence.Converter; + +@Converter +public class StorageTypeConverter extends DatabaseEnumConverter { + public StorageType of(Short i) { + return StorageType.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/SupportiveMaterialFieldTypeConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/SupportiveMaterialFieldTypeConverter.java new file mode 100644 index 000000000..930ba5208 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/SupportiveMaterialFieldTypeConverter.java @@ -0,0 +1,11 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.SupportiveMaterialFieldType; +import jakarta.persistence.Converter; + +@Converter +public class SupportiveMaterialFieldTypeConverter extends DatabaseEnumConverter { + public SupportiveMaterialFieldType of(Short i) { + return SupportiveMaterialFieldType.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/TenantConfigurationTypeConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/TenantConfigurationTypeConverter.java new file mode 100644 index 000000000..0431ba3b5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/TenantConfigurationTypeConverter.java @@ -0,0 +1,11 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.TenantConfigurationType; +import jakarta.persistence.Converter; + +@Converter +public class TenantConfigurationTypeConverter extends DatabaseEnumConverter { + public TenantConfigurationType of(Short i) { + return TenantConfigurationType.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/UserDescriptionTemplateRoleConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/UserDescriptionTemplateRoleConverter.java new file mode 100644 index 000000000..28bb06fc0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/UserDescriptionTemplateRoleConverter.java @@ -0,0 +1,11 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.UserDescriptionTemplateRole; +import jakarta.persistence.Converter; + +@Converter +public class UserDescriptionTemplateRoleConverter extends DatabaseEnumConverter{ + protected UserDescriptionTemplateRole of(Short i) { + return UserDescriptionTemplateRole.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/converters/enums/UserSettingsTypeConverter.java b/backend/core/src/main/java/org/opencdmp/data/converters/enums/UserSettingsTypeConverter.java new file mode 100644 index 000000000..79f50e394 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/converters/enums/UserSettingsTypeConverter.java @@ -0,0 +1,11 @@ +package org.opencdmp.data.converters.enums; + +import org.opencdmp.commons.enums.UserSettingsType; +import jakarta.persistence.Converter; + +@Converter +public class UserSettingsTypeConverter extends DatabaseEnumConverter { + public UserSettingsType of(Short i) { + return UserSettingsType.of(i); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/namingstrategy/NamingStrategyProperties.java b/backend/core/src/main/java/org/opencdmp/data/namingstrategy/NamingStrategyProperties.java new file mode 100644 index 000000000..b17402f8f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/namingstrategy/NamingStrategyProperties.java @@ -0,0 +1,20 @@ +package org.opencdmp.data.namingstrategy; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.ConstructorBinding; + +@ConfigurationProperties(prefix = "naming-strategy") +public class NamingStrategyProperties { + + private final String prefix; + + @ConstructorBinding + public NamingStrategyProperties(String prefix) { + this.prefix = prefix; + } + + public String getPrefix() { + return prefix; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/namingstrategy/PrefixPhysicalNamingStrategy.java b/backend/core/src/main/java/org/opencdmp/data/namingstrategy/PrefixPhysicalNamingStrategy.java new file mode 100644 index 000000000..8e98558e6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/namingstrategy/PrefixPhysicalNamingStrategy.java @@ -0,0 +1,30 @@ +package org.opencdmp.data.namingstrategy; + +import org.opencdmp.convention.ConventionService; +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@EnableConfigurationProperties({NamingStrategyProperties.class}) +public class PrefixPhysicalNamingStrategy extends PhysicalNamingStrategyStandardImpl { + + private final NamingStrategyProperties namingStrategyProperties; + private final ConventionService conventionService; + + public PrefixPhysicalNamingStrategy(NamingStrategyProperties namingStrategyProperties, ConventionService conventionService) { + this.namingStrategyProperties = namingStrategyProperties; + this.conventionService = conventionService; + } + + @Override + public Identifier toPhysicalTableName(Identifier logicalName, JdbcEnvironment context) { + if (conventionService.isNullOrEmpty(namingStrategyProperties.getPrefix())) + return super.toPhysicalTableName(logicalName, context); + Identifier identifier = new Identifier(namingStrategyProperties.getPrefix() + logicalName.getText(), logicalName.isQuoted()); + return super.toPhysicalTableName(identifier, context); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/tenant/TenantFilterAspect.java b/backend/core/src/main/java/org/opencdmp/data/tenant/TenantFilterAspect.java new file mode 100644 index 000000000..f51c36f38 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/tenant/TenantFilterAspect.java @@ -0,0 +1,45 @@ +package org.opencdmp.data.tenant; + +import org.opencdmp.commons.scope.tenant.TenantScope; +import jakarta.persistence.EntityManager; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.Aspect; +import org.hibernate.Session; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; + + +@Aspect +@Component +public class TenantFilterAspect { + + private final TenantScope tenantScope; + + @Autowired + public TenantFilterAspect( + TenantScope tenantScope + ) { + this.tenantScope = tenantScope; + } + + @AfterReturning( + pointcut = "bean(entityManagerFactory) && execution(* createEntityManager(..))", + returning = "retVal") + public void getSessionAfter(JoinPoint joinPoint, Object retVal) throws InvalidApplicationException { + if (retVal instanceof EntityManager && tenantScope.isSet()) { + Session session = ((EntityManager) retVal).unwrap(Session.class); + if(!tenantScope.isDefaultTenant()) { + session + .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) + .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); + } else { + session + .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); + } + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/data/tenant/TenantListener.java b/backend/core/src/main/java/org/opencdmp/data/tenant/TenantListener.java new file mode 100644 index 000000000..60d78ff47 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/tenant/TenantListener.java @@ -0,0 +1,81 @@ +package org.opencdmp.data.tenant; + + +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.scope.tenant.TenantScoped; +import org.opencdmp.errorcode.ErrorThesaurusProperties; +import gr.cite.tools.exception.MyForbiddenException; +import gr.cite.tools.exception.MyValidationException; +import gr.cite.tools.logging.LoggerService; +import jakarta.persistence.PrePersist; +import jakarta.persistence.PreRemove; +import jakarta.persistence.PreUpdate; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.management.InvalidApplicationException; + +import java.util.UUID; + +public class TenantListener { + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantListener.class)); + private final TenantScope tenantScope; + + private final ErrorThesaurusProperties errors; + + + @Autowired + public TenantListener( + TenantScope tenantScope, ErrorThesaurusProperties errors + ) { + this.tenantScope = tenantScope; + this.errors = errors; + } + + @PrePersist + public void setTenantOnCreate(TenantScoped entity) throws InvalidApplicationException { + if (tenantScope.isMultitenant()) { + if (entity.getTenantId() != null && (this.tenantScope.isDefaultTenant() || entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { + logger.error("somebody tried to set not login tenant"); + throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + } + if (!tenantScope.isDefaultTenant()) { + final UUID tenantId = tenantScope.getTenant(); + entity.setTenantId(tenantId); + } + } else { + entity.setTenantId(null); + } + } + + @PreUpdate + @PreRemove + public void setTenantOnUpdate(TenantScoped entity) throws InvalidApplicationException { + if (tenantScope.isMultitenant()) { + if (!tenantScope.isDefaultTenant()) { + if (entity.getTenantId() == null) { + logger.error("somebody tried to set null tenant"); + throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + } + if (entity.getTenantId().compareTo(tenantScope.getTenant()) != 0) { + logger.error("somebody tried to change an entries tenant"); + throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + } + + final UUID tenantId = tenantScope.getTenant(); + entity.setTenantId(tenantId); + } else { + if (entity.getTenantId() != null) { + logger.error("somebody tried to set null tenant"); + throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + } + } + } else { + if (entity.getTenantId() != null && (!this.tenantScope.isDefaultTenant() ||entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { + logger.error("somebody tried to change an entries tenant"); + throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); + } + } + + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/tenant/TenantScopedBaseEntity.java b/backend/core/src/main/java/org/opencdmp/data/tenant/TenantScopedBaseEntity.java new file mode 100644 index 000000000..6b3902b75 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/tenant/TenantScopedBaseEntity.java @@ -0,0 +1,39 @@ +package org.opencdmp.data.tenant; + +import org.opencdmp.commons.scope.tenant.TenantScoped; +import jakarta.persistence.*; +import org.hibernate.annotations.Filter; +import org.hibernate.annotations.FilterDef; +import org.hibernate.annotations.ParamDef; + + +import java.io.Serializable; +import java.util.UUID; + +@MappedSuperclass +//@Getter +//@Setter +//@NoArgsConstructor +@FilterDef(name = TenantScopedBaseEntity.TENANT_FILTER, parameters = {@ParamDef(name = TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, type = String.class)}) +@FilterDef(name = TenantScopedBaseEntity.DEFAULT_TENANT_FILTER) +@Filter(name = TenantScopedBaseEntity.DEFAULT_TENANT_FILTER, condition = "(tenant = tenant is null)") +@Filter(name = TenantScopedBaseEntity.TENANT_FILTER, condition = "(tenant = (cast(:tenantId as uuid)) or tenant is null)") +@EntityListeners(TenantListener.class) +public abstract class TenantScopedBaseEntity implements TenantScoped, Serializable { + private static final long serialVersionUID = 1L; + public static final String TENANT_FILTER = "tenantFilter"; + public static final String DEFAULT_TENANT_FILTER = "defaultTenantFilter"; + public static final String TENANT_FILTER_TENANT_PARAM = "tenantId"; + + @Column(name = "tenant", columnDefinition = "uuid", nullable = true) + private UUID tenantId; + public static final String _tenantId = "tenantId"; + public UUID getTenantId() { + return tenantId; + } + + @Override + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/data/types/JsonSQLType.java b/backend/core/src/main/java/org/opencdmp/data/types/JsonSQLType.java new file mode 100644 index 000000000..23196c222 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/types/JsonSQLType.java @@ -0,0 +1,80 @@ +package org.opencdmp.data.types; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.type.SqlTypes; +import org.hibernate.usertype.UserType; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; + +public class JsonSQLType implements UserType { + + @Override + public int getSqlType() { + return SqlTypes.JSON; + } + + @Override + public Class returnedClass() { + return String.class; + } + + @Override + public boolean equals(String x, String y) { + if (x == null) { + return y == null; + } else { + return x.equals(y); + } + } + + @Override + public int hashCode(String x) { + return x.hashCode(); + } + + @Override + public String nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { + String json = rs.getString(position); + return rs.wasNull() ? null : json; + } + + @Override + public void nullSafeSet(PreparedStatement st, String value, int index, SharedSessionContractImplementor session) throws SQLException { + if (value == null) { + st.setNull(index, Types.OTHER); + } else { + st.setObject(index, value, Types.OTHER); + } + } + + @Override + public String deepCopy(String value) throws HibernateException { + return value; + } + + @Override + public boolean isMutable() { + return false; + } + + @Override + public Serializable disassemble(String value) throws HibernateException { + return value; + } + + @Override + public String assemble(Serializable cached, Object owner) throws HibernateException { + return (String) cached; + } + + @Override + public String replace(String original, String target, Object owner) throws HibernateException { + return original; + } + +} \ No newline at end of file diff --git a/backend/core/src/main/java/org/opencdmp/data/types/SQLXMLType.java b/backend/core/src/main/java/org/opencdmp/data/types/SQLXMLType.java new file mode 100644 index 000000000..7f252d481 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/data/types/SQLXMLType.java @@ -0,0 +1,85 @@ +package org.opencdmp.data.types; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.usertype.UserType; + +/** + * Store and retrieve a PostgreSQL "xml" column as a Java string. + * https://wiki.postgresql.org/wiki/Hibernate_XML_Type + */ +public class SQLXMLType implements UserType { + + private final int[] sqlTypesSupported = new int[] { Types.VARCHAR }; + + @Override + public int getSqlType() { + return Types.VARCHAR; + } + + @Override + public Class returnedClass() { + return String.class; + } + + @Override + public boolean equals(String x, String y) throws HibernateException { + if (x == null) { + return y == null; + } else { + return x.equals(y); + } + } + + @Override + public int hashCode(String x) throws HibernateException { + return x == null ? null : x.hashCode(); + } + + @Override + public String nullSafeGet(ResultSet rs, int i, SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws SQLException { + String xmldoc = rs.getString( i ); + return rs.wasNull() ? null : xmldoc; + } + + @Override + public void nullSafeSet(PreparedStatement st, String value, int index, SharedSessionContractImplementor sharedSessionContractImplementor) throws SQLException { + if (value == null) { + st.setNull(index, Types.OTHER); + } else { + st.setObject(index, value, Types.OTHER); + } + } + + @Override + public String deepCopy(String value) throws HibernateException { + if (value == null) + return null; + return new String( (String)value ); + } + + @Override + public boolean isMutable() { + return false; + } + + @Override + public Serializable disassemble(String value) throws HibernateException { + return (String) value; + } + + @Override + public String assemble(Serializable cached, Object owner) throws HibernateException { + return (String) cached; + } + + @Override + public String replace(String original, String target, Object owner) throws HibernateException { + return original; + } +} \ No newline at end of file diff --git a/backend/core/src/main/java/org/opencdmp/elastic/ElasticConfiguration.java b/backend/core/src/main/java/org/opencdmp/elastic/ElasticConfiguration.java new file mode 100644 index 000000000..a8325dafe --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/ElasticConfiguration.java @@ -0,0 +1,49 @@ +package org.opencdmp.elastic; + + +import org.opencdmp.elastic.converter.*; +import gr.cite.tools.elastic.configuration.AbstractElasticConfiguration; +import gr.cite.tools.elastic.configuration.ElasticCertificateProvider; +import gr.cite.tools.elastic.configuration.ElasticProperties; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.elasticsearch.core.convert.ElasticsearchCustomConversions; + +import java.util.List; + +@Configuration +@EnableConfigurationProperties(ElasticProperties.class) +@ConditionalOnProperty(prefix = "elastic", name = "enabled", matchIfMissing = false) +public class ElasticConfiguration extends AbstractElasticConfiguration { + + public ElasticConfiguration(ElasticProperties elasticProperties, ElasticCertificateProvider elasticCertificateProvider) { + super(elasticProperties, elasticCertificateProvider); + } + + @Bean + @Override + public ElasticsearchCustomConversions elasticsearchCustomConversions() { + return new ElasticsearchCustomConversions( + List.of( + new DmpUserRoleToShortConverter(), + new DescriptionTemplateVersionStatusToShortConverter(), + new DmpStatusToShortConverter(), + new DescriptionStatusToShortConverter(), + new IsActiveToShortConverter(), + new DmpVersionStatusToShortConverter(), + new DmpAccessTypeToShortConverter(), + + new ShortToDmpStatusConverter(), + new ShortToDmpUserRoleConverter(), + new ShortToDescriptionTemplateVersionStatusConverter(), + new ShortToDmpStatusConverter(), + new ShortToDescriptionStatusConverter(), + new ShortToIsActiveConverter(), + new ShortToDmpVersionStatusConverter(), + new ShortToDmpAccessTypeConverter() + )); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/DescriptionStatusToShortConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/DescriptionStatusToShortConverter.java new file mode 100644 index 000000000..55aaa86a3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/DescriptionStatusToShortConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DescriptionStatus; +import org.opencdmp.commons.enums.DmpStatus; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.WritingConverter; + +@WritingConverter +public class DescriptionStatusToShortConverter implements Converter { + @Override + public Short convert(DescriptionStatus source) { + return source.getValue(); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/DescriptionTemplateVersionStatusToShortConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/DescriptionTemplateVersionStatusToShortConverter.java new file mode 100644 index 000000000..071ba073f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/DescriptionTemplateVersionStatusToShortConverter.java @@ -0,0 +1,13 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.WritingConverter; + +@WritingConverter +public class DescriptionTemplateVersionStatusToShortConverter implements Converter { + @Override + public Short convert(DescriptionTemplateVersionStatus source) { + return source.getValue(); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpAccessTypeToShortConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpAccessTypeToShortConverter.java new file mode 100644 index 000000000..edd116619 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpAccessTypeToShortConverter.java @@ -0,0 +1,13 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DmpAccessType; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.WritingConverter; + +@WritingConverter +public class DmpAccessTypeToShortConverter implements Converter { + @Override + public Short convert(DmpAccessType source) { + return source.getValue(); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpStatusToShortConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpStatusToShortConverter.java new file mode 100644 index 000000000..fef1380e6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpStatusToShortConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DmpStatus; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.WritingConverter; + +@WritingConverter +public class DmpStatusToShortConverter implements Converter { + @Override + public Short convert(DmpStatus source) { + return source.getValue(); + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpUserRoleToShortConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpUserRoleToShortConverter.java new file mode 100644 index 000000000..7b74c6b14 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpUserRoleToShortConverter.java @@ -0,0 +1,13 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DmpUserRole; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.WritingConverter; + +@WritingConverter +public class DmpUserRoleToShortConverter implements Converter { + @Override + public Short convert(DmpUserRole source) { + return source.getValue(); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpVersionStatusToShortConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpVersionStatusToShortConverter.java new file mode 100644 index 000000000..0709ee264 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/DmpVersionStatusToShortConverter.java @@ -0,0 +1,13 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DmpVersionStatus; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.WritingConverter; + +@WritingConverter +public class DmpVersionStatusToShortConverter implements Converter { + @Override + public Short convert(DmpVersionStatus source) { + return source.getValue(); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/IsActiveToShortConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/IsActiveToShortConverter.java new file mode 100644 index 000000000..c8c93d851 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/IsActiveToShortConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DmpStatus; +import org.opencdmp.commons.enums.IsActive; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.WritingConverter; + +@WritingConverter +public class IsActiveToShortConverter implements Converter { + @Override + public Short convert(IsActive source) { + return source.getValue(); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDescriptionStatusConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDescriptionStatusConverter.java new file mode 100644 index 000000000..7e09d5c28 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDescriptionStatusConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DescriptionStatus; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.ReadingConverter; +import org.springframework.data.convert.WritingConverter; + +@ReadingConverter +public class ShortToDescriptionStatusConverter implements Converter { + @Override + public DescriptionStatus convert(Integer source) { + return DescriptionStatus.of(source.shortValue()); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDescriptionTemplateVersionStatusConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDescriptionTemplateVersionStatusConverter.java new file mode 100644 index 000000000..6c3cffc0f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDescriptionTemplateVersionStatusConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.ReadingConverter; +import org.springframework.data.convert.WritingConverter; + +@ReadingConverter +public class ShortToDescriptionTemplateVersionStatusConverter implements Converter { + @Override + public DescriptionTemplateVersionStatus convert(Integer source) { + return DescriptionTemplateVersionStatus.of(source.shortValue()); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpAccessTypeConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpAccessTypeConverter.java new file mode 100644 index 000000000..93fead4a5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpAccessTypeConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DmpAccessType; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.ReadingConverter; +import org.springframework.data.convert.WritingConverter; + +@ReadingConverter +public class ShortToDmpAccessTypeConverter implements Converter { + @Override + public DmpAccessType convert(Integer source) { + return DmpAccessType.of(source.shortValue()); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpStatusConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpStatusConverter.java new file mode 100644 index 000000000..17b2722bb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpStatusConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.*; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.ReadingConverter; + +@ReadingConverter +public class ShortToDmpStatusConverter implements Converter { + @Override + public DmpStatus convert(Integer source) { + return DmpStatus.of(source.shortValue()); + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpUserRoleConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpUserRoleConverter.java new file mode 100644 index 000000000..0a9356c75 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpUserRoleConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DmpUserRole; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.ReadingConverter; +import org.springframework.data.convert.WritingConverter; + +@ReadingConverter +public class ShortToDmpUserRoleConverter implements Converter { + @Override + public DmpUserRole convert(Integer source) { + return DmpUserRole.of(source.shortValue()); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpVersionStatusConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpVersionStatusConverter.java new file mode 100644 index 000000000..7e1b47f55 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToDmpVersionStatusConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.DmpVersionStatus; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.ReadingConverter; +import org.springframework.data.convert.WritingConverter; + +@ReadingConverter +public class ShortToDmpVersionStatusConverter implements Converter { + @Override + public DmpVersionStatus convert(Integer source) { + return DmpVersionStatus.of(source.shortValue()); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToIsActiveConverter.java b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToIsActiveConverter.java new file mode 100644 index 000000000..1b10a4732 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/converter/ShortToIsActiveConverter.java @@ -0,0 +1,14 @@ +package org.opencdmp.elastic.converter; + +import org.opencdmp.commons.enums.IsActive; +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.convert.ReadingConverter; +import org.springframework.data.convert.WritingConverter; + +@ReadingConverter +public class ShortToIsActiveConverter implements Converter { + @Override + public IsActive convert(Integer source) { + return IsActive.of(source.shortValue()); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/data/DescriptionElasticEntity.java b/backend/core/src/main/java/org/opencdmp/elastic/data/DescriptionElasticEntity.java new file mode 100644 index 000000000..9c190127e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/data/DescriptionElasticEntity.java @@ -0,0 +1,150 @@ +package org.opencdmp.elastic.data; + +import org.opencdmp.commons.enums.DescriptionStatus; +import org.opencdmp.elastic.data.nested.*; +import gr.cite.tools.elastic.ElasticConstants; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.*; + +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Document(indexName = "description") +public class DescriptionElasticEntity { + + @Id + @Field(value = DescriptionElasticEntity._id, type = FieldType.Keyword) + private UUID id; + public final static String _id = "id"; + + @Field(value = DescriptionElasticEntity._tenantId, type = FieldType.Keyword) + private UUID tenantId; + public final static String _tenantId = "tenantId"; + + @MultiField(mainField = @Field(value = DescriptionElasticEntity._label, type = FieldType.Text), otherFields = { + @InnerField(suffix = ElasticConstants.SubFields.keyword, type = FieldType.Keyword) + }) + private String label; + public final static String _label = "label"; + + @Field(value = DescriptionElasticEntity._description, type = FieldType.Text) + private String description; + public final static String _description = "description"; + + @Field(value = DescriptionElasticEntity._status, type = FieldType.Short) + private DescriptionStatus status; + public final static String _status = "status"; + + @Field(value = DescriptionElasticEntity._finalizedAt, type = FieldType.Date) + private Date finalizedAt; + public final static String _finalizedAt = "finalizedAt"; + + @Field(value = DescriptionElasticEntity._createdAt, type = FieldType.Date) + private Date createdAt; + public final static String _createdAt = "createdAt"; + + @Field(value = DescriptionElasticEntity._tags, type = FieldType.Nested) + private List tags; + public final static String _tags = "tags"; + + @Field(value = DescriptionElasticEntity._descriptionTemplate, type = FieldType.Object) + private NestedDescriptionTemplateElasticEntity descriptionTemplate; + public final static String _descriptionTemplate = "descriptionTemplate"; + + @Field(value = DescriptionElasticEntity._dmp, type = FieldType.Object) + private NestedDmpElasticEntity dmp; + public final static String _dmp = "dmp"; + + @Field(value = DescriptionElasticEntity._references, type = FieldType.Nested) + private List references; + public final static String _references = "references"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } + + 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 DescriptionStatus getStatus() { + return status; + } + + public void setStatus(DescriptionStatus status) { + this.status = status; + } + + public Date getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Date finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public NestedDescriptionTemplateElasticEntity getDescriptionTemplate() { + return descriptionTemplate; + } + + public void setDescriptionTemplate(NestedDescriptionTemplateElasticEntity descriptionTemplate) { + this.descriptionTemplate = descriptionTemplate; + } + + public NestedDmpElasticEntity getDmp() { + return dmp; + } + + public void setDmp(NestedDmpElasticEntity dmp) { + this.dmp = dmp; + } + + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + + public Date getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/data/DmpElasticEntity.java b/backend/core/src/main/java/org/opencdmp/elastic/data/DmpElasticEntity.java new file mode 100644 index 000000000..8fa58eb12 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/data/DmpElasticEntity.java @@ -0,0 +1,210 @@ +package org.opencdmp.elastic.data; + +import org.opencdmp.commons.enums.DmpAccessType; +import org.opencdmp.commons.enums.DmpStatus; +import org.opencdmp.commons.enums.DmpVersionStatus; +import org.opencdmp.elastic.data.nested.*; +import gr.cite.tools.elastic.ElasticConstants; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.*; + +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Document(indexName = "dmp") +public class DmpElasticEntity { + @Id + @Field(value = DmpElasticEntity._id, type = FieldType.Keyword) + private UUID id; + public final static String _id = "id"; + + @Field(value = DmpElasticEntity._tenantId, type = FieldType.Keyword) + private UUID tenantId; + public final static String _tenantId = "tenantId"; + + @MultiField(mainField = @Field(value = DmpElasticEntity._label, type = FieldType.Text), otherFields = { + @InnerField(suffix = ElasticConstants.SubFields.keyword, type = FieldType.Keyword) + }) + private String label; + public final static String _label = "label"; + + @Field(value = DmpElasticEntity._description, type = FieldType.Text) + private String description; + public final static String _description = "description"; + + @Field(value = DmpElasticEntity._version, type = FieldType.Keyword) + private Short version; + public final static String _version = "version"; + + @Field(value = DmpElasticEntity._status, type = FieldType.Short) + private DmpStatus status; + public final static String _status = "status"; + + @Field(value = DmpElasticEntity._accessType, type = FieldType.Short) + private DmpAccessType accessType; + public final static String _accessType = "accessType"; + @Field(value = DmpElasticEntity._versionStatus, type = FieldType.Short) + private DmpVersionStatus versionStatus; + public final static String _versionStatus = "versionStatus"; + + @Field(value = DmpElasticEntity._language, type = FieldType.Keyword) + private String language; + public final static String _language = "language"; + + @Field(value = DmpElasticEntity._blueprintId, type = FieldType.Keyword) + private UUID blueprintId; + public final static String _blueprintId = "blueprintId"; + + @Field(value = DmpElasticEntity._groupId, type = FieldType.Keyword) + private UUID groupId; + public final static String _groupId = "groupId"; + + @Field(value = DmpElasticEntity._finalizedAt, type = FieldType.Date) + private Date finalizedAt; + public final static String _finalizedAt = "finalizedAt"; + + @Field(value = DmpElasticEntity._references, type = FieldType.Nested) + private List references; + public final static String _references = "references"; + + @Field(value = DmpElasticEntity._collaborators, type = FieldType.Nested) + private List collaborators; + public final static String _collaborators = "collaborators"; + + @Field(value = DmpElasticEntity._descriptions, type = FieldType.Nested) + private List descriptions; + public final static String _descriptions = "descriptions"; + + @Field(value = DmpElasticEntity._dois, type = FieldType.Nested) + private List dois; + public final static String _dois = "dois"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } + + 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 Short getVersion() { + return version; + } + + public void setVersion(Short version) { + this.version = version; + } + + public DmpStatus getStatus() { + return status; + } + + public void setStatus(DmpStatus status) { + this.status = status; + } + + public DmpAccessType getAccessType() { + return accessType; + } + + public void setAccessType(DmpAccessType accessType) { + this.accessType = accessType; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public UUID getBlueprintId() { + return blueprintId; + } + + public void setBlueprintId(UUID blueprintId) { + this.blueprintId = blueprintId; + } + + public UUID getGroupId() { + return groupId; + } + + public void setGroupId(UUID groupId) { + this.groupId = groupId; + } + + public Date getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Date finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + + public List getCollaborators() { + return collaborators; + } + + public void setCollaborators(List collaborators) { + this.collaborators = collaborators; + } + + public List getDescriptions() { + return descriptions; + } + + public void setDescriptions(List descriptions) { + this.descriptions = descriptions; + } + + public List getDois() { + return dois; + } + + public void setDois(List dois) { + this.dois = dois; + } + + public DmpVersionStatus getVersionStatus() { + return versionStatus; + } + + public void setVersionStatus(DmpVersionStatus versionStatus) { + this.versionStatus = versionStatus; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedCollaboratorElasticEntity.java b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedCollaboratorElasticEntity.java new file mode 100644 index 000000000..6ca1d9ad0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedCollaboratorElasticEntity.java @@ -0,0 +1,49 @@ +package org.opencdmp.elastic.data.nested; + +import org.opencdmp.commons.enums.DmpUserRole; +import gr.cite.tools.elastic.ElasticConstants; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.*; + +import java.util.UUID; + +public class NestedCollaboratorElasticEntity { + @Id + @Field(value = NestedCollaboratorElasticEntity._id, type = FieldType.Keyword) + private UUID id; + public final static String _id = "id"; + + @MultiField(mainField = @Field(value = NestedCollaboratorElasticEntity._name, type = FieldType.Text), otherFields = { + @InnerField(suffix = ElasticConstants.SubFields.keyword, type = FieldType.Keyword) + }) + private String name; + public final static String _name = "name"; + + @Field(value = NestedCollaboratorElasticEntity._role, type = FieldType.Short) + private DmpUserRole role; + public final static String _role = "role"; + + 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 DmpUserRole getRole() { + return role; + } + + public void setRole(DmpUserRole role) { + this.role = role; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDescriptionElasticEntity.java b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDescriptionElasticEntity.java new file mode 100644 index 000000000..114826abd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDescriptionElasticEntity.java @@ -0,0 +1,125 @@ +package org.opencdmp.elastic.data.nested; + +import org.opencdmp.commons.enums.DescriptionStatus; +import org.opencdmp.elastic.data.DescriptionElasticEntity; +import gr.cite.tools.elastic.ElasticConstants; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.*; + +import java.util.Date; +import java.util.List; +import java.util.UUID; + +public class NestedDescriptionElasticEntity { + + @Id + @Field(value = NestedDescriptionElasticEntity._id, type = FieldType.Keyword) + private UUID id; + public final static String _id = "id"; + + @Field(value = NestedDescriptionElasticEntity._dmpId, type = FieldType.Keyword) + private UUID dmpId; + public final static String _dmpId = "dmpId"; + + @MultiField(mainField = @Field(value = NestedDescriptionElasticEntity._label, type = FieldType.Text), otherFields = { + @InnerField(suffix = ElasticConstants.SubFields.keyword, type = FieldType.Keyword) + }) + private String label; + public final static String _label = "label"; + + @Field(value = NestedDescriptionElasticEntity._description, type = FieldType.Text) + private String description; + public final static String _description = "description"; + + @Field(value = NestedDescriptionElasticEntity._status, type = FieldType.Short ) + private DescriptionStatus status; + public final static String _status = "status"; + + @Field(value = NestedDescriptionElasticEntity._finalizedAt, type = FieldType.Date) + private Date finalizedAt; + public final static String _finalizedAt = "finalizedAt"; + + @Field(value = NestedDescriptionElasticEntity._tags, type = FieldType.Nested) + private List tags; + public final static String _tags = "tags"; + + @Field(value = NestedDescriptionElasticEntity._references, type = FieldType.Nested) + private List references; + public final static String _references = "references"; + + @Field(value = DescriptionElasticEntity._descriptionTemplate, type = FieldType.Object) + private NestedDescriptionTemplateElasticEntity descriptionTemplate; + public final static String _descriptionTemplate = "descriptionTemplate"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getDmpId() { + return dmpId; + } + + public void setDmpId(UUID dmpId) { + this.dmpId = dmpId; + } + + 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 DescriptionStatus getStatus() { + return status; + } + + public void setStatus(DescriptionStatus status) { + this.status = status; + } + + public Date getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Date finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + + public NestedDescriptionTemplateElasticEntity getDescriptionTemplate() { + return descriptionTemplate; + } + + public void setDescriptionTemplate(NestedDescriptionTemplateElasticEntity descriptionTemplate) { + this.descriptionTemplate = descriptionTemplate; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDescriptionTemplateElasticEntity.java b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDescriptionTemplateElasticEntity.java new file mode 100644 index 000000000..e653c9519 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDescriptionTemplateElasticEntity.java @@ -0,0 +1,52 @@ +package org.opencdmp.elastic.data.nested; + +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import org.opencdmp.elastic.data.DescriptionElasticEntity; +import gr.cite.tools.elastic.ElasticConstants; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.*; + +import java.util.UUID; + +public class NestedDescriptionTemplateElasticEntity { + + @Id + @Field(value = NestedDescriptionTemplateElasticEntity._id, type = FieldType.Keyword) + private UUID id; + public final static String _id = "id"; + + @MultiField(mainField = @Field(value = NestedDescriptionTemplateElasticEntity._label, type = FieldType.Text), otherFields = { + @InnerField(suffix = ElasticConstants.SubFields.keyword, type = FieldType.Keyword) + }) + private String label; + public final static String _label = "label"; + + + @Field(value = NestedDescriptionTemplateElasticEntity._versionStatus, type = FieldType.Short) + private DescriptionTemplateVersionStatus versionStatus; + public final static String _versionStatus = "versionStatus"; + + 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 DescriptionTemplateVersionStatus getVersionStatus() { + return versionStatus; + } + + public void setVersionStatus(DescriptionTemplateVersionStatus versionStatus) { + this.versionStatus = versionStatus; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDmpElasticEntity.java b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDmpElasticEntity.java new file mode 100644 index 000000000..d0ce3b8d1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDmpElasticEntity.java @@ -0,0 +1,186 @@ +package org.opencdmp.elastic.data.nested; + +import org.opencdmp.commons.enums.DmpAccessType; +import org.opencdmp.commons.enums.DmpStatus; +import org.opencdmp.commons.enums.DmpVersionStatus; +import org.opencdmp.elastic.data.DmpElasticEntity; +import gr.cite.tools.elastic.ElasticConstants; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.*; + +import java.util.Date; +import java.util.List; +import java.util.UUID; + +public class NestedDmpElasticEntity { + @Id + @Field(value = NestedDmpElasticEntity._id, type = FieldType.Keyword) + private UUID id; + public final static String _id = "id"; + + @MultiField(mainField = @Field(value = NestedDmpElasticEntity._label, type = FieldType.Text), otherFields = { + @InnerField(suffix = ElasticConstants.SubFields.keyword, type = FieldType.Keyword) + }) + private String label; + public final static String _label = "label"; + + @Field(value = NestedDmpElasticEntity._description, type = FieldType.Text) + private String description; + public final static String _description = "description"; + + @Field(value = NestedDmpElasticEntity._version, type = FieldType.Keyword) + private Short version; + public final static String _version = "version"; + + @Field(value = NestedDmpElasticEntity._versionStatus, type = FieldType.Short) + private DmpVersionStatus versionStatus; + public final static String _versionStatus = "versionStatus"; + + @Field(value = NestedDmpElasticEntity._status, type = FieldType.Short) + private DmpStatus status; + public final static String _status = "status"; + + @Field(value = NestedDmpElasticEntity._accessType, type = FieldType.Short) + private DmpAccessType accessType; + public final static String _accessType = "accessType"; + + @Field(value = NestedDmpElasticEntity._language, type = FieldType.Keyword) + private String language; + public final static String _language = "language"; + + @Field(value = NestedDmpElasticEntity._blueprintId, type = FieldType.Keyword) + private UUID blueprintId; + public final static String _blueprintId = "blueprintId"; + + @Field(value = NestedDmpElasticEntity._groupId, type = FieldType.Keyword) + private UUID groupId; + public final static String _groupId = "groupId"; + + @Field(value = NestedDmpElasticEntity._finalizedAt, type = FieldType.Date) + private Date finalizedAt; + public final static String _finalizedAt = "finalizedAt"; + + @Field(value = NestedDmpElasticEntity._references, type = FieldType.Nested) + private List references; + public final static String _references = "references"; + + @Field(value = NestedDmpElasticEntity._collaborators, type = FieldType.Nested) + private List collaborators; + public final static String _collaborators = "collaborators"; + + @Field(value = NestedDmpElasticEntity._dois, type = FieldType.Nested) + private List dois; + public final static String _dois = "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 Short getVersion() { + return version; + } + + public void setVersion(Short version) { + this.version = version; + } + + public DmpStatus getStatus() { + return status; + } + + public void setStatus(DmpStatus status) { + this.status = status; + } + + public DmpAccessType getAccessType() { + return accessType; + } + + public void setAccessType(DmpAccessType accessType) { + this.accessType = accessType; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public UUID getBlueprintId() { + return blueprintId; + } + + public void setBlueprintId(UUID blueprintId) { + this.blueprintId = blueprintId; + } + + public UUID getGroupId() { + return groupId; + } + + public void setGroupId(UUID groupId) { + this.groupId = groupId; + } + + public Date getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Date finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + + public List getCollaborators() { + return collaborators; + } + + public void setCollaborators(List collaborators) { + this.collaborators = collaborators; + } + + public List getDois() { + return dois; + } + + public void setDois(List dois) { + this.dois = dois; + } + + public DmpVersionStatus getVersionStatus() { + return versionStatus; + } + + public void setVersionStatus(DmpVersionStatus versionStatus) { + this.versionStatus = versionStatus; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDoiElasticEntity.java b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDoiElasticEntity.java new file mode 100644 index 000000000..7305d3648 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedDoiElasticEntity.java @@ -0,0 +1,46 @@ +package org.opencdmp.elastic.data.nested; + +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.*; + +import java.util.UUID; + +public class NestedDoiElasticEntity { + + @Id + @Field(value = NestedDoiElasticEntity._id, type = FieldType.Keyword) + private UUID id; + public final static String _id = "id"; + + @Field(value = NestedDoiElasticEntity._repositoryId, type = FieldType.Keyword) + private String repositoryId; + public final static String _repositoryId = "repositoryId"; + + @Field(value = NestedDoiElasticEntity._doi, type = FieldType.Keyword) + private String doi; + public final static String _doi = "doi"; + + 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; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedReferenceElasticEntity.java b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedReferenceElasticEntity.java new file mode 100644 index 000000000..1b6a443be --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedReferenceElasticEntity.java @@ -0,0 +1,36 @@ +package org.opencdmp.elastic.data.nested; + +import gr.cite.tools.elastic.ElasticConstants; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.*; + +import java.util.UUID; + +public class NestedReferenceElasticEntity { + @Id + @Field(value = NestedReferenceElasticEntity._id, type = FieldType.Keyword) + private UUID id; + public final static String _id = "id"; + + @MultiField(mainField = @Field(value = NestedReferenceElasticEntity._label, type = FieldType.Text), otherFields = { + @InnerField(suffix = ElasticConstants.SubFields.keyword, type = FieldType.Keyword) + }) + private String label; + public final static String _label = "label"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedTagElasticEntity.java b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedTagElasticEntity.java new file mode 100644 index 000000000..6571cb8e8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/data/nested/NestedTagElasticEntity.java @@ -0,0 +1,36 @@ +package org.opencdmp.elastic.data.nested; + +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.*; +import gr.cite.tools.elastic.ElasticConstants; + +import java.util.UUID; + +public class NestedTagElasticEntity { + @Id + @Field(value = NestedTagElasticEntity._id, type = FieldType.Keyword) + private UUID id; + public final static String _id = "id"; + + @MultiField(mainField = @Field(value = NestedTagElasticEntity._label, type = FieldType.Text), otherFields = { + @InnerField(suffix = ElasticConstants.SubFields.keyword, type = FieldType.Keyword) + }) + private String label; + public final static String _label = "label"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/BaseElasticBuilder.java b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/BaseElasticBuilder.java new file mode 100644 index 000000000..f4b56a20e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/BaseElasticBuilder.java @@ -0,0 +1,93 @@ +package org.opencdmp.elastic.elasticbuilder; + +import org.opencdmp.convention.ConventionService; +import gr.cite.tools.data.builder.Builder; +import gr.cite.tools.data.query.QueryBase; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; + +import java.time.Instant; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +public abstract class BaseElasticBuilder implements Builder { + protected final LoggerService logger; + protected final ConventionService conventionService; + + public BaseElasticBuilder( + ConventionService conventionService, + LoggerService logger + ) { + this.conventionService = conventionService; + this.logger = logger; + } + + public M build(D data) throws MyApplicationException { + if (data == null) { + M model = null; + return null; //TODO + } + List models = this.build(Arrays.asList(data)); + return models.stream().findFirst().orElse(null); //TODO + } + + public abstract List build(List datas) throws MyApplicationException; + + public Map asForeignKey(QueryBase query, Function keySelector) throws MyApplicationException { + this.logger.trace("Building references from query"); + List datas = query.collect(); + this.logger.debug("collected {} items to build", Optional.ofNullable(datas).map(e -> e.size()).orElse(0)); + return this.asForeignKey(datas, keySelector); + } + + public Map asForeignKey(List datas, Function keySelector) throws MyApplicationException { + this.logger.trace("building references"); + List models = this.build(datas); + this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(e -> e.size()).orElse(0), Optional.ofNullable(datas).map(e -> e.size()).orElse(0)); + Map map = models.stream().collect(Collectors.toMap(o -> keySelector.apply(o), o -> o)); + return map; + } + + public Map> asMasterKey(QueryBase query, Function keySelector) throws MyApplicationException { + this.logger.trace("Building details from query"); + List datas = query.collect(); + this.logger.debug("collected {} items to build", Optional.ofNullable(datas).map(e -> e.size()).orElse(0)); + return this.asMasterKey(datas, keySelector); + } + + public Map> asMasterKey(List datas, Function keySelector) throws MyApplicationException { + this.logger.trace("building details"); + List models = this.build(datas); + this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(e -> e.size()).orElse(0), Optional.ofNullable(datas).map(e -> e.size()).orElse(0)); + Map> map = new HashMap<>(); + for (M model : models) { + K key = keySelector.apply(model); + if (!map.containsKey(key)) map.put(key, new ArrayList()); + map.get(key).add(model); + } + return map; + } + + public Map asEmpty(List keys, Function mapper, Function keySelector) { + this.logger.trace("building static references"); + List models = keys.stream().map(x -> mapper.apply(x)).collect(Collectors.toList()); + this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(x -> x.size()).orElse(0), Optional.ofNullable(keys).map(x -> x.size())); + Map map = models.stream().collect(Collectors.toMap(o -> keySelector.apply(o), o -> o)); + return map; + } + + protected String hashValue(Instant value) throws MyApplicationException { + return this.conventionService.hashValue(value); + } + + protected String asPrefix(String name) { + return this.conventionService.asPrefix(name); + } + + protected String asIndexer(String... names) { + return this.conventionService.asIndexer(names); + } + +} + diff --git a/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/DescriptionElasticBuilder.java b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/DescriptionElasticBuilder.java new file mode 100644 index 000000000..1b958fbab --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/DescriptionElasticBuilder.java @@ -0,0 +1,146 @@ +package org.opencdmp.elastic.elasticbuilder; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionEntity; +import org.opencdmp.data.DescriptionReferenceEntity; +import org.opencdmp.data.DescriptionTagEntity; +import org.opencdmp.data.DmpDescriptionTemplateEntity; +import org.opencdmp.elastic.data.DescriptionElasticEntity; +import org.opencdmp.elastic.data.nested.*; +import org.opencdmp.elastic.elasticbuilder.nested.NestedDescriptionTemplateElasticBuilder; +import org.opencdmp.elastic.elasticbuilder.nested.NestedDmpElasticBuilder; +import org.opencdmp.elastic.elasticbuilder.nested.NestedReferenceElasticBuilder; +import org.opencdmp.elastic.elasticbuilder.nested.NestedTagElasticBuilder; +import org.opencdmp.model.*; +import org.opencdmp.model.builder.DescriptionBuilder; +import org.opencdmp.model.builder.ReferenceBuilder; +import org.opencdmp.query.*; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionElasticBuilder extends BaseElasticBuilder { + + private final QueryFactory queryFactory; + private final BuilderFactory builderFactory; + + @Autowired + public DescriptionElasticBuilder( + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionElasticBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + @Override + public List build(List data) throws MyApplicationException { + if (data == null) + return new ArrayList<>(); + + Map> referenceElasticEntityMap = this.collectDescriptionReferences(data); + Map> tagElasticEntityMap = this.collectDescriptionTags(data); + Map dmpElasticEntityMap = this.collectDmps(data); + Map descriptionTemplateElasticEntityMap = this.collectDescriptionTemplates(data); + + List models = new ArrayList<>(); + for (DescriptionEntity d : data) { + DescriptionElasticEntity m = new DescriptionElasticEntity(); + m.setId(d.getId()); + m.setLabel(d.getLabel()); + m.setDescription(d.getDescription()); + m.setStatus(d.getStatus()); + m.setCreatedAt(Date.from(d.getCreatedAt())); + if (d.getFinalizedAt() != null) { + m.setFinalizedAt(Date.from(d.getFinalizedAt())); + } + if (d.getTenantId() != null) { + m.setTenantId(d.getTenantId()); + } + if (referenceElasticEntityMap != null) m.setReferences(referenceElasticEntityMap.getOrDefault(d.getId(), null)); + if (tagElasticEntityMap != null) m.setTags(tagElasticEntityMap.getOrDefault(d.getId(), null)); + if (dmpElasticEntityMap != null) m.setDmp(dmpElasticEntityMap.getOrDefault(d.getDmpId(), null)); + if (descriptionTemplateElasticEntityMap != null) m.setDescriptionTemplate(descriptionTemplateElasticEntityMap.getOrDefault(d.getDmpId(), null)); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map> collectDescriptionReferences(List data) throws MyApplicationException { + if (data.isEmpty()) return null; + this.logger.debug("checking related - {}", DescriptionReference.class.getSimpleName()); + + DescriptionReferenceQuery associationQuery = this.queryFactory.query(DescriptionReferenceQuery.class).descriptionIds(data.stream().map(DescriptionEntity::getId).collect(Collectors.toList())).isActive(IsActive.Active); + List associationEntities = associationQuery.collect(); + + ReferenceQuery query = this.queryFactory.query(ReferenceQuery.class).isActive(IsActive.Active).ids(associationEntities.stream().map(DescriptionReferenceEntity::getReferenceId).distinct().collect(Collectors.toList())); + Map itemMapById = this.builderFactory.builder(NestedReferenceElasticBuilder.class).asForeignKey(query, NestedReferenceElasticEntity::getId); + + Map> itemMap = new HashMap<>(); + for (DescriptionReferenceEntity associationEntity : associationEntities){ + if (!itemMap.containsKey(associationEntity.getDescriptionId())) itemMap.put(associationEntity.getDescriptionId(), new ArrayList<>()); + NestedReferenceElasticEntity item = itemMapById.getOrDefault(associationEntity.getReferenceId(), null); + if (item != null) itemMap.get(associationEntity.getDescriptionId()).add(item); + } + + return itemMap; + } + + private Map> collectDescriptionTags(List data) throws MyApplicationException { + if (data.isEmpty()) return null; + this.logger.debug("checking related - {}", DescriptionTag.class.getSimpleName()); + + DescriptionTagQuery associationQuery = this.queryFactory.query(DescriptionTagQuery.class).descriptionIds(data.stream().map(DescriptionEntity::getId).collect(Collectors.toList())).isActive(IsActive.Active); + List associationEntities = associationQuery.collect(); + + TagQuery query = this.queryFactory.query(TagQuery.class).isActive(IsActive.Active).ids(associationEntities.stream().map(DescriptionTagEntity::getTagId).distinct().collect(Collectors.toList())); + Map itemMapById = this.builderFactory.builder(NestedTagElasticBuilder.class).asForeignKey(query, NestedTagElasticEntity::getId); + + Map> itemMap = new HashMap<>(); + for (DescriptionTagEntity associationEntity : associationEntities){ + if (!itemMap.containsKey(associationEntity.getDescriptionId())) itemMap.put(associationEntity.getDescriptionId(), new ArrayList<>()); + NestedTagElasticEntity item = itemMapById.getOrDefault(associationEntity.getTagId(), null); + if (item != null) itemMap.get(associationEntity.getDescriptionId()).add(item); + } + + return itemMap; + } + + private Map collectDmps(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Dmp.class.getSimpleName()); + + Map itemMap; + DmpQuery q = this.queryFactory.query(DmpQuery.class).isActive(IsActive.Active).ids(data.stream().map(DescriptionEntity::getDmpId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(NestedDmpElasticBuilder.class).asForeignKey(q, NestedDmpElasticEntity::getId); + + return itemMap; + } + + private Map collectDescriptionTemplates(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DescriptionTemplate.class.getSimpleName()); + + Map itemMap; + DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).isActive(IsActive.Active).ids(data.stream().map(DescriptionEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(NestedDescriptionTemplateElasticBuilder.class).asForeignKey(q, NestedDescriptionTemplateElasticEntity::getId); + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/DmpElasticBuilder.java b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/DmpElasticBuilder.java new file mode 100644 index 000000000..abc3d8dec --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/DmpElasticBuilder.java @@ -0,0 +1,147 @@ +package org.opencdmp.elastic.elasticbuilder; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.*; +import org.opencdmp.elastic.data.DmpElasticEntity; +import org.opencdmp.elastic.data.nested.*; +import org.opencdmp.elastic.elasticbuilder.nested.*; +import org.opencdmp.model.DmpReference; +import org.opencdmp.query.*; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpElasticBuilder extends BaseElasticBuilder { + + private final QueryFactory queryFactory; + private final BuilderFactory builderFactory; + + @Autowired + public DmpElasticBuilder( + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpElasticBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + @Override + public List build(List data) throws MyApplicationException { + if (data == null) + return new ArrayList<>(); + + Map> referenceElasticEntityMap = this.collectDmpReferences(data); + Map> descriptionElasticEntityMap = this.collectDescriptions(data); + Map> collaboratorElasticEntityMap = this.collectCollaborators(data); + Map> doiElasticEntityMap = this.collectDois(data); + + List models = new ArrayList<>(); + for (DmpEntity d : data) { + DmpElasticEntity m = new DmpElasticEntity(); + m.setId(d.getId()); + m.setLabel(d.getLabel()); + m.setDescription(d.getDescription()); + m.setVersion(d.getVersion()); + m.setVersionStatus(d.getVersionStatus()); + m.setStatus(d.getStatus()); + m.setAccessType(d.getAccessType()); + m.setLanguage(d.getLanguage()); + m.setBlueprintId(d.getBlueprintId()); + m.setGroupId(d.getGroupId()); + if (d.getFinalizedAt() != null) { + m.setFinalizedAt(Date.from(d.getFinalizedAt())); + } + if (d.getTenantId() != null) { + m.setTenantId(d.getTenantId()); + } + if (referenceElasticEntityMap != null) m.setReferences(referenceElasticEntityMap.getOrDefault(d.getId(), null)); + if (descriptionElasticEntityMap != null) m.setDescriptions(descriptionElasticEntityMap.getOrDefault(d.getId(), null)); + if (collaboratorElasticEntityMap != null) m.setCollaborators(collaboratorElasticEntityMap.getOrDefault(d.getId(), null)); + if (doiElasticEntityMap != null) m.setDois(doiElasticEntityMap.getOrDefault(d.getId(), null)); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map> collectDmpReferences(List data) throws MyApplicationException { + if (data.isEmpty()) return null; + this.logger.debug("checking related - {}", DmpReference.class.getSimpleName()); + + DmpReferenceQuery associationQuery = this.queryFactory.query(DmpReferenceQuery.class).dmpIds(data.stream().map(DmpEntity::getId).collect(Collectors.toList())).isActives(IsActive.Active); + List associationEntities = associationQuery.collect(); + + ReferenceQuery query = this.queryFactory.query(ReferenceQuery.class).isActive(IsActive.Active).ids(associationEntities.stream().map(DmpReferenceEntity::getReferenceId).distinct().collect(Collectors.toList())); + Map itemMapById = this.builderFactory.builder(NestedReferenceElasticBuilder.class).asForeignKey(query, NestedReferenceElasticEntity::getId); + + Map> itemMap = new HashMap<>(); + for (DmpReferenceEntity associationEntity : associationEntities){ + if (!itemMap.containsKey(associationEntity.getDmpId())) itemMap.put(associationEntity.getDmpId(), new ArrayList<>()); + NestedReferenceElasticEntity item = itemMapById.getOrDefault(associationEntity.getReferenceId(), null); + if (item != null) itemMap.get(associationEntity.getDmpId()).add(item); + } + + return itemMap; + } + + private Map> collectDescriptions(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DescriptionEntity.class.getSimpleName()); + + Map> itemMap; + DescriptionQuery q = this.queryFactory.query(DescriptionQuery.class).isActive(IsActive.Active).dmpSubQuery(this.queryFactory.query(DmpQuery.class).ids(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList()))); + itemMap = this.builderFactory.builder(NestedDescriptionElasticBuilder.class).asMasterKey(q, NestedDescriptionElasticEntity::getDmpId); + + return itemMap; + } + + private Map> collectCollaborators(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DmpUserEntity.class.getSimpleName()); + + DmpUserQuery associationQuery = this.queryFactory.query(DmpUserQuery.class).dmpIds(data.stream().map(DmpEntity::getId).collect(Collectors.toList())).isActives(IsActive.Active); + List associationEntities = associationQuery.collect(); + + Map itemMapById = this.builderFactory.builder(NestedCollaboratorElasticBuilder.class).asForeignKey(associationEntities, NestedCollaboratorElasticEntity::getId); + + Map> itemMap = new HashMap<>(); + for (DmpUserEntity associationEntity : associationEntities){ + if (!itemMap.containsKey(associationEntity.getId())) itemMap.put(associationEntity.getDmpId(), new ArrayList<>()); + NestedCollaboratorElasticEntity item = itemMapById.getOrDefault(associationEntity.getId(), null); + if (item != null) itemMap.get(associationEntity.getDmpId()).add(item); + } + return itemMap; + } + + private Map> collectDois(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", EntityDoiEntity.class.getSimpleName()); + + EntityDoiQuery associationQuery = this.queryFactory.query(EntityDoiQuery.class).entityIds(data.stream().map(DmpEntity::getId).collect(Collectors.toList())).isActive(IsActive.Active); + List associationEntities = associationQuery.collect(); + + Map itemMapById = this.builderFactory.builder(NestedDoiElasticBuilder.class).asForeignKey(associationEntities, NestedDoiElasticEntity::getId); + + Map> itemMap = new HashMap<>(); + for (EntityDoiEntity associationEntity : associationEntities){ + if (!itemMap.containsKey(associationEntity.getId())) itemMap.put(associationEntity.getEntityId(), new ArrayList<>()); + NestedDoiElasticEntity item = itemMapById.getOrDefault(associationEntity.getId(), null); + if (item != null) itemMap.get(associationEntity.getEntityId()).add(item); + } + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedCollaboratorElasticBuilder.java b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedCollaboratorElasticBuilder.java new file mode 100644 index 000000000..d11f38e38 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedCollaboratorElasticBuilder.java @@ -0,0 +1,56 @@ +package org.opencdmp.elastic.elasticbuilder.nested; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionEntity; +import org.opencdmp.data.DmpUserEntity; +import org.opencdmp.data.UserEntity; +import org.opencdmp.elastic.data.nested.NestedCollaboratorElasticEntity; +import org.opencdmp.elastic.elasticbuilder.BaseElasticBuilder; +import org.opencdmp.model.User; +import org.opencdmp.query.DescriptionTemplateQuery; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedCollaboratorElasticBuilder extends BaseElasticBuilder { + + private final QueryFactory queryFactory; + @Autowired + public NestedCollaboratorElasticBuilder( + ConventionService conventionService, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(NestedCollaboratorElasticBuilder.class))); + this.queryFactory = queryFactory; + } + + @Override + public List build(List data) throws MyApplicationException { + if (data == null) + return new ArrayList<>(); + + List models = new ArrayList<>(); + Map userNameMap = this.queryFactory.query(UserQuery.class).isActive(IsActive.Active).ids(data.stream().map(DmpUserEntity::getUserId).distinct().collect(Collectors.toList())).collectAs(new BaseFieldSet().ensure(User._id).ensure(User._name)) + .stream().collect(Collectors.toMap(UserEntity::getId, UserEntity::getName)); + for (DmpUserEntity d : data) { + NestedCollaboratorElasticEntity m = new NestedCollaboratorElasticEntity(); + m.setId(d.getId()); + m.setRole(d.getRole()); + m.setName(userNameMap.getOrDefault(d.getUserId(), d.getUserId().toString())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDescriptionElasticBuilder.java b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDescriptionElasticBuilder.java new file mode 100644 index 000000000..43afba1cc --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDescriptionElasticBuilder.java @@ -0,0 +1,124 @@ +package org.opencdmp.elastic.elasticbuilder.nested; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionEntity; +import org.opencdmp.data.DescriptionReferenceEntity; +import org.opencdmp.data.DescriptionTagEntity; +import org.opencdmp.elastic.data.nested.NestedDescriptionElasticEntity; +import org.opencdmp.elastic.data.nested.NestedDescriptionTemplateElasticEntity; +import org.opencdmp.elastic.data.nested.NestedReferenceElasticEntity; +import org.opencdmp.elastic.data.nested.NestedTagElasticEntity; +import org.opencdmp.elastic.elasticbuilder.BaseElasticBuilder; +import org.opencdmp.model.DescriptionReference; +import org.opencdmp.model.DescriptionTag; +import org.opencdmp.model.DescriptionTemplate; +import org.opencdmp.query.*; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedDescriptionElasticBuilder extends BaseElasticBuilder { + + private final QueryFactory queryFactory; + private final BuilderFactory builderFactory; + + @Autowired + public NestedDescriptionElasticBuilder( + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(NestedDescriptionElasticBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + @Override + public List build(List data) throws MyApplicationException { + if (data == null) + return new ArrayList<>(); + + Map> referenceElasticEntityMap = this.collectDescriptionReferences(data); + Map> tagElasticEntityMap = this.collectDescriptionTags(data); + Map descriptionTemplateElasticEntityMap = this.collectDescriptionTemplates(data); + + List models = new ArrayList<>(); + for (DescriptionEntity d : data) { + NestedDescriptionElasticEntity m = new NestedDescriptionElasticEntity(); + m.setId(d.getId()); + m.setDmpId(d.getDmpId()); + m.setLabel(d.getLabel()); + m.setDescription(d.getDescription()); + m.setStatus(d.getStatus()); + if (d.getFinalizedAt() != null) { + m.setFinalizedAt(Date.from(d.getFinalizedAt())); + } + if (referenceElasticEntityMap != null) m.setReferences(referenceElasticEntityMap.getOrDefault(d.getId(), null)); + if (tagElasticEntityMap != null) m.setTags(tagElasticEntityMap.getOrDefault(d.getId(), null)); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map> collectDescriptionReferences(List data) throws MyApplicationException { + if (data.isEmpty()) return null; + this.logger.debug("checking related - {}", DescriptionReference.class.getSimpleName()); + + DescriptionReferenceQuery associationQuery = this.queryFactory.query(DescriptionReferenceQuery.class).descriptionIds(data.stream().map(DescriptionEntity::getId).collect(Collectors.toList())).isActive(IsActive.Active); + List associationEntities = associationQuery.collect(); + + ReferenceQuery query = this.queryFactory.query(ReferenceQuery.class).isActive(IsActive.Active).ids(associationEntities.stream().map(DescriptionReferenceEntity::getReferenceId).distinct().collect(Collectors.toList())); + Map itemMapById = this.builderFactory.builder(NestedReferenceElasticBuilder.class).asForeignKey(query, NestedReferenceElasticEntity::getId); + + Map> itemMap = new HashMap<>(); + for (DescriptionReferenceEntity associationEntity : associationEntities){ + if (!itemMap.containsKey(associationEntity.getDescriptionId())) itemMap.put(associationEntity.getDescriptionId(), new ArrayList<>()); + NestedReferenceElasticEntity item = itemMapById.getOrDefault(associationEntity.getReferenceId(), null); + if (item != null) itemMap.get(associationEntity.getDescriptionId()).add(item); + } + + return itemMap; + } + + private Map> collectDescriptionTags(List data) throws MyApplicationException { + if (data.isEmpty()) return null; + this.logger.debug("checking related - {}", DescriptionTag.class.getSimpleName()); + + DescriptionTagQuery associationQuery = this.queryFactory.query(DescriptionTagQuery.class).descriptionIds(data.stream().map(DescriptionEntity::getId).collect(Collectors.toList())).isActive(IsActive.Active); + List associationEntities = associationQuery.collect(); + + TagQuery query = this.queryFactory.query(TagQuery.class).isActive(IsActive.Active).ids(associationEntities.stream().map(DescriptionTagEntity::getTagId).distinct().collect(Collectors.toList())); + Map itemMapById = this.builderFactory.builder(NestedTagElasticBuilder.class).asForeignKey(query, NestedTagElasticEntity::getId); + + Map> itemMap = new HashMap<>(); + for (DescriptionTagEntity associationEntity : associationEntities){ + if (!itemMap.containsKey(associationEntity.getDescriptionId())) itemMap.put(associationEntity.getDescriptionId(), new ArrayList<>()); + NestedTagElasticEntity item = itemMapById.getOrDefault(associationEntity.getTagId(), null); + if (item != null) itemMap.get(associationEntity.getDescriptionId()).add(item); + } + + return itemMap; + } + + private Map collectDescriptionTemplates(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DescriptionTemplate.class.getSimpleName()); + + Map itemMap; + DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).isActive(IsActive.Active).ids(data.stream().map(DescriptionEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(NestedDescriptionTemplateElasticBuilder.class).asForeignKey(q, NestedDescriptionTemplateElasticEntity::getId); + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDescriptionTemplateElasticBuilder.java b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDescriptionTemplateElasticBuilder.java new file mode 100644 index 000000000..606b0226a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDescriptionTemplateElasticBuilder.java @@ -0,0 +1,45 @@ +package org.opencdmp.elastic.elasticbuilder.nested; + +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionTemplateEntity; +import org.opencdmp.elastic.data.nested.NestedDescriptionTemplateElasticEntity; +import org.opencdmp.elastic.elasticbuilder.BaseElasticBuilder; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedDescriptionTemplateElasticBuilder extends BaseElasticBuilder { + + @Autowired + public NestedDescriptionTemplateElasticBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(NestedDescriptionTemplateElasticBuilder.class))); + } + + @Override + public List build(List data) throws MyApplicationException { + if (data == null) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (DescriptionTemplateEntity d : data) { + NestedDescriptionTemplateElasticEntity m = new NestedDescriptionTemplateElasticEntity(); + m.setId(d.getId()); + m.setVersionStatus(d.getVersionStatus()); + m.setLabel(d.getLabel()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDmpElasticBuilder.java b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDmpElasticBuilder.java new file mode 100644 index 000000000..044e5f288 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDmpElasticBuilder.java @@ -0,0 +1,137 @@ +package org.opencdmp.elastic.elasticbuilder.nested; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpEntity; +import org.opencdmp.data.DmpReferenceEntity; +import org.opencdmp.data.DmpUserEntity; +import org.opencdmp.data.EntityDoiEntity; +import org.opencdmp.elastic.data.nested.*; +import org.opencdmp.elastic.elasticbuilder.BaseElasticBuilder; +import org.opencdmp.model.DmpReference; +import org.opencdmp.query.DmpReferenceQuery; +import org.opencdmp.query.DmpUserQuery; +import org.opencdmp.query.EntityDoiQuery; +import org.opencdmp.query.ReferenceQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedDmpElasticBuilder extends BaseElasticBuilder { + + private final QueryFactory queryFactory; + private final BuilderFactory builderFactory; + + @Autowired + public NestedDmpElasticBuilder( + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(NestedDmpElasticBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + @Override + public List build(List data) throws MyApplicationException { + if (data == null) + return new ArrayList<>(); + + Map> referenceElasticEntityMap = this.collectDmpReferences(data); + Map> collaboratorElasticEntityMap = this.collectCollaborators(data); + Map> doiElasticEntityMap = this.collectDois(data); + + List models = new ArrayList<>(); + for (DmpEntity d : data) { + NestedDmpElasticEntity m = new NestedDmpElasticEntity(); + m.setId(d.getId()); + m.setLabel(d.getLabel()); + m.setDescription(d.getDescription()); + m.setVersion(d.getVersion()); + m.setStatus(d.getStatus()); + m.setAccessType(d.getAccessType()); + m.setLanguage(d.getLanguage()); + m.setBlueprintId(d.getBlueprintId()); + m.setGroupId(d.getGroupId()); + m.setGroupId(d.getGroupId()); + m.setVersionStatus(d.getVersionStatus()); + if (d.getFinalizedAt() != null) { + m.setFinalizedAt(Date.from(d.getFinalizedAt())); + } + if (referenceElasticEntityMap != null) m.setReferences(referenceElasticEntityMap.getOrDefault(d.getId(), null)); + if (collaboratorElasticEntityMap != null) m.setCollaborators(collaboratorElasticEntityMap.getOrDefault(d.getId(), null)); + if (doiElasticEntityMap != null) m.setDois(doiElasticEntityMap.getOrDefault(d.getId(), null)); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map> collectDmpReferences(List data) throws MyApplicationException { + if (data.isEmpty()) return null; + this.logger.debug("checking related - {}", DmpReference.class.getSimpleName()); + + DmpReferenceQuery associationQuery = this.queryFactory.query(DmpReferenceQuery.class).dmpIds(data.stream().map(DmpEntity::getId).collect(Collectors.toList())).isActives(IsActive.Active); + List associationEntities = associationQuery.collect(); + + ReferenceQuery query = this.queryFactory.query(ReferenceQuery.class).isActive(IsActive.Active).ids(associationEntities.stream().map(DmpReferenceEntity::getReferenceId).distinct().collect(Collectors.toList())); + Map itemMapById = this.builderFactory.builder(NestedReferenceElasticBuilder.class).asForeignKey(query, NestedReferenceElasticEntity::getId); + + Map> itemMap = new HashMap<>(); + for (DmpReferenceEntity associationEntity : associationEntities){ + if (!itemMap.containsKey(associationEntity.getDmpId())) itemMap.put(associationEntity.getDmpId(), new ArrayList<>()); + NestedReferenceElasticEntity item = itemMapById.getOrDefault(associationEntity.getReferenceId(), null); + if (item != null) itemMap.get(associationEntity.getDmpId()).add(item); + } + + return itemMap; + } + + private Map> collectCollaborators(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DmpUserEntity.class.getSimpleName()); + + DmpUserQuery associationQuery = this.queryFactory.query(DmpUserQuery.class).dmpIds(data.stream().map(DmpEntity::getId).collect(Collectors.toList())).isActives(IsActive.Active); + List associationEntities = associationQuery.collect(); + + Map itemMapById = this.builderFactory.builder(NestedCollaboratorElasticBuilder.class).asForeignKey(associationEntities, NestedCollaboratorElasticEntity::getId); + + Map> itemMap = new HashMap<>(); + for (DmpUserEntity associationEntity : associationEntities){ + if (!itemMap.containsKey(associationEntity.getId())) itemMap.put(associationEntity.getDmpId(), new ArrayList<>()); + NestedCollaboratorElasticEntity item = itemMapById.getOrDefault(associationEntity.getId(), null); + if (item != null) itemMap.get(associationEntity.getDmpId()).add(item); + } + return itemMap; + } + + private Map> collectDois(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", EntityDoiEntity.class.getSimpleName()); + + EntityDoiQuery associationQuery = this.queryFactory.query(EntityDoiQuery.class).entityIds(data.stream().map(DmpEntity::getId).collect(Collectors.toList())).isActive(IsActive.Active); + List associationEntities = associationQuery.collect(); + + Map itemMapById = this.builderFactory.builder(NestedDoiElasticBuilder.class).asForeignKey(associationEntities, NestedDoiElasticEntity::getId); + + Map> itemMap = new HashMap<>(); + for (EntityDoiEntity associationEntity : associationEntities){ + if (!itemMap.containsKey(associationEntity.getId())) itemMap.put(associationEntity.getEntityId(), new ArrayList<>()); + NestedDoiElasticEntity item = itemMapById.getOrDefault(associationEntity.getId(), null); + if (item != null) itemMap.get(associationEntity.getEntityId()).add(item); + } + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDoiElasticBuilder.java b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDoiElasticBuilder.java new file mode 100644 index 000000000..6f446b80f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedDoiElasticBuilder.java @@ -0,0 +1,45 @@ +package org.opencdmp.elastic.elasticbuilder.nested; + +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.EntityDoiEntity; +import org.opencdmp.elastic.data.nested.NestedDoiElasticEntity; +import org.opencdmp.elastic.elasticbuilder.BaseElasticBuilder; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedDoiElasticBuilder extends BaseElasticBuilder { + + @Autowired + public NestedDoiElasticBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(NestedDoiElasticBuilder.class))); + } + + @Override + public List build(List data) throws MyApplicationException { + if (data == null) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (EntityDoiEntity d : data) { + NestedDoiElasticEntity m = new NestedDoiElasticEntity(); + m.setId(d.getId()); + m.setDoi(d.getDoi()); + m.setRepositoryId(d.getRepositoryId()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedReferenceElasticBuilder.java b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedReferenceElasticBuilder.java new file mode 100644 index 000000000..d60367899 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedReferenceElasticBuilder.java @@ -0,0 +1,42 @@ +package org.opencdmp.elastic.elasticbuilder.nested; + +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.ReferenceEntity; +import org.opencdmp.elastic.data.nested.NestedReferenceElasticEntity; +import org.opencdmp.elastic.elasticbuilder.BaseElasticBuilder; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedReferenceElasticBuilder extends BaseElasticBuilder { + + @Autowired + public NestedReferenceElasticBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(NestedReferenceElasticBuilder.class))); + } + + @Override + public List build(List data) throws MyApplicationException { + if (data == null) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (ReferenceEntity d : data) { + NestedReferenceElasticEntity m = new NestedReferenceElasticEntity(); + m.setId(d.getId()); + m.setLabel(d.getLabel()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedTagElasticBuilder.java b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedTagElasticBuilder.java new file mode 100644 index 000000000..d61bf9bb5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/elasticbuilder/nested/NestedTagElasticBuilder.java @@ -0,0 +1,44 @@ +package org.opencdmp.elastic.elasticbuilder.nested; + +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.TagEntity; +import org.opencdmp.elastic.data.nested.NestedTagElasticEntity; +import org.opencdmp.elastic.elasticbuilder.BaseElasticBuilder; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedTagElasticBuilder extends BaseElasticBuilder { + + @Autowired + public NestedTagElasticBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(NestedTagElasticBuilder.class))); + } + + @Override + public List build(List data) throws MyApplicationException { + if (data == null) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (TagEntity d : data) { + NestedTagElasticEntity m = new NestedTagElasticEntity(); + m.setId(d.getId()); + m.setLabel(d.getLabel()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/query/DescriptionElasticQuery.java b/backend/core/src/main/java/org/opencdmp/elastic/query/DescriptionElasticQuery.java new file mode 100644 index 000000000..d8e47d3a1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/query/DescriptionElasticQuery.java @@ -0,0 +1,331 @@ +package org.opencdmp.elastic.query; +import co.elastic.clients.elasticsearch._types.query_dsl.Query; +import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders; +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.authorization.Permission; +import org.opencdmp.commons.enums.DescriptionStatus; +import org.opencdmp.commons.enums.DmpAccessType; +import org.opencdmp.commons.enums.DmpStatus; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.scope.user.UserScope; +import org.opencdmp.service.elastic.AppElasticProperties; +import org.opencdmp.elastic.data.DescriptionElasticEntity; +import org.opencdmp.elastic.data.DmpElasticEntity; +import org.opencdmp.elastic.data.nested.NestedDmpElasticEntity; +import org.opencdmp.service.elastic.ElasticService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.query.FieldResolver; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.elastic.configuration.ElasticProperties; +import gr.cite.tools.elastic.mapper.FieldBasedMapper; +import gr.cite.tools.elastic.query.ElasticField; +import gr.cite.tools.elastic.query.ElasticFields; +import gr.cite.tools.elastic.query.ElasticNestedQuery; +import gr.cite.tools.elastic.query.ElasticQuery; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Scope; +import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.io.IOException; +import java.time.Instant; +import java.util.*; + +@Component +//Like in C# make it Transient +@Scope(BeanDefinition.SCOPE_PROTOTYPE) +public class DescriptionElasticQuery extends ElasticQuery { + + private Collection ids; + private String like; + private InnerObjectDmpElasticQuery dmpSubQuery; + private Instant createdAfter; + private Instant createdBefore; + private Instant finalizedAfter; + private Instant finalizedBefore; + private Collection excludedIds; + private Collection statuses; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + public DescriptionElasticQuery like(String value) { + this.like = value; + return this; + } + + public DescriptionElasticQuery ids(UUID value) { + this.ids = List.of(value); + return this; + } + + public DescriptionElasticQuery ids(UUID... value) { + this.ids = Arrays.asList(value); + return this; + } + + public DescriptionElasticQuery ids(Collection values) { + this.ids = values; + return this; + } + + public DescriptionElasticQuery dmpSubQuery(InnerObjectDmpElasticQuery subQuery) { + this.dmpSubQuery = subQuery; + return this; + } + + + public DescriptionElasticQuery createdAfter(Instant value) { + this.createdAfter = value; + return this; + } + + public DescriptionElasticQuery createdBefore(Instant value) { + this.createdBefore = value; + return this; + } + + public DescriptionElasticQuery finalizedAfter(Instant value) { + this.finalizedAfter = value; + return this; + } + + public DescriptionElasticQuery finalizedBefore(Instant value) { + this.finalizedBefore = value; + return this; + } + + + public DescriptionElasticQuery excludedIds(Collection values) { + this.excludedIds = values; + return this; + } + + public DescriptionElasticQuery excludedIds(UUID value) { + this.excludedIds = List.of(value); + return this; + } + + public DescriptionElasticQuery excludedIds(UUID... value) { + this.excludedIds = Arrays.asList(value); + return this; + } + + public DescriptionElasticQuery statuses(DescriptionStatus value) { + this.statuses = List.of(value); + return this; + } + + public DescriptionElasticQuery statuses(DescriptionStatus... value) { + this.statuses = Arrays.asList(value); + return this; + } + + public DescriptionElasticQuery statuses(Collection values) { + this.statuses = values; + return this; + } + + public DescriptionElasticQuery authorize(EnumSet values) { + this.authorize = values; + return this; + } + + private final QueryFactory queryFactory; + private final AppElasticProperties appElasticProperties; + private final ElasticService elasticService; + private final UserScope userScope; + private final TenantScope tenantScope; + private final AuthorizationService authService; + @Autowired() + public DescriptionElasticQuery(ElasticsearchTemplate elasticsearchTemplate, ElasticProperties elasticProperties, QueryFactory queryFactory, AppElasticProperties appElasticProperties, ElasticService elasticService, UserScope userScope, TenantScope tenantScope, AuthorizationService authService) { + super(elasticsearchTemplate, elasticProperties); + this.queryFactory = queryFactory; + this.appElasticProperties = appElasticProperties; + this.elasticService = elasticService; + this.userScope = userScope; + this.tenantScope = tenantScope; + this.authService = authService; + } + + @Override + protected Boolean isFalseQuery() { + return this.isEmpty(this.ids) || + this.isEmpty(this.excludedIds) || + this.isEmpty(this.statuses); + } + + @Override + protected Class entityClass() { + return DescriptionElasticEntity.class; + } + + private Query applyTenant(List predicates){ + if (this.tenantScope.isSet()){ + Query tenantQuery; + if (this.tenantScope.isDefaultTenant()){ + tenantQuery = this.fieldNotExists(this.elasticFieldOf(DescriptionElasticEntity._tenantId))._toQuery(); + } + else { + try { + tenantQuery = this.or(this.fieldNotExists(this.elasticFieldOf(DescriptionElasticEntity._tenantId))._toQuery(), + this.equals(this.elasticFieldOf(DescriptionElasticEntity._tenantId), this.tenantScope.getTenant()))._toQuery(); + } catch (InvalidApplicationException e) { + throw new RuntimeException(e); + } + } + if (predicates == null) return tenantQuery; + else return this.and(tenantQuery, this.or(predicates)._toQuery()); + } else { + if (predicates != null) return this.or(predicates)._toQuery(); + } + return null; + } + + @Override + protected Query applyAuthZ() { + if (this.authorize.contains(AuthorizationFlags.None)) return this.applyTenant(null); + if (this.authorize.contains(AuthorizationFlags.Permission) && this.authService.authorize(Permission.BrowseDescription)) return this.applyTenant(null); + UUID userId = null; + boolean usePublic = this.authorize.contains(AuthorizationFlags.Public); + if (this.authorize.contains(AuthorizationFlags.DmpAssociated)) userId = this.userScope.getUserIdSafe(); + + List predicates = new ArrayList<>(); + if (usePublic ) { + predicates.add(this.and( + this.equals(new ElasticField(DescriptionElasticEntity._dmp + "." + DmpElasticEntity._status, this.entityClass()).disableInfer(true), DmpStatus.Finalized.getValue()), + this.equals(new ElasticField(DescriptionElasticEntity._dmp + "." + DmpElasticEntity._accessType, this.entityClass()).disableInfer(true), DmpAccessType.Public.getValue()) + )); + } + if (userId != null) { + NestedCollaboratorElasticQuery query = this.queryFactory.query(NestedCollaboratorElasticQuery.class).nestedPath(DescriptionElasticEntity._dmp + "." + NestedDmpElasticEntity._collaborators); + query.ids(userId); + predicates.add(this.nestedQuery(query).build()._toQuery()); + } + + if (!predicates.isEmpty()) { + return this.applyTenant(predicates); + } else { + return this.equals(this.elasticFieldOf(DescriptionElasticEntity._id), UUID.randomUUID()); + } + } + + @Override + protected Query applyFilters() { + List predicates = new ArrayList<>(); + if (like != null && !like.isBlank()) { + if (!like.startsWith("*")) like = "*" + like; + if (!like.endsWith("*")) like = like + "*"; + ElasticFields elasticFields = this.elasticFieldsOf(); + elasticFields.add("*", null, true); + + predicates.add(this.or( + this.like(elasticFields, List.of(like))._toQuery(), + QueryBuilders.nested().path(DescriptionElasticEntity._tags).query( + this.like(elasticFields, List.of(like))._toQuery() + ).build()._toQuery(), + QueryBuilders.nested().path(DescriptionElasticEntity._references).query( + this.like(elasticFields, List.of(like))._toQuery() + ).build()._toQuery(), + QueryBuilders.nested().path(DescriptionElasticEntity._dmp + "." + NestedDmpElasticEntity._references).query( + this.like(elasticFields, List.of(like))._toQuery() + ).build()._toQuery(), + QueryBuilders.nested().path(DescriptionElasticEntity._dmp + "." + NestedDmpElasticEntity._collaborators).query( + this.like(elasticFields, List.of(like))._toQuery() + ).build()._toQuery(), + QueryBuilders.nested().path(DescriptionElasticEntity._dmp + "." + NestedDmpElasticEntity._dois).query( + this.like(elasticFields, List.of(like))._toQuery() + ).build()._toQuery() + )._toQuery()); + } + if (ids != null) { + predicates.add(this.containsUUID(this.elasticFieldOf(DescriptionElasticEntity._id), ids)._toQuery()); + } + if (excludedIds != null) { + predicates.add(this.not(this.containsUUID(this.elasticFieldOf(DescriptionElasticEntity._id), excludedIds)._toQuery())._toQuery()); + } + if (statuses != null) { + predicates.add(this.contains(this.elasticFieldOf(DescriptionElasticEntity._status), statuses.stream().map(DescriptionStatus::getValue).toList().toArray(new Short[statuses.size()]))._toQuery()); + } + if (this.finalizedAfter != null) { + predicates.add(this.dateGreaterThanQuery(this.elasticFieldOf(DescriptionElasticEntity._finalizedAt), this.finalizedAfter)._toQuery()); + } + if (this.finalizedBefore != null) { + predicates.add(this.dateLessThanQuery(this.elasticFieldOf(DescriptionElasticEntity._finalizedAt), this.finalizedBefore)._toQuery()); + } + if (this.createdAfter != null) { + predicates.add(this.dateGreaterThanQuery(this.elasticFieldOf(DescriptionElasticEntity._createdAt), this.createdAfter)._toQuery()); + } + if (this.createdBefore != null) { + predicates.add(this.dateLessThanQuery(this.elasticFieldOf(DescriptionElasticEntity._createdAt), this.createdBefore)._toQuery()); + } + if (dmpSubQuery != null) { + predicates.add(dmpSubQuery.innerPath(DescriptionElasticEntity._dmp).applyFilters()); + } + if (!predicates.isEmpty()) { + return this.and(predicates); + } else { + return null; + } + } + + @Override + public DescriptionElasticEntity convert(Map rawData, Set columns) { + DescriptionElasticEntity mocDoc = new DescriptionElasticEntity(); + if (columns.contains(DescriptionElasticEntity._id)) mocDoc.setId(FieldBasedMapper.shallowSafeConversion(rawData.get(DescriptionElasticEntity._id), UUID.class)); + if (columns.contains(DescriptionElasticEntity._label)) mocDoc.setLabel(FieldBasedMapper.shallowSafeConversion(rawData.get(DescriptionElasticEntity._label), String.class)); + if (columns.contains(DescriptionElasticEntity._description)) mocDoc.setDescription(FieldBasedMapper.shallowSafeConversion(rawData.get(DescriptionElasticEntity._description), String.class)); + if (columns.contains(DescriptionElasticEntity._status)) mocDoc.setStatus(FieldBasedMapper.shallowSafeConversion(rawData.get(DescriptionElasticEntity._status), DescriptionStatus.class)); + if (columns.contains(DescriptionElasticEntity._finalizedAt)) mocDoc.setFinalizedAt(FieldBasedMapper.shallowSafeConversion(rawData.get(DescriptionElasticEntity._finalizedAt), Date.class)); + if (columns.contains(DescriptionElasticEntity._createdAt)) mocDoc.setFinalizedAt(FieldBasedMapper.shallowSafeConversion(rawData.get(DescriptionElasticEntity._createdAt), Date.class)); + mocDoc.setTags(this.convertNested(rawData, columns, this.queryFactory.query(NestedTagElasticQuery.class), DescriptionElasticEntity._tags, null)); + mocDoc.setReferences(this.convertNested(rawData, columns, this.queryFactory.query(NestedReferenceElasticQuery.class), DescriptionElasticEntity._references, null)); + mocDoc.setDescriptionTemplate(this.convertInnerObject(rawData, columns, this.queryFactory.query(InnerObjectDescriptionTemplateElasticQuery.class), DescriptionElasticEntity._descriptionTemplate, null)); + mocDoc.setDmp(this.convertInnerObject(rawData, columns, this.queryFactory.query(InnerObjectDmpElasticQuery.class), DescriptionElasticEntity._dmp, null)); + return mocDoc; + } + + @Override + protected ElasticField fieldNameOf(FieldResolver item) { + if (item.match(DescriptionElasticEntity._id)) return this.elasticFieldOf(DescriptionElasticEntity._id); + else if (item.match(DescriptionElasticEntity._label)) return this.elasticFieldOf(DescriptionElasticEntity._label); + else if (item.match(DescriptionElasticEntity._description)) return this.elasticFieldOf(DescriptionElasticEntity._description); + else if (item.match(DescriptionElasticEntity._status)) return this.elasticFieldOf(DescriptionElasticEntity._status); + else if (item.match(DescriptionElasticEntity._finalizedAt)) return this.elasticFieldOf(DescriptionElasticEntity._finalizedAt); + else if (item.match(DescriptionElasticEntity._createdAt)) return this.elasticFieldOf(DescriptionElasticEntity._createdAt); + else if (item.prefix(DescriptionElasticEntity._references)) return this.queryFactory.query(NestedReferenceElasticQuery.class).nestedPath(DescriptionElasticEntity._references).fieldNameOf(this.extractPrefixed(item, DescriptionElasticEntity._references)); + else if (item.prefix(DescriptionElasticEntity._tags)) return this.queryFactory.query(NestedTagElasticQuery.class).nestedPath(DescriptionElasticEntity._tags).fieldNameOf(this.extractPrefixed(item, DescriptionElasticEntity._tags)); + else if (item.prefix(DescriptionElasticEntity._descriptionTemplate)) return this.queryFactory.query(InnerObjectDescriptionTemplateElasticQuery.class).innerPath(DescriptionElasticEntity._descriptionTemplate).fieldNameOf(this.extractPrefixed(item, DescriptionElasticEntity._description)); + else if (item.prefix(DescriptionElasticEntity._dmp)) return this.queryFactory.query(InnerObjectDmpElasticQuery.class).innerPath(DescriptionElasticEntity._dmp).fieldNameOf(this.extractPrefixed(item, DescriptionElasticEntity._dmp)); + else return null; + } + + @Override + protected String[] getIndex() { + List indexNames = new ArrayList<>(); + indexNames.add(this.appElasticProperties.getDescriptionIndexName()); + try { + this.elasticService.ensureDescriptionIndex(); + } catch (IOException e) { + throw new RuntimeException(e); + } + return indexNames.toArray(new String[indexNames.size()]); + } + + @Override + protected UUID toKey(String key) { + return UUID.fromString(key); + } + + @Override + protected ElasticField getKeyField() { + return this.elasticFieldOf(DescriptionElasticEntity._id); + } + + @Override + protected ElasticNestedQuery nestedQueryOf(FieldResolver item) { + if (item.prefix(DescriptionElasticEntity._references)) return this.queryFactory.query(NestedReferenceElasticQuery.class).nestedPath(DescriptionElasticEntity._references); + else if (item.prefix(DescriptionElasticEntity._tags)) return this.queryFactory.query(NestedTagElasticQuery.class).nestedPath(DescriptionElasticEntity._tags); + else return null; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/query/DmpElasticQuery.java b/backend/core/src/main/java/org/opencdmp/elastic/query/DmpElasticQuery.java new file mode 100644 index 000000000..8f3d8048d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/query/DmpElasticQuery.java @@ -0,0 +1,364 @@ +package org.opencdmp.elastic.query; +import co.elastic.clients.elasticsearch._types.query_dsl.Query; +import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders; +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.authorization.Permission; +import org.opencdmp.commons.enums.DmpAccessType; +import org.opencdmp.commons.enums.DmpStatus; +import org.opencdmp.commons.enums.DmpVersionStatus; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.scope.user.UserScope; +import org.opencdmp.elastic.data.DescriptionElasticEntity; +import org.opencdmp.service.elastic.AppElasticProperties; +import org.opencdmp.elastic.data.DmpElasticEntity; +import org.opencdmp.elastic.data.nested.NestedDescriptionElasticEntity; +import org.opencdmp.service.elastic.ElasticService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.query.FieldResolver; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.elastic.configuration.ElasticProperties; +import gr.cite.tools.elastic.mapper.FieldBasedMapper; +import gr.cite.tools.elastic.query.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Scope; +import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +@Component +//Like in C# make it Transient +@Scope(BeanDefinition.SCOPE_PROTOTYPE) +public class DmpElasticQuery extends ElasticQuery { + + private String like; + private Collection ids; + private Collection excludedIds; + private Collection statuses; + private Collection versionStatuses; + private Collection accessTypes; + private Collection versions; + private Collection groupIds; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + + public DmpElasticQuery like(String value) { + this.like = value; + return this; + } + + public DmpElasticQuery ids(UUID value) { + this.ids = List.of(value); + return this; + } + + public DmpElasticQuery ids(UUID... value) { + this.ids = Arrays.asList(value); + return this; + } + + public DmpElasticQuery ids(Collection values) { + this.ids = values; + return this; + } + + public DmpElasticQuery excludedIds(Collection values) { + this.excludedIds = values; + return this; + } + + public DmpElasticQuery excludedIds(UUID value) { + this.excludedIds = List.of(value); + return this; + } + + public DmpElasticQuery excludedIds(UUID... value) { + this.excludedIds = Arrays.asList(value); + return this; + } + + public DmpElasticQuery versionStatuses(DmpVersionStatus value) { + this.versionStatuses = List.of(value); + return this; + } + + public DmpElasticQuery versionStatuses(DmpVersionStatus... value) { + this.versionStatuses = Arrays.asList(value); + return this; + } + + public DmpElasticQuery versionStatuses(Collection values) { + this.versionStatuses = values; + return this; + } + + public DmpElasticQuery accessTypes(DmpAccessType value) { + this.accessTypes = List.of(value); + return this; + } + + public DmpElasticQuery accessTypes(DmpAccessType... value) { + this.accessTypes = Arrays.asList(value); + return this; + } + + public DmpElasticQuery accessTypes(Collection values) { + this.accessTypes = values; + return this; + } + + public DmpElasticQuery statuses(DmpStatus value) { + this.statuses = List.of(value); + return this; + } + + public DmpElasticQuery statuses(DmpStatus... value) { + this.statuses = Arrays.asList(value); + return this; + } + + public DmpElasticQuery statuses(Collection values) { + this.statuses = values; + return this; + } + + public DmpElasticQuery versions(Integer value) { + this.versions = List.of(value); + return this; + } + + public DmpElasticQuery versions(Integer... value) { + this.versions = Arrays.asList(value); + return this; + } + + public DmpElasticQuery versions(Collection values) { + this.versions = values; + return this; + } + + public DmpElasticQuery groupIds(UUID value) { + this.groupIds = List.of(value); + return this; + } + + public DmpElasticQuery groupIds(UUID... value) { + this.groupIds = Arrays.asList(value); + return this; + } + + public DmpElasticQuery groupIds(Collection values) { + this.groupIds = values; + return this; + } + + public DmpElasticQuery authorize(EnumSet values) { + this.authorize = values; + return this; + } + + private final QueryFactory queryFactory; + private final AppElasticProperties appElasticProperties; + private final ElasticService elasticService; + private final UserScope userScope; + private final TenantScope tenantScope; + private final AuthorizationService authService; + @Autowired() + public DmpElasticQuery(ElasticsearchTemplate elasticsearchTemplate, ElasticProperties elasticProperties, QueryFactory queryFactory, AppElasticProperties appElasticProperties, ElasticService elasticService, UserScope userScope, TenantScope tenantScope, AuthorizationService authService) { + super(elasticsearchTemplate, elasticProperties); + this.queryFactory = queryFactory; + this.appElasticProperties = appElasticProperties; + this.elasticService = elasticService; + this.userScope = userScope; + this.tenantScope = tenantScope; + this.authService = authService; + } + + @Override + protected Boolean isFalseQuery() { + return this.isEmpty(this.ids) || this.isEmpty(this.versionStatuses) || this.isEmpty(this.excludedIds) || this.isEmpty(this.accessTypes)|| this.isEmpty(this.statuses); + } + + @Override + protected Class entityClass() { + return DmpElasticEntity.class; + } + + private Query applyTenant(List predicates){ + if (this.tenantScope.isSet()){ + Query tenantQuery; + if (this.tenantScope.isDefaultTenant()){ + tenantQuery = this.fieldNotExists(this.elasticFieldOf(DmpElasticEntity._tenantId))._toQuery(); + } + else { + try { + tenantQuery = this.or(this.fieldNotExists(this.elasticFieldOf(DmpElasticEntity._tenantId))._toQuery(), + this.equals(this.elasticFieldOf(DmpElasticEntity._tenantId), this.tenantScope.getTenant()))._toQuery(); + } catch (InvalidApplicationException e) { + throw new RuntimeException(e); + } + } + if (predicates == null) return tenantQuery; + else return this.and(tenantQuery, this.or(predicates)._toQuery()); + } else { + if (predicates != null) return this.or(predicates)._toQuery(); + } + return null; + } + @Override + protected Query applyAuthZ() { + + if (this.authorize.contains(AuthorizationFlags.None)) return this.applyTenant(null); + if (this.authorize.contains(AuthorizationFlags.Permission) && this.authService.authorize(Permission.BrowseDmp)) return this.applyTenant(null); + UUID userId = null; + boolean usePublic = this.authorize.contains(AuthorizationFlags.Public); + if (this.authorize.contains(AuthorizationFlags.DmpAssociated)) userId = this.userScope.getUserIdSafe(); + + List predicates = new ArrayList<>(); + if (usePublic) { + predicates.add(this.and( + this.equals(this.elasticFieldOf(DmpElasticEntity._status), DmpStatus.Finalized.getValue()), + this.equals(this.elasticFieldOf(DmpElasticEntity._accessType), DmpAccessType.Public.getValue()) + )); + } + if (userId != null) { + NestedCollaboratorElasticQuery query = this.queryFactory.query(NestedCollaboratorElasticQuery.class).nestedPath(DmpElasticEntity._collaborators); + query.ids(userId); + predicates.add(this.nestedQuery(query).build()._toQuery()); + } + if (!predicates.isEmpty()) { + return this.applyTenant(predicates); + } else { + return this.equals(this.elasticFieldOf(DescriptionElasticEntity._id), UUID.randomUUID()); + } + } + + @Override + protected Query applyFilters() { + List predicates = new ArrayList<>(); + + if (like != null && !like.isBlank()) { + + if (!like.startsWith("*")) like = "*" + like; + if (!like.endsWith("*")) like = like + "*"; + ElasticFields elasticFields = this.elasticFieldsOf(); + elasticFields.add("*", null, true); + + predicates.add(this.or( + this.like(elasticFields, List.of(like))._toQuery(), + QueryBuilders.nested().path(DmpElasticEntity._collaborators).query( + this.like(elasticFields, List.of(like))._toQuery() + ).build()._toQuery(), + QueryBuilders.nested().path(DmpElasticEntity._references).query( + this.like(elasticFields, List.of(like))._toQuery() + ).build()._toQuery(), + QueryBuilders.nested().path(DmpElasticEntity._descriptions + "." + NestedDescriptionElasticEntity._references).query( + this.like(elasticFields, List.of(like))._toQuery() + ).build()._toQuery(), + QueryBuilders.nested().path(DmpElasticEntity._descriptions + "." + NestedDescriptionElasticEntity._tags).query( + this.like(elasticFields, List.of(like))._toQuery() + ).build()._toQuery(), + QueryBuilders.nested().path(DmpElasticEntity._descriptions).query( + this.like(elasticFields, List.of(like))._toQuery() + ).build()._toQuery() + + )._toQuery()); + } + if (ids != null) { + predicates.add(this.containsUUID(this.elasticFieldOf(DmpElasticEntity._id), ids)._toQuery()); + } + if (groupIds != null) { + predicates.add(this.containsUUID(this.elasticFieldOf(DmpElasticEntity._groupId), groupIds)._toQuery()); + } + if (versions != null) { + predicates.add(this.contains(this.elasticFieldOf(DmpElasticEntity._version), versions.toArray(new Integer[versions.size()]))._toQuery()); + } + if (excludedIds != null) { + predicates.add(this.not(this.containsUUID(this.elasticFieldOf(DmpElasticEntity._id), excludedIds)._toQuery())._toQuery()); + } + if (statuses != null) { + predicates.add(this.contains(this.elasticFieldOf(DmpElasticEntity._status), statuses.stream().map(x-> x.getValue()).collect(Collectors.toList()).toArray(new Short[statuses.size()]))._toQuery()); + } + if (versionStatuses != null) { + predicates.add(this.contains(this.elasticFieldOf(DmpElasticEntity._versionStatus), versionStatuses.stream().map(x-> x.getValue()).collect(Collectors.toList()).toArray(new Short[versionStatuses.size()]))._toQuery()); + } + if (accessTypes != null) { + predicates.add(this.contains(this.elasticFieldOf(DmpElasticEntity._accessType), accessTypes.stream().map(x-> x.getValue()).collect(Collectors.toList()).toArray(new Short[accessTypes.size()]))._toQuery()); + } + + if (!predicates.isEmpty()) { + return this.and(predicates); + } else { + return null; + } + } + + @Override + public DmpElasticEntity convert(Map rawData, Set columns) { + DmpElasticEntity mocDoc = new DmpElasticEntity(); + if (columns.contains(DmpElasticEntity._id)) mocDoc.setId(FieldBasedMapper.shallowSafeConversion(rawData.get(DmpElasticEntity._id), UUID.class)); + if (columns.contains(DmpElasticEntity._label)) mocDoc.setLabel(FieldBasedMapper.shallowSafeConversion(rawData.get(DmpElasticEntity._label), String.class)); + if (columns.contains(DmpElasticEntity._description)) mocDoc.setDescription(FieldBasedMapper.shallowSafeConversion(rawData.get(DmpElasticEntity._description), String.class)); + if (columns.contains(DmpElasticEntity._status)) mocDoc.setStatus(FieldBasedMapper.shallowSafeConversion(rawData.get(DmpElasticEntity._status), DmpStatus.class)); + if (columns.contains(DmpElasticEntity._versionStatus)) mocDoc.setVersionStatus(FieldBasedMapper.shallowSafeConversion(rawData.get(DmpElasticEntity._versionStatus), DmpVersionStatus.class)); + if (columns.contains(DmpElasticEntity._version)) mocDoc.setVersion(FieldBasedMapper.shallowSafeConversion(rawData.get(DmpElasticEntity._version), Short.class)); + if (columns.contains(DmpElasticEntity._groupId)) mocDoc.setGroupId(FieldBasedMapper.shallowSafeConversion(rawData.get(DmpElasticEntity._groupId), UUID.class)); + if (columns.contains(DmpElasticEntity._accessType)) mocDoc.setAccessType(FieldBasedMapper.shallowSafeConversion(rawData.get(DmpElasticEntity._accessType), DmpAccessType.class)); + if (columns.contains(DmpElasticEntity._finalizedAt)) mocDoc.setFinalizedAt(FieldBasedMapper.shallowSafeConversion(rawData.get(DmpElasticEntity._finalizedAt), Date.class)); + mocDoc.setCollaborators(this.convertNested(rawData, columns, this.queryFactory.query(NestedCollaboratorElasticQuery.class), DmpElasticEntity._collaborators, null)); + mocDoc.setReferences(this.convertNested(rawData, columns, this.queryFactory.query(NestedReferenceElasticQuery.class), DmpElasticEntity._references, null)); + mocDoc.setDescriptions(this.convertNested(rawData, columns, this.queryFactory.query(NestedDescriptionElasticQuery.class), DmpElasticEntity._descriptions, null)); + return mocDoc; + } + + @Override + protected ElasticField fieldNameOf(FieldResolver item) { + if (item.match(DmpElasticEntity._id)) return this.elasticFieldOf(DmpElasticEntity._id); + else if (item.match(DmpElasticEntity._label)) return this.elasticFieldOf(DmpElasticEntity._label); + else if (item.match(DmpElasticEntity._description)) return this.elasticFieldOf(DmpElasticEntity._description); + else if (item.match(DmpElasticEntity._status)) return this.elasticFieldOf(DmpElasticEntity._status); + else if (item.match(DmpElasticEntity._version)) return this.elasticFieldOf(DmpElasticEntity._version); + else if (item.match(DmpElasticEntity._versionStatus)) return this.elasticFieldOf(DmpElasticEntity._versionStatus); + else if (item.match(DmpElasticEntity._groupId)) return this.elasticFieldOf(DmpElasticEntity._groupId); + else if (item.match(DmpElasticEntity._finalizedAt)) return this.elasticFieldOf(DmpElasticEntity._finalizedAt); + else if (item.match(DmpElasticEntity._accessType)) return this.elasticFieldOf(DmpElasticEntity._accessType); + else if (item.prefix(DmpElasticEntity._collaborators)) return this.queryFactory.query(NestedCollaboratorElasticQuery.class).nestedPath(DmpElasticEntity._collaborators).fieldNameOf(this.extractPrefixed(item, DmpElasticEntity._collaborators)); + else if (item.prefix(DmpElasticEntity._references)) return this.queryFactory.query(NestedReferenceElasticQuery.class).nestedPath(DmpElasticEntity._references).fieldNameOf(this.extractPrefixed(item, DmpElasticEntity._references)); + else if (item.prefix(DmpElasticEntity._descriptions)) return this.queryFactory.query(NestedDescriptionElasticQuery.class).nestedPath(DmpElasticEntity._descriptions).fieldNameOf(this.extractPrefixed(item, DmpElasticEntity._descriptions)); + else return null; + } + + @Override + protected String[] getIndex() { + List indexNames = new ArrayList<>(); + indexNames.add(this.appElasticProperties.getDmpIndexName()); + try { + this.elasticService.ensureDescriptionIndex(); + } catch (IOException e) { + throw new RuntimeException(e); + } + return indexNames.toArray(new String[indexNames.size()]); + } + + @Override + protected UUID toKey(String key) { + return UUID.fromString(key); + } + + @Override + protected ElasticField getKeyField() { + return this.elasticFieldOf(DmpElasticEntity._id); + } + + @Override + protected ElasticNestedQuery nestedQueryOf(FieldResolver item) { + if (item.prefix(DmpElasticEntity._collaborators)) return this.queryFactory.query(NestedCollaboratorElasticQuery.class).nestedPath(DmpElasticEntity._collaborators); + else if (item.prefix(DmpElasticEntity._references)) return this.queryFactory.query(NestedReferenceElasticQuery.class).nestedPath(DmpElasticEntity._references); + else if (item.prefix(DmpElasticEntity._descriptions)) return this.queryFactory.query(NestedDescriptionElasticQuery.class).nestedPath(DmpElasticEntity._descriptions); + else return null; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/query/InnerObjectDescriptionTemplateElasticQuery.java b/backend/core/src/main/java/org/opencdmp/elastic/query/InnerObjectDescriptionTemplateElasticQuery.java new file mode 100644 index 000000000..05d71f485 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/query/InnerObjectDescriptionTemplateElasticQuery.java @@ -0,0 +1,97 @@ +package org.opencdmp.elastic.query; + +import co.elastic.clients.elasticsearch._types.query_dsl.Query; +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import org.opencdmp.elastic.data.nested.NestedDescriptionTemplateElasticEntity; +import gr.cite.tools.data.query.FieldResolver; +import gr.cite.tools.elastic.configuration.ElasticProperties; +import gr.cite.tools.elastic.mapper.FieldBasedMapper; +import gr.cite.tools.elastic.query.ElasticField; +import gr.cite.tools.elastic.query.ElasticInnerObjectQuery; +import gr.cite.tools.elastic.query.ElasticNestedQuery; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate; +import org.springframework.stereotype.Component; + +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class InnerObjectDescriptionTemplateElasticQuery extends ElasticInnerObjectQuery { + + private String innerPath; + + @Override + public InnerObjectDescriptionTemplateElasticQuery innerPath(String value) { + this.innerPath = value; + return this; + } + + + public InnerObjectDescriptionTemplateElasticQuery( + ElasticsearchTemplate elasticsearchRestTemplate, + ElasticProperties elasticProperties + ) { + super(elasticsearchRestTemplate, elasticProperties); + } + + @Override + protected Class entityClass() { + return NestedDescriptionTemplateElasticEntity.class; + } + + @Override + protected Boolean isFalseQuery() { + return false; + } + + @Override + protected Query applyAuthZ() { + return null; + } + + @Override + protected Query applyFilters() { + return null; + } + + @Override + public NestedDescriptionTemplateElasticEntity convert(Map rawData, Set columns) { + NestedDescriptionTemplateElasticEntity mocDoc = new NestedDescriptionTemplateElasticEntity(); + if (columns.contains(NestedDescriptionTemplateElasticEntity._id)) mocDoc.setId(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionTemplateElasticEntity._id), UUID.class)); + if (columns.contains(NestedDescriptionTemplateElasticEntity._label)) mocDoc.setLabel(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionTemplateElasticEntity._label), String.class)); + if (columns.contains(NestedDescriptionTemplateElasticEntity._versionStatus)) mocDoc.setVersionStatus(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionTemplateElasticEntity._versionStatus), DescriptionTemplateVersionStatus.class)); + return mocDoc; + } + + @Override + protected ElasticField fieldNameOf(FieldResolver item) { + if (item.match(NestedDescriptionTemplateElasticEntity._id)) return this.elasticFieldOf(NestedDescriptionTemplateElasticEntity._id).disableInfer(true); + else if (item.match(NestedDescriptionTemplateElasticEntity._label)) return this.elasticFieldOf(NestedDescriptionTemplateElasticEntity._label).disableInfer(true); + else if (item.match(NestedDescriptionTemplateElasticEntity._versionStatus)) return this.elasticFieldOf(NestedDescriptionTemplateElasticEntity._versionStatus).disableInfer(true); + else return null; + } + + @Override + protected String getInnerPath() { + return this.innerPath; + } + + @Override + protected UUID toKey(String key) { + return UUID.fromString(key); + } + + @Override + protected ElasticField getKeyField() { + return this.elasticFieldOf(NestedDescriptionTemplateElasticEntity._id); + } + + @Override + protected ElasticNestedQuery nestedQueryOf(FieldResolver item) { + return null; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/query/InnerObjectDmpElasticQuery.java b/backend/core/src/main/java/org/opencdmp/elastic/query/InnerObjectDmpElasticQuery.java new file mode 100644 index 000000000..6728eb6c9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/query/InnerObjectDmpElasticQuery.java @@ -0,0 +1,273 @@ +package org.opencdmp.elastic.query; +import co.elastic.clients.elasticsearch._types.query_dsl.Query; +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.DmpAccessType; +import org.opencdmp.commons.enums.DmpStatus; +import org.opencdmp.commons.enums.DmpVersionStatus; +import org.opencdmp.elastic.data.DmpElasticEntity; +import org.opencdmp.elastic.data.nested.NestedDmpElasticEntity; +import gr.cite.tools.data.query.FieldResolver; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.elastic.configuration.ElasticProperties; +import gr.cite.tools.elastic.mapper.FieldBasedMapper; +import gr.cite.tools.elastic.query.ElasticField; +import gr.cite.tools.elastic.query.ElasticFields; +import gr.cite.tools.elastic.query.ElasticInnerObjectQuery; +import gr.cite.tools.elastic.query.ElasticNestedQuery; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Scope; +import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +//Like in C# make it Transient +@Scope(BeanDefinition.SCOPE_PROTOTYPE) +public class InnerObjectDmpElasticQuery extends ElasticInnerObjectQuery { + private String like; + private Collection ids; + private Collection excludedIds; + private Collection statuses; + private Collection versionStatuses; + private Collection accessTypes; + private Collection versions; + private Collection groupIds; + + + + + public InnerObjectDmpElasticQuery like(String value) { + this.like = value; + return this; + } + + public InnerObjectDmpElasticQuery ids(UUID value) { + this.ids = List.of(value); + return this; + } + + public InnerObjectDmpElasticQuery ids(UUID... value) { + this.ids = Arrays.asList(value); + return this; + } + + public InnerObjectDmpElasticQuery ids(Collection values) { + this.ids = values; + return this; + } + + public InnerObjectDmpElasticQuery excludedIds(Collection values) { + this.excludedIds = values; + return this; + } + + public InnerObjectDmpElasticQuery excludedIds(UUID value) { + this.excludedIds = List.of(value); + return this; + } + + public InnerObjectDmpElasticQuery excludedIds(UUID... value) { + this.excludedIds = Arrays.asList(value); + return this; + } + + public InnerObjectDmpElasticQuery versionStatuses(DmpVersionStatus value) { + this.versionStatuses = List.of(value); + return this; + } + + public InnerObjectDmpElasticQuery versionStatuses(DmpVersionStatus... value) { + this.versionStatuses = Arrays.asList(value); + return this; + } + + public InnerObjectDmpElasticQuery versionStatuses(Collection values) { + this.versionStatuses = values; + return this; + } + + public InnerObjectDmpElasticQuery accessTypes(DmpAccessType value) { + this.accessTypes = List.of(value); + return this; + } + + public InnerObjectDmpElasticQuery accessTypes(DmpAccessType... value) { + this.accessTypes = Arrays.asList(value); + return this; + } + + public InnerObjectDmpElasticQuery accessTypes(Collection values) { + this.accessTypes = values; + return this; + } + + public InnerObjectDmpElasticQuery statuses(DmpStatus value) { + this.statuses = List.of(value); + return this; + } + + public InnerObjectDmpElasticQuery statuses(DmpStatus... value) { + this.statuses = Arrays.asList(value); + return this; + } + + public InnerObjectDmpElasticQuery statuses(Collection values) { + this.statuses = values; + return this; + } + + public InnerObjectDmpElasticQuery versions(Integer value) { + this.versions = List.of(value); + return this; + } + + public InnerObjectDmpElasticQuery versions(Integer... value) { + this.versions = Arrays.asList(value); + return this; + } + + public InnerObjectDmpElasticQuery versions(Collection values) { + this.versions = values; + return this; + } + + public InnerObjectDmpElasticQuery groupIds(UUID value) { + this.groupIds = List.of(value); + return this; + } + + public InnerObjectDmpElasticQuery groupIds(UUID... value) { + this.groupIds = Arrays.asList(value); + return this; + } + + public InnerObjectDmpElasticQuery groupIds(Collection values) { + this.groupIds = values; + return this; + } + + private String innerPath; + + @Override + public InnerObjectDmpElasticQuery innerPath(String value) { + this.innerPath = value; + return this; + } + + + private final QueryFactory queryFactory; + @Autowired() + public InnerObjectDmpElasticQuery(ElasticsearchTemplate elasticsearchTemplate, ElasticProperties elasticProperties, QueryFactory queryFactory) { + super(elasticsearchTemplate, elasticProperties); + this.queryFactory = queryFactory; + } + + @Override + protected Class entityClass() { + return NestedDmpElasticEntity.class; + } + + @Override + protected Boolean isFalseQuery() { + return false; + } + + @Override + protected Query applyFilters() { + List predicates = new ArrayList<>(); + + if (like != null && !like.isBlank()) { + if (!like.startsWith("*")) like = "*" + like; + if (!like.endsWith("*")) like = like + "*"; + ElasticFields elasticFields = new ElasticFields(this.entityClass(), List.of(this.getInnerPath())); + elasticFields.add(DmpElasticEntity._label, true); + elasticFields.add(DmpElasticEntity._descriptions, true); + predicates.add(this.like(elasticFields, List.of(like))._toQuery()); + } + if (ids != null) { + predicates.add(this.containsUUID(this.elasticFieldOf(DmpElasticEntity._id).disableInfer(true), ids)._toQuery()); + } + if (groupIds != null) { + predicates.add(this.containsUUID(this.elasticFieldOf(DmpElasticEntity._groupId).disableInfer(true), groupIds)._toQuery()); + } + if (versions != null) { + predicates.add(this.contains(this.elasticFieldOf(DmpElasticEntity._version).disableInfer(true), versions.toArray(new Integer[versions.size()]))._toQuery()); + } + if (excludedIds != null) { + predicates.add(this.not(this.containsUUID(this.elasticFieldOf(DmpElasticEntity._id).disableInfer(true), excludedIds)._toQuery())._toQuery()); + } + if (statuses != null) { + predicates.add(this.contains(this.elasticFieldOf(DmpElasticEntity._status).disableInfer(true), statuses.stream().map(x-> x.getValue()).collect(Collectors.toList()).toArray(new Short[statuses.size()]))._toQuery()); + } + if (versionStatuses != null) { + predicates.add(this.contains(this.elasticFieldOf(DmpElasticEntity._versionStatus).disableInfer(true), versionStatuses.stream().map(x-> x.getValue()).collect(Collectors.toList()).toArray(new Short[versionStatuses.size()]))._toQuery()); + } + if (accessTypes != null) { + predicates.add(this.contains(this.elasticFieldOf(DmpElasticEntity._accessType).disableInfer(true), accessTypes.stream().map(x-> x.getValue()).collect(Collectors.toList()).toArray(new Short[accessTypes.size()]))._toQuery()); + } + + if (!predicates.isEmpty()) { + return this.and(predicates); + } else { + return null; + } + } + + @Override + public NestedDmpElasticEntity convert(Map rawData, Set columns) { + NestedDmpElasticEntity mocDoc = new NestedDmpElasticEntity(); + if (columns.contains(NestedDmpElasticEntity._id)) mocDoc.setId(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDmpElasticEntity._id), UUID.class)); + if (columns.contains(NestedDmpElasticEntity._label)) mocDoc.setLabel(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDmpElasticEntity._label), String.class)); + if (columns.contains(NestedDmpElasticEntity._description)) mocDoc.setDescription(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDmpElasticEntity._description), String.class)); + if (columns.contains(NestedDmpElasticEntity._status)) mocDoc.setStatus(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDmpElasticEntity._status), DmpStatus.class)); + if (columns.contains(NestedDmpElasticEntity._versionStatus)) mocDoc.setVersionStatus(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDmpElasticEntity._versionStatus), DmpVersionStatus.class)); + if (columns.contains(NestedDmpElasticEntity._version)) mocDoc.setVersion(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDmpElasticEntity._version), Short.class)); + if (columns.contains(NestedDmpElasticEntity._groupId)) mocDoc.setGroupId(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDmpElasticEntity._groupId), UUID.class)); + if (columns.contains(NestedDmpElasticEntity._accessType)) mocDoc.setAccessType(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDmpElasticEntity._accessType), DmpAccessType.class)); + if (columns.contains(NestedDmpElasticEntity._finalizedAt)) mocDoc.setFinalizedAt(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDmpElasticEntity._finalizedAt), Date.class)); + mocDoc.setCollaborators(this.convertNested(rawData, columns, this.queryFactory.query(NestedCollaboratorElasticQuery.class), NestedDmpElasticEntity._collaborators, null)); + mocDoc.setReferences(this.convertNested(rawData, columns, this.queryFactory.query(NestedReferenceElasticQuery.class), NestedDmpElasticEntity._references, null)); + return mocDoc; + } + + @Override + protected ElasticField fieldNameOf(FieldResolver item) { + if (item.match(NestedDmpElasticEntity._id)) return this.elasticFieldOf(NestedDmpElasticEntity._id); + else if (item.match(NestedDmpElasticEntity._label)) return this.elasticFieldOf(NestedDmpElasticEntity._label); + else if (item.match(NestedDmpElasticEntity._description)) return this.elasticFieldOf(NestedDmpElasticEntity._description); + else if (item.match(NestedDmpElasticEntity._status)) return this.elasticFieldOf(NestedDmpElasticEntity._status); + else if (item.match(NestedDmpElasticEntity._versionStatus)) return this.elasticFieldOf(NestedDmpElasticEntity._versionStatus); + else if (item.match(NestedDmpElasticEntity._version)) return this.elasticFieldOf(NestedDmpElasticEntity._version); + else if (item.match(NestedDmpElasticEntity._groupId)) return this.elasticFieldOf(NestedDmpElasticEntity._groupId); + else if (item.match(NestedDmpElasticEntity._finalizedAt)) return this.elasticFieldOf(NestedDmpElasticEntity._finalizedAt); + else if (item.match(NestedDmpElasticEntity._accessType)) return this.elasticFieldOf(NestedDmpElasticEntity._accessType); + else if (item.prefix(NestedDmpElasticEntity._collaborators)) return this.queryFactory.query(NestedCollaboratorElasticQuery.class).nestedPath(NestedDmpElasticEntity._collaborators).fieldNameOf(this.extractPrefixed(item, NestedDmpElasticEntity._collaborators)); + else if (item.prefix(NestedDmpElasticEntity._references)) return this.queryFactory.query(NestedReferenceElasticQuery.class).nestedPath(NestedDmpElasticEntity._references).fieldNameOf(this.extractPrefixed(item, NestedDmpElasticEntity._references)); + else return null; + } + + @Override + protected String getInnerPath() { + return this.innerPath; + } + + @Override + protected UUID toKey(String key) { + return UUID.fromString(key); + } + + @Override + protected ElasticField getKeyField() { + return this.elasticFieldOf(NestedDmpElasticEntity._id); + } + + @Override + protected ElasticNestedQuery nestedQueryOf(FieldResolver item) { + if (item.prefix(NestedDmpElasticEntity._collaborators)) return this.queryFactory.query(NestedCollaboratorElasticQuery.class).nestedPath(NestedDmpElasticEntity._collaborators); + else if (item.prefix(NestedDmpElasticEntity._references)) return this.queryFactory.query(NestedReferenceElasticQuery.class).nestedPath(NestedDmpElasticEntity._references); + else return null; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/query/NestedCollaboratorElasticQuery.java b/backend/core/src/main/java/org/opencdmp/elastic/query/NestedCollaboratorElasticQuery.java new file mode 100644 index 000000000..c0ec0404d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/query/NestedCollaboratorElasticQuery.java @@ -0,0 +1,144 @@ +package org.opencdmp.elastic.query; + +import co.elastic.clients.elasticsearch._types.query_dsl.Query; +import org.opencdmp.commons.enums.DescriptionStatus; +import org.opencdmp.commons.enums.DmpUserRole; +import org.opencdmp.elastic.data.DescriptionElasticEntity; +import org.opencdmp.elastic.data.DmpElasticEntity; +import org.opencdmp.elastic.data.nested.NestedCollaboratorElasticEntity; +import gr.cite.tools.data.query.FieldResolver; +import gr.cite.tools.elastic.configuration.ElasticProperties; +import gr.cite.tools.elastic.mapper.FieldBasedMapper; +import gr.cite.tools.elastic.query.ElasticField; +import gr.cite.tools.elastic.query.ElasticNestedQuery; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedCollaboratorElasticQuery extends ElasticNestedQuery { + private Collection ids; + + + private Collection userRoles; + + public NestedCollaboratorElasticQuery ids(UUID value) { + this.ids = List.of(value); + return this; + } + + public NestedCollaboratorElasticQuery ids(UUID... value) { + this.ids = Arrays.asList(value); + return this; + } + + public NestedCollaboratorElasticQuery ids(Collection values) { + this.ids = values; + return this; + } + + public NestedCollaboratorElasticQuery userRoles(DmpUserRole value) { + this.userRoles = List.of(value); + return this; + } + + public NestedCollaboratorElasticQuery userRoles(DmpUserRole... value) { + this.userRoles = Arrays.asList(value); + return this; + } + + public NestedCollaboratorElasticQuery userRoles(Collection values) { + this.userRoles = values; + return this; + } + private String nestedPath; + + @Override + public NestedCollaboratorElasticQuery nestedPath(String value) { + this.nestedPath = value; + return this; + } + + + public NestedCollaboratorElasticQuery( + ElasticsearchTemplate elasticsearchRestTemplate, + ElasticProperties elasticProperties + ) { + super(elasticsearchRestTemplate, elasticProperties); + } + + @Override + protected Class entityClass() { + return NestedCollaboratorElasticEntity.class; + } + + @Override + protected Boolean isFalseQuery() { + return this.isEmpty(this.ids) || this.isEmpty(this.userRoles); + } + + @Override + protected Query applyAuthZ() { + return null; + } + + @Override + protected Query applyFilters() { + List predicates = new ArrayList<>(); + if (ids != null) { + predicates.add(this.containsUUID(this.elasticFieldOf(NestedCollaboratorElasticEntity._id), ids)._toQuery()); + } + + if (userRoles != null) { + predicates.add(this.contains(this.elasticFieldOf(NestedCollaboratorElasticEntity._role), userRoles.stream().map(DmpUserRole::getValue).toList().toArray(new Short[userRoles.size()]))._toQuery()); + } + + if (!predicates.isEmpty()) { + return this.and(predicates); + } else { + return null; + } + } + + @Override + public NestedCollaboratorElasticEntity convert(Map rawData, Set columns) { + NestedCollaboratorElasticEntity mocDoc = new NestedCollaboratorElasticEntity(); + if (columns.contains(NestedCollaboratorElasticEntity._id)) mocDoc.setId(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedCollaboratorElasticEntity._id), UUID.class)); + if (columns.contains(NestedCollaboratorElasticEntity._name)) mocDoc.setName(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedCollaboratorElasticEntity._name), String.class)); + if (columns.contains(NestedCollaboratorElasticEntity._role)) mocDoc.setRole(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedCollaboratorElasticEntity._role), DmpUserRole.class)); + return mocDoc; + } + + @Override + protected ElasticField fieldNameOf(FieldResolver item) { + if (item.match(NestedCollaboratorElasticEntity._id)) return this.elasticFieldOf(NestedCollaboratorElasticEntity._id).disableInfer(true); + else if (item.match(NestedCollaboratorElasticEntity._name)) return this.elasticFieldOf(NestedCollaboratorElasticEntity._name).disableInfer(true); + else if (item.match(NestedCollaboratorElasticEntity._role)) return this.elasticFieldOf(NestedCollaboratorElasticEntity._role).disableInfer(true); + else return null; + } + + @Override + protected String getNestedPath() { + return this.nestedPath; + } + + @Override + protected UUID toKey(String key) { + return UUID.fromString(key); + } + + @Override + protected ElasticField getKeyField() { + return this.elasticFieldOf(NestedCollaboratorElasticEntity._id); + } + + @Override + protected ElasticNestedQuery nestedQueryOf(FieldResolver item) { + return null; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/query/NestedDescriptionElasticQuery.java b/backend/core/src/main/java/org/opencdmp/elastic/query/NestedDescriptionElasticQuery.java new file mode 100644 index 000000000..fa97b3f34 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/query/NestedDescriptionElasticQuery.java @@ -0,0 +1,117 @@ +package org.opencdmp.elastic.query; + +import co.elastic.clients.elasticsearch._types.query_dsl.Query; +import org.opencdmp.commons.enums.DescriptionStatus; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.elastic.data.DescriptionElasticEntity; +import org.opencdmp.elastic.data.nested.NestedDescriptionElasticEntity; +import gr.cite.tools.data.query.FieldResolver; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.elastic.configuration.ElasticProperties; +import gr.cite.tools.elastic.mapper.FieldBasedMapper; +import gr.cite.tools.elastic.query.ElasticField; +import gr.cite.tools.elastic.query.ElasticNestedQuery; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedDescriptionElasticQuery extends ElasticNestedQuery { + + private String nestedPath; + + @Override + public NestedDescriptionElasticQuery nestedPath(String value) { + this.nestedPath = value; + return this; + } + + private final QueryFactory queryFactory; + private final ConventionService conventionService; + public NestedDescriptionElasticQuery( + ElasticsearchTemplate elasticsearchRestTemplate, + ElasticProperties elasticProperties, + QueryFactory queryFactory, ConventionService conventionService) { + super(elasticsearchRestTemplate, elasticProperties); + this.queryFactory = queryFactory; + this.conventionService = conventionService; + } + + @Override + protected Class entityClass() { + return NestedDescriptionElasticEntity.class; + } + + @Override + protected Boolean isFalseQuery() { + return false; + } + + @Override + protected Query applyAuthZ() { + return null; + } + + @Override + protected Query applyFilters() { + return null; + } + + @Override + public NestedDescriptionElasticEntity convert(Map rawData, Set columns) { + NestedDescriptionElasticEntity mocDoc = new NestedDescriptionElasticEntity(); + if (columns.contains(NestedDescriptionElasticEntity._id)) mocDoc.setId(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionElasticEntity._id), UUID.class)); + if (columns.contains(NestedDescriptionElasticEntity._label)) mocDoc.setLabel(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionElasticEntity._label), String.class)); + if (columns.contains(NestedDescriptionElasticEntity._dmpId)) mocDoc.setDmpId(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionElasticEntity._dmpId), UUID.class)); + if (columns.contains(NestedDescriptionElasticEntity._description)) mocDoc.setDescription(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionElasticEntity._description), String.class)); + if (columns.contains(NestedDescriptionElasticEntity._status)) mocDoc.setStatus(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionElasticEntity._status), DescriptionStatus.class)); + if (columns.contains(NestedDescriptionElasticEntity._finalizedAt)) mocDoc.setFinalizedAt(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionElasticEntity._finalizedAt), Date.class)); + mocDoc.setReferences(this.convertNested(rawData, columns, this.queryFactory.query(NestedReferenceElasticQuery.class), NestedDescriptionElasticEntity._references, this.getNestedPath())); + mocDoc.setTags(this.convertNested(rawData, columns, this.queryFactory.query(NestedTagElasticQuery.class), NestedDescriptionElasticEntity._tags, this.getNestedPath())); + mocDoc.setDescriptionTemplate(this.convertInnerObject(rawData, columns, this.queryFactory.query(InnerObjectDescriptionTemplateElasticQuery.class), NestedDescriptionElasticEntity._descriptionTemplate, null)); + return mocDoc; + } + + @Override + protected ElasticField fieldNameOf(FieldResolver item) { + if (item.match(NestedDescriptionElasticEntity._id)) return this.elasticFieldOf(NestedDescriptionElasticEntity._id); + else if (item.match(NestedDescriptionElasticEntity._label)) return this.elasticFieldOf(NestedDescriptionElasticEntity._label); + else if (item.match(NestedDescriptionElasticEntity._dmpId)) return this.elasticFieldOf(NestedDescriptionElasticEntity._dmpId); + else if (item.match(NestedDescriptionElasticEntity._description)) return this.elasticFieldOf(NestedDescriptionElasticEntity._description); + else if (item.match(NestedDescriptionElasticEntity._status)) return this.elasticFieldOf(NestedDescriptionElasticEntity._status); + else if (item.match(NestedDescriptionElasticEntity._finalizedAt)) return this.elasticFieldOf(NestedDescriptionElasticEntity._finalizedAt); + else if (item.prefix(NestedDescriptionElasticEntity._references)) return this.queryFactory.query(NestedReferenceElasticQuery.class).nestedPath(this.conventionService.asIndexer(this.getNestedPath(), NestedDescriptionElasticEntity._references)).fieldNameOf(this.extractPrefixed(item, NestedDescriptionElasticEntity._references)); + else if (item.prefix(NestedDescriptionElasticEntity._tags)) return this.queryFactory.query(NestedTagElasticQuery.class).nestedPath(this.conventionService.asIndexer(this.getNestedPath(), NestedDescriptionElasticEntity._tags)).fieldNameOf(this.extractPrefixed(item, NestedDescriptionElasticEntity._tags)); + else if (item.prefix(NestedDescriptionElasticEntity._descriptionTemplate)) return this.queryFactory.query(InnerObjectDescriptionTemplateElasticQuery.class).innerPath(this.conventionService.asIndexer(this.getNestedPath(), NestedDescriptionElasticEntity._descriptionTemplate)).fieldNameOf(this.extractPrefixed(item, NestedDescriptionElasticEntity._description)); + else return null; + } + + @Override + protected String getNestedPath() { + return this.nestedPath; + } + + @Override + protected UUID toKey(String key) { + return UUID.fromString(key); + } + + @Override + protected ElasticField getKeyField() { + return this.elasticFieldOf(NestedDescriptionElasticEntity._id); + } + + @Override + protected ElasticNestedQuery nestedQueryOf(FieldResolver item) { + if (item.prefix(NestedDescriptionElasticEntity._references)) return this.queryFactory.query(NestedReferenceElasticQuery.class).nestedPath(this.conventionService.asIndexer(this.getNestedPath(), NestedDescriptionElasticEntity._references)); + else if (item.prefix(NestedDescriptionElasticEntity._tags)) return this.queryFactory.query(NestedTagElasticQuery.class).nestedPath(this.conventionService.asIndexer(this.getNestedPath(), NestedDescriptionElasticEntity._tags)); + else return null; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/query/NestedDescriptionTemplateElasticQuery.java b/backend/core/src/main/java/org/opencdmp/elastic/query/NestedDescriptionTemplateElasticQuery.java new file mode 100644 index 000000000..7c8b1f648 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/query/NestedDescriptionTemplateElasticQuery.java @@ -0,0 +1,96 @@ +package org.opencdmp.elastic.query; + +import co.elastic.clients.elasticsearch._types.query_dsl.Query; +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import org.opencdmp.elastic.data.nested.NestedDescriptionTemplateElasticEntity; +import gr.cite.tools.data.query.FieldResolver; +import gr.cite.tools.elastic.configuration.ElasticProperties; +import gr.cite.tools.elastic.mapper.FieldBasedMapper; +import gr.cite.tools.elastic.query.ElasticField; +import gr.cite.tools.elastic.query.ElasticNestedQuery; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate; +import org.springframework.stereotype.Component; + +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedDescriptionTemplateElasticQuery extends ElasticNestedQuery { + + private String nestedPath; + + @Override + public NestedDescriptionTemplateElasticQuery nestedPath(String value) { + this.nestedPath = value; + return this; + } + + + public NestedDescriptionTemplateElasticQuery( + ElasticsearchTemplate elasticsearchRestTemplate, + ElasticProperties elasticProperties + ) { + super(elasticsearchRestTemplate, elasticProperties); + } + + @Override + protected Class entityClass() { + return NestedDescriptionTemplateElasticEntity.class; + } + + @Override + protected Boolean isFalseQuery() { + return false; + } + + @Override + protected Query applyAuthZ() { + return null; + } + + @Override + protected Query applyFilters() { + return null; + } + + @Override + public NestedDescriptionTemplateElasticEntity convert(Map rawData, Set columns) { + NestedDescriptionTemplateElasticEntity mocDoc = new NestedDescriptionTemplateElasticEntity(); + if (columns.contains(NestedDescriptionTemplateElasticEntity._id)) mocDoc.setId(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionTemplateElasticEntity._id), UUID.class)); + if (columns.contains(NestedDescriptionTemplateElasticEntity._label)) mocDoc.setLabel(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionTemplateElasticEntity._label), String.class)); + if (columns.contains(NestedDescriptionTemplateElasticEntity._versionStatus)) mocDoc.setVersionStatus(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedDescriptionTemplateElasticEntity._versionStatus), DescriptionTemplateVersionStatus.class)); + return mocDoc; + } + + @Override + protected ElasticField fieldNameOf(FieldResolver item) { + if (item.match(NestedDescriptionTemplateElasticEntity._id)) return this.elasticFieldOf(NestedDescriptionTemplateElasticEntity._id).disableInfer(true); + else if (item.match(NestedDescriptionTemplateElasticEntity._label)) return this.elasticFieldOf(NestedDescriptionTemplateElasticEntity._label).disableInfer(true); + else if (item.match(NestedDescriptionTemplateElasticEntity._versionStatus)) return this.elasticFieldOf(NestedDescriptionTemplateElasticEntity._versionStatus).disableInfer(true); + else return null; + } + + @Override + protected String getNestedPath() { + return this.nestedPath; + } + + @Override + protected UUID toKey(String key) { + return UUID.fromString(key); + } + + @Override + protected ElasticField getKeyField() { + return this.elasticFieldOf(NestedDescriptionTemplateElasticEntity._id); + } + + @Override + protected ElasticNestedQuery nestedQueryOf(FieldResolver item) { + return null; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/query/NestedReferenceElasticQuery.java b/backend/core/src/main/java/org/opencdmp/elastic/query/NestedReferenceElasticQuery.java new file mode 100644 index 000000000..478c63b44 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/query/NestedReferenceElasticQuery.java @@ -0,0 +1,90 @@ +package org.opencdmp.elastic.query; + +import co.elastic.clients.elasticsearch._types.query_dsl.Query; +import org.opencdmp.elastic.data.nested.NestedReferenceElasticEntity; +import gr.cite.tools.data.query.FieldResolver; +import gr.cite.tools.elastic.configuration.ElasticProperties; +import gr.cite.tools.elastic.mapper.FieldBasedMapper; +import gr.cite.tools.elastic.query.ElasticField; +import gr.cite.tools.elastic.query.ElasticNestedQuery; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedReferenceElasticQuery extends ElasticNestedQuery { + + private String nestedPath; + + @Override + public NestedReferenceElasticQuery nestedPath(String value) { + this.nestedPath = value; + return this; + } + + public NestedReferenceElasticQuery( + ElasticsearchTemplate elasticsearchTemplate, + ElasticProperties elasticProperties + ) { + super(elasticsearchTemplate, elasticProperties); + } + + @Override + protected Class entityClass() { + return NestedReferenceElasticEntity.class; + } + + @Override + protected Boolean isFalseQuery() { + return false; + } + + @Override + protected Query applyAuthZ() { + return null; + } + + @Override + protected Query applyFilters() { + return null; + } + + @Override + public NestedReferenceElasticEntity convert(Map rawData, Set columns) { + NestedReferenceElasticEntity mocDoc = new NestedReferenceElasticEntity(); + if (columns.contains(NestedReferenceElasticEntity._id)) mocDoc.setId(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedReferenceElasticEntity._id), UUID.class)); + if (columns.contains(NestedReferenceElasticEntity._label)) mocDoc.setLabel(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedReferenceElasticEntity._label), String.class)); + return mocDoc; + } + + @Override + protected ElasticField fieldNameOf(FieldResolver item) { + if (item.match(NestedReferenceElasticEntity._id)) return this.elasticFieldOf(NestedReferenceElasticEntity._id).disableInfer(true); + else if (item.match(NestedReferenceElasticEntity._label)) return this.elasticFieldOf(NestedReferenceElasticEntity._label).disableInfer(true); + else return null; + } + + @Override + protected String getNestedPath() { + return this.nestedPath; + } + + @Override + protected UUID toKey(String key) { + return UUID.fromString(key); + } + + @Override + protected ElasticField getKeyField() { + return this.elasticFieldOf(NestedReferenceElasticEntity._id); + } + + @Override + protected ElasticNestedQuery nestedQueryOf(FieldResolver item) { + return null; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/elastic/query/NestedTagElasticQuery.java b/backend/core/src/main/java/org/opencdmp/elastic/query/NestedTagElasticQuery.java new file mode 100644 index 000000000..038576930 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/elastic/query/NestedTagElasticQuery.java @@ -0,0 +1,91 @@ +package org.opencdmp.elastic.query; + +import co.elastic.clients.elasticsearch._types.query_dsl.Query; +import org.opencdmp.elastic.data.nested.NestedTagElasticEntity; +import gr.cite.tools.data.query.FieldResolver; +import gr.cite.tools.elastic.configuration.ElasticProperties; +import gr.cite.tools.elastic.mapper.FieldBasedMapper; +import gr.cite.tools.elastic.query.ElasticField; +import gr.cite.tools.elastic.query.ElasticNestedQuery; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NestedTagElasticQuery extends ElasticNestedQuery { + + private String nestedPath; + + @Override + public NestedTagElasticQuery nestedPath(String value) { + this.nestedPath = value; + return this; + } + + + public NestedTagElasticQuery( + ElasticsearchTemplate elasticsearchTemplate, + ElasticProperties elasticProperties + ) { + super(elasticsearchTemplate, elasticProperties); + } + + @Override + protected Class entityClass() { + return NestedTagElasticEntity.class; + } + + @Override + protected Boolean isFalseQuery() { + return false; + } + + @Override + protected Query applyAuthZ() { + return null; + } + + @Override + protected Query applyFilters() { + return null; + } + + @Override + public NestedTagElasticEntity convert(Map rawData, Set columns) { + NestedTagElasticEntity mocDoc = new NestedTagElasticEntity(); + if (columns.contains(NestedTagElasticEntity._id)) mocDoc.setId(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedTagElasticEntity._id), UUID.class)); + if (columns.contains(NestedTagElasticEntity._label)) mocDoc.setLabel(FieldBasedMapper.shallowSafeConversion(rawData.get(NestedTagElasticEntity._label), String.class)); + return mocDoc; + } + + @Override + protected ElasticField fieldNameOf(FieldResolver item) { + if (item.match(NestedTagElasticEntity._id)) return this.elasticFieldOf(NestedTagElasticEntity._id).disableInfer(true); + else if (item.match(NestedTagElasticEntity._label)) return this.elasticFieldOf(NestedTagElasticEntity._label).disableInfer(true); + else return null; + } + + @Override + protected String getNestedPath() { + return this.nestedPath; + } + + @Override + protected UUID toKey(String key) { + return UUID.fromString(key); + } + + @Override + protected ElasticField getKeyField() { + return this.elasticFieldOf(NestedTagElasticEntity._id); + } + + @Override + protected ElasticNestedQuery nestedQueryOf(FieldResolver item) { + return null; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/errorcode/ErrorDescription.java b/backend/core/src/main/java/org/opencdmp/errorcode/ErrorDescription.java new file mode 100644 index 000000000..4efecd315 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/errorcode/ErrorDescription.java @@ -0,0 +1,25 @@ +package org.opencdmp.errorcode; + +public class ErrorDescription { + + private int code; + + private String message; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/errorcode/ErrorThesaurusConfiguration.java b/backend/core/src/main/java/org/opencdmp/errorcode/ErrorThesaurusConfiguration.java new file mode 100644 index 000000000..25f70cd14 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/errorcode/ErrorThesaurusConfiguration.java @@ -0,0 +1,12 @@ +package org.opencdmp.errorcode; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties(ErrorThesaurusProperties.class) +public class ErrorThesaurusConfiguration { + + + +} diff --git a/backend/core/src/main/java/org/opencdmp/errorcode/ErrorThesaurusProperties.java b/backend/core/src/main/java/org/opencdmp/errorcode/ErrorThesaurusProperties.java new file mode 100644 index 000000000..ddd3ab82c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/errorcode/ErrorThesaurusProperties.java @@ -0,0 +1,197 @@ +package org.opencdmp.errorcode; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "error-thesaurus") +public class ErrorThesaurusProperties { + + private ErrorDescription systemError; + + public ErrorDescription getSystemError() { + return systemError; + } + + public void setSystemError(ErrorDescription systemError) { + this.systemError = systemError; + } + + private ErrorDescription forbidden; + + public ErrorDescription getForbidden() { + return forbidden; + } + + public void setForbidden(ErrorDescription forbidden) { + this.forbidden = forbidden; + } + + private ErrorDescription hashConflict; + + public ErrorDescription getHashConflict() { + return hashConflict; + } + + public void setHashConflict(ErrorDescription hashConflict) { + this.hashConflict = hashConflict; + } + + private ErrorDescription modelValidation; + + public ErrorDescription getModelValidation() { + return modelValidation; + } + + public void setModelValidation(ErrorDescription modelValidation) { + this.modelValidation = modelValidation; + } + + private ErrorDescription descriptionTemplateNewVersionConflict; + + public ErrorDescription getDescriptionTemplateNewVersionConflict() { + return descriptionTemplateNewVersionConflict; + } + + public void setDescriptionTemplateNewVersionConflict(ErrorDescription descriptionTemplateNewVersionConflict) { + this.descriptionTemplateNewVersionConflict = descriptionTemplateNewVersionConflict; + } + + private ErrorDescription dmpNewVersionConflict; + + public ErrorDescription getDmpNewVersionConflict() { + return dmpNewVersionConflict; + } + + public void setDmpNewVersionConflict(ErrorDescription dmpNewVersionConflict) { + this.dmpNewVersionConflict = dmpNewVersionConflict; + } + + public ErrorDescription dmpBlueprintNewVersionConflict; + + public ErrorDescription getDmpBlueprintNewVersionConflict() { + return dmpBlueprintNewVersionConflict; + } + + public void setDmpBlueprintNewVersionConflict(ErrorDescription dmpBlueprintNewVersionConflict) { + this.dmpBlueprintNewVersionConflict = dmpBlueprintNewVersionConflict; + } + + private ErrorDescription dmpIsFinalized; + + public ErrorDescription getDmpIsFinalized() { + return dmpIsFinalized; + } + + public void setDmpIsFinalized(ErrorDescription dmpIsFinalized) { + this.dmpIsFinalized = dmpIsFinalized; + } + + private ErrorDescription dmpCanNotChange; + + public ErrorDescription getDmpCanNotChange() { + return dmpCanNotChange; + } + + public void setDmpCanNotChange(ErrorDescription dmpCanNotChange) { + this.dmpCanNotChange = dmpCanNotChange; + } + + private ErrorDescription dmpDescriptionTemplateCanNotChange; + + public ErrorDescription getDmpDescriptionTemplateCanNotChange() { + return dmpDescriptionTemplateCanNotChange; + } + + public void setDmpDescriptionTemplateCanNotChange(ErrorDescription dmpDescriptionTemplateCanNotChange) { + this.dmpDescriptionTemplateCanNotChange = dmpDescriptionTemplateCanNotChange; + } + + private ErrorDescription invalidDescriptionTemplate; + + public ErrorDescription getInvalidDescriptionTemplate() { + return invalidDescriptionTemplate; + } + + public void setInvalidDescriptionTemplate(ErrorDescription invalidDescriptionTemplate) { + this.invalidDescriptionTemplate = invalidDescriptionTemplate; + } + + private ErrorDescription descriptionIsFinalized; + + public ErrorDescription getDescriptionIsFinalized() { + return descriptionIsFinalized; + } + + public void setDescriptionIsFinalized(ErrorDescription descriptionIsFinalized) { + this.descriptionIsFinalized = descriptionIsFinalized; + } + + private ErrorDescription dmpBlueprintHasNoDescriptionTemplates; + + public ErrorDescription getDmpBlueprintHasNoDescriptionTemplates() { + return dmpBlueprintHasNoDescriptionTemplates; + } + + public void setDmpBlueprintHasNoDescriptionTemplates(ErrorDescription dmpBlueprintHasNoDescriptionTemplates) { + this.dmpBlueprintHasNoDescriptionTemplates = dmpBlueprintHasNoDescriptionTemplates; + } + + private ErrorDescription dmpDescriptionTemplateCanNotRemove; + + public ErrorDescription getDmpDescriptionTemplateCanNotRemove() { + return dmpDescriptionTemplateCanNotRemove; + } + + public void setDmpDescriptionTemplateCanNotRemove(ErrorDescription dmpDescriptionTemplateCanNotRemove) { + this.dmpDescriptionTemplateCanNotRemove = dmpDescriptionTemplateCanNotRemove; + } + + private ErrorDescription missingTenant; + + public ErrorDescription getMissingTenant() { + return missingTenant; + } + + public void setMissingTenant(ErrorDescription missingTenant) { + this.missingTenant = missingTenant; + } + + private ErrorDescription tenantNotAllowed; + + public ErrorDescription getTenantNotAllowed() { + return tenantNotAllowed; + } + + public void setTenantNotAllowed(ErrorDescription tenantNotAllowed) { + this.tenantNotAllowed = tenantNotAllowed; + } + + private ErrorDescription tenantTampering; + + public ErrorDescription getTenantTampering() { + return tenantTampering; + } + + public void setTenantTampering(ErrorDescription tenantTampering) { + this.tenantTampering = tenantTampering; + } + + private ErrorDescription tenantConfigurationTypeCanNotChange; + + public ErrorDescription getTenantConfigurationTypeCanNotChange() { + return tenantConfigurationTypeCanNotChange; + } + + public void setTenantConfigurationTypeCanNotChange(ErrorDescription tenantConfigurationTypeCanNotChange) { + this.tenantConfigurationTypeCanNotChange = tenantConfigurationTypeCanNotChange; + } + + private ErrorDescription multipleTenantConfigurationTypeNotAllowed; + + public ErrorDescription getMultipleTenantConfigurationTypeNotAllowed() { + return multipleTenantConfigurationTypeNotAllowed; + } + + public void setMultipleTenantConfigurationTypeNotAllowed(ErrorDescription multipleTenantConfigurationTypeNotAllowed) { + this.multipleTenantConfigurationTypeNotAllowed = multipleTenantConfigurationTypeNotAllowed; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/event/DescriptionTemplateTypeTouchedEvent.java b/backend/core/src/main/java/org/opencdmp/event/DescriptionTemplateTypeTouchedEvent.java new file mode 100644 index 000000000..1647798ea --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/event/DescriptionTemplateTypeTouchedEvent.java @@ -0,0 +1,24 @@ +package org.opencdmp.event; + +import java.util.UUID; + +public class DescriptionTemplateTypeTouchedEvent { + + public DescriptionTemplateTypeTouchedEvent() { + } + + public DescriptionTemplateTypeTouchedEvent(UUID id) { + this.id = id; + } + + private UUID id; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/event/DescriptionTouchedEvent.java b/backend/core/src/main/java/org/opencdmp/event/DescriptionTouchedEvent.java new file mode 100644 index 000000000..bb7f1cc3b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/event/DescriptionTouchedEvent.java @@ -0,0 +1,24 @@ +package org.opencdmp.event; + +import java.util.UUID; + +public class DescriptionTouchedEvent { + + public DescriptionTouchedEvent() { + } + + public DescriptionTouchedEvent(UUID id) { + this.id = id; + } + + private UUID id; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/event/DmpTouchedEvent.java b/backend/core/src/main/java/org/opencdmp/event/DmpTouchedEvent.java new file mode 100644 index 000000000..93b733cea --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/event/DmpTouchedEvent.java @@ -0,0 +1,24 @@ +package org.opencdmp.event; + +import java.util.UUID; + +public class DmpTouchedEvent { + + public DmpTouchedEvent() { + } + + public DmpTouchedEvent(UUID id) { + this.id = id; + } + + private UUID id; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/event/EntityDoiTouchedEvent.java b/backend/core/src/main/java/org/opencdmp/event/EntityDoiTouchedEvent.java new file mode 100644 index 000000000..32fdf9159 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/event/EntityDoiTouchedEvent.java @@ -0,0 +1,24 @@ +package org.opencdmp.event; + +import java.util.UUID; + +public class EntityDoiTouchedEvent { + + public EntityDoiTouchedEvent() { + } + + public EntityDoiTouchedEvent(UUID id) { + this.id = id; + } + + private UUID id; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/event/EventBroker.java b/backend/core/src/main/java/org/opencdmp/event/EventBroker.java new file mode 100644 index 000000000..57131e304 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/event/EventBroker.java @@ -0,0 +1,60 @@ +package org.opencdmp.event; + +import gr.cite.commons.web.oidc.apikey.events.ApiKeyStaleEvent; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; + +@Service +public class EventBroker { + @Autowired + private ApplicationEventPublisher applicationEventPublisher; + + public void emitApiKeyStale(String apiKey) { + this.applicationEventPublisher.publishEvent(new ApiKeyStaleEvent(apiKey)); + } + + public void emit(ApiKeyStaleEvent event) { + this.applicationEventPublisher.publishEvent(event); + } + public void emit(TenantConfigurationTouchedEvent event) { + this.applicationEventPublisher.publishEvent(event); + } + + public void emit(TenantTouchedEvent event) { + this.applicationEventPublisher.publishEvent(event); + } + + public void emit(UserTouchedEvent event) { + this.applicationEventPublisher.publishEvent(event); + } + + public void emit(UserAddedToTenantEvent event) { + this.applicationEventPublisher.publishEvent(event); + } + + public void emit(UserRemovedFromTenantEvent event) { + this.applicationEventPublisher.publishEvent(event); + } + + public void emit(DescriptionTouchedEvent event) { + this.applicationEventPublisher.publishEvent(event); + } + + public void emit(DescriptionTemplateTypeTouchedEvent event) { + this.applicationEventPublisher.publishEvent(event); + } + + public void emit(EntityDoiTouchedEvent event) { + this.applicationEventPublisher.publishEvent(event); + } + + public void emit(DmpTouchedEvent event) { + this.applicationEventPublisher.publishEvent(event); + } + + public void emit(TagTouchedEvent event) { + this.applicationEventPublisher.publishEvent(event); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/event/TagTouchedEvent.java b/backend/core/src/main/java/org/opencdmp/event/TagTouchedEvent.java new file mode 100644 index 000000000..f58ace5f8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/event/TagTouchedEvent.java @@ -0,0 +1,24 @@ +package org.opencdmp.event; + +import java.util.UUID; + +public class TagTouchedEvent { + + public TagTouchedEvent() { + } + + public TagTouchedEvent(UUID id) { + this.id = id; + } + + private UUID id; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/event/TenantConfigurationTouchedEvent.java b/backend/core/src/main/java/org/opencdmp/event/TenantConfigurationTouchedEvent.java new file mode 100644 index 000000000..20b784bee --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/event/TenantConfigurationTouchedEvent.java @@ -0,0 +1,44 @@ +package org.opencdmp.event; + +import org.opencdmp.commons.enums.TenantConfigurationType; + +import java.util.UUID; + +public class TenantConfigurationTouchedEvent { + public TenantConfigurationTouchedEvent() { + } + + public TenantConfigurationTouchedEvent(UUID tenantId, String tenantCode, TenantConfigurationType type) { + this.tenantId = tenantId; + this.tenantCode = tenantCode; + this.type = type; + } + + private UUID tenantId; + private String tenantCode; + private TenantConfigurationType type; + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } + + public TenantConfigurationType getType() { + return type; + } + + public void setType(TenantConfigurationType type) { + this.type = type; + } + + public String getTenantCode() { + return tenantCode; + } + + public void setTenantCode(String tenantCode) { + this.tenantCode = tenantCode; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/event/TenantTouchedEvent.java b/backend/core/src/main/java/org/opencdmp/event/TenantTouchedEvent.java new file mode 100644 index 000000000..ee47646f0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/event/TenantTouchedEvent.java @@ -0,0 +1,42 @@ +package org.opencdmp.event; + +import java.util.UUID; + +public class TenantTouchedEvent { + public TenantTouchedEvent() { + } + + public TenantTouchedEvent(UUID tenantId, String tenantCode, String previousTenantCode) { + this.tenantId = tenantId; + this.tenantCode = tenantCode; + this.previousTenantCode = previousTenantCode; + } + + private UUID tenantId; + private String tenantCode; + private String previousTenantCode; + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } + + public String getTenantCode() { + return tenantCode; + } + + public void setTenantCode(String tenantCode) { + this.tenantCode = tenantCode; + } + + public String getPreviousTenantCode() { + return previousTenantCode; + } + + public void setPreviousTenantCode(String previousTenantCode) { + this.previousTenantCode = previousTenantCode; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/event/UserAddedToTenantEvent.java b/backend/core/src/main/java/org/opencdmp/event/UserAddedToTenantEvent.java new file mode 100644 index 000000000..36d630e85 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/event/UserAddedToTenantEvent.java @@ -0,0 +1,32 @@ +package org.opencdmp.event; + +import java.util.UUID; + +public class UserAddedToTenantEvent { + public UserAddedToTenantEvent() { + } + + public UserAddedToTenantEvent(UUID userId, UUID tenantId) { + this.userId = userId; + this.tenantId = tenantId; + } + + private UUID userId; + private UUID tenantId; + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/event/UserRemovedFromTenantEvent.java b/backend/core/src/main/java/org/opencdmp/event/UserRemovedFromTenantEvent.java new file mode 100644 index 000000000..3c37b4128 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/event/UserRemovedFromTenantEvent.java @@ -0,0 +1,32 @@ +package org.opencdmp.event; + +import java.util.UUID; + +public class UserRemovedFromTenantEvent { + public UserRemovedFromTenantEvent() { + } + + public UserRemovedFromTenantEvent(UUID userId, UUID tenantId) { + this.userId = userId; + this.tenantId = tenantId; + } + + private UUID userId; + private UUID tenantId; + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/event/UserTouchedEvent.java b/backend/core/src/main/java/org/opencdmp/event/UserTouchedEvent.java new file mode 100644 index 000000000..638ee8060 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/event/UserTouchedEvent.java @@ -0,0 +1,22 @@ +package org.opencdmp.event; + +import java.util.UUID; + +public class UserTouchedEvent { + public UserTouchedEvent() { + } + + public UserTouchedEvent(UUID userId) { + this.userId = userId; + } + + private UUID userId; + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/AppRabbitConfigurer.java b/backend/core/src/main/java/org/opencdmp/integrationevent/AppRabbitConfigurer.java new file mode 100644 index 000000000..3d40f0a4d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/AppRabbitConfigurer.java @@ -0,0 +1,43 @@ +package org.opencdmp.integrationevent; + +import org.opencdmp.integrationevent.inbox.InboxProperties; +import org.opencdmp.integrationevent.outbox.OutboxProperties; +import gr.cite.queueinbox.repository.InboxRepository; +import gr.cite.rabbitmq.RabbitConfigurer; +import gr.cite.rabbitmq.consumer.InboxBindings; +import gr.cite.rabbitmq.consumer.InboxCreator; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +@Configuration +@EnableConfigurationProperties({OutboxProperties.class, InboxProperties.class}) +@ConditionalOnProperty(prefix = "queue.rabbitmq", name = "listenerEnabled") +public class AppRabbitConfigurer extends RabbitConfigurer { + + private ApplicationContext applicationContext; + + + public AppRabbitConfigurer(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + // @Bean + public InboxBindings inboxBindingsCreator() { + List bindingItems = new ArrayList<>(); + + return new InboxBindings(bindingItems); + } + + // @Bean + public InboxCreator inboxCreator() { + return (params) -> { + InboxRepository inboxRepository = this.applicationContext.getBean(InboxRepository.class); + return inboxRepository.create(params) != null; + }; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/InboxIntegrationEventConfigurer.java b/backend/core/src/main/java/org/opencdmp/integrationevent/InboxIntegrationEventConfigurer.java new file mode 100644 index 000000000..0ccf54333 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/InboxIntegrationEventConfigurer.java @@ -0,0 +1,31 @@ +package org.opencdmp.integrationevent; + +import org.opencdmp.integrationevent.inbox.InboxProperties; +import org.opencdmp.integrationevent.inbox.InboxRepositoryImpl; +import gr.cite.queueinbox.InboxConfigurer; +import gr.cite.queueinbox.repository.InboxRepository; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; + +@Configuration +@EnableConfigurationProperties({InboxProperties.class}) +@ConditionalOnProperty(prefix = "queue.task.listener", name = "enable", matchIfMissing = false) +public class InboxIntegrationEventConfigurer extends InboxConfigurer { + private ApplicationContext applicationContext; + private InboxProperties inboxProperties; + + public InboxIntegrationEventConfigurer(ApplicationContext applicationContext, InboxProperties inboxProperties) { + this.applicationContext = applicationContext; + this.inboxProperties = inboxProperties; + } + + @Bean + public InboxRepository inboxRepositoryCreator() { + return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties); + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/IntegrationEventContextImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/IntegrationEventContextImpl.java new file mode 100644 index 000000000..a74379198 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/IntegrationEventContextImpl.java @@ -0,0 +1,20 @@ +package org.opencdmp.integrationevent; + +import gr.cite.rabbitmq.IntegrationEventContext; + +import java.util.UUID; + +public class IntegrationEventContextImpl implements IntegrationEventContext { + private UUID tenant; + + public IntegrationEventContextImpl() { + } + + public UUID getTenant() { + return tenant; + } + + public void setTenant(UUID tenant) { + this.tenant = tenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxIntegrationEventConfigurer.java b/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxIntegrationEventConfigurer.java new file mode 100644 index 000000000..45b71f14a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxIntegrationEventConfigurer.java @@ -0,0 +1,74 @@ +package org.opencdmp.integrationevent; + + +import org.opencdmp.data.QueueOutboxEntity; +import org.opencdmp.integrationevent.outbox.OutboxProperties; +import org.opencdmp.integrationevent.outbox.OutboxRepositoryImpl; +import gr.cite.queueoutbox.IntegrationEventContextCreator; +import gr.cite.queueoutbox.OutboxConfigurer; +import gr.cite.queueoutbox.repository.OutboxRepository; +import gr.cite.rabbitmq.IntegrationEventMessageConstants; +import gr.cite.rabbitmq.RabbitProperties; +import gr.cite.rabbitmq.broker.MessageHydrator; +import org.springframework.amqp.core.MessageProperties; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.nio.charset.StandardCharsets; +import java.sql.Date; +import java.time.Instant; +import java.util.UUID; + +@Configuration +@EnableConfigurationProperties({OutboxProperties.class}) +@ConditionalOnProperty(prefix = "queue.task.publisher", name = "enable", matchIfMissing = false) +public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { + private ApplicationContext applicationContext; + private OutboxProperties outboxProperties; + + public OutboxIntegrationEventConfigurer(ApplicationContext applicationContext, OutboxProperties outboxProperties) { + this.applicationContext = applicationContext; + this.outboxProperties = outboxProperties; + } + + @Bean + public MessageHydrator messageHydrator(RabbitProperties rabbitProperties) { + return (message, event, eventContext) -> { + MessageProperties messageProperties = message.getMessageProperties(); + messageProperties.setAppId(rabbitProperties.getAppId()); + messageProperties.setContentEncoding(StandardCharsets.UTF_8.displayName()); + messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON); + //messageProperties.setUserId(userContext.getCurrentUser().toString()); + messageProperties.setTimestamp(Date.from(Instant.now())); + messageProperties.setMessageId(event.getMessageId().toString()); + + if (eventContext != null) { + UUID tenant = ((IntegrationEventContextImpl) eventContext).getTenant(); + if (tenant != null) { + messageProperties.setHeader(IntegrationEventMessageConstants.TENANT, tenant); + } + } + + return message; + }; + } + + @Bean + public IntegrationEventContextCreator integrationEventContextCreator() { + return (message) -> { + IntegrationEventContextImpl integrationEventContext = new IntegrationEventContextImpl(); + if (message instanceof QueueOutboxEntity) integrationEventContext.setTenant(((QueueOutboxEntity)message).getTenantId()); + return integrationEventContext; + }; + } + + @Bean + public OutboxRepository outboxRepositoryCreator() { + return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties); + } +} + + diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxPropertiesConfiguration.java b/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxPropertiesConfiguration.java new file mode 100644 index 000000000..d1e93bf9b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/OutboxPropertiesConfiguration.java @@ -0,0 +1,11 @@ +package org.opencdmp.integrationevent; + +import org.opencdmp.integrationevent.outbox.OutboxProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties(OutboxProperties.class) +public class OutboxPropertiesConfiguration { + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/TrackedEvent.java b/backend/core/src/main/java/org/opencdmp/integrationevent/TrackedEvent.java new file mode 100644 index 000000000..f524790b1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/TrackedEvent.java @@ -0,0 +1,18 @@ +package org.opencdmp.integrationevent; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class TrackedEvent { + public String trackingContextTag; + + public String getTrackingContextTag() { + return trackingContextTag; + } + + public void setTrackingContextTag(String trackingContextTag) { + this.trackingContextTag = trackingContextTag; + } + + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/ConsistencyHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/ConsistencyHandler.java new file mode 100644 index 000000000..c281dc147 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/ConsistencyHandler.java @@ -0,0 +1,5 @@ +package org.opencdmp.integrationevent.inbox; + +public interface ConsistencyHandler { + Boolean isConsistent(T consistencyPredicates); +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/ConsistencyPredicates.java b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/ConsistencyPredicates.java new file mode 100644 index 000000000..be7e5e312 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/ConsistencyPredicates.java @@ -0,0 +1,4 @@ +package org.opencdmp.integrationevent.inbox; + +public interface ConsistencyPredicates { +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/EventProcessingStatus.java b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/EventProcessingStatus.java new file mode 100644 index 000000000..6caf7b728 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/EventProcessingStatus.java @@ -0,0 +1,8 @@ +package org.opencdmp.integrationevent.inbox; + +public enum EventProcessingStatus { + Error, + Success, + Postponed, + Discard +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxPrincipal.java b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxPrincipal.java new file mode 100644 index 000000000..bd24e39fb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxPrincipal.java @@ -0,0 +1,65 @@ +package org.opencdmp.integrationevent.inbox; + +import gr.cite.commons.web.oidc.principal.MyPrincipal; +import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; +import org.springframework.security.oauth2.core.ClaimAccessor; +import org.springframework.security.oauth2.jwt.JwtClaimNames; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class InboxPrincipal implements MyPrincipal, ClaimAccessor { + private final Map claims; + + private final boolean isAuthenticated; + + public InboxPrincipal(Boolean isAuthenticated, String name) { + this.claims = new HashMap<>(); + this.put(JwtClaimNames.SUB, name); + this.isAuthenticated = isAuthenticated; + } + + public static InboxPrincipal build(IntegrationEventProperties properties, ClaimExtractorProperties claimExtractorProperties) { + InboxPrincipal inboxPrincipal = new InboxPrincipal(true, "IntegrationEventQueueAppId"); + List clientKey = claimExtractorProperties.getMapping().getOrDefault("Client", null); + inboxPrincipal.put(clientKey != null && clientKey.getFirst() != null ? clientKey.getFirst().getType() : "client_id", properties.getAppId()); + inboxPrincipal.put("active", "true"); + List notBeforeKey = claimExtractorProperties.getMapping().getOrDefault("NotBefore", null); + inboxPrincipal.put(notBeforeKey != null && notBeforeKey.getFirst() != null ? notBeforeKey.getFirst().getType() :"nbf", Instant.now().minus(30, ChronoUnit.SECONDS).toString()); + List expiresAt = claimExtractorProperties.getMapping().getOrDefault("ExpiresAt", null); + inboxPrincipal.put(expiresAt != null && expiresAt.getFirst() != null ? expiresAt.getFirst().getType() :"exp", Instant.now().plus(10, ChronoUnit.MINUTES).toString()); + return inboxPrincipal; + } + + @Override + public Boolean isAuthenticated() { + return this.isAuthenticated; + } + + @Override + public Map getClaims() { + return this.claims; + } + + @Override + public List getClaimAsStringList(String claim) { + if (claims == null) + return null; + if (this.claims.containsKey(claim)){ + return List.of(this.claims.get(claim).toString()); + } + return null; + } + + @Override + public String getName() { + return this.getClaimAsString(JwtClaimNames.SUB); + } + + public void put(String key, Object value) { + this.claims.put(key, value); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxProperties.java b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxProperties.java new file mode 100644 index 000000000..d5c29630a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxProperties.java @@ -0,0 +1,25 @@ +package org.opencdmp.integrationevent.inbox; + +import jakarta.validation.constraints.NotNull; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.validation.annotation.Validated; + +@Validated +@ConfigurationProperties(prefix = "queue.task.listener.options") +//@ConstructorBinding +public class InboxProperties { + + @NotNull + private final String exchange; + + public InboxProperties( + String exchange + ) { + this.exchange = exchange; + } + + public String getExchange() { + return exchange; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxRepositoryImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxRepositoryImpl.java new file mode 100644 index 000000000..2251896b7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/InboxRepositoryImpl.java @@ -0,0 +1,367 @@ +package org.opencdmp.integrationevent.inbox; + +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.fake.FakeRequestScope; +import org.opencdmp.data.QueueInboxEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.integrationevent.TrackedEvent; +import org.opencdmp.query.QueueInboxQuery; +import gr.cite.queueinbox.entity.QueueInbox; +import gr.cite.queueinbox.entity.QueueInboxStatus; +import gr.cite.queueinbox.repository.CandidateInfo; +import gr.cite.queueinbox.repository.InboxRepository; +import gr.cite.queueinbox.task.MessageOptions; +import gr.cite.rabbitmq.IntegrationEventMessageConstants; +import gr.cite.rabbitmq.consumer.InboxCreatorParams; +import gr.cite.tools.data.query.Ordering; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.EntityTransaction; +import jakarta.persistence.OptimisticLockException; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import java.util.function.Function; + +public class InboxRepositoryImpl implements InboxRepository { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InboxRepositoryImpl.class)); + + protected final ApplicationContext applicationContext; + + private final JsonHandlingService jsonHandlingService; + + private final InboxProperties inboxProperties; + + public InboxRepositoryImpl( + ApplicationContext applicationContext, + InboxProperties inboxProperties + ) { + this.applicationContext = applicationContext; + this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); + this.inboxProperties = inboxProperties; + } + + @Override + public CandidateInfo candidate(Instant lastCandidateCreationTimestamp, MessageOptions options) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + CandidateInfo candidate = null; + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + entityManager = entityManagerFactory.createEntityManager(); + + transaction = entityManager.getTransaction(); + transaction.begin(); + + QueueInboxEntity item = queryFactory.query(QueueInboxQuery.class) + .isActives(IsActive.Active) + .status(QueueInboxStatus.PENDING, QueueInboxStatus.ERROR) + .retryThreshold(options.getRetryThreashold()) + .createdAfter(lastCandidateCreationTimestamp) + .ordering(new Ordering().addAscending(QueueInboxEntity._createdAt)) + .first(); + + if (item != null) { + QueueInboxStatus prevState = item.getStatus(); + item.setStatus(QueueInboxStatus.PROCESSING); + + entityManager.merge(item); + entityManager.flush(); + + candidate = new CandidateInfo(); + candidate.setId(item.getId()); + candidate.setCreatedAt(item.getCreatedAt()); + candidate.setPreviousState(prevState); + } + + transaction.commit(); + } catch (OptimisticLockException ex) { + // we get this if/when someone else already modified the notifications. We want to essentially ignore this, and keep working + logger.debug("Concurrency exception getting queue inbox. Skipping: {} ", ex.getMessage()); + if (transaction != null) + transaction.rollback(); + candidate = null; + } catch (Exception ex) { + logger.error("Problem getting list of queue inbox. Skipping: {}", ex.getMessage(), ex); + if (transaction != null) + transaction.rollback(); + candidate = null; + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem getting list of queue inbox. Skipping: {}", ex.getMessage(), ex); + } + + return candidate; + } + + @Override + public Boolean shouldOmit(CandidateInfo candidate, Function shouldOmit) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + boolean success = false; + + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + + entityManager = entityManagerFactory.createEntityManager(); + transaction = entityManager.getTransaction(); + + transaction.begin(); + + QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); + QueueInboxEntity item = queryFactory.query(QueueInboxQuery.class).ids(candidate.getId()).first(); + + if (item == null) { + logger.warn("Could not lookup queue inbox {} to process. Continuing...", candidate.getId()); + } else { + if (shouldOmit.apply(item)) { + item.setStatus(QueueInboxStatus.OMITTED); + + entityManager.merge(item); + entityManager.flush(); + success = true; + } + } + + transaction.commit(); + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + if (transaction != null) + transaction.rollback(); + success = false; + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + } + return success; + } + + @Override + public boolean shouldWait(CandidateInfo candidate, Function itIsTimeFunc) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + boolean success = false; + + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + + entityManager = entityManagerFactory.createEntityManager(); + transaction = entityManager.getTransaction(); + + transaction.begin(); + + QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); + QueueInboxEntity item = queryFactory.query(QueueInboxQuery.class).ids(candidate.getId()).first(); + + if (item.getRetryCount() != null && item.getRetryCount() >= 1) { + Boolean itIsTime = itIsTimeFunc.apply(item); + + if (!itIsTime) { + item.setStatus(candidate.getPreviousState()); + + entityManager.merge(item); + entityManager.flush(); + success = true; + } + + success = !itIsTime; + } + transaction.commit(); + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + if (transaction != null) + transaction.rollback(); + success = false; + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + } + return success; + } + + @Override + public QueueInbox create(InboxCreatorParams inboxCreatorParams) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + boolean success = false; + QueueInboxEntity queueMessage = null; + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + queueMessage = this.createQueueInboxEntity(inboxCreatorParams); + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + + entityManager = entityManagerFactory.createEntityManager(); + transaction = entityManager.getTransaction(); + + transaction.begin(); + + entityManager.persist(queueMessage); + entityManager.flush(); + + transaction.commit(); + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + if (transaction != null) + transaction.rollback(); + success = false; + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + } + return queueMessage; + } + + private QueueInboxEntity createQueueInboxEntity(InboxCreatorParams inboxCreatorParams) { + + QueueInboxEntity queueMessage = new QueueInboxEntity(); + queueMessage.setId(UUID.randomUUID()); + Object tenantId = inboxCreatorParams.getHeaders() != null ? inboxCreatorParams.getHeaders().getOrDefault(IntegrationEventMessageConstants.TENANT, null) : null; + if (tenantId instanceof UUID) queueMessage.setTenantId((UUID) tenantId); + else if (tenantId instanceof String) { + try { + queueMessage.setTenantId(UUID.fromString((String) tenantId)); + } catch (Exception e) { + } + } + queueMessage.setExchange(this.inboxProperties.getExchange()); + queueMessage.setRoute(inboxCreatorParams.getRoutingKey()); + queueMessage.setQueue(inboxCreatorParams.getQueueName()); + queueMessage.setApplicationId(inboxCreatorParams.getAppId()); + queueMessage.setMessageId(UUID.fromString(inboxCreatorParams.getMessageId())); + queueMessage.setMessage(inboxCreatorParams.getMessageBody()); + queueMessage.setIsActive(IsActive.Active); + queueMessage.setStatus(QueueInboxStatus.PENDING); + queueMessage.setRetryCount(0); + queueMessage.setCreatedAt(Instant.now()); + + return queueMessage; + } + + @Override + public Boolean emit(CandidateInfo candidateInfo) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + boolean success = false; + + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + + entityManager = entityManagerFactory.createEntityManager(); + transaction = entityManager.getTransaction(); + + TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); + tenantEntityManager.setEntityManager(entityManager); + + transaction.begin(); + + QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); + QueueInboxEntity queueInboxMessage = queryFactory.query(QueueInboxQuery.class).ids(candidateInfo.getId()).first(); + + if (queueInboxMessage == null) { + logger.warn("Could not lookup queue inbox {} to process. Continuing...", candidateInfo.getId()); + } else { + + EventProcessingStatus status = this.processMessage(queueInboxMessage); + switch (status) { + case Success: { + queueInboxMessage.setStatus(QueueInboxStatus.SUCCESSFUL); + break; + } + case Postponed: { + queueInboxMessage.setStatus(QueueInboxStatus.PARKED); + break; + } + case Error: { + queueInboxMessage.setStatus(QueueInboxStatus.ERROR); + queueInboxMessage.setRetryCount(queueInboxMessage.getRetryCount() != null ? queueInboxMessage.getRetryCount() + 1 : 0); + break; + } + case Discard: + default: { + queueInboxMessage.setStatus(QueueInboxStatus.DISCARD); + break; + } + } + success = status == EventProcessingStatus.Success; + + entityManager.merge(queueInboxMessage); + entityManager.flush(); + } + + transaction.commit(); + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + if (transaction != null) + transaction.rollback(); + success = false; + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + } + return success; + } + + + + private EventProcessingStatus processMessage(QueueInboxEntity queueInboxMessage) { + IntegrationEventHandler handler = null; + logger.debug("Processing message with routing key '{}'", queueInboxMessage.getRoute()); +// if (this.routingKeyMatched(queueInboxMessage.getRoute(), this.inboxProperties.getTenantRemovalTopic())) +// handler = this.applicationContext.getBean(TenantRemovalIntegrationEventHandler.class); +// else { +// logger.error("No handler found for message routing key '{}'. Discarding.", queueInboxMessage.getRoute()); +// handler = null; +// } + + if (handler == null) + return EventProcessingStatus.Discard; + + IntegrationEventProperties properties = new IntegrationEventProperties(); + properties.setAppId(queueInboxMessage.getApplicationId()); + properties.setMessageId(queueInboxMessage.getMessageId().toString()); + properties.setTenantId(queueInboxMessage.getTenantId()); + + TrackedEvent event = this.jsonHandlingService.fromJsonSafe(TrackedEvent.class, queueInboxMessage.getMessage()); +// using (LogContext.PushProperty(this._logTrackingConfig.LogTrackingContextName, @event.TrackingContextTag)) +// { + try { + return handler.handle(properties, queueInboxMessage.getMessage()); + } catch (Exception ex) { + logger.error("problem handling event from routing key " + queueInboxMessage.getRoute() + ". Setting nack and continuing...", ex); + return EventProcessingStatus.Error; + } +// } + } + + private Boolean routingKeyMatched(String routingKey, List topics) { + if (topics == null || topics.isEmpty()) + return false; + return topics.stream().anyMatch(x -> x.equals(routingKey)); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/IntegrationEventHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/IntegrationEventHandler.java new file mode 100644 index 000000000..5ba093351 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/IntegrationEventHandler.java @@ -0,0 +1,7 @@ +package org.opencdmp.integrationevent.inbox; + +public interface IntegrationEventHandler { + + EventProcessingStatus handle(IntegrationEventProperties properties, String message); + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/IntegrationEventProperties.java b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/IntegrationEventProperties.java new file mode 100644 index 000000000..ebd43587f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/inbox/IntegrationEventProperties.java @@ -0,0 +1,35 @@ +package org.opencdmp.integrationevent.inbox; + +import java.util.UUID; + +public class IntegrationEventProperties { + + private String messageId; + + private String appId; + private UUID tenantId; + + public String getMessageId() { + return messageId; + } + + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + public String getAppId() { + return appId; + } + + public void setAppId(String appId) { + this.appId = appId; + } + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxIntegrationEvent.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxIntegrationEvent.java new file mode 100644 index 000000000..24326fc4f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxIntegrationEvent.java @@ -0,0 +1,48 @@ +package org.opencdmp.integrationevent.outbox; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.opencdmp.integrationevent.TrackedEvent; +import gr.cite.rabbitmq.IntegrationEvent; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class OutboxIntegrationEvent extends IntegrationEvent { + + public static final String FORGET_ME_COMPLETED = "FORGET_ME_COMPLETED"; + + public static final String NOTIFY = "NOTIFY"; + public static final String TENANT_DEFAULT_LOCALE_REMOVAL = "TENANT_DEFAULT_LOCALE_REMOVAL"; + public static final String TENANT_DEFAULT_LOCALE_TOUCHED = "TENANT_DEFAULT_LOCALE_TOUCHED"; + + public static final String TENANT_REACTIVATE = "TENANT_REACTIVATE"; + + public static final String TENANT_REMOVE = "TENANT_REMOVE"; + + public static final String TENANT_TOUCH = "TENANT_TOUCH"; + + public static final String TENANT_USER_INVITE = "TENANT_USER_INVITE"; + + public static final String USER_TOUCH = "USER_TOUCH"; + + public static final String USER_REMOVE = "USER_REMOVE"; + + public static final String DMP_TOUCH = "DMP_TOUCH"; + + public static final String DESCRIPTION_TOUCH = "DESCRIPTION_TOUCH"; + + public static final String ANNOTATION_ENTITY_TOUCH = "ANNOTATION_ENTITY_TOUCH"; + public static final String ANNOTATION_ENTITY_REMOVE = "ANNOTATION_ENTITY_REMOVE"; + + public static final String WHAT_YOU_KNOW_ABOUT_ME_COMPLETED = "WHAT_YOU_KNOW_ABOUT_ME_COMPLETED"; + + public static final String GENERATE_FILE = "GENERATE_FILE"; + + private TrackedEvent event; + + public TrackedEvent getEvent() { + return event; + } + + public void setEvent(TrackedEvent event) { + this.event = event; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxProperties.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxProperties.java new file mode 100644 index 000000000..884e51cb6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxProperties.java @@ -0,0 +1,145 @@ +package org.opencdmp.integrationevent.outbox; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.List; + +@ConfigurationProperties(prefix = "queue.task.publisher.options") +public class OutboxProperties { + + private final String exchange; + private final String tenantDefaultLocaleRemovalTopic; + private final String tenantDefaultLocaleTouchedTopic; + + private final String tenantTouchTopic; + + private final String tenantRemovalTopic; + + private final String tenantReactivationTopic; + + private final String tenantUserInviteTopic; + + private final String userRemovalTopic; + + private final String userTouchTopic; + + private final String dmpTouchTopic; + + private final String descriptionTouchTopic; + + private final String annotationEntitiesTouchTopic; + private final String annotationEntitiesRemovalTopic; + + private final String notifyTopic; + + private final String forgetMeCompletedTopic; + + private final String whatYouKnowAboutMeCompletedTopic; + + private final String generateFileTopic; + + public OutboxProperties(String exchange, + String tenantDefaultLocaleRemovalTopic, + String tenantDefaultLocaleTouchedTopic, + String tenantTouchTopic, + String tenantRemovalTopic, + String tenantReactivationTopic, + String tenantUserInviteTopic, + String userRemovalTopic, + String userTouchTopic, + String dmpTouchTopic, + String descriptionTouchTopic, + String annotationEntitiesTouchTopic, + String annotationEntitiesRemovalTopic, + String notifyTopic, + String forgetMeCompletedTopic, + String whatYouKnowAboutMeCompletedTopic, + String generateFileTopic + ) { + this.exchange = exchange; + this.tenantDefaultLocaleRemovalTopic = tenantDefaultLocaleRemovalTopic; + this.tenantDefaultLocaleTouchedTopic = tenantDefaultLocaleTouchedTopic; + this.tenantTouchTopic = tenantTouchTopic; + this.tenantRemovalTopic = tenantRemovalTopic; + this.tenantReactivationTopic = tenantReactivationTopic; + this.tenantUserInviteTopic = tenantUserInviteTopic; + this.userRemovalTopic = userRemovalTopic; + this.userTouchTopic = userTouchTopic; + this.dmpTouchTopic = dmpTouchTopic; + this.descriptionTouchTopic = descriptionTouchTopic; + this.annotationEntitiesTouchTopic = annotationEntitiesTouchTopic; + this.annotationEntitiesRemovalTopic = annotationEntitiesRemovalTopic; + this.notifyTopic = notifyTopic; + this.forgetMeCompletedTopic = forgetMeCompletedTopic; + this.whatYouKnowAboutMeCompletedTopic = whatYouKnowAboutMeCompletedTopic; + this.generateFileTopic = generateFileTopic; + } + + public String getExchange() { + return exchange; + } + + public String getTenantDefaultLocaleRemovalTopic() { + return tenantDefaultLocaleRemovalTopic; + } + + public String getTenantDefaultLocaleTouchedTopic() { + return tenantDefaultLocaleTouchedTopic; + } + + public String getTenantTouchTopic() { + return tenantTouchTopic; + } + + public String getTenantRemovalTopic() { + return tenantRemovalTopic; + } + + public String getTenantReactivationTopic() { + return tenantReactivationTopic; + } + + public String getTenantUserInviteTopic() { + return tenantUserInviteTopic; + } + + public String getUserRemovalTopic() { + return userRemovalTopic; + } + + public String getUserTouchTopic() { + return userTouchTopic; + } + + public String getDmpTouchTopic() { + return dmpTouchTopic; + } + + public String getDescriptionTouchTopic() { + return descriptionTouchTopic; + } + + public String getAnnotationEntitiesTouchTopic() { + return annotationEntitiesTouchTopic; + } + + public String getAnnotationEntitiesRemovalTopic() { + return annotationEntitiesRemovalTopic; + } + + public String getNotifyTopic() { + return notifyTopic; + } + + public String getForgetMeCompletedTopic() { + return forgetMeCompletedTopic; + } + + public String getWhatYouKnowAboutMeCompletedTopic() { + return whatYouKnowAboutMeCompletedTopic; + } + + public String getGenerateFileTopic() { + return generateFileTopic; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxRepositoryImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxRepositoryImpl.java new file mode 100644 index 000000000..85bdb12cb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxRepositoryImpl.java @@ -0,0 +1,475 @@ +package org.opencdmp.integrationevent.outbox; + +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.fake.FakeRequestScope; +import org.opencdmp.data.QueueOutboxEntity; +import org.opencdmp.query.QueueOutboxQuery; +import gr.cite.queueoutbox.entity.QueueOutbox; +import gr.cite.queueoutbox.entity.QueueOutboxNotifyStatus; +import gr.cite.queueoutbox.repository.CandidateInfo; +import gr.cite.queueoutbox.repository.OutboxRepository; +import gr.cite.queueoutbox.task.MessageOptions; +import gr.cite.rabbitmq.IntegrationEvent; +import gr.cite.tools.data.query.Ordering; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.EntityTransaction; +import jakarta.persistence.OptimisticLockException; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class OutboxRepositoryImpl implements OutboxRepository { + + protected final ApplicationContext applicationContext; + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(OutboxRepositoryImpl.class)); + + private final JsonHandlingService jsonHandlingService; + + private final OutboxProperties outboxProperties; + + public OutboxRepositoryImpl( + ApplicationContext applicationContext, + OutboxProperties outboxProperties + ) { + this.applicationContext = applicationContext; + this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); + this.outboxProperties = outboxProperties; + } + + @Override + public CandidateInfo candidate(Instant lastCandidateCreationTimestamp, MessageOptions messageOptions, Function onConfirmTimeout) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + CandidateInfo candidate = null; + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + entityManager = entityManagerFactory.createEntityManager(); + + transaction = entityManager.getTransaction(); + transaction.begin(); + + QueueOutboxEntity item = queryFactory.query(QueueOutboxQuery.class) + .isActives(IsActive.Active) + .notifyStatus(QueueOutboxNotifyStatus.PENDING, QueueOutboxNotifyStatus.WAITING_CONFIRMATION, QueueOutboxNotifyStatus.ERROR) + .retryThreshold(messageOptions.getRetryThreashold()) + .confirmTimeout(messageOptions.getConfirmTimeoutSeconds()) + .createdAfter(lastCandidateCreationTimestamp) + .ordering(new Ordering().addAscending(QueueOutboxEntity._createdAt)) + .first(); + + if (item != null) { + boolean confirmTimeout = onConfirmTimeout.apply(item); + + QueueOutboxNotifyStatus prevState = item.getNotifyStatus(); + item.setNotifyStatus(QueueOutboxNotifyStatus.PROCESSING); + + entityManager.merge(item); + entityManager.flush(); + + candidate = new CandidateInfo(); + candidate.setId(item.getId()); + candidate.setCreatedAt(item.getCreatedAt()); + candidate.setPreviousState(prevState); + } + + transaction.commit(); + } catch (OptimisticLockException ex) { + // we get this if/when someone else already modified the notifications. We want to essentially ignore this, and keep working + logger.debug("Concurrency exception getting queue outbox. Skipping: {} ", ex.getMessage()); + if (transaction != null) + transaction.rollback(); + candidate = null; + } catch (Exception ex) { + logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); + if (transaction != null) + transaction.rollback(); + candidate = null; + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); + } + + return candidate; + } + + @Override + public Boolean shouldOmit(CandidateInfo candidate, Function shouldOmit) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + boolean success = false; + + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + + entityManager = entityManagerFactory.createEntityManager(); + transaction = entityManager.getTransaction(); + + transaction.begin(); + + QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); + QueueOutboxEntity item = queryFactory.query(QueueOutboxQuery.class).ids(candidate.getId()).first(); + + if (item == null) { + logger.warn("Could not lookup queue outbox {} to process. Continuing...", candidate.getId()); + } else { + if (shouldOmit.apply(item)) { + item.setNotifyStatus(QueueOutboxNotifyStatus.OMITTED); + + entityManager.merge(item); + entityManager.flush(); + success = true; + } + } + + transaction.commit(); + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + if (transaction != null) + transaction.rollback(); + success = false; + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + } + return success; + } + + @Override + public Boolean shouldWait(CandidateInfo candidate, Function itIsTimeFunc) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + boolean success = false; + + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + + entityManager = entityManagerFactory.createEntityManager(); + transaction = entityManager.getTransaction(); + + transaction.begin(); + + QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); + QueueOutboxEntity item = queryFactory.query(QueueOutboxQuery.class).ids(candidate.getId()).first(); + + if (item.getRetryCount() != null && item.getRetryCount() >= 1) { + Boolean itIsTime = itIsTimeFunc.apply(item); + + if (!itIsTime) { + item.setNotifyStatus(candidate.getPreviousState()); + + entityManager.merge(item); + entityManager.flush(); + success = true; + } + + success = !itIsTime; + } + transaction.commit(); + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + if (transaction != null) + transaction.rollback(); + success = false; + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + } + return success; + } + + @Override + public Boolean process(CandidateInfo candidateInfo, Boolean isAutoconfirmOnPublish, Function publish) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + Boolean success = false; + + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + + entityManager = entityManagerFactory.createEntityManager(); + transaction = entityManager.getTransaction(); + transaction.begin(); + + QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); + QueueOutboxEntity item = queryFactory.query(QueueOutboxQuery.class).ids(candidateInfo.getId()).first(); + + if (item == null) { + logger.warn("Could not lookup queue outbox {} to process. Continuing...", candidateInfo.getId()); + } else { + + success = publish.apply(item); + if (success) { + if (isAutoconfirmOnPublish) { + item.setNotifyStatus(QueueOutboxNotifyStatus.CONFIRMED); + item.setConfirmedAt(Instant.now()); + } else { + item.setNotifyStatus(QueueOutboxNotifyStatus.WAITING_CONFIRMATION); + } + item.setPublishedAt(Instant.now()); + } else { + item.setNotifyStatus(QueueOutboxNotifyStatus.ERROR); + item.setRetryCount(item.getRetryCount() != null ? item.getRetryCount() + 1 : 0); + item.setPublishedAt(null); + } + + entityManager.merge(item); + entityManager.flush(); + } + + transaction.commit(); + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + if (transaction != null) + transaction.rollback(); + success = false; + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + } + return success; + } + + @Override + public void handleConfirm(List confirmedMessages) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + + entityManager = entityManagerFactory.createEntityManager(); + transaction = entityManager.getTransaction(); + transaction.begin(); + + QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); + List queueOutboxMessages = queryFactory.query(QueueOutboxQuery.class).ids(confirmedMessages).collect(); + + if (queueOutboxMessages == null) { + logger.warn("Could not lookup messages {} to process. Continuing...", confirmedMessages.stream().map(UUID::toString).collect(Collectors.joining(","))); + } else { + + for (QueueOutboxEntity queueOutboxMessage : queueOutboxMessages) { + queueOutboxMessage.setNotifyStatus(QueueOutboxNotifyStatus.CONFIRMED); + queueOutboxMessage.setConfirmedAt(Instant.now()); + entityManager.merge(queueOutboxMessage); + } + + entityManager.flush(); + } + + transaction.commit(); + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + if (transaction != null) + transaction.rollback(); + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + } + } + + @Override + public void handleNack(List nackedMessages) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + + entityManager = entityManagerFactory.createEntityManager(); + transaction = entityManager.getTransaction(); + transaction.begin(); + + QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); + List queueOutboxMessages = queryFactory.query(QueueOutboxQuery.class).ids(nackedMessages).collect(); + + if (queueOutboxMessages == null) { + logger.warn("Could not lookup messages {} to process. Continuing...", nackedMessages.stream().map(UUID::toString).collect(Collectors.joining(","))); + } else { + + for (QueueOutboxEntity queueOutboxMessage : queueOutboxMessages) { + queueOutboxMessage.setNotifyStatus(QueueOutboxNotifyStatus.ERROR); + queueOutboxMessage.setRetryCount(queueOutboxMessage.getRetryCount() != null ? queueOutboxMessage.getRetryCount() + 1 : 0); + entityManager.merge(queueOutboxMessage); + } + + entityManager.flush(); + } + + transaction.commit(); + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + if (transaction != null) + transaction.rollback(); + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + } + } + + @Override + public QueueOutbox create(IntegrationEvent item) { + EntityTransaction transaction = null; + EntityManager entityManager = null; + QueueOutboxEntity queueMessage = null; + try (FakeRequestScope ignored = new FakeRequestScope()) { + try { + queueMessage = this.mapEvent((OutboxIntegrationEvent) item); + EntityManagerFactory entityManagerFactory = this.applicationContext.getBean(EntityManagerFactory.class); + + entityManager = entityManagerFactory.createEntityManager(); + transaction = entityManager.getTransaction(); + + transaction.begin(); + + entityManager.persist(queueMessage); + entityManager.flush(); + + transaction.commit(); + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + if (transaction != null) + transaction.rollback(); + } finally { + if (entityManager != null) + entityManager.close(); + } + } catch (Exception ex) { + logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); + } + return queueMessage; + } + + private QueueOutboxEntity mapEvent(OutboxIntegrationEvent event) { + String routingKey; + switch (event.getType()) { + case OutboxIntegrationEvent.TENANT_REACTIVATE: { + routingKey = this.outboxProperties.getTenantReactivationTopic(); + break; + } + case OutboxIntegrationEvent.TENANT_REMOVE: { + routingKey = this.outboxProperties.getTenantRemovalTopic(); + break; + } + case OutboxIntegrationEvent.TENANT_TOUCH: { + routingKey = this.outboxProperties.getTenantTouchTopic(); + break; + } + case OutboxIntegrationEvent.TENANT_USER_INVITE: { + routingKey = this.outboxProperties.getTenantUserInviteTopic(); + break; + } + case OutboxIntegrationEvent.USER_REMOVE: { + routingKey = this.outboxProperties.getUserRemovalTopic(); + break; + } + case OutboxIntegrationEvent.USER_TOUCH: { + routingKey = this.outboxProperties.getUserTouchTopic(); + break; + } + case OutboxIntegrationEvent.DMP_TOUCH: { + routingKey = this.outboxProperties.getDmpTouchTopic(); + break; + } + case OutboxIntegrationEvent.DESCRIPTION_TOUCH: { + routingKey = this.outboxProperties.getDescriptionTouchTopic(); + break; + } + case OutboxIntegrationEvent.ANNOTATION_ENTITY_TOUCH: { + routingKey = this.outboxProperties.getAnnotationEntitiesTouchTopic(); + break; + } + case OutboxIntegrationEvent.ANNOTATION_ENTITY_REMOVE: { + routingKey = this.outboxProperties.getAnnotationEntitiesRemovalTopic(); + break; + } + case OutboxIntegrationEvent.FORGET_ME_COMPLETED: { + routingKey = this.outboxProperties.getForgetMeCompletedTopic(); + break; + } + case OutboxIntegrationEvent.NOTIFY: { + routingKey = this.outboxProperties.getNotifyTopic(); + break; + } + case OutboxIntegrationEvent.TENANT_DEFAULT_LOCALE_REMOVAL: { + routingKey = this.outboxProperties.getTenantDefaultLocaleRemovalTopic(); + break; + } + case OutboxIntegrationEvent.TENANT_DEFAULT_LOCALE_TOUCHED: { + routingKey = this.outboxProperties.getTenantDefaultLocaleTouchedTopic(); + break; + } + case OutboxIntegrationEvent.WHAT_YOU_KNOW_ABOUT_ME_COMPLETED: { + routingKey = this.outboxProperties.getWhatYouKnowAboutMeCompletedTopic(); + break; + } + case OutboxIntegrationEvent.GENERATE_FILE: { + routingKey = this.outboxProperties.getGenerateFileTopic(); + break; + } + default: { + logger.error("unrecognized outgoing integration event {}. Skipping...", event.getType()); + return null; + } + } + + UUID correlationId = UUID.randomUUID(); + if (event.getEvent() != null) + event.getEvent().setTrackingContextTag(correlationId.toString()); + event.setMessage(this.jsonHandlingService.toJsonSafe(event.getEvent())); + //this._logTrackingService.Trace(correlationId.ToString(), $"Correlating current tracking context with new correlationId {correlationId}"); + + QueueOutboxEntity queueMessage = new QueueOutboxEntity(); + queueMessage.setId(UUID.randomUUID()); + queueMessage.setTenantId(event.getTenantId()); + queueMessage.setExchange(this.outboxProperties.getExchange()); + queueMessage.setRoute(routingKey); + queueMessage.setMessageId(event.getMessageId()); + queueMessage.setMessage(this.jsonHandlingService.toJsonSafe(event)); + queueMessage.setIsActive(IsActive.Active); + queueMessage.setNotifyStatus(QueueOutboxNotifyStatus.PENDING); + queueMessage.setRetryCount(0); + queueMessage.setCreatedAt(Instant.now()); + queueMessage.setUpdatedAt(Instant.now()); + + return queueMessage; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxService.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxService.java new file mode 100644 index 000000000..7fef4ed2a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxService.java @@ -0,0 +1,5 @@ +package org.opencdmp.integrationevent.outbox; + +public interface OutboxService { + void publish(OutboxIntegrationEvent event); +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxServiceImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxServiceImpl.java new file mode 100644 index 000000000..d68a5f964 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/OutboxServiceImpl.java @@ -0,0 +1,35 @@ +package org.opencdmp.integrationevent.outbox; + + +import org.opencdmp.commons.JsonHandlingService; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Component; +import org.springframework.web.context.annotation.RequestScope; + +@Component +@RequestScope +public class OutboxServiceImpl implements OutboxService { + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(OutboxServiceImpl.class)); + + private final ApplicationEventPublisher eventPublisher; + + public OutboxServiceImpl( + ApplicationEventPublisher eventPublisher + ) { + this.eventPublisher = eventPublisher; + } + + @Override + public void publish(OutboxIntegrationEvent event) { + try { + eventPublisher.publishEvent(event); + } catch (Exception ex) { + logger.error(new MapLogEntry(String.format("Could not save message ", event.getMessage())).And("message", event.getMessage()).And("ex", ex)); + //Still want to skip it from processing + } + + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentityremoval/AnnotationEntitiesRemovalIntegrationEvent.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentityremoval/AnnotationEntitiesRemovalIntegrationEvent.java new file mode 100644 index 000000000..c284ded67 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentityremoval/AnnotationEntitiesRemovalIntegrationEvent.java @@ -0,0 +1,19 @@ +package org.opencdmp.integrationevent.outbox.annotationentityremoval; + +import org.opencdmp.integrationevent.TrackedEvent; + +import java.util.List; +import java.util.UUID; + +public class AnnotationEntitiesRemovalIntegrationEvent extends TrackedEvent { + + private List entityIds; + + public List getEntityIds() { + return entityIds; + } + + public void setEntityIds(List entityIds) { + this.entityIds = entityIds; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentityremoval/AnnotationEntityRemovalIntegrationEventHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentityremoval/AnnotationEntityRemovalIntegrationEventHandler.java new file mode 100644 index 000000000..c7150d9cf --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentityremoval/AnnotationEntityRemovalIntegrationEventHandler.java @@ -0,0 +1,10 @@ +package org.opencdmp.integrationevent.outbox.annotationentityremoval; + +import javax.management.InvalidApplicationException; +import java.util.UUID; + +public interface AnnotationEntityRemovalIntegrationEventHandler { + + void handleDescription(UUID descriptionId) throws InvalidApplicationException; + void handleDmp(UUID dmpId) throws InvalidApplicationException; +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentityremoval/AnnotationEntityRemovalIntegrationEventHandlerImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentityremoval/AnnotationEntityRemovalIntegrationEventHandlerImpl.java new file mode 100644 index 000000000..99d7594c8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentityremoval/AnnotationEntityRemovalIntegrationEventHandlerImpl.java @@ -0,0 +1,72 @@ +package org.opencdmp.integrationevent.outbox.annotationentityremoval; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.data.DescriptionEntity; +import org.opencdmp.data.DmpUserEntity; +import org.opencdmp.integrationevent.outbox.OutboxIntegrationEvent; +import org.opencdmp.integrationevent.outbox.OutboxService; +import org.opencdmp.model.Description; +import org.opencdmp.model.DmpUser; +import org.opencdmp.query.DescriptionQuery; +import org.opencdmp.query.DmpUserQuery; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class AnnotationEntityRemovalIntegrationEventHandlerImpl implements AnnotationEntityRemovalIntegrationEventHandler { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(AnnotationEntityRemovalIntegrationEventHandlerImpl.class)); + + private final OutboxService outboxService; + + private final QueryFactory queryFactory; + private final TenantScope tenantScope; + + public AnnotationEntityRemovalIntegrationEventHandlerImpl(OutboxService outboxService, QueryFactory queryFactory, TenantScope tenantScope) { + this.outboxService = outboxService; + this.queryFactory = queryFactory; + this.tenantScope = tenantScope; + } + + private void handle(AnnotationEntitiesRemovalIntegrationEvent event) throws InvalidApplicationException { + OutboxIntegrationEvent message = new OutboxIntegrationEvent(); + message.setMessageId(UUID.randomUUID()); + message.setType(OutboxIntegrationEvent.ANNOTATION_ENTITY_REMOVE); + message.setEvent(event); + if (this.tenantScope.isSet()) message.setTenantId(tenantScope.getTenant()); + this.outboxService.publish(message); + } + + @Override + public void handleDescription(UUID descriptionId) throws InvalidApplicationException { + AnnotationEntitiesRemovalIntegrationEvent event = new AnnotationEntitiesRemovalIntegrationEvent(); + event.setEntityIds(List.of(descriptionId)); + + this.handle(event); + } + + @Override + public void handleDmp(UUID dmpId) throws InvalidApplicationException { + List descriptionEntities = this.queryFactory.query(DescriptionQuery.class).dmpIds(dmpId).collectAs(new BaseFieldSet().ensure(Description._id)); + + AnnotationEntitiesRemovalIntegrationEvent event = new AnnotationEntitiesRemovalIntegrationEvent(); + event.setEntityIds(new ArrayList<>()); + event.getEntityIds().add(dmpId); + + for (DescriptionEntity description : descriptionEntities) event.getEntityIds().add(description.getId()); + + this.handle(event); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentitytouch/AnnotationEntitiesTouchedIntegrationEvent.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentitytouch/AnnotationEntitiesTouchedIntegrationEvent.java new file mode 100644 index 000000000..a913e53fd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentitytouch/AnnotationEntitiesTouchedIntegrationEvent.java @@ -0,0 +1,43 @@ +package org.opencdmp.integrationevent.outbox.annotationentitytouch; + +import org.opencdmp.integrationevent.TrackedEvent; + +import java.util.List; +import java.util.UUID; + +public class AnnotationEntitiesTouchedIntegrationEvent extends TrackedEvent { + + private List events; + + public List getEvents() { + return events; + } + + public void setEvents(List events) { + this.events = events; + } + + public static class AnnotationEntityTouchedIntegrationEvent { + + private UUID entityId; + + private List userIds; + + public UUID getEntityId() { + return entityId; + } + + public void setEntityId(UUID entityId) { + this.entityId = entityId; + } + + public List getUserIds() { + return userIds; + } + + public void setUserIds(List userIds) { + this.userIds = userIds; + } + + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentitytouch/AnnotationEntityTouchedIntegrationEventHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentitytouch/AnnotationEntityTouchedIntegrationEventHandler.java new file mode 100644 index 000000000..5db2e6ed3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentitytouch/AnnotationEntityTouchedIntegrationEventHandler.java @@ -0,0 +1,9 @@ +package org.opencdmp.integrationevent.outbox.annotationentitytouch; + +import java.util.UUID; + +public interface AnnotationEntityTouchedIntegrationEventHandler { + + void handleDescription(UUID descriptionId); + void handleDmp(UUID dmpId); +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentitytouch/AnnotationEntityTouchedIntegrationEventHandlerImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentitytouch/AnnotationEntityTouchedIntegrationEventHandlerImpl.java new file mode 100644 index 000000000..374734e3b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/annotationentitytouch/AnnotationEntityTouchedIntegrationEventHandlerImpl.java @@ -0,0 +1,85 @@ +package org.opencdmp.integrationevent.outbox.annotationentitytouch; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DescriptionEntity; +import org.opencdmp.data.DmpUserEntity; +import org.opencdmp.integrationevent.outbox.OutboxIntegrationEvent; +import org.opencdmp.integrationevent.outbox.OutboxService; +import org.opencdmp.model.Description; +import org.opencdmp.model.DmpUser; +import org.opencdmp.query.DescriptionQuery; +import org.opencdmp.query.DmpUserQuery; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class AnnotationEntityTouchedIntegrationEventHandlerImpl implements AnnotationEntityTouchedIntegrationEventHandler { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(AnnotationEntityTouchedIntegrationEventHandlerImpl.class)); + + private final OutboxService outboxService; + + private final QueryFactory queryFactory; + + public AnnotationEntityTouchedIntegrationEventHandlerImpl(OutboxService outboxService, QueryFactory queryFactory) { + this.outboxService = outboxService; + this.queryFactory = queryFactory; + } + + private void handle(AnnotationEntitiesTouchedIntegrationEvent event, UUID tenantId) { + OutboxIntegrationEvent message = new OutboxIntegrationEvent(); + message.setMessageId(UUID.randomUUID()); + message.setType(OutboxIntegrationEvent.ANNOTATION_ENTITY_TOUCH); + message.setEvent(event); + message.setTenantId(tenantId); + this.outboxService.publish(message); + } + + @Override + public void handleDescription(UUID descriptionId) { + DescriptionEntity entity = this.queryFactory.query(DescriptionQuery.class).ids(descriptionId).firstAs(new BaseFieldSet().ensure(Description._dmp).ensure(DescriptionEntity._tenantId)); + if (entity == null) return; + List dmpUsers = this.queryFactory.query(DmpUserQuery.class).dmpIds(entity.getDmpId()).isActives(IsActive.Active).collectAs(new BaseFieldSet().ensure(DmpUser._user)); + + AnnotationEntitiesTouchedIntegrationEvent event = new AnnotationEntitiesTouchedIntegrationEvent(); + event.setEvents(List.of(this.buildEventItem(descriptionId, dmpUsers))); + + this.handle(event, entity.getTenantId()); + } + + @Override + public void handleDmp(UUID dmpId) { + List descriptionEntities = this.queryFactory.query(DescriptionQuery.class).dmpIds(dmpId).collectAs(new BaseFieldSet().ensure(Description._id)); + if (descriptionEntities == null || descriptionEntities.isEmpty()) return; + List dmpUsers = this.queryFactory.query(DmpUserQuery.class).dmpIds(dmpId).isActives(IsActive.Active).collectAs(new BaseFieldSet().ensure(DmpUser._user)); + + AnnotationEntitiesTouchedIntegrationEvent event = new AnnotationEntitiesTouchedIntegrationEvent(); + event.setEvents(new ArrayList<>()); + event.getEvents().add(this.buildEventItem(dmpId, dmpUsers)); + + for (DescriptionEntity description : descriptionEntities) event.getEvents().add(this.buildEventItem(description.getId(), dmpUsers)); + + this.handle(event, descriptionEntities.getFirst().getTenantId()); + } + + private AnnotationEntitiesTouchedIntegrationEvent.AnnotationEntityTouchedIntegrationEvent buildEventItem(UUID entityId, List dmpUsers){ + AnnotationEntitiesTouchedIntegrationEvent.AnnotationEntityTouchedIntegrationEvent eventItem = new AnnotationEntitiesTouchedIntegrationEvent.AnnotationEntityTouchedIntegrationEvent(); + eventItem.setEntityId(entityId); + List users = new ArrayList<>(); + for (DmpUserEntity dmpUser : dmpUsers){ + users.add(dmpUser.getUserId()); + } + eventItem.setUserIds(users); + return eventItem; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/notification/NotifyIntegrationEvent.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/notification/NotifyIntegrationEvent.java new file mode 100644 index 000000000..6516b3d17 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/notification/NotifyIntegrationEvent.java @@ -0,0 +1,72 @@ +package org.opencdmp.integrationevent.outbox.notification; + +import org.opencdmp.commons.enums.notification.NotificationContactType; +import org.opencdmp.integrationevent.TrackedEvent; + +import java.util.UUID; + +public class NotifyIntegrationEvent extends TrackedEvent { + + private UUID userId; + + private UUID notificationType; + + private NotificationContactType contactTypeHint; + + private String contactHint; + + private String data; + + private String provenanceRef; + + public NotifyIntegrationEvent() { + } + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public UUID getNotificationType() { + return notificationType; + } + + public void setNotificationType(UUID notificationType) { + this.notificationType = notificationType; + } + + public NotificationContactType getContactTypeHint() { + return contactTypeHint; + } + + public void setContactTypeHint(NotificationContactType 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 String getProvenanceRef() { + return provenanceRef; + } + + public void setProvenanceRef(String provenanceRef) { + this.provenanceRef = provenanceRef; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/notification/NotifyIntegrationEventHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/notification/NotifyIntegrationEventHandler.java new file mode 100644 index 000000000..e5cd539e0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/notification/NotifyIntegrationEventHandler.java @@ -0,0 +1,7 @@ +package org.opencdmp.integrationevent.outbox.notification; + +import javax.management.InvalidApplicationException; + +public interface NotifyIntegrationEventHandler { + void handle(NotifyIntegrationEvent event) throws InvalidApplicationException; +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/notification/NotifyIntegrationEventHandlerImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/notification/NotifyIntegrationEventHandlerImpl.java new file mode 100644 index 000000000..f58ae8ace --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/notification/NotifyIntegrationEventHandlerImpl.java @@ -0,0 +1,40 @@ +package org.opencdmp.integrationevent.outbox.notification; + +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.integrationevent.outbox.OutboxIntegrationEvent; +import org.opencdmp.integrationevent.outbox.OutboxService; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.context.annotation.RequestScope; + +import javax.management.InvalidApplicationException; +import java.util.UUID; + +@Component +@RequestScope +public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEventHandler { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotifyIntegrationEventHandlerImpl.class)); + + private final OutboxService outboxService; + private final TenantScope tenantScope; + + @Autowired + public NotifyIntegrationEventHandlerImpl( + OutboxService outboxService, TenantScope tenantScope) { + this.outboxService = outboxService; + this.tenantScope = tenantScope; + } + + @Override + public void handle(NotifyIntegrationEvent event) throws InvalidApplicationException { + OutboxIntegrationEvent message = new OutboxIntegrationEvent(); + message.setMessageId(UUID.randomUUID()); + message.setType(OutboxIntegrationEvent.NOTIFY); + message.setEvent(event); + if (this.tenantScope.isSet()) message.setTenantId(tenantScope.getTenant()); + this.outboxService.publish(message); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEvent.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEvent.java new file mode 100644 index 000000000..f0a9be955 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEvent.java @@ -0,0 +1,22 @@ +package org.opencdmp.integrationevent.outbox.tenantdefaultlocaleremoval; + +import org.opencdmp.integrationevent.TrackedEvent; + +import java.util.UUID; + +public class TenantDefaultLocaleRemovalIntegrationEvent extends TrackedEvent { + + private UUID tenantId; + + public TenantDefaultLocaleRemovalIntegrationEvent() { + } + + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandler.java new file mode 100644 index 000000000..93f1e9d52 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandler.java @@ -0,0 +1,7 @@ +package org.opencdmp.integrationevent.outbox.tenantdefaultlocaleremoval; + +import javax.management.InvalidApplicationException; + +public interface TenantDefaultLocaleRemovalIntegrationEventHandler { + void handle(TenantDefaultLocaleRemovalIntegrationEvent event) throws InvalidApplicationException; +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java new file mode 100644 index 000000000..1930ec4fe --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java @@ -0,0 +1,40 @@ +package org.opencdmp.integrationevent.outbox.tenantdefaultlocaleremoval; + +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.integrationevent.outbox.OutboxIntegrationEvent; +import org.opencdmp.integrationevent.outbox.OutboxService; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.context.annotation.RequestScope; + +import javax.management.InvalidApplicationException; +import java.util.UUID; + +@Component +@RequestScope +public class TenantDefaultLocaleRemovalIntegrationEventHandlerImpl implements TenantDefaultLocaleRemovalIntegrationEventHandler { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.class)); + + private final OutboxService outboxService; + private final TenantScope tenantScope; + + @Autowired + public TenantDefaultLocaleRemovalIntegrationEventHandlerImpl( + OutboxService outboxService, TenantScope tenantScope) { + this.outboxService = outboxService; + this.tenantScope = tenantScope; + } + + @Override + public void handle(TenantDefaultLocaleRemovalIntegrationEvent event) throws InvalidApplicationException { + OutboxIntegrationEvent message = new OutboxIntegrationEvent(); + message.setMessageId(UUID.randomUUID()); + message.setType(OutboxIntegrationEvent.TENANT_DEFAULT_LOCALE_REMOVAL); + message.setEvent(event); + if (this.tenantScope.isSet()) message.setTenantId(tenantScope.getTenant()); + this.outboxService.publish(message); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEvent.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEvent.java new file mode 100644 index 000000000..f380cfde8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEvent.java @@ -0,0 +1,49 @@ +package org.opencdmp.integrationevent.outbox.tenantdefaultlocaletouched; + +import org.opencdmp.integrationevent.TrackedEvent; + +import java.util.UUID; + +public class TenantDefaultLocaleTouchedIntegrationEvent extends TrackedEvent { + + private UUID tenantId; + private String timezone; + private String language; + private String culture; + + + public TenantDefaultLocaleTouchedIntegrationEvent() { + } + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getCulture() { + return culture; + } + + public void setCulture(String culture) { + this.culture = culture; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandler.java new file mode 100644 index 000000000..3b74c323d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandler.java @@ -0,0 +1,7 @@ +package org.opencdmp.integrationevent.outbox.tenantdefaultlocaletouched; + +import javax.management.InvalidApplicationException; + +public interface TenantDefaultLocaleTouchedIntegrationEventHandler { + void handle(TenantDefaultLocaleTouchedIntegrationEvent event) throws InvalidApplicationException; +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java new file mode 100644 index 000000000..ea3a48043 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java @@ -0,0 +1,40 @@ +package org.opencdmp.integrationevent.outbox.tenantdefaultlocaletouched; + +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.integrationevent.outbox.OutboxIntegrationEvent; +import org.opencdmp.integrationevent.outbox.OutboxService; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.context.annotation.RequestScope; + +import javax.management.InvalidApplicationException; +import java.util.UUID; + +@Component +@RequestScope +public class TenantDefaultLocaleTouchedIntegrationEventHandlerImpl implements TenantDefaultLocaleTouchedIntegrationEventHandler { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.class)); + + private final OutboxService outboxService; + private final TenantScope tenantScope; + + @Autowired + public TenantDefaultLocaleTouchedIntegrationEventHandlerImpl( + OutboxService outboxService, TenantScope tenantScope) { + this.outboxService = outboxService; + this.tenantScope = tenantScope; + } + + @Override + public void handle(TenantDefaultLocaleTouchedIntegrationEvent event) throws InvalidApplicationException { + OutboxIntegrationEvent message = new OutboxIntegrationEvent(); + message.setMessageId(UUID.randomUUID()); + message.setType(OutboxIntegrationEvent.TENANT_DEFAULT_LOCALE_TOUCHED); + message.setEvent(event); + if (this.tenantScope.isSet()) message.setTenantId(tenantScope.getTenant()); + this.outboxService.publish(message); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalConsistencyHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalConsistencyHandler.java new file mode 100644 index 000000000..a8935d71c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalConsistencyHandler.java @@ -0,0 +1,26 @@ +package org.opencdmp.integrationevent.outbox.tenantremoval; + +import org.opencdmp.integrationevent.inbox.ConsistencyHandler; +import org.opencdmp.query.TenantQuery; +import gr.cite.tools.data.query.QueryFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantRemovalConsistencyHandler implements ConsistencyHandler { + + private final QueryFactory queryFactory; + + public TenantRemovalConsistencyHandler(QueryFactory queryFactory) { + this.queryFactory = queryFactory; + } + + @Override + public Boolean isConsistent(TenantRemovalConsistencyPredicates consistencyPredicates) { + long count = this.queryFactory.query(TenantQuery.class).ids(consistencyPredicates.getTenantId()).count(); + return count > 0; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalConsistencyPredicates.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalConsistencyPredicates.java new file mode 100644 index 000000000..8df3a5313 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalConsistencyPredicates.java @@ -0,0 +1,23 @@ +package org.opencdmp.integrationevent.outbox.tenantremoval; + +import org.opencdmp.integrationevent.inbox.ConsistencyPredicates; + +import java.util.UUID; + +public class TenantRemovalConsistencyPredicates implements ConsistencyPredicates { + + private UUID tenantId; + + public TenantRemovalConsistencyPredicates(UUID tenantId) { + this.tenantId = tenantId; + } + + public UUID getTenantId() { + return tenantId; + } + + public void setTenantId(UUID tenantId) { + this.tenantId = tenantId; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalIntegrationEvent.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalIntegrationEvent.java new file mode 100644 index 000000000..357d209cd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalIntegrationEvent.java @@ -0,0 +1,19 @@ +package org.opencdmp.integrationevent.outbox.tenantremoval; + +import org.opencdmp.integrationevent.TrackedEvent; + +import java.util.UUID; + +public class TenantRemovalIntegrationEvent extends TrackedEvent { + + private UUID id; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + +} \ No newline at end of file diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalIntegrationEventHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalIntegrationEventHandler.java new file mode 100644 index 000000000..62847ef38 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalIntegrationEventHandler.java @@ -0,0 +1,11 @@ +package org.opencdmp.integrationevent.outbox.tenantremoval; + +import java.util.UUID; + +public interface TenantRemovalIntegrationEventHandler { + + void handle(TenantRemovalIntegrationEvent event); + + void handle(UUID tenantId); + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalIntegrationEventHandlerImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalIntegrationEventHandlerImpl.java new file mode 100644 index 000000000..ff37cb1e4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenantremoval/TenantRemovalIntegrationEventHandlerImpl.java @@ -0,0 +1,63 @@ +package org.opencdmp.integrationevent.outbox.tenantremoval; + +import org.opencdmp.integrationevent.outbox.OutboxIntegrationEvent; +import org.opencdmp.integrationevent.outbox.OutboxService; +import org.opencdmp.integrationevent.outbox.userremoval.UserRemovalConsistencyHandler; +import org.opencdmp.integrationevent.outbox.userremoval.UserRemovalConsistencyPredicates; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantRemovalIntegrationEventHandlerImpl implements TenantRemovalIntegrationEventHandler { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantRemovalIntegrationEventHandlerImpl.class)); + + private final OutboxService outboxService; + + private final ApplicationContext applicationContext; + + @Autowired + public TenantRemovalIntegrationEventHandlerImpl(OutboxService outboxService, ApplicationContext applicationContext) { + this.outboxService = outboxService; + this.applicationContext = applicationContext; + } + + @Override + public void handle(TenantRemovalIntegrationEvent event) { + TenantRemovalConsistencyHandler tenantRemovalConsistencyHandler = this.applicationContext.getBean(TenantRemovalConsistencyHandler.class); + if (!tenantRemovalConsistencyHandler.isConsistent(new TenantRemovalConsistencyPredicates(event.getId()))) + return; + + OutboxIntegrationEvent message = new OutboxIntegrationEvent(); + message.setMessageId(UUID.randomUUID()); + message.setType(OutboxIntegrationEvent.TENANT_REMOVE); + message.setEvent(event); + message.setTenantId(event.getId()); + this.outboxService.publish(message); + } + + @Override + public void handle(UUID tenantId) { + TenantRemovalConsistencyHandler tenantRemovalConsistencyHandler = this.applicationContext.getBean(TenantRemovalConsistencyHandler.class); + if (!tenantRemovalConsistencyHandler.isConsistent(new TenantRemovalConsistencyPredicates(tenantId))) + return; + + OutboxIntegrationEvent message = new OutboxIntegrationEvent(); + message.setMessageId(UUID.randomUUID()); + message.setType(OutboxIntegrationEvent.TENANT_REMOVE); + TenantRemovalIntegrationEvent event = new TenantRemovalIntegrationEvent(); + event.setId(tenantId); + message.setEvent(event); + message.setTenantId(event.getId()); + this.outboxService.publish(message); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenanttouched/TenantTouchedIntegrationEvent.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenanttouched/TenantTouchedIntegrationEvent.java new file mode 100644 index 000000000..8114f7e98 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenanttouched/TenantTouchedIntegrationEvent.java @@ -0,0 +1,29 @@ +package org.opencdmp.integrationevent.outbox.tenanttouched; + +import org.opencdmp.integrationevent.TrackedEvent; + +import java.util.UUID; + +public class TenantTouchedIntegrationEvent extends TrackedEvent { + + private UUID id; + + private String code; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenanttouched/TenantTouchedIntegrationEventHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenanttouched/TenantTouchedIntegrationEventHandler.java new file mode 100644 index 000000000..be4f589ff --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenanttouched/TenantTouchedIntegrationEventHandler.java @@ -0,0 +1,7 @@ +package org.opencdmp.integrationevent.outbox.tenanttouched; + +public interface TenantTouchedIntegrationEventHandler { + + void handle(TenantTouchedIntegrationEvent event); + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenanttouched/TenantTouchedIntegrationEventHandlerImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenanttouched/TenantTouchedIntegrationEventHandlerImpl.java new file mode 100644 index 000000000..410c1ee4e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/tenanttouched/TenantTouchedIntegrationEventHandlerImpl.java @@ -0,0 +1,32 @@ +package org.opencdmp.integrationevent.outbox.tenanttouched; + +import org.opencdmp.integrationevent.outbox.OutboxIntegrationEvent; +import org.opencdmp.integrationevent.outbox.OutboxService; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("outboxtenanttouchedintegrationeventhandler") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantTouchedIntegrationEventHandlerImpl implements TenantTouchedIntegrationEventHandler { + + private final OutboxService outboxService; + + public TenantTouchedIntegrationEventHandlerImpl(OutboxService outboxService) { + this.outboxService = outboxService; + } + + @Override + public void handle(TenantTouchedIntegrationEvent event) { + OutboxIntegrationEvent message = new OutboxIntegrationEvent(); + message.setMessageId(UUID.randomUUID()); + message.setType(OutboxIntegrationEvent.TENANT_TOUCH); +// message.setTenantId(event.getId()); //Hack Can not Queue inbox before tenant created + message.setEvent(event); + + this.outboxService.publish(message); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalConsistencyHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalConsistencyHandler.java new file mode 100644 index 000000000..01677d555 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalConsistencyHandler.java @@ -0,0 +1,25 @@ +package org.opencdmp.integrationevent.outbox.userremoval; + +import org.opencdmp.integrationevent.inbox.ConsistencyHandler; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.query.QueryFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component("outboxuserremovalconsistencyhandler") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserRemovalConsistencyHandler implements ConsistencyHandler { + + private final QueryFactory queryFactory; + + public UserRemovalConsistencyHandler(QueryFactory queryFactory) { + this.queryFactory = queryFactory; + } + + @Override + public Boolean isConsistent(UserRemovalConsistencyPredicates consistencyPredicates) { + long count = this.queryFactory.query(UserQuery.class).ids(consistencyPredicates.getUserId()).count(); + return count != 0; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalConsistencyPredicates.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalConsistencyPredicates.java new file mode 100644 index 000000000..4de86e981 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalConsistencyPredicates.java @@ -0,0 +1,21 @@ +package org.opencdmp.integrationevent.outbox.userremoval; + +import org.opencdmp.integrationevent.inbox.ConsistencyPredicates; + +import java.util.UUID; + +public class UserRemovalConsistencyPredicates implements ConsistencyPredicates { + public UserRemovalConsistencyPredicates(UUID userId) { + this.userId = userId; + } + + private UUID userId; + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalIntegrationEvent.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalIntegrationEvent.java new file mode 100644 index 000000000..c37c578de --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalIntegrationEvent.java @@ -0,0 +1,19 @@ +package org.opencdmp.integrationevent.outbox.userremoval; + +import org.opencdmp.integrationevent.TrackedEvent; + +import java.util.UUID; + +public class UserRemovalIntegrationEvent extends TrackedEvent { + + private UUID userId; + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalIntegrationEventHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalIntegrationEventHandler.java new file mode 100644 index 000000000..dc6ab445a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalIntegrationEventHandler.java @@ -0,0 +1,10 @@ +package org.opencdmp.integrationevent.outbox.userremoval; + +import javax.management.InvalidApplicationException; +import java.util.UUID; + +public interface UserRemovalIntegrationEventHandler { + + void handle(UUID userId) throws InvalidApplicationException; + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java new file mode 100644 index 000000000..7bcdd904c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java @@ -0,0 +1,54 @@ +package org.opencdmp.integrationevent.outbox.userremoval; + +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.data.UserEntity; +import org.opencdmp.integrationevent.outbox.OutboxIntegrationEvent; +import org.opencdmp.integrationevent.outbox.OutboxService; +import org.opencdmp.integrationevent.outbox.usertouched.UserTouchedIntegrationEvent; +import org.opencdmp.model.User; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.util.UUID; + +@Component("outboxuserremovalintegrationeventhandler") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserRemovalIntegrationEventHandlerImpl implements UserRemovalIntegrationEventHandler { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserRemovalIntegrationEventHandlerImpl.class)); + + private final OutboxService outboxService; + + private final ApplicationContext applicationContext; + private final TenantScope tenantScope; + + public UserRemovalIntegrationEventHandlerImpl(OutboxService outboxService, ApplicationContext applicationContext, TenantScope tenantScope) { + this.outboxService = outboxService; + this.applicationContext = applicationContext; + this.tenantScope = tenantScope; + } + + @Override + public void handle(UUID userId) throws InvalidApplicationException { + UserRemovalConsistencyHandler userRemovalConsistencyHandler = this.applicationContext.getBean(UserRemovalConsistencyHandler.class); + if (!userRemovalConsistencyHandler.isConsistent(new UserRemovalConsistencyPredicates(userId))) + return; + + OutboxIntegrationEvent message = new OutboxIntegrationEvent(); + message.setMessageId(UUID.randomUUID()); + message.setType(OutboxIntegrationEvent.USER_REMOVE); + if (this.tenantScope.isSet()) message.setTenantId(tenantScope.getTenant()); + UserRemovalIntegrationEvent event = new UserRemovalIntegrationEvent(); + event.setUserId(userId); + message.setEvent(event); + + this.outboxService.publish(message); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/usertouched/UserTouchedIntegrationEvent.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/usertouched/UserTouchedIntegrationEvent.java new file mode 100644 index 000000000..b95d003fe --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/usertouched/UserTouchedIntegrationEvent.java @@ -0,0 +1,164 @@ +package org.opencdmp.integrationevent.outbox.usertouched; + +import org.opencdmp.commons.enums.ContactInfoType; +import org.opencdmp.integrationevent.TrackedEvent; +import org.opencdmp.model.UserContactInfo; + +import java.util.List; +import java.util.UUID; + +public class UserTouchedIntegrationEvent extends TrackedEvent { + + private UUID id; + + private String name; + + private UserProfile profile; + + private List userContactInfo; + private List tenantUsers; + private List credentials; + + 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 UserProfile getProfile() { + return profile; + } + + public void setProfile(UserProfile profile) { + this.profile = profile; + } + + public List getUserContactInfo() { + return userContactInfo; + } + + public void setUserContactInfo(List userContactInfo) { + this.userContactInfo = userContactInfo; + } + + public List getTenantUsers() { + return tenantUsers; + } + + public void setTenantUsers(List tenantUsers) { + this.tenantUsers = tenantUsers; + } + + public List getCredentials() { + return credentials; + } + + public void setCredentials(List credentials) { + this.credentials = credentials; + } + + public static class UserProfile { + + private String timezone; + + private String culture; + + private String language; + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + public String getCulture() { + return culture; + } + + public void setCulture(String culture) { + this.culture = culture; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + } + + public static class UserContactInfo { + + private ContactInfoType type; + + private String value; + private int ordinal; + + public ContactInfoType getType() { + return type; + } + + public void setType(ContactInfoType type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public int getOrdinal() { + return ordinal; + } + + public void setOrdinal(int ordinal) { + this.ordinal = ordinal; + } + } + + + + + public static class UserCredential { + private String subjectId; + + public String getSubjectId() { + return subjectId; + } + + public void setSubjectId(String subjectId) { + this.subjectId = subjectId; + } + } + + public static class TenantUser { + + private UUID tenant; + + public UUID getTenant() { + return tenant; + } + + public void setTenant(UUID tenant) { + this.tenant = tenant; + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/usertouched/UserTouchedIntegrationEventHandler.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/usertouched/UserTouchedIntegrationEventHandler.java new file mode 100644 index 000000000..8e10e3e43 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/usertouched/UserTouchedIntegrationEventHandler.java @@ -0,0 +1,10 @@ +package org.opencdmp.integrationevent.outbox.usertouched; + +import javax.management.InvalidApplicationException; +import java.util.UUID; + +public interface UserTouchedIntegrationEventHandler { + + void handle(UUID userId) throws InvalidApplicationException; + +} diff --git a/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java new file mode 100644 index 000000000..701fa7606 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/integrationevent/outbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java @@ -0,0 +1,127 @@ +package org.opencdmp.integrationevent.outbox.usertouched; + +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.user.AdditionalInfoEntity; +import org.opencdmp.data.*; +import org.opencdmp.elastic.data.DmpElasticEntity; +import org.opencdmp.elastic.elasticbuilder.DmpElasticBuilder; +import org.opencdmp.integrationevent.outbox.OutboxIntegrationEvent; +import org.opencdmp.integrationevent.outbox.OutboxService; +import org.opencdmp.model.*; +import org.opencdmp.model.builder.UserAdditionalInfoBuilder; +import org.opencdmp.query.*; +import gr.cite.tools.data.query.Ordering; +import gr.cite.tools.data.query.Paging; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyNotFoundException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Scope; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Component("outboxusertouchedintegrationeventhandler") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserTouchedIntegrationEventHandlerImpl implements UserTouchedIntegrationEventHandler { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserTouchedIntegrationEventHandlerImpl.class)); + + private final OutboxService outboxService; + private final JsonHandlingService jsonHandlingService; + private final MessageSource messageSource; + private final TenantScope tenantScope; + private final TenantEntityManager entityManager; + + private final QueryFactory queryFactory; + public UserTouchedIntegrationEventHandlerImpl( + OutboxService outboxService, JsonHandlingService jsonHandlingService, MessageSource messageSource, TenantScope tenantScope, TenantEntityManager entityManager, QueryFactory queryFactory) { + this.outboxService = outboxService; + this.jsonHandlingService = jsonHandlingService; + this.messageSource = messageSource; + this.tenantScope = tenantScope; + this.entityManager = entityManager; + this.queryFactory = queryFactory; + } + + @Override + public void handle(UUID userId) throws InvalidApplicationException { + OutboxIntegrationEvent message = new OutboxIntegrationEvent(); + message.setMessageId(UUID.randomUUID()); + message.setType(OutboxIntegrationEvent.USER_TOUCH); + if (this.tenantScope.isSet()) message.setTenantId(tenantScope.getTenant()); + + try { + this.entityManager.disableTenantFilters(); + + UserEntity user = this.queryFactory.query(UserQuery.class).ids(userId) + .firstAs(new BaseFieldSet().ensure(User._name).ensure(User._additionalInfo)); + if (user == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{userId, User.class.getSimpleName()}, LocaleContextHolder.getLocale())); + + List userContactInfoEntities = this.queryFactory.query(UserContactInfoQuery.class).userIds(userId) + .collectAs(new BaseFieldSet().ensure(UserContactInfo._type).ensure(UserContactInfo._ordinal).ensure(UserContactInfo._value)); + + List userCredentialEntities = this.queryFactory.query(UserCredentialQuery.class).userIds(userId) + .collectAs(new BaseFieldSet().ensure(UserCredential._id, UserCredential._externalId)); + + List tenantUserEntities = this.queryFactory.query(TenantUserQuery.class).userIds(userId) + .collectAs(new BaseFieldSet().ensure(TenantUser._id, TenantUser._tenant)); + + UserTouchedIntegrationEvent event = new UserTouchedIntegrationEvent(); + event.setId(userId); + event.setName(user.getName()); + if (userCredentialEntities != null && !userCredentialEntities.isEmpty()) { + event.setCredentials(new ArrayList<>()); + for (UserCredentialEntity userCredential : userCredentialEntities){ + UserTouchedIntegrationEvent.UserCredential userCredentialEvent = new UserTouchedIntegrationEvent.UserCredential(); + userCredentialEvent.setSubjectId(userCredential.getExternalId()); + event.getCredentials().add(userCredentialEvent); + } + } + + if (tenantUserEntities != null && !tenantUserEntities.isEmpty()) { + event.setTenantUsers(new ArrayList<>()); + for (TenantUserEntity tenantUserEntity : tenantUserEntities){ + UserTouchedIntegrationEvent.TenantUser tenantUser = new UserTouchedIntegrationEvent.TenantUser(); + tenantUser.setTenant(tenantUserEntity.getTenantId()); + event.getTenantUsers().add(tenantUser); + } + } + + AdditionalInfoEntity definition = this.jsonHandlingService.fromJsonSafe(AdditionalInfoEntity.class, user.getAdditionalInfo()); + if (definition != null) { + event.setProfile(new UserTouchedIntegrationEvent.UserProfile()); + event.getProfile().setCulture(definition.getCulture()); + event.getProfile().setLanguage(definition.getLanguage()); + event.getProfile().setTimezone(definition.getTimezone()); + } + + if (userContactInfoEntities != null&& !userContactInfoEntities.isEmpty()){ + event.setUserContactInfo(new ArrayList<>()); + for (UserContactInfoEntity contactInfoEntity : userContactInfoEntities){ + UserTouchedIntegrationEvent.UserContactInfo contactInfo = new UserTouchedIntegrationEvent.UserContactInfo(); + contactInfo.setType(contactInfoEntity.getType()); + contactInfo.setValue(contactInfoEntity.getValue()); + contactInfo.setOrdinal(contactInfoEntity.getOrdinal()); + event.getUserContactInfo().add(contactInfo); + } + } + + message.setEvent(event); + }finally { + this.entityManager.enableTenantFilters(); + } + + + this.outboxService.publish(message); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/ActionConfirmation.java b/backend/core/src/main/java/org/opencdmp/model/ActionConfirmation.java new file mode 100644 index 000000000..bcc7dc3b1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/ActionConfirmation.java @@ -0,0 +1,161 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.ActionConfirmationStatus; +import org.opencdmp.commons.enums.ActionConfirmationType; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.model.actionconfirmation.DmpInvitation; +import org.opencdmp.model.actionconfirmation.MergeAccountConfirmation; +import org.opencdmp.model.actionconfirmation.RemoveCredentialRequest; +import org.opencdmp.model.persist.actionconfirmation.MergeAccountConfirmationPersist; +import org.opencdmp.model.persist.actionconfirmation.RemoveCredentialRequestPersist; + +import java.time.Instant; +import java.util.UUID; + +public class ActionConfirmation { + + private UUID id; + public static final String _id = "id"; + + private ActionConfirmationType type; + public static final String _type = "type"; + + private ActionConfirmationStatus status; + public static final String _status = "status"; + private MergeAccountConfirmation mergeAccountConfirmation; + + public static final String _mergeAccountConfirmation = "mergeAccountConfirmation"; + + private RemoveCredentialRequest removeCredentialRequest; + + public static final String _removeCredentialRequest = "removeCredentialRequest"; + + private DmpInvitation dmpInvitation; + public static final String _dmpInvitation = "dmpInvitation"; + + private Instant expiresAt; + public static final String _expiresAt = "expiresAt"; + + private User createdBy; + public static final String _createdBy = "createdBy"; + + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + + private IsActive isActive; + public static final String _isActive = "isActive"; + + private String hash; + public static final String _hash = "hash"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public ActionConfirmationType getType() { + return type; + } + + public void setType(ActionConfirmationType type) { + this.type = type; + } + + public ActionConfirmationStatus getStatus() { + return status; + } + + public void setStatus(ActionConfirmationStatus status) { + this.status = status; + } + + public DmpInvitation getDmpInvitation() { + return dmpInvitation; + } + + public void setDmpInvitation(DmpInvitation dmpInvitation) { + this.dmpInvitation = dmpInvitation; + } + + public Instant getExpiresAt() { + return expiresAt; + } + + public void setExpiresAt(Instant expiresAt) { + this.expiresAt = expiresAt; + } + + public User getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(User createdBy) { + this.createdBy = createdBy; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } + + public MergeAccountConfirmation getMergeAccountConfirmation() { + return mergeAccountConfirmation; + } + + public void setMergeAccountConfirmation(MergeAccountConfirmation mergeAccountConfirmation) { + this.mergeAccountConfirmation = mergeAccountConfirmation; + } + + public RemoveCredentialRequest getRemoveCredentialRequest() { + return removeCredentialRequest; + } + + public void setRemoveCredentialRequest(RemoveCredentialRequest removeCredentialRequest) { + this.removeCredentialRequest = removeCredentialRequest; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DashboardReferenceTypeStatistics.java b/backend/core/src/main/java/org/opencdmp/model/DashboardReferenceTypeStatistics.java new file mode 100644 index 000000000..86c51b70e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DashboardReferenceTypeStatistics.java @@ -0,0 +1,27 @@ +package org.opencdmp.model; + +public class DashboardReferenceTypeStatistics { + + private long count; + + public static final String _count = "count"; + + private PublicReferenceType referenceType; + + public static final String _referenceType = "referenceType"; + public long getCount() { + return count; + } + + public void setCount(long count) { + this.count = count; + } + + public PublicReferenceType getReferenceType() { + return referenceType; + } + + public void setReferenceType(PublicReferenceType referenceType) { + this.referenceType = referenceType; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DashboardStatistics.java b/backend/core/src/main/java/org/opencdmp/model/DashboardStatistics.java new file mode 100644 index 000000000..94dab28d6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DashboardStatistics.java @@ -0,0 +1,39 @@ +package org.opencdmp.model; + +import java.util.List; +import java.util.UUID; + +public class DashboardStatistics { + + private long dmpCount; + + public static final String _dmpCount = "dmpCount"; + + private long descriptionCount; + + private List referenceTypeStatistics; + + public long getDmpCount() { + return dmpCount; + } + + public void setDmpCount(long dmpCount) { + this.dmpCount = dmpCount; + } + + public long getDescriptionCount() { + return descriptionCount; + } + + public void setDescriptionCount(long descriptionCount) { + this.descriptionCount = descriptionCount; + } + + public List getReferenceTypeStatistics() { + return referenceTypeStatistics; + } + + public void setReferenceTypeStatistics(List referenceTypeStatistics) { + this.referenceTypeStatistics = referenceTypeStatistics; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/Description.java b/backend/core/src/main/java/org/opencdmp/model/Description.java new file mode 100644 index 000000000..c9c777b7a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/Description.java @@ -0,0 +1,228 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DescriptionStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.model.descriptionproperties.PropertyDefinition; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public class Description { + + private UUID id; + + public static final String _id = "id"; + + private String label; + + public static final String _label = "label"; + + private PropertyDefinition properties; + + public static final String _properties = "properties"; + + + private DescriptionStatus status; + + public static final String _status = "status"; + + private String description; + + public static final String _description = "description"; + + private User createdBy; + + public static final String _createdBy = "createdBy"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + + public static final String _isActive = "isActive"; + + private Instant finalizedAt; + + public static final String _finalizedAt = "finalizedAt"; + + private String hash; + + public static final String _hash = "hash"; + + private List descriptionReferences; + + public static final String _descriptionReferences = "descriptionReferences"; + + private List descriptionTags; + + public static final String _descriptionTags = "descriptionTags"; + + private DmpDescriptionTemplate dmpDescriptionTemplate; + + public static final String _dmpDescriptionTemplate = "dmpDescriptionTemplate"; + + private DescriptionTemplate descriptionTemplate; + + public static final String _descriptionTemplate = "descriptionTemplate"; + + private List authorizationFlags; + public static final String _authorizationFlags = "authorizationFlags"; + + private Dmp dmp; + + public static final String _dmp = "dmp"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 PropertyDefinition getProperties() { + return properties; + } + + public void setProperties(PropertyDefinition properties) { + this.properties = properties; + } + + public DescriptionStatus getStatus() { + return status; + } + + public void setStatus(DescriptionStatus status) { + this.status = status; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public User getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(User createdBy) { + this.createdBy = createdBy; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Instant finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public List getDescriptionReferences() { + return descriptionReferences; + } + + public void setDescriptionReferences(List descriptionReferences) { + this.descriptionReferences = descriptionReferences; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public DmpDescriptionTemplate getDmpDescriptionTemplate() { + return dmpDescriptionTemplate; + } + + public void setDmpDescriptionTemplate(DmpDescriptionTemplate dmpDescriptionTemplate) { + this.dmpDescriptionTemplate = dmpDescriptionTemplate; + } + + public List getDescriptionTags() { + return descriptionTags; + } + + public void setDescriptionTags(List descriptionTags) { + this.descriptionTags = descriptionTags; + } + + public Dmp getDmp() { + return dmp; + } + + public void setDmp(Dmp dmp) { + this.dmp = dmp; + } + + public DescriptionTemplate getDescriptionTemplate() { + return descriptionTemplate; + } + + public void setDescriptionTemplate(DescriptionTemplate descriptionTemplate) { + this.descriptionTemplate = descriptionTemplate; + } + + public List getAuthorizationFlags() { + return authorizationFlags; + } + + public void setAuthorizationFlags(List authorizationFlags) { + this.authorizationFlags = authorizationFlags; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DescriptionReference.java b/backend/core/src/main/java/org/opencdmp/model/DescriptionReference.java new file mode 100644 index 000000000..e2e6dfc8b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DescriptionReference.java @@ -0,0 +1,117 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.model.descriptionreference.DescriptionReferenceData; +import org.opencdmp.model.dmpreference.DmpReferenceData; + +import java.time.Instant; +import java.util.UUID; + +public class DescriptionReference { + + private UUID id; + + public static final String _id = "id"; + + private Description description; + + public static final String _description = "description"; + + private Reference reference; + + public static final String _reference = "reference"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + + public static final String _isActive = "isActive"; + + private String hash; + + public static final String _hash = "hash"; + + private DescriptionReferenceData data; + public static final String _data = "data"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public Description getDescription() { + return description; + } + + public void setDescription(Description description) { + this.description = description; + } + + public Reference getReference() { + return reference; + } + + public void setReference(Reference reference) { + this.reference = reference; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public DescriptionReferenceData getData() { + return data; + } + + public void setData(DescriptionReferenceData data) { + this.data = data; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DescriptionTag.java b/backend/core/src/main/java/org/opencdmp/model/DescriptionTag.java new file mode 100644 index 000000000..3123a1330 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DescriptionTag.java @@ -0,0 +1,104 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; + +import java.time.Instant; +import java.util.UUID; + +public class DescriptionTag { + + private UUID id; + + public static final String _id = "id"; + + private Description description; + + public static final String _description = "description"; + + private Tag tag; + + public static final String _tag = "tag"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + + public static final String _isActive = "isActive"; + + private String hash; + + public static final String _hash = "hash"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public Description getDescription() { + return description; + } + + public void setDescription(Description description) { + this.description = description; + } + + public Tag getTag() { + return tag; + } + + public void setTag(Tag tag) { + this.tag = tag; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DescriptionTemplate.java b/backend/core/src/main/java/org/opencdmp/model/DescriptionTemplate.java new file mode 100644 index 000000000..6e04ba948 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DescriptionTemplate.java @@ -0,0 +1,190 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DescriptionTemplateStatus; +import org.opencdmp.commons.enums.DescriptionTemplateTypeStatus; +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.model.descriptiontemplatedefinition.Definition; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public class DescriptionTemplate { + + public final static String _id = "id"; + private UUID id; + + public final static String _label = "label"; + private String label; + + public final static String _description = "description"; + private String description; + + public final static String _groupId = "groupId"; + private UUID groupId; + + public static final String _versionStatus = "versionStatus"; + private DescriptionTemplateVersionStatus versionStatus; + + public final static String _version = "version"; + private Short version; + + public final static String _language = "language"; + private String language; + + public final static String _type = "type"; + private DescriptionTemplateType type; + + public final static String _definition = "definition"; + private Definition definition; + + public final static String _createdAt = "createdAt"; + private Instant createdAt; + + public final static String _updatedAt = "updatedAt"; + private Instant updatedAt; + + public final static String _isActive = "isActive"; + private IsActive isActive; + + public final static String _status = "status"; + private DescriptionTemplateStatus status; + + public final static String _users = "users"; + private List users; + + public final static String _hash = "hash"; + private String hash; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 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 Definition getDefinition() { + return definition; + } + + public void setDefinition(Definition definition) { + this.definition = definition; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public DescriptionTemplateStatus getStatus() { + return status; + } + + public void setStatus(DescriptionTemplateStatus status) { + this.status = status; + } + + public List getUsers() { + return users; + } + + public void setUsers(List users) { + this.users = users; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public DescriptionTemplateVersionStatus getVersionStatus() { + return versionStatus; + } + + public void setVersionStatus(DescriptionTemplateVersionStatus versionStatus) { + this.versionStatus = versionStatus; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DescriptionTemplateType.java b/backend/core/src/main/java/org/opencdmp/model/DescriptionTemplateType.java new file mode 100644 index 000000000..f51aec8fb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DescriptionTemplateType.java @@ -0,0 +1,110 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DescriptionTemplateTypeStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.model.descriptiontemplatedefinition.Definition; + +import java.time.Instant; +import java.util.UUID; + +public class DescriptionTemplateType { + + public final static String _id = "id"; + private UUID id; + + public final static String _name = "name"; + private String name; + + public final static String _createdAt = "createdAt"; + private Instant createdAt; + + public final static String _updatedAt = "updatedAt"; + private Instant updatedAt; + + public final static String _isActive = "isActive"; + private IsActive isActive; + + public final static String _status = "status"; + private DescriptionTemplateTypeStatus status; + + public final static String _definition = "definition"; + private Definition definition; + + public final static String _hash = "hash"; + private String hash; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public DescriptionTemplateTypeStatus getStatus() { + return status; + } + + public void setStatus(DescriptionTemplateTypeStatus status) { + this.status = status; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Definition getDefinition() { + return definition; + } + + public void setDefinition(Definition definition) { + this.definition = definition; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DescriptionValidationResult.java b/backend/core/src/main/java/org/opencdmp/model/DescriptionValidationResult.java new file mode 100644 index 000000000..468f0c6b4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DescriptionValidationResult.java @@ -0,0 +1,40 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DescriptionValidationOutput; + +import java.util.UUID; + +public class DescriptionValidationResult { + + private UUID descriptionId; + + public static final String _id = "id"; + + private DescriptionValidationOutput result; + + public static final String _result = "result"; + + public DescriptionValidationResult() { + } + + public DescriptionValidationResult(UUID descriptionId, DescriptionValidationOutput result) { + this.descriptionId = descriptionId; + this.result = result; + } + + public UUID getDescriptionId() { + return descriptionId; + } + + public void setDescriptionId(UUID descriptionId) { + this.descriptionId = descriptionId; + } + + public DescriptionValidationOutput getResult() { + return result; + } + + public void setResult(DescriptionValidationOutput result) { + this.result = result; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DescriptionsToBeFinalized.java b/backend/core/src/main/java/org/opencdmp/model/DescriptionsToBeFinalized.java new file mode 100644 index 000000000..582b2b032 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DescriptionsToBeFinalized.java @@ -0,0 +1,17 @@ +package org.opencdmp.model; + +import java.util.List; +import java.util.UUID; + +public class DescriptionsToBeFinalized { + + private List descriptionIds; + + public List getDescriptionIds() { + return descriptionIds; + } + + public void setDescriptionIds(List descriptionIds) { + this.descriptionIds = descriptionIds; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/Dmp.java b/backend/core/src/main/java/org/opencdmp/model/Dmp.java new file mode 100644 index 000000000..4794ff56d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/Dmp.java @@ -0,0 +1,301 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DmpAccessType; +import org.opencdmp.commons.enums.DmpStatus; +import org.opencdmp.commons.enums.DmpVersionStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.model.dmpproperties.DmpProperties; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public class Dmp { + + private UUID id; + public static final String _id = "id"; + + private String label; + public static final String _label = "label"; + + private Short version; + public static final String _version = "version"; + + private DmpStatus status; + public static final String _status = "status"; + + private DmpVersionStatus versionStatus; + public static final String _versionStatus = "versionStatus"; + + private DmpProperties properties; + public static final String _properties = "properties"; + + private UUID groupId; + public static final String _groupId = "groupId"; + + private String description; + public static final String _description = "description"; + + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + public static final String _isActive = "isActive"; + + private Instant finalizedAt; + public static final String _finalizedAt = "finalizedAt"; + + private Instant publishedAt; + public static final String _publishedAt = "publishedAt"; + + private User creator; + public static final String _creator = "creator"; + + private DmpAccessType accessType; + public static final String _accessType = "accessType"; + + private DmpBlueprint blueprint; + public static final String _blueprint = "blueprint"; + + private String language; + public static final String _language = "language"; + + private Instant publicAfter; + public static final String _publicAfter = "publicAfter"; + + private String hash; + public static final String _hash = "hash"; + + private List dmpReferences; + public static final String _dmpReferences = "dmpReferences"; + + private List dmpUsers; + public static final String _dmpUsers = "dmpUsers"; + + private List descriptions; + public static final String _descriptions = "descriptions"; + + private List dmpDescriptionTemplates; + public static final String _dmpDescriptionTemplates = "dmpDescriptionTemplates"; + + private List entityDois; + public static final String _entityDois = "entityDois"; + + private List authorizationFlags; + public static final String _authorizationFlags = "authorizationFlags"; + + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 Short getVersion() { + return version; + } + + public void setVersion(Short version) { + this.version = version; + } + + public DmpStatus getStatus() { + return status; + } + + public void setStatus(DmpStatus status) { + this.status = status; + } + + public DmpProperties getProperties() { + return properties; + } + + public void setProperties(DmpProperties properties) { + this.properties = properties; + } + + public UUID getGroupId() { + return groupId; + } + + public void setGroupId(UUID groupId) { + this.groupId = groupId; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Instant finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public Instant getPublishedAt() { + return publishedAt; + } + + public void setPublishedAt(Instant publishedAt) { + this.publishedAt = publishedAt; + } + + public User getCreator() { + return creator; + } + + public void setCreator(User creator) { + this.creator = creator; + } + + public DmpAccessType getAccessType() { + return accessType; + } + + public void setAccessType(DmpAccessType accessType) { + this.accessType = accessType; + } + + public DmpBlueprint getBlueprint() { + return blueprint; + } + + public void setBlueprint(DmpBlueprint blueprint) { + this.blueprint = blueprint; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public Instant getPublicAfter() { + return publicAfter; + } + + public void setPublicAfter(Instant publicAfter) { + this.publicAfter = publicAfter; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public List getDmpReferences() { + return dmpReferences; + } + + public void setDmpReferences(List dmpReferences) { + this.dmpReferences = dmpReferences; + } + + public List getDmpUsers() { + return dmpUsers; + } + + public void setDmpUsers(List dmpUsers) { + this.dmpUsers = dmpUsers; + } + + public DmpVersionStatus getVersionStatus() { + return versionStatus; + } + + public void setVersionStatus(DmpVersionStatus versionStatus) { + this.versionStatus = versionStatus; + } + + public List getDescriptions() { + return descriptions; + } + + public void setDescriptions(List descriptions) { + this.descriptions = descriptions; + } + + public List getDmpDescriptionTemplates() { + return dmpDescriptionTemplates; + } + + public void setDmpDescriptionTemplates(List dmpDescriptionTemplates) { + this.dmpDescriptionTemplates = dmpDescriptionTemplates; + } + + public List getEntityDois() { + return entityDois; + } + + public void setEntityDois(List entityDois) { + this.entityDois = entityDois; + } + + public List getAuthorizationFlags() { + return authorizationFlags; + } + + public void setAuthorizationFlags(List authorizationFlags) { + this.authorizationFlags = authorizationFlags; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DmpAssociatedUser.java b/backend/core/src/main/java/org/opencdmp/model/DmpAssociatedUser.java new file mode 100644 index 000000000..aee9a1111 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DmpAssociatedUser.java @@ -0,0 +1,39 @@ +package org.opencdmp.model; + +import java.util.UUID; + +public class DmpAssociatedUser { + + private UUID id; + public static final String _id = "id"; + + private String name; + public static final String _name = "name"; + + private String email; + public static final String _email = "email"; + + 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 getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DmpBlueprint.java b/backend/core/src/main/java/org/opencdmp/model/DmpBlueprint.java new file mode 100644 index 000000000..7ce1a5e11 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DmpBlueprint.java @@ -0,0 +1,155 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DmpBlueprintStatus; +import org.opencdmp.commons.enums.DmpBlueprintVersionStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.model.dmpblueprintdefinition.Definition; + +import java.time.Instant; +import java.util.UUID; + +public class DmpBlueprint { + + private UUID id; + + public static final String _id = "id"; + + private String label; + + public static final String _label = "label"; + + private Definition definition; + + public static final String _definition = "definition"; + + private DmpBlueprintStatus status; + + public static final String _status = "status"; + + private UUID groupId; + + public static final String _groupId = "groupId"; + + private Short version; + + public static final String _version = "version"; + + private DmpBlueprintVersionStatus versionStatus; + + public static final String _versionStatus = "versionStatus"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + + public static final String _isActive = "isActive"; + + private String hash; + + public static final String _hash = "hash"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 Definition getDefinition() { + return definition; + } + + public void setDefinition(Definition definition) { + this.definition = definition; + } + + public DmpBlueprintStatus getStatus() { + return status; + } + + public void setStatus(DmpBlueprintStatus status) { + this.status = status; + } + + 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 DmpBlueprintVersionStatus getVersionStatus() { + return versionStatus; + } + + public void setVersionStatus(DmpBlueprintVersionStatus versionStatus) { + this.versionStatus = versionStatus; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DmpDescriptionTemplate.java b/backend/core/src/main/java/org/opencdmp/model/DmpDescriptionTemplate.java new file mode 100644 index 000000000..085bd4a6c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DmpDescriptionTemplate.java @@ -0,0 +1,141 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public class DmpDescriptionTemplate{ + + private UUID id; + + public static final String _id = "id"; + + private Dmp dmp; + + public static final String _dmp = "dmp"; + + private DescriptionTemplate currentDescriptionTemplate; + + public static final String _currentDescriptionTemplate = "currentDescriptionTemplate"; + + + private List descriptionTemplates; + + public static final String _descriptionTemplates = "descriptionTemplates"; + + private UUID sectionId; + + public static final String _sectionId = "sectionId"; + + private UUID descriptionTemplateGroupId; + + public static final String _descriptionTemplateGroupId = "descriptionTemplateGroupId"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + + public static final String _isActive = "isActive"; + + public final static String _hash = "hash"; + private String hash; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 getCurrentDescriptionTemplate() { + return currentDescriptionTemplate; + } + + public void setCurrentDescriptionTemplate(DescriptionTemplate currentDescriptionTemplate) { + this.currentDescriptionTemplate = currentDescriptionTemplate; + } + + public List getDescriptionTemplates() { + return descriptionTemplates; + } + + public void setDescriptionTemplates(List descriptionTemplates) { + this.descriptionTemplates = descriptionTemplates; + } + + public UUID getDescriptionTemplateGroupId() { + return descriptionTemplateGroupId; + } + + public void setDescriptionTemplateGroupId(UUID descriptionTemplateGroupId) { + this.descriptionTemplateGroupId = descriptionTemplateGroupId; + } + + public UUID getSectionId() { + return sectionId; + } + + public void setSectionId(UUID sectionId) { + this.sectionId = sectionId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DmpReference.java b/backend/core/src/main/java/org/opencdmp/model/DmpReference.java new file mode 100644 index 000000000..c0b7794ad --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DmpReference.java @@ -0,0 +1,102 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.model.dmpreference.DmpReferenceData; + +import java.time.Instant; +import java.util.UUID; + +public class DmpReference { + + private UUID id; + public static final String _id = "id"; + + private Dmp dmp; + public static final String _dmp = "dmp"; + + private Reference reference; + public static final String _reference = "reference"; + + private IsActive isActive; + public static final String _isActive = "isActive"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + public final static String _hash = "hash"; + private String hash; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + private DmpReferenceData data; + public static final String _data = "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 Reference getReference() { + return reference; + } + + public void setReference(Reference reference) { + this.reference = reference; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { return createdAt;} + + public void setCreatedAt(Instant createdAt) {this.createdAt = createdAt;} + + public Instant getUpdatedAt() {return updatedAt;} + + public void setUpdatedAt(Instant updatedAt) {this.updatedAt = updatedAt;} + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public void setData(DmpReferenceData data) { + this.data = data; + } + + public DmpReferenceData getData() { + return data; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DmpUser.java b/backend/core/src/main/java/org/opencdmp/model/DmpUser.java new file mode 100644 index 000000000..d97017170 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DmpUser.java @@ -0,0 +1,129 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DmpUserRole; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.converters.enums.IsActiveConverter; +import org.opencdmp.data.UserEntity; +import jakarta.persistence.*; + +import java.time.Instant; +import java.util.UUID; + +public class DmpUser { + + private UUID id; + + public static final String _id = "id"; + + private Dmp dmp; + + public static final String _dmp = "dmp"; + + private User user; + + public static final String _user = "user"; + + private String hash; + public final static String _hash = "hash"; + + private DmpUserRole role; + + public static final String _role = "role"; + + private UUID sectionId; + public static final String _sectionId = "sectionId"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + public static final String _isActive = "isActive"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public DmpUserRole getRole() { + return role; + } + + public void setRole(DmpUserRole role) { + this.role = role; + } + + public UUID getSectionId() { + return sectionId; + } + + public void setSectionId(UUID sectionId) { + this.sectionId = sectionId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/DmpValidationResult.java b/backend/core/src/main/java/org/opencdmp/model/DmpValidationResult.java new file mode 100644 index 000000000..874dfbc2e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/DmpValidationResult.java @@ -0,0 +1,51 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DmpValidationOutput; + +import java.util.List; +import java.util.UUID; + +public class DmpValidationResult { + + private UUID id; + + public static final String _id = "id"; + + private DmpValidationOutput result; + + private List errors; + + public static final String _result = "result"; + + public DmpValidationResult() { + } + + public DmpValidationResult(UUID id, DmpValidationOutput result) { + this.id = id; + this.result = result; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public DmpValidationOutput getResult() { + return result; + } + + public void setResult(DmpValidationOutput result) { + this.result = result; + } + + public List getErrors() { + return errors; + } + + public void setErrors(List errors) { + this.errors = errors; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/EntityDoi.java b/backend/core/src/main/java/org/opencdmp/model/EntityDoi.java new file mode 100644 index 000000000..05a9ae262 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/EntityDoi.java @@ -0,0 +1,130 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.EntityType; +import org.opencdmp.commons.enums.IsActive; + +import java.time.Instant; +import java.util.Date; +import java.util.UUID; + +public class EntityDoi { + + private UUID id; + + public static final String _id = "id"; + + private EntityType entityType; + + public static final String _entityType = "entityType"; + + private String repositoryId; + + public static final String _repositoryId = "repositoryId"; + + private String doi; + + public static final String _doi = "doi"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + + public static final String _isActive = "isActive"; + + private UUID entityId; + + public static final String _entityId = "entityId"; + + private String hash; + + public static final String _hash = "hash"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public UUID getEntityId() { + return entityId; + } + + public void setEntityId(UUID entityId) { + this.entityId = entityId; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/Language.java b/backend/core/src/main/java/org/opencdmp/model/Language.java new file mode 100644 index 000000000..ccc2b1066 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/Language.java @@ -0,0 +1,108 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; + +import java.time.Instant; +import java.util.UUID; + +public class Language { + + private UUID id; + public static final String _id = "id"; + + private String code; + public static final String _code = "code"; + + private String payload; + public static final String _payload = "payload"; + + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + public static final String _isActive = "isActive"; + + private Integer ordinal; + public static final String _ordinal = "ordinal"; + + private String hash; + public final static String _hash = "hash"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getPayload() { + return payload; + } + + public void setPayload(String payload) { + this.payload = payload; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Integer getOrdinal() { + return ordinal; + } + + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/Lock.java b/backend/core/src/main/java/org/opencdmp/model/Lock.java new file mode 100644 index 000000000..74cbf05ae --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/Lock.java @@ -0,0 +1,98 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.LockTargetType; + +import java.time.Instant; +import java.util.UUID; + +public class Lock { + + private UUID id; + public static final String _id = "id"; + + private UUID target; + public static final String _target = "target"; + + private LockTargetType targetType; + public static final String _targetType = "targetType"; + + private User lockedBy; + public static final String _lockedBy = "lockedBy"; + + private Instant lockedAt; + public static final String _lockedAt = "lockedAt"; + + private Instant touchedAt; + public static final String _touchedAt = "touchedAt"; + + private String hash; + + public static final String _hash = "hash"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 LockTargetType getTargetType() { + return targetType; + } + + public void setTargetType(LockTargetType targetType) { + this.targetType = targetType; + } + + public User getLockedBy() { + return lockedBy; + } + + public void setLockedBy(User lockedBy) { + this.lockedBy = lockedBy; + } + + public Instant getLockedAt() { + return lockedAt; + } + + public void setLockedAt(Instant lockedAt) { + this.lockedAt = lockedAt; + } + + public Instant getTouchedAt() { + return touchedAt; + } + + public void setTouchedAt(Instant touchedAt) { + this.touchedAt = touchedAt; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/LockStatus.java b/backend/core/src/main/java/org/opencdmp/model/LockStatus.java new file mode 100644 index 000000000..605e09ccb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/LockStatus.java @@ -0,0 +1,24 @@ +package org.opencdmp.model; + +public class LockStatus { + + Boolean status; + + Lock lock; + + public Boolean getStatus() { + return status; + } + + public void setStatus(Boolean status) { + this.status = status; + } + + public Lock getLock() { + return lock; + } + + public void setLock(Lock lock) { + this.lock = lock; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/Prefilling.java b/backend/core/src/main/java/org/opencdmp/model/Prefilling.java new file mode 100644 index 000000000..5ce846f4d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/Prefilling.java @@ -0,0 +1,59 @@ +package org.opencdmp.model; + +import java.util.Map; + +public class Prefilling { + + private String id; + public static final String _id = "reference_id"; + + private String label; + public static final String _label = "label"; + + private Map data; + public static final String _data = "data"; + private String key; + public static final String _key = "key"; + private String tag; + public static final String _tag = "tag"; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public Map getData() { + return data; + } + + public void setData(Map data) { + this.data = data; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/PrefillingLookup.java b/backend/core/src/main/java/org/opencdmp/model/PrefillingLookup.java new file mode 100644 index 000000000..d7f9beac0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PrefillingLookup.java @@ -0,0 +1,23 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.query.UserQuery; +import org.opencdmp.query.lookup.UserRoleLookup; +import gr.cite.tools.data.query.Lookup; +import gr.cite.tools.data.query.QueryFactory; + +import java.util.List; +import java.util.UUID; + +public class PrefillingLookup extends Lookup { + private String like; + + public String getLike() { + return like; + } + + public void setLike(String like) { + this.like = like; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/PrefillingSource.java b/backend/core/src/main/java/org/opencdmp/model/PrefillingSource.java new file mode 100644 index 000000000..7b6e6327d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PrefillingSource.java @@ -0,0 +1,98 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.model.prefillingsourcedefinition.PrefillingSourceDefinition; + +import java.time.Instant; +import java.util.UUID; + +public class PrefillingSource { + + private UUID id; + public static final String _id = "id"; + + private String label; + public static final String _label = "label"; + + private PrefillingSourceDefinition definition; + public static final String _definition = "definition"; + + private IsActive isActive; + public static final String _isActive = "isActive"; + + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + public final static String _hash = "hash"; + private String hash; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 PrefillingSourceDefinition getDefinition() { + return definition; + } + + public void setDefinition(PrefillingSourceDefinition definition) { + this.definition = definition; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/PublicDescription.java b/backend/core/src/main/java/org/opencdmp/model/PublicDescription.java new file mode 100644 index 000000000..390225e9d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PublicDescription.java @@ -0,0 +1,131 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DescriptionStatus; + +import java.time.Instant; +import java.util.UUID; + +public class PublicDescription { + + private UUID id; + + public static final String _id = "id"; + + private String label; + + public static final String _label = "label"; + + private DescriptionStatus status; + + public static final String _status = "status"; + + private String description; + + public static final String _description = "description"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + private Instant finalizedAt; + + public static final String _finalizedAt = "finalizedAt"; + + private PublicDmpDescriptionTemplate dmpDescriptionTemplate; + + public static final String _dmpDescriptionTemplate = "dmpDescriptionTemplate"; + + private PublicDescriptionTemplate descriptionTemplate; + + public static final String _descriptionTemplate = "descriptionTemplate"; + + private PublicDmp dmp; + + public static final String _dmp = "dmp"; + + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + + public DescriptionStatus getStatus() { + return status; + } + + public void setStatus(DescriptionStatus status) { + this.status = status; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public Instant getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Instant finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public PublicDmpDescriptionTemplate getDmpDescriptionTemplate() { + return dmpDescriptionTemplate; + } + + public void setDmpDescriptionTemplate(PublicDmpDescriptionTemplate dmpDescriptionTemplate) { + this.dmpDescriptionTemplate = dmpDescriptionTemplate; + } + + public PublicDescriptionTemplate getDescriptionTemplate() { + return descriptionTemplate; + } + + public void setDescriptionTemplate(PublicDescriptionTemplate descriptionTemplate) { + this.descriptionTemplate = descriptionTemplate; + } + + public PublicDmp getDmp() { + return dmp; + } + + public void setDmp(PublicDmp dmp) { + this.dmp = dmp; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/PublicDescriptionTemplate.java b/backend/core/src/main/java/org/opencdmp/model/PublicDescriptionTemplate.java new file mode 100644 index 000000000..6707661da --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PublicDescriptionTemplate.java @@ -0,0 +1,46 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DescriptionTemplateStatus; +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.model.descriptiontemplatedefinition.Definition; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public class PublicDescriptionTemplate { + + public final static String _id = "id"; + private UUID id; + + public final static String _label = "label"; + private String label; + + public final static String _description = "description"; + private String description; + + 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; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/PublicDmp.java b/backend/core/src/main/java/org/opencdmp/model/PublicDmp.java new file mode 100644 index 000000000..82a7875b9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PublicDmp.java @@ -0,0 +1,174 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DmpAccessType; +import org.opencdmp.commons.enums.DmpStatus; +import org.opencdmp.commons.enums.IsActive; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public class PublicDmp { + + private UUID id; + + public static final String _id = "id"; + + private String label; + + public static final String _label = "label"; + + private Short version; + + public static final String _version = "version"; + + private String description; + + public static final String _description = "description"; + + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + private Instant finalizedAt; + + public static final String _finalizedAt = "finalizedAt"; + + private Instant publishedAt; + + public static final String _publishedAt = "publishedAt"; + + private DmpStatus status; + public static final String _status = "status"; + + private UUID groupId; + public static final String _groupId = "groupId"; + + private DmpAccessType accessType; + public static final String _accessType = "accessType"; + + private List dmpUsers; + + public static final String _dmpUsers = "dmpUsers"; + + private List dmpReferences; + + public static final String _dmpReferences = "dmpReferences"; + + private List descriptions; + public static final String _descriptions = "descriptions"; + + private List entityDois; + public static final String _entityDois = "entityDois"; + + 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 Short getVersion() { + return version; + } + + public void setVersion(Short version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public Instant getFinalizedAt() { + return finalizedAt; + } + + public void setFinalizedAt(Instant finalizedAt) { + this.finalizedAt = finalizedAt; + } + + public Instant getPublishedAt() { + return publishedAt; + } + + public void setPublishedAt(Instant publishedAt) { + this.publishedAt = publishedAt; + } + + public DmpStatus getStatus() { + return status; + } + + public void setStatus(DmpStatus status) { + this.status = status; + } + + public UUID getGroupId() { + return groupId; + } + + public void setGroupId(UUID groupId) { + this.groupId = groupId; + } + + public DmpAccessType getAccessType() { + return accessType; + } + + public void setAccessType(DmpAccessType accessType) { + this.accessType = accessType; + } + + public List getDmpUsers() { + return dmpUsers; + } + + public void setDmpUsers(List dmpUsers) { + this.dmpUsers = dmpUsers; + } + + public List getDmpReferences() { + return dmpReferences; + } + + public void setDmpReferences(List dmpReferences) { + this.dmpReferences = dmpReferences; + } + + public List getDescriptions() { + return descriptions; + } + + public void setDescriptions(List descriptions) { + this.descriptions = descriptions; + } + + public List getEntityDois() { + return entityDois; + } + + public void setEntityDois(List entityDois) { + this.entityDois = entityDois; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/PublicDmpDescriptionTemplate.java b/backend/core/src/main/java/org/opencdmp/model/PublicDmpDescriptionTemplate.java new file mode 100644 index 000000000..6e3e07e3d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PublicDmpDescriptionTemplate.java @@ -0,0 +1,34 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; + +import java.time.Instant; +import java.util.UUID; + +public class PublicDmpDescriptionTemplate { + + private UUID id; + + public static final String _id = "id"; + + private PublicDmp dmp; + + public static final String _dmp = "dmp"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public PublicDmp getDmp() { + return dmp; + } + + public void setDmp(PublicDmp dmp) { + this.dmp = dmp; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/PublicDmpReference.java b/backend/core/src/main/java/org/opencdmp/model/PublicDmpReference.java new file mode 100644 index 000000000..e12fd708b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PublicDmpReference.java @@ -0,0 +1,53 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; + +import java.time.Instant; +import java.util.UUID; + +public class PublicDmpReference { + + private UUID id; + public static final String _id = "id"; + + private PublicDmp dmp; + public static final String _dmp = "dmp"; + + private PublicReference reference; + public static final String _reference = "reference"; + + private IsActive isActive; + public static final String _isActive = "isActive"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public PublicDmp getDmp() { + return dmp; + } + + public void setDmp(PublicDmp dmp) { + this.dmp = dmp; + } + + public PublicReference getReference() { + return reference; + } + + public void setReference(PublicReference reference) { + this.reference = reference; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/PublicDmpUser.java b/backend/core/src/main/java/org/opencdmp/model/PublicDmpUser.java new file mode 100644 index 000000000..ecd6befbb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PublicDmpUser.java @@ -0,0 +1,54 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DmpUserRole; +import java.util.UUID; + +public class PublicDmpUser { + + public static final String _id = "id"; + private UUID id; + + + public static final String _dmp = "dmp"; + private PublicDmp dmp; + + + public static final String _user = "user"; + private PublicUser user; + + + public static final String _role = "role"; + private DmpUserRole role; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public PublicDmp getDmp() { + return dmp; + } + + public void setDmp(PublicDmp dmp) { + this.dmp = dmp; + } + + public PublicUser getUser() { + return user; + } + + public void setUser(PublicUser user) { + this.user = user; + } + + public DmpUserRole getRole() { + return role; + } + + public void setRole(DmpUserRole role) { + this.role = role; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/PublicEntityDoi.java b/backend/core/src/main/java/org/opencdmp/model/PublicEntityDoi.java new file mode 100644 index 000000000..7c705d6a3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PublicEntityDoi.java @@ -0,0 +1,69 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.EntityType; + +import java.util.UUID; + +public class PublicEntityDoi { + + private UUID id; + + public static final String _id = "id"; + + private EntityType entityType; + + public static final String _entityType = "entityType"; + + private String repositoryId; + + public static final String _repositoryId = "repositoryId"; + + private String doi; + + public static final String _doi = "doi"; + + private UUID entityId; + + public static final String _entityId = "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 UUID getEntityId() { + return entityId; + } + + public void setEntityId(UUID entityId) { + this.entityId = entityId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/PublicReference.java b/backend/core/src/main/java/org/opencdmp/model/PublicReference.java new file mode 100644 index 000000000..ba10bf426 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PublicReference.java @@ -0,0 +1,63 @@ +package org.opencdmp.model; + +import java.util.UUID; + +public class PublicReference { + + private UUID id; + public static final String _id = "id"; + + private String label; + public static final String _label = "label"; + + private PublicReferenceType type; + public static final String _type = "type"; + + private String description; + public static final String _description = "description"; + + private String reference; + public static final String _reference = "reference"; + + 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 PublicReferenceType getType() { + return type; + } + + public void setType(PublicReferenceType type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getReference() { + return reference; + } + + public void setReference(String reference) { + this.reference = reference; + } +} + + diff --git a/backend/core/src/main/java/org/opencdmp/model/PublicReferenceType.java b/backend/core/src/main/java/org/opencdmp/model/PublicReferenceType.java new file mode 100644 index 000000000..2126981aa --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PublicReferenceType.java @@ -0,0 +1,42 @@ +package org.opencdmp.model; + +import java.util.UUID; + +public class PublicReferenceType { + + private UUID id; + public static final String _id = "id"; + + + private String name; + public static final String _name = "name"; + + + private String code; + public static final String _code = "code"; + + + 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 getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/PublicUser.java b/backend/core/src/main/java/org/opencdmp/model/PublicUser.java new file mode 100644 index 000000000..2311ea6e5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/PublicUser.java @@ -0,0 +1,29 @@ +package org.opencdmp.model; + + +import java.util.UUID; + +public class PublicUser { + + public final static String _id = "id"; + private UUID id; + + public final static String _name = "name"; + private String name = null; + + 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; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/RecentActivityItem.java b/backend/core/src/main/java/org/opencdmp/model/RecentActivityItem.java new file mode 100644 index 000000000..f3b0af3b5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/RecentActivityItem.java @@ -0,0 +1,46 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DmpBlueprintStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.enums.RecentActivityItemType; +import org.opencdmp.model.dmpblueprintdefinition.Definition; + +import java.time.Instant; +import java.util.UUID; + +public class RecentActivityItem { + private RecentActivityItemType type; + public final static String _type = "type"; + private Dmp dmp; + public final static String _dmp = "dmp"; + private Description description; + + public final static String _description = "description"; + + public RecentActivityItemType getType() { + return type; + } + + public void setType(RecentActivityItemType type) { + this.type = type; + } + + public Dmp getDmp() { + return dmp; + } + + public void setDmp(Dmp dmp) { + this.dmp = dmp; + } + + public Description getDescription() { + return description; + } + + public void setDescription(Description description) { + this.description = description; + } +} + + + diff --git a/backend/core/src/main/java/org/opencdmp/model/RecentActivityItemLookup.java b/backend/core/src/main/java/org/opencdmp/model/RecentActivityItemLookup.java new file mode 100644 index 000000000..fff8d5dbb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/RecentActivityItemLookup.java @@ -0,0 +1,157 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DescriptionStatus; +import org.opencdmp.commons.enums.DmpStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.enums.RecentActivityOrder; +import org.opencdmp.query.lookup.DescriptionLookup; +import org.opencdmp.query.lookup.DmpLookup; +import org.opencdmp.query.lookup.DmpUserLookup; +import gr.cite.tools.data.query.Lookup; +import gr.cite.tools.data.query.Ordering; +import gr.cite.tools.data.query.Paging; +import gr.cite.tools.fieldset.BaseFieldSet; + +import java.util.List; +import java.util.UUID; + +public class RecentActivityItemLookup{ + + private String like; + private Boolean onlyDraft; + private Boolean onlyDmp; + private Boolean onlyDescription; + private List userIds; + private Paging page; + private BaseFieldSet project; + private RecentActivityOrder orderField; + + public String getLike() { + return like; + } + + public void setLike(String like) { + this.like = like; + } + + public Boolean getOnlyDraft() { + return onlyDraft; + } + + public void setOnlyDraft(Boolean onlyDraft) { + this.onlyDraft = onlyDraft; + } + + public List getUserIds() { + return userIds; + } + + public void setUserIds(List userIds) { + this.userIds = userIds; + } + + public Paging getPage() { + return page; + } + + public void setPage(Paging page) { + this.page = page; + } + + public BaseFieldSet getProject() { + return project; + } + + public void setProject(BaseFieldSet project) { + this.project = project; + } + + public RecentActivityOrder getOrderField() { + return orderField; + } + + public void setOrderField(RecentActivityOrder orderField) { + this.orderField = orderField; + } + + public Boolean getOnlyDmp() { + return onlyDmp; + } + + public void setOnlyDmp(Boolean onlyDmp) { + this.onlyDmp = onlyDmp; + } + + public Boolean getOnlyDescription() { + return onlyDescription; + } + + public void setOnlyDescription(Boolean onlyDescription) { + this.onlyDescription = onlyDescription; + } + + public DescriptionLookup asDescriptionLookup() { + if (this.onlyDmp != null) return null; + + DescriptionLookup lookup = new DescriptionLookup(); + lookup.setIsActive(List.of(IsActive.Active)); + if (this.like != null) lookup.setLike(this.like); + if (this.onlyDraft != null) lookup.setStatuses(List.of(DescriptionStatus.Draft)); + else lookup.setStatuses(List.of(DescriptionStatus.Draft, DescriptionStatus.Finalized)); + if (this.userIds != null) { + DmpLookup dmpLookup = new DmpLookup(); + DmpUserLookup dmpUserLookup = new DmpUserLookup(); + dmpUserLookup.setUserIds(this.userIds); + dmpUserLookup.setIsActive(List.of(IsActive.Active)); + dmpLookup.setDmpUserSubQuery(dmpUserLookup); + dmpLookup.setIsActive(List.of(IsActive.Active)); + lookup.setDmpSubQuery(dmpLookup); + } + if (this.page != null) lookup.setPage(new Paging(this.page.getOffset(), this.page.getSize())); + Ordering ordering = new Ordering(); + if (this.orderField != null) { + switch (this.orderField){ + case Label -> ordering.addDescending(Description._label).addDescending(Description._updatedAt); + case UpdatedAt -> ordering.addDescending(Description._updatedAt); + case Status -> ordering.addDescending(Description._status).addDescending(Description._updatedAt); + default -> throw new IllegalArgumentException("Type not found" + this.orderField) ; + } + } else { + ordering.addDescending(Description._updatedAt); + } + lookup.setOrder(ordering); + if (this.project !=null) lookup.setProject((BaseFieldSet) this.project.extractPrefixed(RecentActivityItem._description)); + return lookup; + } + + public DmpLookup asDmpLookup() { + if (this.onlyDescription != null) return null; + + DmpLookup lookup = new DmpLookup(); + lookup.setIsActive(List.of(IsActive.Active)); + if (this.like != null) lookup.setLike(this.like); + if (this.onlyDraft != null) lookup.setStatuses(List.of(DmpStatus.Draft)); + if (this.userIds != null) { + DmpUserLookup dmpUserLookup = new DmpUserLookup(); + dmpUserLookup.setUserIds(this.userIds); + dmpUserLookup.setIsActive(List.of(IsActive.Active)); + lookup.setDmpUserSubQuery(dmpUserLookup); + } + if (this.page != null) lookup.setPage(new Paging(this.page.getOffset(), this.page.getSize())); + Ordering ordering = new Ordering(); + if (this.orderField != null) { + switch (this.orderField){ + case Label -> ordering.addDescending(Dmp._label); + case UpdatedAt -> ordering.addDescending(Dmp._updatedAt); + case Status -> ordering.addDescending(Dmp._status).addDescending(Dmp._updatedAt); + default -> throw new IllegalArgumentException("Type not found" + this.orderField) ; + } + } else { + ordering.addDescending(Dmp._updatedAt); + } + lookup.setOrder(ordering); + if (this.project !=null)lookup.setProject((BaseFieldSet) this.project.extractPrefixed(RecentActivityItem._dmp)); + return lookup; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/Reference.java b/backend/core/src/main/java/org/opencdmp/model/Reference.java new file mode 100644 index 000000000..8c5bc5fb8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/Reference.java @@ -0,0 +1,188 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.enums.ReferenceSourceType; +import org.opencdmp.model.referencedefinition.Definition; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public class Reference { + + private UUID id; + public static final String _id = "id"; + + private String label; + public static final String _label = "label"; + + private ReferenceType type; + public static final String _type = "type"; + + private String description; + public static final String _description = "description"; + + private Definition definition; + public static final String _definition = "definition"; + + private String reference; + public static final String _reference = "reference"; + + private String abbreviation; + public static final String _abbreviation = "abbreviation"; + + private String source; + public static final String _source = "source"; + + private ReferenceSourceType sourceType; + public static final String _sourceType = "sourceType"; + + private IsActive isActive; + public static final String _isActive = "isActive"; + + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + private User createdBy; + public static final String _createdBy = "createdBy"; + + private List dmpReferences; + public static final String _dmpReferences = "dmpReferences"; + + private String hash; + public final static String _hash = "hash"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 ReferenceType getType() { + return type; + } + + public void setType(ReferenceType type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Definition getDefinition() { + return definition; + } + + public void setDefinition(Definition definition) { + this.definition = definition; + } + + public String getReference() { + return reference; + } + + public void setReference(String reference) { + this.reference = reference; + } + + public String getAbbreviation() { + return abbreviation; + } + + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public ReferenceSourceType getSourceType() { + return sourceType; + } + + public void setSourceType(ReferenceSourceType sourceType) { + this.sourceType = sourceType; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public List getDmpReferences() { + return dmpReferences; + } + + public void setDmpReferences(List dmpReferences) { + this.dmpReferences = dmpReferences; + } + + public User getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(User createdBy) { + this.createdBy = createdBy; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/ReferenceType.java b/backend/core/src/main/java/org/opencdmp/model/ReferenceType.java new file mode 100644 index 000000000..a04b52786 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/ReferenceType.java @@ -0,0 +1,109 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.model.referencetypedefinition.ReferenceTypeDefinition; + +import java.time.Instant; +import java.util.UUID; + +public class ReferenceType { + + private UUID id; + public static final String _id = "id"; + + private String name; + public static final String _name = "name"; + + private String code; + public static final String _code = "code"; + + private ReferenceTypeDefinition definition; + public static final String _definition = "definition"; + + private IsActive isActive; + public static final String _isActive = "isActive"; + + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + public final static String _hash = "hash"; + private String hash; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public ReferenceTypeDefinition getDefinition() { + return definition; + } + + public void setDefinition(ReferenceTypeDefinition definition) { + this.definition = definition; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/StorageFile.java b/backend/core/src/main/java/org/opencdmp/model/StorageFile.java new file mode 100644 index 000000000..113dd2bc1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/StorageFile.java @@ -0,0 +1,141 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.StorageType; + +import java.time.Instant; +import java.util.UUID; + +public class StorageFile { + + private UUID id; + public final static String _id = "id"; + + private String fileRef; + public final static String _fileRef = "fileRef"; + + private String name; + public final static String _name = "name"; + + private String fullName; + public final static String _fullName = "fullName"; + + private String extension; + public final static String _extension = "extension"; + + private String mimeType; + public final static String _mimeType = "mimeType"; + + private StorageType storageType; + public final static String _storageType = "storageType"; + + private Instant createdAt; + public final static String _createdAt = "createdAt"; + + private Instant purgeAt; + public final static String _purgeAt = "purgeAt"; + + private Instant purgedAt; + public final static String _purgedAt = "purgedAt"; + + private User owner; + public final static String _owner = "owner"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getFileRef() { + return fileRef; + } + + public void setFileRef(String fileRef) { + this.fileRef = fileRef; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public String getMimeType() { + return mimeType; + } + + public void setMimeType(String mimeType) { + this.mimeType = mimeType; + } + + public StorageType getStorageType() { + return storageType; + } + + public void setStorageType(StorageType storageType) { + this.storageType = storageType; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getPurgeAt() { + return purgeAt; + } + + public void setPurgeAt(Instant purgeAt) { + this.purgeAt = purgeAt; + } + + public Instant getPurgedAt() { + return purgedAt; + } + + public void setPurgedAt(Instant purgedAt) { + this.purgedAt = purgedAt; + } + + public User getOwner() { + return owner; + } + + public void setOwner(User owner) { + this.owner = owner; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/SupportiveMaterial.java b/backend/core/src/main/java/org/opencdmp/model/SupportiveMaterial.java new file mode 100644 index 000000000..a77ba6841 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/SupportiveMaterial.java @@ -0,0 +1,110 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.enums.SupportiveMaterialFieldType; + +import java.time.Instant; +import java.util.UUID; + + +public class SupportiveMaterial { + + private UUID id; + public static final String _id = "id"; + + private SupportiveMaterialFieldType type; + public static final String _type = "type"; + + private String languageCode; + public static final String _languageCode = "languageCode"; + + private String payload; + public static final String _payload = "payload"; + + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + public static final String _isActive = "isActive"; + + private String hash; + public final static String _hash = "hash"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public SupportiveMaterialFieldType getType() { + return type; + } + + public void setType(SupportiveMaterialFieldType type) { + this.type = type; + } + + public String getLanguageCode() { + return languageCode; + } + + public void setLanguageCode(String languageCode) { + this.languageCode = languageCode; + } + + public String getPayload() { + return payload; + } + + public void setPayload(String payload) { + this.payload = payload; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/Tag.java b/backend/core/src/main/java/org/opencdmp/model/Tag.java new file mode 100644 index 000000000..e50aff7ab --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/Tag.java @@ -0,0 +1,106 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DescriptionStatus; +import org.opencdmp.commons.enums.IsActive; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public class Tag { + + private UUID id; + + public static final String _id = "id"; + + private String label; + + public static final String _label = "label"; + + private User createdBy; + + public static final String _createdBy = "createdBy"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + + public static final String _isActive = "isActive"; + + private String hash; + + public static final String _hash = "hash"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + 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 User getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(User createdBy) { + this.createdBy = createdBy; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/Tenant.java b/backend/core/src/main/java/org/opencdmp/model/Tenant.java new file mode 100644 index 000000000..8aaabcc8b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/Tenant.java @@ -0,0 +1,97 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; + +import java.time.Instant; +import java.util.UUID; + + +public class Tenant { + + private UUID id; + public final static String _id = "id"; + + private String code; + public final static String _code = "code"; + + private String name; + public final static String _name = "name"; + + private String description; + public final static String _description = "description"; + + private IsActive isActive; + public final static String _isActive = "isActive"; + + private Instant createdAt; + public final static String _createdAt = "createdAt"; + + private Instant updatedAt; + public final static String _updatedAt = "updatedAt"; + + public final static String _hash = "hash"; + private String hash; + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/TenantUser.java b/backend/core/src/main/java/org/opencdmp/model/TenantUser.java new file mode 100644 index 000000000..631dd02da --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/TenantUser.java @@ -0,0 +1,97 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; + +import java.time.Instant; +import java.util.UUID; + +public class TenantUser { + + private UUID id; + public final static String _id = "id"; + + private User user; + public final static String _user = "user"; + + private Tenant tenant; + public final static String _tenant = "tenant"; + + private IsActive isActive; + public final static String _isActive = "isActive"; + + private Instant createdAt; + public final static String _createdAt = "createdAt"; + + private Instant updatedAt; + public final static String _updatedAt = "updatedAt"; + + private String hash; + public final static String _hash = "hash"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Tenant getTenant() { + return tenant; + } + + public void setTenant(Tenant tenant) { + this.tenant = tenant; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/User.java b/backend/core/src/main/java/org/opencdmp/model/User.java new file mode 100644 index 000000000..7d4cacfc1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/User.java @@ -0,0 +1,152 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.enums.UserSettingsType; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public class User { + + private UUID id; + public static final String _id = "id"; + + private String name; + public static final String _name = "name"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + + public static final String _updatedAt = "updatedAt"; + + private IsActive isActive; + + public static final String _isActive = "isActive"; + + private String hash; + + public static final String _hash = "hash"; + + private UserAdditionalInfo additionalInfo; + + public static final String _additionalInfo = "additionalInfo"; + + private List contacts; + + public static final String _contacts = "contacts"; + + private List globalRoles; + + public static final String _globalRoles = "globalRoles"; + + private List tenantRoles; + + public static final String _tenantRoles = "tenantRoles"; + + private List credentials; + + public static final String _credentials = "credentials"; + + public final static String _tenantUsers = "tenantUsers"; + private List tenantUsers; + + 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 Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public UserAdditionalInfo getAdditionalInfo() { + return additionalInfo; + } + + public void setAdditionalInfo(UserAdditionalInfo additionalInfo) { + this.additionalInfo = additionalInfo; + } + + public List getContacts() { + return contacts; + } + + public void setContacts(List contacts) { + this.contacts = contacts; + } + + public List getCredentials() { + return credentials; + } + + public void setCredentials(List credentials) { + this.credentials = credentials; + } + + public List getTenantUsers() { + return tenantUsers; + } + + public void setTenantUsers(List tenantUsers) { + this.tenantUsers = tenantUsers; + } + + public List getTenantRoles() { + return tenantRoles; + } + + public void setTenantRoles(List tenantRoles) { + this.tenantRoles = tenantRoles; + } + + public List getGlobalRoles() { + return globalRoles; + } + + public void setGlobalRoles(List globalRoles) { + this.globalRoles = globalRoles; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/UserAdditionalInfo.java b/backend/core/src/main/java/org/opencdmp/model/UserAdditionalInfo.java new file mode 100644 index 000000000..632dd39fa --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/UserAdditionalInfo.java @@ -0,0 +1,74 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.ContactInfoType; + +import java.time.Instant; +import java.util.UUID; + +public class UserAdditionalInfo { + private String avatarUrl; + public static final String _avatarUrl = "avatarUrl"; + + private String timezone; + public static final String _timezone = "timezone"; + + private String culture; + public static final String _culture = "culture"; + + private String language; + public static final String _language = "language"; + + private String roleOrganization; + public static final String _roleOrganization = "roleOrganization"; + + private Reference organization; + public static final String _organization = "organization"; + + public String getAvatarUrl() { + return avatarUrl; + } + + public void setAvatarUrl(String avatarUrl) { + this.avatarUrl = avatarUrl; + } + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + public String getCulture() { + return culture; + } + + public void setCulture(String culture) { + this.culture = culture; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getRoleOrganization() { + return roleOrganization; + } + + public void setRoleOrganization(String roleOrganization) { + this.roleOrganization = roleOrganization; + } + + public Reference getOrganization() { + return organization; + } + + public void setOrganization(Reference organization) { + this.organization = organization; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/UserContactInfo.java b/backend/core/src/main/java/org/opencdmp/model/UserContactInfo.java new file mode 100644 index 000000000..21636bfa3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/UserContactInfo.java @@ -0,0 +1,75 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.ContactInfoType; + +import java.time.Instant; +import java.util.UUID; + +public class UserContactInfo { + private UUID id; + public static final String _id = "id"; + + private String value; + public static final String _value = "value"; + + private ContactInfoType type; + public static final String _type = "type"; + + private int ordinal; + public static final String _ordinal = "ordinal"; + + private User user; + public static final String _user = "user"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public ContactInfoType getType() { + return type; + } + + public void setType(ContactInfoType type) { + this.type = type; + } + + public int getOrdinal() { + return ordinal; + } + + public void setOrdinal(int ordinal) { + this.ordinal = ordinal; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/UserCredential.java b/backend/core/src/main/java/org/opencdmp/model/UserCredential.java new file mode 100644 index 000000000..f94a1f544 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/UserCredential.java @@ -0,0 +1,63 @@ +package org.opencdmp.model; + +import org.opencdmp.model.usercredential.UserCredentialData; + +import java.time.Instant; +import java.util.UUID; + +public class UserCredential { + private UUID id; + public static final String _id = "id"; + + private String externalId; + public static final String _externalId = "externalId"; + + private User user; + public static final String _user = "user"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + private UserCredentialData data; + public static final String _data = "data"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getExternalId() { + return externalId; + } + + public void setExternalId(String externalId) { + this.externalId = externalId; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public UserCredentialData getData() { + return data; + } + + public void setData(UserCredentialData data) { + this.data = data; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/UserDescriptionTemplate.java b/backend/core/src/main/java/org/opencdmp/model/UserDescriptionTemplate.java new file mode 100644 index 000000000..8bc6e4fff --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/UserDescriptionTemplate.java @@ -0,0 +1,111 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.DescriptionTemplateStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.enums.UserDescriptionTemplateRole; +import org.opencdmp.model.descriptiontemplatedefinition.Definition; + +import java.time.Instant; +import java.util.UUID; + +public class UserDescriptionTemplate { + + public final static String _id = "id"; + private UUID id; + + public final static String _descriptionTemplate = "descriptionTemplate"; + private DescriptionTemplate descriptionTemplate; + + public final static String _role = "role"; + private UserDescriptionTemplateRole role; + + public final static String _user = "user"; + private User user; + + public final static String _createdAt = "createdAt"; + private Instant createdAt; + + public final static String _updatedAt = "updatedAt"; + private Instant updatedAt; + + public final static String _isActive = "isActive"; + private IsActive isActive; + + public final static String _hash = "hash"; + private String hash; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public DescriptionTemplate getDescriptionTemplate() { + return descriptionTemplate; + } + + public void setDescriptionTemplate(DescriptionTemplate descriptionTemplate) { + this.descriptionTemplate = descriptionTemplate; + } + + public UserDescriptionTemplateRole getRole() { + return role; + } + + public void setRole(UserDescriptionTemplateRole role) { + this.role = role; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/UserRole.java b/backend/core/src/main/java/org/opencdmp/model/UserRole.java new file mode 100644 index 000000000..d32108511 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/UserRole.java @@ -0,0 +1,63 @@ +package org.opencdmp.model; + +import java.time.Instant; +import java.util.UUID; + +public class UserRole { + private UUID id; + public static final String _id = "id"; + + private String role; + public static final String _role = "role"; + + private User user; + public static final String _user = "user"; + + private Instant createdAt; + + public static final String _createdAt = "createdAt"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/model/UserSettings.java b/backend/core/src/main/java/org/opencdmp/model/UserSettings.java new file mode 100644 index 000000000..194520c92 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/UserSettings.java @@ -0,0 +1,108 @@ +package org.opencdmp.model; + +import org.opencdmp.commons.enums.UserSettingsType; + +import java.time.Instant; +import java.util.UUID; + +public class UserSettings { + + private UUID id; + public static final String _id = "id"; + + private String key; + public static final String _key = "key"; + + private String value; + public static final String _value = "value"; + + private UUID entityId; + public static final String _entityId = "entityId"; + + private Instant createdAt; + public static final String _createdAt = "createdAt"; + + private Instant updatedAt; + public static final String _updatedAt = "updatedAt"; + + private UserSettingsType type; + public static final String _type = "type"; + + private String hash; + public static final String _hash = "hash"; + + private Boolean belongsToCurrentTenant; + public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public UUID getEntityId() { + return entityId; + } + + public void setEntityId(UUID entityId) { + this.entityId = entityId; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public UserSettingsType getType() { + return type; + } + + public void setType(UserSettingsType type) { + this.type = type; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public Boolean getBelongsToCurrentTenant() { + return belongsToCurrentTenant; + } + + public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { + this.belongsToCurrentTenant = belongsToCurrentTenant; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/actionconfirmation/DmpInvitation.java b/backend/core/src/main/java/org/opencdmp/model/actionconfirmation/DmpInvitation.java new file mode 100644 index 000000000..8a5687afe --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/actionconfirmation/DmpInvitation.java @@ -0,0 +1,42 @@ +package org.opencdmp.model.actionconfirmation; + +import org.opencdmp.commons.enums.DmpUserRole; + +import java.util.UUID; + +public class DmpInvitation { + + private String email; + public static final String _email = "email"; + + private UUID dmpId; + public static final String _dmpId = "dmpId"; + + private DmpUserRole role; + public static final String _role = "role"; + + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public UUID getDmpId() { + return dmpId; + } + + public void setDmpId(UUID dmpId) { + this.dmpId = dmpId; + } + + public DmpUserRole getRole() { + return role; + } + + public void setRole(DmpUserRole role) { + this.role = role; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/actionconfirmation/MergeAccountConfirmation.java b/backend/core/src/main/java/org/opencdmp/model/actionconfirmation/MergeAccountConfirmation.java new file mode 100644 index 000000000..649359daf --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/actionconfirmation/MergeAccountConfirmation.java @@ -0,0 +1,16 @@ +package org.opencdmp.model.actionconfirmation; + + +public class MergeAccountConfirmation { + + private String email; + public static final String _email = "email"; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/actionconfirmation/RemoveCredentialRequest.java b/backend/core/src/main/java/org/opencdmp/model/actionconfirmation/RemoveCredentialRequest.java new file mode 100644 index 000000000..55165c379 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/actionconfirmation/RemoveCredentialRequest.java @@ -0,0 +1,31 @@ +package org.opencdmp.model.actionconfirmation; + +import org.opencdmp.commons.validation.BaseValidator; +import gr.cite.tools.validation.specification.Specification; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.errorcode.ErrorThesaurusProperties; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Scope; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +public class RemoveCredentialRequest { + + private UUID credentialId; + public static final String _credentialId = "credentialId"; + + public UUID getCredentialId() { + return credentialId; + } + + public void setCredentialId(UUID credentialId) { + this.credentialId = credentialId; + } + +} + diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/ActionConfirmationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/ActionConfirmationBuilder.java new file mode 100644 index 000000000..c875dccda --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/ActionConfirmationBuilder.java @@ -0,0 +1,142 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.enums.ActionConfirmationType; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.actionconfirmation.DmpInvitationEntity; +import org.opencdmp.commons.types.actionconfirmation.MergeAccountConfirmationEntity; +import org.opencdmp.commons.types.actionconfirmation.RemoveCredentialRequestEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.ActionConfirmationEntity; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import org.opencdmp.model.ActionConfirmation; +import org.opencdmp.model.Tenant; +import org.opencdmp.model.User; +import org.opencdmp.model.builder.actionconfirmation.DmpInvitationBuilder; +import org.opencdmp.model.builder.actionconfirmation.MergeAccountConfirmationBuilder; +import org.opencdmp.model.builder.actionconfirmation.RemoveCredentialRequestBuilder; +import org.opencdmp.query.TenantQuery; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ActionConfirmationBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private final TenantScope tenantScope; + private final XmlHandlingService xmlHandlingService; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public ActionConfirmationBuilder(ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory, TenantScope tenantScope, XmlHandlingService xmlHandlingService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ActionConfirmationBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.tenantScope = tenantScope; + this.xmlHandlingService = xmlHandlingService; + } + + public ActionConfirmationBuilder authorize(EnumSet values){ + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0),Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size) .orElse(0)); + this.logger.trace(new DataLogEntry("requested fields",fields)); + if(fields == null || data == null || fields.isEmpty()) return new ArrayList<>(); + + FieldSet mergeAccountConfirmationFields = fields.extractPrefixed(this.asPrefix(ActionConfirmation._mergeAccountConfirmation)); + FieldSet removeCredentialRequestFields = fields.extractPrefixed(this.asPrefix(ActionConfirmation._removeCredentialRequest)); + FieldSet dmpInvitationFields = fields.extractPrefixed(this.asPrefix(ActionConfirmation._dmpInvitation)); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(ActionConfirmation._createdBy)); + Map userMap = this.collectUsers(userFields, data); + + List models = new ArrayList<>(); + for(ActionConfirmationEntity d : data){ + ActionConfirmation m = new ActionConfirmation(); + if(fields.hasField(this.asIndexer(ActionConfirmation._id))) m.setId(d.getId()); + if(fields.hasField(this.asIndexer(ActionConfirmation._type))) m.setType(d.getType()); + if(fields.hasField(this.asIndexer(ActionConfirmation._status))) m.setStatus(d.getStatus()); + if(fields.hasField(this.asIndexer(ActionConfirmation._isActive))) m.setIsActive(d.getIsActive()); + if(fields.hasField(this.asIndexer(ActionConfirmation._expiresAt))) m.setExpiresAt(d.getExpiresAt()); + if (fields.hasField(this.asIndexer(ActionConfirmation._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!removeCredentialRequestFields.isEmpty() && d.getData() != null){ + switch (d.getType()) + { + case MergeAccount -> { + MergeAccountConfirmationEntity emailConfirmation = this.xmlHandlingService.fromXmlSafe(MergeAccountConfirmationEntity.class, d.getData()); + m.setMergeAccountConfirmation(this.builderFactory.builder(MergeAccountConfirmationBuilder.class).authorize(this.authorize).build(mergeAccountConfirmationFields, emailConfirmation)); + } + case DmpInvitation -> { + DmpInvitationEntity dmpInvitation = this.xmlHandlingService.fromXmlSafe(DmpInvitationEntity.class, d.getData()); + m.setDmpInvitation(this.builderFactory.builder(DmpInvitationBuilder.class).authorize(this.authorize).build(dmpInvitationFields, dmpInvitation)); + } + case RemoveCredential -> { + RemoveCredentialRequestEntity emailConfirmation = this.xmlHandlingService.fromXmlSafe(RemoveCredentialRequestEntity.class, d.getData()); + m.setRemoveCredentialRequest(this.builderFactory.builder(RemoveCredentialRequestBuilder.class).authorize(this.authorize).build(removeCredentialRequestFields, emailConfirmation)); + } + default -> throw new InternalError("unknown type: " + d.getType()); + } + + } + if (!userFields.isEmpty() && userMap != null && userMap.containsKey(d.getCreatedById())) m.setCreatedBy(userMap.get(d.getCreatedById())); + if(fields.hasField(this.asIndexer(ActionConfirmation._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if(fields.hasField(this.asIndexer(ActionConfirmation._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if(fields.hasField(this.asIndexer(ActionConfirmation._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + models.add(m); + } + this.logger.debug("build {} items",Optional.of(models).map(List::size).orElse(0)); + return models; + } + + + private Map collectUsers(FieldSet fields, List datas) throws MyApplicationException { + if (fields.isEmpty() || datas.isEmpty()) return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap = null; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + datas.stream().map(x -> x.getCreatedById()).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + x -> x.getId()); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(datas.stream().map(x -> x.getCreatedById()).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, x -> x.getId()); + } + if (!fields.hasField(User._id)) { + itemMap.values().stream().filter(x -> x != null).map(x -> { + x.setId(null); + return x; + }).collect(Collectors.toList()); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/BaseBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/BaseBuilder.java new file mode 100644 index 000000000..eecd73851 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/BaseBuilder.java @@ -0,0 +1,140 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AffiliatedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.authorization.PermissionNameProvider; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.tenant.TenantScopedBaseEntity; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.builder.Builder; +import gr.cite.tools.data.query.QueryBase; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; + +import javax.management.InvalidApplicationException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.time.Instant; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +public abstract class BaseBuilder implements Builder { + protected final LoggerService logger; + protected final ConventionService conventionService; + + public BaseBuilder( + ConventionService conventionService, + LoggerService logger + ) { + this.conventionService = conventionService; + this.logger = logger; + } + + public M build(FieldSet directives, D data) throws MyApplicationException { + if (data == null) { + //this.logger.Debug(new MapLogEntry("requested build for null item requesting fields").And("fields", directives)); +// return default(M); + M model = null; + return null; //TODO + } + List models = this.build(directives, Arrays.asList(data)); + return models.stream().findFirst().orElse(null); //TODO + } + + public abstract List build(FieldSet directives, List data) throws MyApplicationException; + + public Map asForeignKey(QueryBase query, FieldSet directives, Function keySelector) throws MyApplicationException { + this.logger.trace("Building references from query"); + List data = query.collectAs(directives); + this.logger.debug("collected {} items to build", Optional.ofNullable(data).map(List::size).orElse(0)); + return this.asForeignKey(data, directives, keySelector); + } + + public Map asForeignKey(List data, FieldSet directives, Function keySelector) throws MyApplicationException { + this.logger.trace("building references"); + List models = this.build(directives, data); + this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(List::size).orElse(0), Optional.ofNullable(data).map(List::size).orElse(0)); + Map map = models.stream().collect(Collectors.toMap(keySelector, o -> o)); + return map; + } + + public Map> asMasterKey(QueryBase query, FieldSet directives, Function keySelector) throws MyApplicationException { + this.logger.trace("Building details from query"); + List data = query.collectAs(directives); + this.logger.debug("collected {} items to build", Optional.ofNullable(data).map(List::size).orElse(0)); + return this.asMasterKey(data, directives, keySelector); + } + + public Map> asMasterKey(List data, FieldSet directives, Function keySelector) throws MyApplicationException { + this.logger.trace("building details"); + List models = this.build(directives, data); + this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(List::size).orElse(0), Optional.ofNullable(data).map(List::size).orElse(0)); + Map> map = new HashMap<>(); + for (M model : models) { + K key = keySelector.apply(model); + if (!map.containsKey(key)) map.put(key, new ArrayList()); + map.get(key).add(model); + } + return map; + } + + public Map asEmpty(List keys, Function mapper, Function keySelector) { + this.logger.trace("building static references"); + List models = keys.stream().map(mapper).collect(Collectors.toList()); + this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(List::size).orElse(0), Optional.ofNullable(keys).map(List::size)); + Map map = models.stream().collect(Collectors.toMap(keySelector, o -> o)); + return map; + } + + protected String hashValue(Instant value) throws MyApplicationException { + return this.conventionService.hashValue(value); + } + + protected String asPrefix(String name) { + return this.conventionService.asPrefix(name); + } + + protected String asIndexer(String... names) { + return this.conventionService.asIndexer(names); + } + + + protected Set extractAuthorizationFlags(FieldSet fields, String propertyName, List permissionNames){ + if (fields == null) return new HashSet<>(); + if (permissionNames == null) return new HashSet<>(); + + FieldSet authorizationFlags = fields.extractPrefixed(this.asPrefix(propertyName)); + List permissions = new ArrayList<>(); + for (String fieldValue : authorizationFlags.getFields()) permissions.addAll(permissionNames.stream().filter(x-> x.equalsIgnoreCase(fieldValue)).toList()); + return new HashSet<>(permissions); + } + + protected List evaluateAuthorizationFlags(AuthorizationService authorizationService, Set authorizationFlags, AffiliatedResource affiliatedResource) { + List allowed = new ArrayList<>(); + if (authorizationFlags == null) return allowed; + if (authorizationService == null) return allowed; + + for (String permission : authorizationFlags) { + Boolean isAllowed = affiliatedResource == null ? authorizationService.authorize(permission) : authorizationService.authorizeAtLeastOne(List.of(affiliatedResource), permission); + if (isAllowed) allowed.add(permission); + } + return allowed; + } + + protected boolean getBelongsToCurrentTenant(TenantScopedBaseEntity entity, TenantScope tenantScope){ + if (!tenantScope.isSet()) return true; + try { + if (entity.getTenantId() == null && tenantScope.getTenant() == null) return true; + if (entity.getTenantId() == null || tenantScope.getTenant() == null) return false; + + return entity.getTenantId().equals(tenantScope.getTenant()); + } catch (InvalidApplicationException e) { + return false; + } + } + +} + diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionBuilder.java new file mode 100644 index 000000000..a4a565b76 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionBuilder.java @@ -0,0 +1,307 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AffiliatedResource; +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.authorization.authorizationcontentresolver.AuthorizationContentResolver; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.description.PropertyDefinitionEntity; +import org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionEntity; +import org.opencdmp.data.DescriptionTemplateEntity; +import org.opencdmp.data.DmpEntity; +import org.opencdmp.data.UserRoleEntity; +import org.opencdmp.model.*; +import org.opencdmp.model.builder.descriptionpropertiesdefinition.PropertyDefinitionBuilder; +import org.opencdmp.query.*; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionBuilder extends BaseBuilder { + + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + private final JsonHandlingService jsonHandlingService; + private final XmlHandlingService xmlHandlingService; + private final AuthorizationService authorizationService; + private final AuthorizationContentResolver authorizationContentResolver; + private final TenantScope tenantScope; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DescriptionBuilder( + ConventionService conventionService, + QueryFactory queryFactory, + BuilderFactory builderFactory, JsonHandlingService jsonHandlingService, XmlHandlingService xmlHandlingService, AuthorizationService authorizationService, AuthorizationContentResolver authorizationContentResolver, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + this.jsonHandlingService = jsonHandlingService; + this.xmlHandlingService = xmlHandlingService; + this.authorizationService = authorizationService; + this.authorizationContentResolver = authorizationContentResolver; + this.tenantScope = tenantScope; + } + + public DescriptionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet dmpDescriptionTemplateFields = fields.extractPrefixed(this.asPrefix(Description._dmpDescriptionTemplate)); + Map dmpDescriptionTemplateItemsMap = this.collectDmpDescriptionTemplates(dmpDescriptionTemplateFields, data); + + FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(Description._dmp)); + Map dmpItemsMap = this.collectDmps(dmpFields, data); + + FieldSet descriptionTemplateFields = fields.extractPrefixed(this.asPrefix(Description._descriptionTemplate)); + Map descriptionTemplateItemsMap = this.collectDescriptionTemplates(descriptionTemplateFields, data); + + FieldSet descriptionReferencesFields = fields.extractPrefixed(this.asPrefix(Description._descriptionReferences)); + Map> descriptionReferencesMap = this.collectDescriptionReferences(descriptionReferencesFields, data); + + FieldSet descriptionTagsFields = fields.extractPrefixed(this.asPrefix(Description._descriptionTags)); + Map> descriptionTagsMap = this.collectDescriptionTags(descriptionTagsFields, data); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(Description._createdBy)); + Map userItemsMap = this.collectUsers(userFields, data); + + FieldSet definitionPropertiesFields = fields.extractPrefixed(this.asPrefix(Description._properties)); + + Map definitionEntityMap = !definitionPropertiesFields.isEmpty() ? this.collectDescriptionTemplateDefinitions(data) : null; + + Set authorizationFlags = this.extractAuthorizationFlags(fields, Description._authorizationFlags, this.authorizationContentResolver.getPermissionNames()); + Map affiliatedResourceMap = authorizationFlags == null || authorizationFlags.isEmpty() ? null : this.authorizationContentResolver.descriptionsAffiliation(data.stream().map(DescriptionEntity::getId).collect(Collectors.toList())); + + List models = new ArrayList<>(); + for (DescriptionEntity d : data) { + Description m = new Description(); + if (fields.hasField(this.asIndexer(Description._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(Description._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(Description._status))) m.setStatus(d.getStatus()); + if (fields.hasField(this.asIndexer(Description._description))) m.setDescription(d.getDescription()); + if (fields.hasField(this.asIndexer(Description._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(Description._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(Description._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(Description._finalizedAt))) m.setFinalizedAt(d.getFinalizedAt()); + if (fields.hasField(this.asIndexer(Description._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(Description._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) m.setDmp(dmpItemsMap.get(d.getDmpId())); + if (!dmpDescriptionTemplateFields.isEmpty() && dmpDescriptionTemplateItemsMap != null && dmpDescriptionTemplateItemsMap.containsKey(d.getDmpDescriptionTemplateId())) m.setDmpDescriptionTemplate(dmpDescriptionTemplateItemsMap.get(d.getDmpDescriptionTemplateId())); + if (!descriptionTemplateFields.isEmpty() && descriptionTemplateItemsMap != null && descriptionTemplateItemsMap.containsKey(d.getDescriptionTemplateId())) m.setDescriptionTemplate(descriptionTemplateItemsMap.get(d.getDescriptionTemplateId())); + if (!descriptionReferencesFields.isEmpty() && descriptionReferencesMap != null && descriptionReferencesMap.containsKey(d.getId())) m.setDescriptionReferences(descriptionReferencesMap.get(d.getId())); + if (!descriptionTagsFields.isEmpty() && descriptionTagsMap != null && descriptionTagsMap.containsKey(d.getId())) m.setDescriptionTags(descriptionTagsMap.get(d.getId())); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getCreatedById())) m.setCreatedBy(userItemsMap.get(d.getCreatedById())); + if (!definitionPropertiesFields.isEmpty() && d.getProperties() != null){ + PropertyDefinitionEntity propertyDefinition = this.jsonHandlingService.fromJsonSafe(PropertyDefinitionEntity.class, d.getProperties()); + m.setProperties(this.builderFactory.builder(PropertyDefinitionBuilder.class).withDefinition(definitionEntityMap != null ? definitionEntityMap.getOrDefault(d.getDescriptionTemplateId(), null) : null).authorize(this.authorize).build(definitionPropertiesFields, propertyDefinition)); + } + if (affiliatedResourceMap != null && !authorizationFlags.isEmpty()) m.setAuthorizationFlags(this.evaluateAuthorizationFlags(this.authorizationService, authorizationFlags, affiliatedResourceMap.getOrDefault(d.getId(), null))); + models.add(m); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionEntity::getCreatedById).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getCreatedById).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectDmpDescriptionTemplates(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DmpDescriptionTemplate.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(DmpDescriptionTemplate._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionEntity::getDmpDescriptionTemplateId).distinct().collect(Collectors.toList()), + x -> { + DmpDescriptionTemplate item = new DmpDescriptionTemplate(); + item.setId(x); + return item; + }, + DmpDescriptionTemplate::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(DmpDescriptionTemplate._id); + DmpDescriptionTemplateQuery q = this.queryFactory.query(DmpDescriptionTemplateQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getDmpDescriptionTemplateId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpDescriptionTemplateBuilder.class).authorize(this.authorize).asForeignKey(q, clone, DmpDescriptionTemplate::getId); + } + if (!fields.hasField(DmpDescriptionTemplate._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectDescriptionTemplates(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DescriptionTemplate.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(DescriptionTemplate._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList()), + x -> { + DescriptionTemplate item = new DescriptionTemplate(); + item.setId(x); + return item; + }, + DescriptionTemplate::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(DescriptionTemplate._id); + DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(this.authorize).asForeignKey(q, clone, DescriptionTemplate::getId); + } + if (!fields.hasField(DescriptionTemplate._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectDescriptionTemplateDefinitions(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DefinitionEntity.class.getSimpleName()); + + Map itemMap = new HashMap<>(); + DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList())); + List items = q.collectAs(new BaseFieldSet().ensure(org.opencdmp.model.DescriptionTemplate._id).ensure(DescriptionTemplate._definition)); + for (DescriptionTemplateEntity item : items){ + DefinitionEntity definition =this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, item.getDefinition()); + itemMap.put(item.getId(), definition); + } + + return itemMap; + } + + private Map collectDmps(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Dmp.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Dmp._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionEntity::getDmpId).distinct().collect(Collectors.toList()), + x -> { + Dmp item = new Dmp(); + item.setId(x); + return item; + }, + Dmp::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Dmp._id); + DmpQuery q = this.queryFactory.query(DmpQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getDmpId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Dmp::getId); + } + if (!fields.hasField(Dmp._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map> collectDescriptionReferences(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", DescriptionReference.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(DescriptionReference._description, Description._id)); + DescriptionReferenceQuery query = this.queryFactory.query(DescriptionReferenceQuery.class).authorize(this.authorize).descriptionIds(data.stream().map(DescriptionEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionReferenceBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDescription().getId()); + + if (!fields.hasField(this.asIndexer(DescriptionReference._description, Description._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDescription() != null).peek(x -> { + x.getDescription().setId(null); + }); + } + + return itemMap; + } + + private Map> collectDescriptionTags(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", DescriptionTag.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(DescriptionTag._description, Description._id)); + DescriptionTagQuery query = this.queryFactory.query(DescriptionTagQuery.class).authorize(this.authorize).descriptionIds(data.stream().map(DescriptionEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionTagBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDescription().getId()); + + if (!fields.hasField(this.asIndexer(DescriptionTag._description, Description._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDescription() != null).peek(x -> { + x.getDescription().setId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionReferenceBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionReferenceBuilder.java new file mode 100644 index 000000000..368ff3cbd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionReferenceBuilder.java @@ -0,0 +1,160 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.descriptionreference.DescriptionReferenceDataEntity; +import org.opencdmp.commons.types.dmpreference.DmpReferenceDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionReferenceEntity; +import org.opencdmp.model.Description; +import org.opencdmp.model.DescriptionReference; +import org.opencdmp.model.DmpReference; +import org.opencdmp.model.Reference; +import org.opencdmp.model.builder.descriptionreference.DescriptionReferenceDataBuilder; +import org.opencdmp.model.builder.dmpreference.DmpReferenceDataBuilder; +import org.opencdmp.query.DescriptionQuery; +import org.opencdmp.query.ReferenceQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionReferenceBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private final JsonHandlingService jsonHandlingService; + private final TenantScope tenantScope; + + @Autowired + public DescriptionReferenceBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory, JsonHandlingService jsonHandlingService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionReferenceBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.jsonHandlingService = jsonHandlingService; + this.tenantScope = tenantScope; + } + + public DescriptionReferenceBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet referenceFields = fields.extractPrefixed(this.asPrefix(DescriptionReference._reference)); + Map referenceItemsMap = this.collectReferences(referenceFields, data); + + FieldSet descriptionFields = fields.extractPrefixed(this.asPrefix(DescriptionReference._description)); + Map descriptionItemsMap = this.collectDescriptions(descriptionFields, data); + + FieldSet dataFields = fields.extractPrefixed(this.asPrefix(DescriptionReference._data)); + + List models = new ArrayList<>(); + for (DescriptionReferenceEntity d : data) { + DescriptionReference m = new DescriptionReference(); + if (fields.hasField(this.asIndexer(DescriptionReference._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DescriptionReference._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DescriptionReference._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DescriptionReference._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(DescriptionReference._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(DescriptionReference._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!referenceFields.isEmpty() && referenceItemsMap != null && referenceItemsMap.containsKey(d.getReferenceId())) m.setReference(referenceItemsMap.get(d.getReferenceId())); + if (!descriptionFields.isEmpty() && descriptionItemsMap != null && descriptionItemsMap.containsKey(d.getDescriptionId())) m.setDescription(descriptionItemsMap.get(d.getDescriptionId())); + if (!dataFields.isEmpty() && d.getData() != null){ + DescriptionReferenceDataEntity propertyDefinition = this.jsonHandlingService.fromJsonSafe(DescriptionReferenceDataEntity.class, d.getData()); + m.setData(this.builderFactory.builder(DescriptionReferenceDataBuilder.class).authorize(this.authorize).build(dataFields, propertyDefinition)); + } + models.add(m); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map collectDescriptions(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Description.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Reference._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionReferenceEntity::getDescriptionId).distinct().collect(Collectors.toList()), + x -> { + Description item = new Description(); + item.setId(x); + return item; + }, + Description::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Reference._id); + DescriptionQuery q = this.queryFactory.query(DescriptionQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionReferenceEntity::getDescriptionId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Description::getId); + } + if (!fields.hasField(Description._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectReferences(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Reference.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Reference._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionReferenceEntity::getReferenceId).distinct().collect(Collectors.toList()), + x -> { + Reference item = new Reference(); + item.setId(x); + return item; + }, + Reference::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Reference._id); + ReferenceQuery q = this.queryFactory.query(ReferenceQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionReferenceEntity::getReferenceId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(ReferenceBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Reference::getId); + } + if (!fields.hasField(Reference._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionTagBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionTagBuilder.java new file mode 100644 index 000000000..ac57bb810 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionTagBuilder.java @@ -0,0 +1,148 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionTagEntity; +import org.opencdmp.model.Description; +import org.opencdmp.model.DescriptionTag; +import org.opencdmp.model.Tag; +import org.opencdmp.query.DescriptionQuery; +import org.opencdmp.query.TagQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTagBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + private final TenantScope tenantScope; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DescriptionTagBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionTagBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.tenantScope = tenantScope; + } + + public DescriptionTagBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet tagFields = fields.extractPrefixed(this.asPrefix(DescriptionTag._tag)); + Map tagItemsMap = this.collectTags(tagFields, data); + + FieldSet descriptionFields = fields.extractPrefixed(this.asPrefix(DescriptionTag._description)); + Map descriptionItemsMap = this.collectDescriptions(descriptionFields, data); + + List models = new ArrayList<>(); + + for (DescriptionTagEntity d : data) { + DescriptionTag m = new DescriptionTag(); + if (fields.hasField(this.asIndexer(DescriptionTag._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DescriptionTag._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DescriptionTag._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DescriptionTag._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(DescriptionTag._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(DescriptionTag._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!tagFields.isEmpty() && tagItemsMap != null && tagItemsMap.containsKey(d.getTagId())) m.setTag(tagItemsMap.get(d.getTagId())); + if (!descriptionFields.isEmpty() && descriptionItemsMap != null && descriptionItemsMap.containsKey(d.getDescriptionId())) m.setDescription(descriptionItemsMap.get(d.getDescriptionId())); + + models.add(m); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map collectDescriptions(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Description.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Tag._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionTagEntity::getDescriptionId).distinct().collect(Collectors.toList()), + x -> { + Description item = new Description(); + item.setId(x); + return item; + }, + Description::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Tag._id); + DescriptionQuery q = this.queryFactory.query(DescriptionQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionTagEntity::getDescriptionId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Description::getId); + } + if (!fields.hasField(Description._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectTags(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Tag.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Tag._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionTagEntity::getTagId).distinct().collect(Collectors.toList()), + x -> { + Tag item = new Tag(); + item.setId(x); + return item; + }, + Tag::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Tag._id); + TagQuery q = this.queryFactory.query(TagQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionTagEntity::getTagId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(TagBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Tag::getId); + } + if (!fields.hasField(Tag._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionTemplateBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionTemplateBuilder.java new file mode 100644 index 000000000..06c235748 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionTemplateBuilder.java @@ -0,0 +1,163 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionTemplateEntity; +import org.opencdmp.model.DescriptionTemplate; +import org.opencdmp.model.DescriptionTemplateType; +import org.opencdmp.model.UserDescriptionTemplate; +import org.opencdmp.model.builder.descriptiontemplatedefinition.DefinitionBuilder; +import org.opencdmp.query.DescriptionTemplateTypeQuery; +import org.opencdmp.query.UserDescriptionTemplateQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTemplateBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + + private final XmlHandlingService xmlHandlingService; + private final TenantScope tenantScope; + + @Autowired + public DescriptionTemplateBuilder( + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory, XmlHandlingService xmlHandlingService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionTemplateBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + this.xmlHandlingService = xmlHandlingService; + this.tenantScope = tenantScope; + } + + public DescriptionTemplateBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet descriptionTemplateTypeFields = fields.extractPrefixed(this.asPrefix(DescriptionTemplate._type)); + Map descriptionTemplateTypeMap = this.collectDescriptionTemplateTypes(descriptionTemplateTypeFields, data); + + FieldSet usersFields = fields.extractPrefixed(this.asPrefix(DescriptionTemplate._users)); + Map> usersMap = this.collectUserDescriptionTemplates(usersFields, data); + + FieldSet definitionFields = fields.extractPrefixed(this.asPrefix(DescriptionTemplate._definition)); + List models = new ArrayList<>(); + for (DescriptionTemplateEntity d : data) { + DescriptionTemplate m = new DescriptionTemplate(); + if (fields.hasField(this.asIndexer(DescriptionTemplate._id))) + m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._label))) + m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._description))) + m.setDescription(d.getDescription()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._groupId))) + m.setGroupId(d.getGroupId()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._version))) + m.setVersion(d.getVersion()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._language))) + m.setLanguage(d.getLanguage()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._createdAt))) + m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._updatedAt))) + m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._isActive))) + m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._versionStatus))) + m.setVersionStatus(d.getVersionStatus()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._status))) + m.setStatus(d.getStatus()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._hash))) + m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(DescriptionTemplate._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!definitionFields.isEmpty() && d.getDefinition() != null) { + DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, d.getDefinition()); + m.setDefinition(this.builderFactory.builder(DefinitionBuilder.class).authorize(this.authorize).build(definitionFields, definition)); + } + if (!usersFields.isEmpty() && usersMap != null && usersMap.containsKey(d.getId())) + m.setUsers(usersMap.get(d.getId())); + if (!descriptionTemplateTypeFields.isEmpty() && descriptionTemplateTypeMap != null && descriptionTemplateTypeMap.containsKey(d.getTypeId())) + m.setType(descriptionTemplateTypeMap.get(d.getTypeId())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectDescriptionTemplateTypes(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DescriptionTemplateType.class.getSimpleName()); + + Map itemMap = null; + if (!fields.hasOtherField(this.asIndexer(DescriptionTemplateType._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionTemplateEntity::getTypeId).distinct().collect(Collectors.toList()), + x -> { + DescriptionTemplateType item = new DescriptionTemplateType(); + item.setId(x); + return item; + }, + x -> x.getId()); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(DescriptionTemplateType._id); + DescriptionTemplateTypeQuery q = this.queryFactory.query(DescriptionTemplateTypeQuery.class).ids(data.stream().map(DescriptionTemplateEntity::getTypeId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionTemplateTypeBuilder.class).asForeignKey(q, clone, DescriptionTemplateType::getId); + } + if (!fields.hasField(DescriptionTemplateType._id)) { + itemMap.values().stream().filter(x -> x != null).map(x -> { + x.setId(null); + return x; + }).collect(Collectors.toList()); + } + + return itemMap; + } + + private Map> collectUserDescriptionTemplates(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", UserDescriptionTemplate.class.getSimpleName()); + + Map> itemMap = null; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserDescriptionTemplate._descriptionTemplate, DescriptionTemplate._id)); + UserDescriptionTemplateQuery query = this.queryFactory.query(UserDescriptionTemplateQuery.class).authorize(this.authorize).descriptionTemplateIds(data.stream().map(DescriptionTemplateEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserDescriptionTemplateBuilder.class).authorize(this.authorize).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDescriptionTemplate().getId()); + + if (!fields.hasField(this.asIndexer(UserDescriptionTemplate._descriptionTemplate, DescriptionTemplate._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDescriptionTemplate() != null).map(x -> { + x.getDescriptionTemplate().setId(null); + return x; + }).collect(Collectors.toList()); + } + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionTemplateTypeBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionTemplateTypeBuilder.java new file mode 100644 index 000000000..8a46d6de6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/DescriptionTemplateTypeBuilder.java @@ -0,0 +1,69 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionTemplateTypeEntity; +import org.opencdmp.model.DescriptionTemplateType; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTemplateTypeBuilder extends BaseBuilder { + + private final TenantScope tenantScope; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DescriptionTemplateTypeBuilder( + ConventionService conventionService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeBuilder.class))); + this.tenantScope = tenantScope; + } + + public DescriptionTemplateTypeBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (DescriptionTemplateTypeEntity d : data) { + DescriptionTemplateType m = new DescriptionTemplateType(); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._id))) + m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._name))) + m.setName(d.getName()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._createdAt))) + m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._updatedAt))) + m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._isActive))) + m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._status))) + m.setStatus(d.getStatus()); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._hash))) + m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/DmpAssociatedUserBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/DmpAssociatedUserBuilder.java new file mode 100644 index 000000000..50512e717 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/DmpAssociatedUserBuilder.java @@ -0,0 +1,96 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.ContactInfoType; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.UserEntity; +import org.opencdmp.model.*; +import org.opencdmp.query.UserContactInfoQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpAssociatedUserBuilder extends BaseBuilder { + + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpAssociatedUserBuilder(ConventionService conventionService, + QueryFactory queryFactory, + BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpAssociatedUserBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + public DmpAssociatedUserBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + + Map> contactsMap = this.collectUserContactInfos(new BaseFieldSet().ensure(UserContactInfo._value).ensure(UserContactInfo._type).ensure(UserContactInfo._ordinal), data); + + for (UserEntity d : data) { + DmpAssociatedUser m = new DmpAssociatedUser(); + if (fields.hasField(this.asIndexer(User._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(User._name))) m.setName(d.getName()); + if (contactsMap != null && contactsMap.containsKey(d.getId())){ + List contactInfos = contactsMap.get(d.getId()); + if (contactInfos != null) { + contactInfos.sort(Comparator.comparing(UserContactInfo::getOrdinal)); + m.setEmail(contactInfos.stream().filter(x -> ContactInfoType.Email.equals(x.getType())).map(UserContactInfo::getValue).findFirst().orElse(null)); + } + } + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map> collectUserContactInfos(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", UserContactInfo.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserContactInfo._user, User._id)); + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).authorize(this.authorize).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserContactInfoBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); + + if (!fields.hasField(this.asIndexer(UserContactInfo._user, User._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).peek(x -> { + x.getUser().setId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/DmpBlueprintBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/DmpBlueprintBuilder.java new file mode 100644 index 000000000..38e265c97 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/DmpBlueprintBuilder.java @@ -0,0 +1,91 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.dmpblueprint.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpBlueprintEntity; +import org.opencdmp.model.DmpBlueprint; +import org.opencdmp.model.builder.dmpblueprintdefinition.DefinitionBuilder; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpBlueprintBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final XmlHandlingService xmlHandlingService; + private final TenantScope tenantScope; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpBlueprintBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, XmlHandlingService xmlHandlingService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpBlueprintBuilder.class))); + this.builderFactory = builderFactory; + this.xmlHandlingService = xmlHandlingService; + this.tenantScope = tenantScope; + } + + public DmpBlueprintBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet definitionFields = fields.extractPrefixed(this.asPrefix(DmpBlueprint._definition)); + List models = new ArrayList<>(); + for (DmpBlueprintEntity d : data) { + DmpBlueprint m = new DmpBlueprint(); + if (fields.hasField(this.asIndexer(DmpBlueprint._id))) + m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DmpBlueprint._label))) + m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(DmpBlueprint._status))) + m.setStatus(d.getStatus()); + if (fields.hasField(this.asIndexer(DmpBlueprint._groupId))) + m.setGroupId(d.getGroupId()); + if (fields.hasField(this.asIndexer(DmpBlueprint._version))) + m.setVersion(d.getVersion()); + if (fields.hasField(this.asIndexer(DmpBlueprint._versionStatus))) + m.setVersionStatus(d.getVersionStatus()); + if (fields.hasField(this.asIndexer(DmpBlueprint._createdAt))) + m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DmpBlueprint._updatedAt))) + m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DmpBlueprint._isActive))) + m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(DmpBlueprint._hash))) + m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(DmpBlueprint._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!definitionFields.isEmpty() && d.getDefinition() != null) { + DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, d.getDefinition()); + m.setDefinition(this.builderFactory.builder(DefinitionBuilder.class).authorize(this.authorize).build(definitionFields, definition)); + } + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/DmpBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/DmpBuilder.java new file mode 100644 index 000000000..62986d7a0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/DmpBuilder.java @@ -0,0 +1,286 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AffiliatedResource; +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.authorization.authorizationcontentresolver.AuthorizationContentResolver; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.enums.EntityType; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.dmp.DmpPropertiesEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpEntity; +import org.opencdmp.model.*; +import org.opencdmp.model.builder.dmpproperties.DmpPropertiesBuilder; +import org.opencdmp.query.*; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpBuilder extends BaseBuilder { + + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + private final JsonHandlingService jsonHandlingService; + private final AuthorizationService authorizationService; + private final AuthorizationContentResolver authorizationContentResolver; + private final TenantScope tenantScope; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpBuilder(ConventionService conventionService, + QueryFactory queryFactory, + BuilderFactory builderFactory, JsonHandlingService jsonHandlingService, AuthorizationService authorizationService, AuthorizationContentResolver authorizationContentResolver, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + this.jsonHandlingService = jsonHandlingService; + this.authorizationService = authorizationService; + this.authorizationContentResolver = authorizationContentResolver; + this.tenantScope = tenantScope; + } + + public DmpBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + + FieldSet entityDoisFields = fields.extractPrefixed(this.asPrefix(Dmp._entityDois)); + Map> entityDoisMap = this.collectEntityDois(entityDoisFields, data); + + FieldSet dmpReferencesFields = fields.extractPrefixed(this.asPrefix(Dmp._dmpReferences)); + Map> dmpReferencesMap = this.collectDmpReferences(dmpReferencesFields, data); + + FieldSet dmpUsersFields = fields.extractPrefixed(this.asPrefix(Dmp._dmpUsers)); + Map> dmpUsersMap = this.collectDmpUsers(dmpUsersFields, data); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(Dmp._creator)); + Map userItemsMap = this.collectUsers(userFields, data); + + FieldSet blueprintFields = fields.extractPrefixed(this.asPrefix(Dmp._blueprint)); + Map blueprintItemsMap = this.collectDmpBlueprints(blueprintFields, data); + + FieldSet descriptionsFields = fields.extractPrefixed(this.asPrefix(Dmp._descriptions)); + Map> descriptionsMap = this.collectDmpDescriptions(descriptionsFields, data); + + FieldSet dmpDescriptionTemplatesFields = fields.extractPrefixed(this.asPrefix(Dmp._dmpDescriptionTemplates)); + Map> dmpDescriptionTemplatesMap = this.collectDmpDescriptionTemplates(dmpDescriptionTemplatesFields, data); + + Set authorizationFlags = this.extractAuthorizationFlags(fields, Dmp._authorizationFlags, this.authorizationContentResolver.getPermissionNames()); + Map affiliatedResourceMap = authorizationFlags == null || authorizationFlags.isEmpty() ? null : this.authorizationContentResolver.dmpsAffiliation(data.stream().map(DmpEntity::getId).collect(Collectors.toList())); + + FieldSet propertiesFields = fields.extractPrefixed(this.asPrefix(Dmp._properties)); + for (DmpEntity d : data) { + Dmp m = new Dmp(); + if (fields.hasField(this.asIndexer(Dmp._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(Dmp._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(Dmp._version))) m.setVersion(d.getVersion()); + if (fields.hasField(this.asIndexer(Dmp._status))) m.setStatus(d.getStatus()); + if (fields.hasField(this.asIndexer(Dmp._groupId))) m.setGroupId(d.getGroupId()); + if (fields.hasField(this.asIndexer(Dmp._description))) m.setDescription(d.getDescription()); + if (fields.hasField(this.asIndexer(Dmp._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(Dmp._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(Dmp._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(Dmp._finalizedAt))) m.setFinalizedAt(d.getFinalizedAt()); + if (fields.hasField(this.asIndexer(Dmp._accessType))) m.setAccessType(d.getAccessType()); + if (fields.hasField(this.asIndexer(Dmp._language))) m.setLanguage(d.getLanguage()); + if (fields.hasField(this.asIndexer(Dmp._versionStatus))) m.setVersionStatus(d.getVersionStatus()); + if (fields.hasField(this.asIndexer(Dmp._publicAfter))) m.setPublicAfter(d.getPublicAfter()); + if (fields.hasField(this.asIndexer(Dmp._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(Dmp._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getCreatorId())) m.setCreator(userItemsMap.get(d.getCreatorId())); + if (!blueprintFields.isEmpty() && blueprintItemsMap != null && blueprintItemsMap.containsKey(d.getBlueprintId())) m.setBlueprint(blueprintItemsMap.get(d.getBlueprintId())); + if (entityDoisMap != null && !entityDoisMap.isEmpty() && entityDoisMap.containsKey(d.getId())) m.setEntityDois(entityDoisMap.get(d.getId())); + if (dmpReferencesMap != null && !dmpReferencesMap.isEmpty() && dmpReferencesMap.containsKey(d.getId())) m.setDmpReferences(dmpReferencesMap.get(d.getId())); + if (dmpUsersMap != null && !dmpUsersMap.isEmpty() && dmpUsersMap.containsKey(d.getId())) m.setDmpUsers(dmpUsersMap.get(d.getId())); + if (descriptionsMap != null && !descriptionsMap.isEmpty() && descriptionsMap.containsKey(d.getId())) m.setDescriptions(descriptionsMap.get(d.getId())); + if (dmpDescriptionTemplatesMap != null && !dmpDescriptionTemplatesMap.isEmpty() && dmpDescriptionTemplatesMap.containsKey(d.getId())) m.setDmpDescriptionTemplates(dmpDescriptionTemplatesMap.get(d.getId())); + if (!propertiesFields.isEmpty() && d.getProperties() != null){ + DmpPropertiesEntity propertyDefinition = this.jsonHandlingService.fromJsonSafe(DmpPropertiesEntity.class, d.getProperties()); + m.setProperties(this.builderFactory.builder(DmpPropertiesBuilder.class).authorize(this.authorize).build(propertiesFields, propertyDefinition)); + } + if (affiliatedResourceMap != null && !authorizationFlags.isEmpty()) m.setAuthorizationFlags(this.evaluateAuthorizationFlags(this.authorizationService, authorizationFlags, affiliatedResourceMap.getOrDefault(d.getId(), null))); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map> collectDmpReferences(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", DmpReference.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(DmpReference._dmp, DmpReference._id)); + DmpReferenceQuery query = this.queryFactory.query(DmpReferenceQuery.class).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpReferenceBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDmp().getId()); + + if (!fields.hasField(this.asIndexer(DmpReference._dmp, Dmp._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDmp() != null).peek(x -> { + x.getDmp().setId(null); + }); + } + + return itemMap; + } + + private Map> collectEntityDois(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", EntityDoi.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(EntityDoi._entityId)); + EntityDoiQuery query = this.queryFactory.query(EntityDoiQuery.class).authorize(this.authorize).types(EntityType.DMP).entityIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(EntityDoiBuilder.class).authorize(this.authorize).asMasterKey(query, clone, EntityDoi::getEntityId); + + if (!fields.hasField(this.asIndexer(EntityDoi._entityId))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getEntityId() != null).peek(x -> { + x.setEntityId(null); + }); + } + + return itemMap; + } + + private Map collectDmpBlueprints(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DmpBlueprint.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(DmpBlueprint._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpEntity::getBlueprintId).distinct().collect(Collectors.toList()), + x -> { + DmpBlueprint item = new DmpBlueprint(); + item.setId(x); + return item; + }, + DmpBlueprint::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(DmpBlueprint._id); + DmpBlueprintQuery q = this.queryFactory.query(DmpBlueprintQuery.class).authorize(this.authorize).ids(data.stream().map(DmpEntity::getBlueprintId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpBlueprintBuilder.class).authorize(this.authorize).asForeignKey(q, clone, DmpBlueprint::getId); + } + if (!fields.hasField(DmpBlueprint._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpEntity::getCreatorId).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(DmpEntity::getCreatorId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map> collectDmpUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DmpUser.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(DmpUser._dmp, DmpUser._id)); + DmpUserQuery query = this.queryFactory.query(DmpUserQuery.class).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpUserBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDmp().getId()); + + if (!fields.hasField(this.asIndexer(DmpUser._dmp, Dmp._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDmp() != null).peek(x -> { + x.getDmp().setId(null); + }); + } + + return itemMap; + } + + private Map> collectDmpDescriptions(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", Description.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(Description._dmp, Description._id)); + DescriptionQuery query = this.queryFactory.query(DescriptionQuery.class).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDmp().getId()); + + if (!fields.hasField(this.asIndexer(Description._dmp, Dmp._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDmp() != null).peek(x -> { + x.getDmp().setId(null); + }); + } + + return itemMap; + } + + private Map> collectDmpDescriptionTemplates(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", Description.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(DmpDescriptionTemplate._dmp, DmpDescriptionTemplate._id)); + DmpDescriptionTemplateQuery query = this.queryFactory.query(DmpDescriptionTemplateQuery.class).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpDescriptionTemplateBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDmp().getId()); + + if (!fields.hasField(this.asIndexer(DmpDescriptionTemplate._dmp, Dmp._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDmp() != null).peek(x -> { + x.getDmp().setId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/DmpDescriptionTemplateBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/DmpDescriptionTemplateBuilder.java new file mode 100644 index 000000000..a0d60100b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/DmpDescriptionTemplateBuilder.java @@ -0,0 +1,165 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpDescriptionTemplateEntity; +import org.opencdmp.data.DmpEntity; +import org.opencdmp.model.*; +import org.opencdmp.query.DescriptionTemplateQuery; +import org.opencdmp.query.DmpQuery; +import org.opencdmp.query.DmpUserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpDescriptionTemplateBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + private final TenantScope tenantScope; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpDescriptionTemplateBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpDescriptionTemplateBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.tenantScope = tenantScope; + } + + public DmpDescriptionTemplateBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet templateFields = fields.extractPrefixed(this.asPrefix(DmpDescriptionTemplate._descriptionTemplates)); + Map> templateItemsMap = this.collectDescriptionTemplates(templateFields, data); + + FieldSet currentDescriptionTemplateFields = fields.extractPrefixed(this.asPrefix(DmpDescriptionTemplate._currentDescriptionTemplate)); + Map currentDescriptionTemplateItemsMap = this.collectCurrentDescriptionTemplates(currentDescriptionTemplateFields, data); + + FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(DmpDescriptionTemplate._dmp)); + Map dmpItemsMap = this.collectDmps(dmpFields, data); + + List models = new ArrayList<>(); + for (DmpDescriptionTemplateEntity d : data) { + DmpDescriptionTemplate m = new DmpDescriptionTemplate(); + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._sectionId))) m.setSectionId(d.getSectionId()); + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._descriptionTemplateGroupId))) m.setDescriptionTemplateGroupId(d.getDescriptionTemplateGroupId()); + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(DmpDescriptionTemplate._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(DescriptionTemplateType._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!templateFields.isEmpty() && templateItemsMap != null && templateItemsMap.containsKey(d.getDescriptionTemplateGroupId())) m.setDescriptionTemplates(templateItemsMap.get(d.getDescriptionTemplateGroupId())); + if (!currentDescriptionTemplateFields.isEmpty() && currentDescriptionTemplateItemsMap != null && currentDescriptionTemplateItemsMap.containsKey(d.getDescriptionTemplateGroupId())) m.setCurrentDescriptionTemplate(currentDescriptionTemplateItemsMap.get(d.getDescriptionTemplateGroupId())); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) m.setDmp(dmpItemsMap.get(d.getDmpId())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + + private Map collectDmps(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Dmp.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Dmp._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpDescriptionTemplateEntity::getDmpId).distinct().collect(Collectors.toList()), + x -> { + Dmp item = new Dmp(); + item.setId(x); + return item; + }, + Dmp::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Dmp._id); + DmpQuery q = this.queryFactory.query(DmpQuery.class).authorize(this.authorize).ids(data.stream().map(DmpDescriptionTemplateEntity::getDmpId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Dmp::getId); + } + if (!fields.hasField(Dmp._id)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + } + + return itemMap; + } + + private Map> collectDescriptionTemplates(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DescriptionTemplate.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(DescriptionTemplate._groupId); + DescriptionTemplateQuery query = this.queryFactory.query(DescriptionTemplateQuery.class).authorize(this.authorize).groupIds(data.stream().map(DmpDescriptionTemplateEntity::getDescriptionTemplateGroupId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(this.authorize).asMasterKey(query, clone, DescriptionTemplate::getGroupId); + + if (!fields.hasField(DescriptionTemplate._groupId)) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getGroupId() != null).peek(x -> { + x.setGroupId(null); + }); + } + + return itemMap; + } + + private Map collectCurrentDescriptionTemplates(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DescriptionTemplate.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(DescriptionTemplate._groupId))) { + itemMap = this.asEmpty( + data.stream().map(DmpDescriptionTemplateEntity::getDescriptionTemplateGroupId).distinct().collect(Collectors.toList()), + x -> { + DescriptionTemplate item = new DescriptionTemplate(); + item.setGroupId(x); + return item; + }, + DescriptionTemplate::getGroupId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(DescriptionTemplate._id, DescriptionTemplate._groupId); + DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).authorize(this.authorize).versionStatuses(DescriptionTemplateVersionStatus.Current).groupIds(data.stream().map(DmpDescriptionTemplateEntity::getDescriptionTemplateGroupId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(this.authorize).asForeignKey(q, clone, DescriptionTemplate::getGroupId); + } + if (!fields.hasField(DescriptionTemplate._groupId)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setGroupId(null)).collect(Collectors.toList()); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/DmpReferenceBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/DmpReferenceBuilder.java new file mode 100644 index 000000000..1ccc754f6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/DmpReferenceBuilder.java @@ -0,0 +1,151 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.description.PropertyDefinitionEntity; +import org.opencdmp.commons.types.dmpreference.DmpReferenceDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpReferenceEntity; +import org.opencdmp.model.Description; +import org.opencdmp.model.Dmp; +import org.opencdmp.model.DmpReference; +import org.opencdmp.model.Reference; +import org.opencdmp.model.builder.descriptionpropertiesdefinition.PropertyDefinitionBuilder; +import org.opencdmp.model.builder.dmpreference.DmpReferenceDataBuilder; +import org.opencdmp.query.DmpQuery; +import org.opencdmp.query.ReferenceQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpReferenceBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + private final JsonHandlingService jsonHandlingService; + private final TenantScope tenantScope; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpReferenceBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory, JsonHandlingService jsonHandlingService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpReferenceBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.jsonHandlingService = jsonHandlingService; + this.tenantScope = tenantScope; + } + + public DmpReferenceBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet referenceFields = fields.extractPrefixed(this.asPrefix(DmpReference._reference)); + Map referenceItemsMap = this.collectReferences(referenceFields, data); + + FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(DmpReference._dmp)); + Map dmpItemsMap = this.collectDmps(dmpFields, data); + + FieldSet dataFields = fields.extractPrefixed(this.asPrefix(DmpReference._data)); + List models = new ArrayList<>(); + for (DmpReferenceEntity d : data) { + DmpReference m = new DmpReference(); + if (fields.hasField(this.asIndexer(DmpReference._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DmpReference._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(DmpReference._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DmpReference._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DmpReference._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(DmpReference._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!referenceFields.isEmpty() && referenceItemsMap != null && referenceItemsMap.containsKey(d.getReferenceId())) m.setReference(referenceItemsMap.get(d.getReferenceId())); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) m.setDmp(dmpItemsMap.get(d.getDmpId())); + if (!dataFields.isEmpty() && d.getData() != null){ + DmpReferenceDataEntity propertyDefinition = this.jsonHandlingService.fromJsonSafe(DmpReferenceDataEntity.class, d.getData()); + m.setData(this.builderFactory.builder(DmpReferenceDataBuilder.class).authorize(this.authorize).build(dataFields, propertyDefinition)); + } + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectReferences(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Reference.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Reference._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpReferenceEntity::getReferenceId).distinct().collect(Collectors.toList()), + x -> { + Reference item = new Reference(); + item.setId(x); + return item; + }, + Reference::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Reference._id); + ReferenceQuery q = this.queryFactory.query(ReferenceQuery.class).authorize(this.authorize).ids(data.stream().map(DmpReferenceEntity::getReferenceId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(ReferenceBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Reference::getId); + } + if (!fields.hasField(Reference._id)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + } + + return itemMap; + } + + private Map collectDmps(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Dmp.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Dmp._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpReferenceEntity::getDmpId).distinct().collect(Collectors.toList()), + x -> { + Dmp item = new Dmp(); + item.setId(x); + return item; + }, + Dmp::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Dmp._id); + DmpQuery q = this.queryFactory.query(DmpQuery.class).authorize(this.authorize).ids(data.stream().map(DmpReferenceEntity::getDmpId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Dmp::getId); + } + if (!fields.hasField(Dmp._id)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/DmpUserBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/DmpUserBuilder.java new file mode 100644 index 000000000..5a87943a0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/DmpUserBuilder.java @@ -0,0 +1,142 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpUserEntity; +import org.opencdmp.model.*; +import org.opencdmp.query.DmpQuery; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpUserBuilder extends BaseBuilder{ + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + private final TenantScope tenantScope; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpUserBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpUserBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.tenantScope = tenantScope; + } + + public DmpUserBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(DmpUser._dmp)); + Map dmpItemsMap = this.collectDmps(dmpFields, data); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(DmpUser._user)); + Map userItemsMap = this.collectUsers(userFields, data); + + List models = new ArrayList<>(); + for (DmpUserEntity d : data) { + DmpUser m = new DmpUser(); + if (fields.hasField(this.asIndexer(DmpUser._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(DmpUser._role))) m.setRole(d.getRole()); + if (fields.hasField(this.asIndexer(DmpUser._sectionId))) m.setSectionId(d.getSectionId()); + if (fields.hasField(this.asIndexer(DmpUser._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(DmpUser._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(DmpUser._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(DmpUser._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(DmpUser._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) m.setDmp(dmpItemsMap.get(d.getDmpId())); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpUserEntity::getUserId).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(DmpUserEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectDmps(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Dmp.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Dmp._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpUserEntity::getDmpId).distinct().collect(Collectors.toList()), + x -> { + Dmp item = new Dmp(); + item.setId(x); + return item; + }, + Dmp::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Dmp._id); + DmpQuery q = this.queryFactory.query(DmpQuery.class).authorize(this.authorize).ids(data.stream().map(DmpUserEntity::getDmpId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Dmp::getId); + } + if (!fields.hasField(Dmp._id)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/EntityDoiBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/EntityDoiBuilder.java new file mode 100644 index 000000000..788ba4097 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/EntityDoiBuilder.java @@ -0,0 +1,76 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.EntityDoiEntity; +import org.opencdmp.model.EntityDoi; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class EntityDoiBuilder extends BaseBuilder { + + private final TenantScope tenantScope; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public EntityDoiBuilder( + ConventionService conventionService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(EntityDoiBuilder.class))); + this.tenantScope = tenantScope; + } + + public EntityDoiBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (EntityDoiEntity d : data) { + EntityDoi m = new EntityDoi(); + if (fields.hasField(this.asIndexer(EntityDoi._id))) + m.setId(d.getId()); + if (fields.hasField(this.asIndexer(EntityDoi._doi))) + m.setDoi(d.getDoi()); + if (fields.hasField(this.asIndexer(EntityDoi._entityId))) + m.setEntityId(d.getEntityId()); + if (fields.hasField(this.asIndexer(EntityDoi._entityType))) + m.setEntityType(d.getEntityType()); + if (fields.hasField(this.asIndexer(EntityDoi._repositoryId))) + m.setRepositoryId(d.getRepositoryId()); + if (fields.hasField(this.asIndexer(EntityDoi._createdAt))) + m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(EntityDoi._updatedAt))) + m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(EntityDoi._isActive))) + m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(EntityDoi._hash))) + m.setHash(hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(EntityDoi._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/LanguageBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/LanguageBuilder.java new file mode 100644 index 000000000..f1e98128e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/LanguageBuilder.java @@ -0,0 +1,66 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.LanguageEntity; +import org.opencdmp.model.Language; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LanguageBuilder extends BaseBuilder{ + private final TenantScope tenantScope; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public LanguageBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory, XmlHandlingService xmlHandlingService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(LanguageBuilder.class))); + this.tenantScope = tenantScope; + } + + public LanguageBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (LanguageEntity d : data) { + Language m = new Language(); + if (fields.hasField(this.asIndexer(Language._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(Language._code))) m.setCode(d.getCode()); + if (fields.hasField(this.asIndexer(Language._payload))) m.setPayload(d.getPayload()); + if (fields.hasField(this.asIndexer(Language._ordinal))) m.setOrdinal(d.getOrdinal()); + if (fields.hasField(this.asIndexer(Language._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(Language._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(Language._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(Language._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(Language._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/LockBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/LockBuilder.java new file mode 100644 index 000000000..c38464cb8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/LockBuilder.java @@ -0,0 +1,109 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.LockEntity; +import org.opencdmp.model.Lock; +import org.opencdmp.model.Tenant; +import org.opencdmp.model.User; +import org.opencdmp.query.TenantQuery; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LockBuilder extends BaseBuilder{ + + private final BuilderFactory builderFactory; + private final TenantScope tenantScope; + private final QueryFactory queryFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public LockBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, TenantScope tenantScope, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(LockBuilder.class))); + this.builderFactory = builderFactory; + this.tenantScope = tenantScope; + this.queryFactory = queryFactory; + } + + public LockBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(Lock._lockedBy)); + Map userMap = this.collectUsers(userFields, data); + + List models = new ArrayList<>(); + for (LockEntity d : data) { + Lock m = new Lock(); + if (fields.hasField(this.asIndexer(Lock._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(Lock._target))) m.setTarget(d.getTarget()); + if (fields.hasField(this.asIndexer(Lock._targetType))) m.setTargetType(d.getTargetType()); + if (fields.hasField(this.asIndexer(Lock._lockedAt))) m.setLockedAt(d.getLockedAt()); + if (fields.hasField(this.asIndexer(Lock._touchedAt))) m.setTouchedAt(d.getTouchedAt()); + if (fields.hasField(this.asIndexer(Lock._hash))) m.setHash(this.hashValue(d.getTouchedAt())); + if (fields.hasField(this.asIndexer(Lock._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!userFields.isEmpty() && userMap != null && userMap.containsKey(d.getLockedBy())) m.setLockedBy(userMap.get(d.getLockedBy())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(LockEntity::getLockedBy).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(LockEntity::getLockedBy).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/PrefillingSourceBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/PrefillingSourceBuilder.java new file mode 100644 index 000000000..c8fb2a7db --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/PrefillingSourceBuilder.java @@ -0,0 +1,77 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.prefillingsource.PrefillingSourceDefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.PrefillingSourceEntity; +import org.opencdmp.model.PrefillingSource; +import org.opencdmp.model.builder.prefillingsourcedefinition.PrefillingSourceDefinitionBuilder; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PrefillingSourceBuilder extends BaseBuilder{ + + private final BuilderFactory builderFactory; + private final XmlHandlingService xmlHandlingService; + private final TenantScope tenantScope; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PrefillingSourceBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, XmlHandlingService xmlHandlingService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PrefillingSourceBuilder.class))); + this.builderFactory = builderFactory; + this.tenantScope = tenantScope; + this.xmlHandlingService = xmlHandlingService; + } + + public PrefillingSourceBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet definitionFields = fields.extractPrefixed(this.asPrefix(PrefillingSource._definition)); + + List models = new ArrayList<>(); + for (PrefillingSourceEntity d : data) { + PrefillingSource m = new PrefillingSource(); + if (fields.hasField(this.asIndexer(PrefillingSource._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(PrefillingSource._label))) m.setLabel(d.getLabel()); + if (!definitionFields.isEmpty() && d.getDefinition() != null){ + PrefillingSourceDefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(PrefillingSourceDefinitionEntity.class, d.getDefinition()); + m.setDefinition(this.builderFactory.builder(PrefillingSourceDefinitionBuilder.class).authorize(this.authorize).build(definitionFields, definition)); + } if (fields.hasField(this.asIndexer(PrefillingSource._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(PrefillingSource._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(PrefillingSource._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(PrefillingSource._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(PrefillingSource._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/PublicDescriptionBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDescriptionBuilder.java new file mode 100644 index 000000000..dd13acb98 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDescriptionBuilder.java @@ -0,0 +1,177 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionEntity; +import org.opencdmp.model.*; +import org.opencdmp.query.DescriptionTemplateQuery; +import org.opencdmp.query.DmpDescriptionTemplateQuery; +import org.opencdmp.query.DmpQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDescriptionBuilder extends BaseBuilder { + + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PublicDescriptionBuilder( + ConventionService conventionService, + QueryFactory queryFactory, + BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PublicDescriptionBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + public PublicDescriptionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet dmpDescriptionTemplateFields = fields.extractPrefixed(this.asPrefix(PublicDescription._dmpDescriptionTemplate)); + Map dmpDescriptionTemplateItemsMap = this.collectDmpDescriptionTemplates(dmpDescriptionTemplateFields, data); + + FieldSet descriptionTemplateFields = fields.extractPrefixed(this.asPrefix(PublicDescription._descriptionTemplate)); + Map descriptionTemplateItemsMap = this.collectDescriptionTemplates(descriptionTemplateFields, data); + + FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(PublicDescription._dmp)); + Map dmpItemsMap = this.collectDmps(dmpFields, data); + + List models = new ArrayList<>(); + for (DescriptionEntity d : data) { + PublicDescription m = new PublicDescription(); + if (fields.hasField(this.asIndexer(PublicDescription._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(PublicDescription._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(PublicDescription._status))) m.setStatus(d.getStatus()); + if (fields.hasField(this.asIndexer(PublicDescription._description))) m.setDescription(d.getDescription()); + if (fields.hasField(this.asIndexer(PublicDescription._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(PublicDescription._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(PublicDescription._finalizedAt))) m.setFinalizedAt(d.getFinalizedAt()); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) m.setDmp(dmpItemsMap.get(d.getDmpId())); + if (!dmpDescriptionTemplateFields.isEmpty() && dmpDescriptionTemplateItemsMap != null && dmpDescriptionTemplateItemsMap.containsKey(d.getDmpDescriptionTemplateId())) m.setDmpDescriptionTemplate(dmpDescriptionTemplateItemsMap.get(d.getDmpDescriptionTemplateId())); + if (!descriptionTemplateFields.isEmpty() && descriptionTemplateItemsMap != null && descriptionTemplateItemsMap.containsKey(d.getDescriptionTemplateId())) m.setDescriptionTemplate(descriptionTemplateItemsMap.get(d.getDescriptionTemplateId())); + models.add(m); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map collectDmpDescriptionTemplates(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", PublicDmpDescriptionTemplate.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(PublicDmpDescriptionTemplate._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionEntity::getDmpDescriptionTemplateId).distinct().collect(Collectors.toList()), + x -> { + PublicDmpDescriptionTemplate item = new PublicDmpDescriptionTemplate(); + item.setId(x); + return item; + }, + PublicDmpDescriptionTemplate::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(PublicDmpDescriptionTemplate._id); + DmpDescriptionTemplateQuery q = this.queryFactory.query(DmpDescriptionTemplateQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getDmpDescriptionTemplateId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicDmpDescriptionTemplateBuilder.class).authorize(this.authorize).asForeignKey(q, clone, PublicDmpDescriptionTemplate::getId); + } + if (!fields.hasField(PublicDmpDescriptionTemplate._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectDescriptionTemplates(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", PublicDescriptionTemplate.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(PublicDescriptionTemplate._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList()), + x -> { + PublicDescriptionTemplate item = new PublicDescriptionTemplate(); + item.setId(x); + return item; + }, + PublicDescriptionTemplate::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(PublicDescriptionTemplate._id); + DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicDescriptionTemplateBuilder.class).authorize(this.authorize).asForeignKey(q, clone, PublicDescriptionTemplate::getId); + } + if (!fields.hasField(PublicDescriptionTemplate._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectDmps(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", PublicDmp.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(PublicDmp._id))) { + itemMap = this.asEmpty( + data.stream().map(DescriptionEntity::getDmpId).distinct().collect(Collectors.toList()), + x -> { + PublicDmp item = new PublicDmp(); + item.setId(x); + return item; + }, + PublicDmp::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(PublicDmp._id); + DmpQuery q = this.queryFactory.query(DmpQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getDmpId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicDmpBuilder.class).authorize(this.authorize).asForeignKey(q, clone, PublicDmp::getId); + } + if (!fields.hasField(PublicDmp._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/PublicDescriptionTemplateBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDescriptionTemplateBuilder.java new file mode 100644 index 000000000..3aeefc151 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDescriptionTemplateBuilder.java @@ -0,0 +1,60 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionTemplateEntity; +import org.opencdmp.model.PublicDescriptionTemplate; +import org.opencdmp.query.DescriptionTemplateTypeQuery; +import org.opencdmp.query.UserDescriptionTemplateQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDescriptionTemplateBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public PublicDescriptionTemplateBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PublicDescriptionTemplateBuilder.class))); + } + + public PublicDescriptionTemplateBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + List models = new ArrayList<>(); + for (DescriptionTemplateEntity d : data) { + PublicDescriptionTemplate m = new PublicDescriptionTemplate(); + if (fields.hasField(this.asIndexer(PublicDescriptionTemplate._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(PublicDescriptionTemplate._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(PublicDescriptionTemplate._description))) m.setDescription(d.getDescription()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpBuilder.java new file mode 100644 index 000000000..83bc8f99f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpBuilder.java @@ -0,0 +1,170 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.EntityType; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpEntity; +import org.opencdmp.model.*; +import org.opencdmp.query.DescriptionQuery; +import org.opencdmp.query.DmpReferenceQuery; +import org.opencdmp.query.DmpUserQuery; +import org.opencdmp.query.EntityDoiQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDmpBuilder extends BaseBuilder { + + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PublicDmpBuilder(ConventionService conventionService, + QueryFactory queryFactory, + BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PublicDmpBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + public PublicDmpBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + + FieldSet dmpReferencesFields = fields.extractPrefixed(this.asPrefix(PublicDmp._dmpReferences)); + Map> dmpReferenceMap = this.collectDmpReferences(dmpReferencesFields, data); + + FieldSet dmpUsersFields = fields.extractPrefixed(this.asPrefix(PublicDmp._dmpUsers)); + Map> dmpUsersMap = this.collectDmpUsers(dmpUsersFields, data); + + FieldSet descriptionsFields = fields.extractPrefixed(this.asPrefix(PublicDmp._descriptions)); + Map> descriptionsMap = this.collectDmpDescriptions(descriptionsFields, data); + + FieldSet entityDoisFields = fields.extractPrefixed(this.asPrefix(PublicDmp._entityDois)); + Map> entityDoisMap = this.collectEntityDois(entityDoisFields, data); + + for (DmpEntity d : data) { + PublicDmp m = new PublicDmp(); + if (fields.hasField(this.asIndexer(PublicDmp._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(PublicDmp._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(PublicDmp._version))) m.setVersion(d.getVersion()); + if (fields.hasField(this.asIndexer(PublicDmp._description))) m.setDescription(d.getDescription()); + if (fields.hasField(this.asIndexer(PublicDmp._finalizedAt))) m.setFinalizedAt(d.getFinalizedAt()); + if (fields.hasField(this.asIndexer(PublicDmp._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(PublicDmp._accessType))) m.setAccessType(d.getAccessType()); + if (fields.hasField(this.asIndexer(PublicDmp._status))) m.setStatus(d.getStatus()); + if (fields.hasField(this.asIndexer(PublicDmp._groupId))) m.setGroupId(d.getGroupId()); + if (fields.hasField(this.asIndexer(PublicDmp._accessType))) m.setAccessType(d.getAccessType()); + + if (dmpReferenceMap != null && !dmpReferenceMap.isEmpty() && dmpReferenceMap.containsKey(d.getId())) m.setDmpReferences(dmpReferenceMap.get(d.getId())); + if (dmpUsersMap != null && !dmpUsersMap.isEmpty() && dmpUsersMap.containsKey(d.getId())) m.setDmpUsers(dmpUsersMap.get(d.getId())); + if (descriptionsMap != null && !descriptionsMap.isEmpty() && descriptionsMap.containsKey(d.getId())) m.setDescriptions(descriptionsMap.get(d.getId())); + if (entityDoisMap != null && !entityDoisMap.isEmpty() && entityDoisMap.containsKey(d.getId())) m.setEntityDois(entityDoisMap.get(d.getId())); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map> collectDmpReferences(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", PublicDmpReference.class.getSimpleName()); + + Map> itemMap = null; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(PublicDmpReference._dmp, PublicDmp._id)); + DmpReferenceQuery query = this.queryFactory.query(DmpReferenceQuery.class).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicDmpReferenceBuilder.class).authorize(this.authorize).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDmp().getId()); + + if (!fields.hasField(this.asIndexer(PublicDmpReference._dmp, PublicDmp._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDmp() != null).peek(x -> { + x.getDmp().setId(null); + }); + } + + return itemMap; + } + + private Map> collectDmpUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", PublicDmpUser.class.getSimpleName()); + + Map> itemMap = null; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(PublicDmpUser._dmp, PublicDmp._id)); + DmpUserQuery query = this.queryFactory.query(DmpUserQuery.class).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicDmpUserBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDmp().getId()); + + if (!fields.hasField(this.asIndexer(PublicDmpUser._dmp, PublicDmp._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDmp() != null).peek(x -> { + x.getDmp().setId(null); + }); + } + + return itemMap; + } + + private Map> collectDmpDescriptions(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", PublicDescription.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(PublicDescription._dmp, PublicDescription._id)); + DescriptionQuery query = this.queryFactory.query(DescriptionQuery.class).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicDescriptionBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getDmp().getId()); + + if (!fields.hasField(this.asIndexer(PublicDescription._dmp, PublicDescription._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getDmp() != null).peek(x -> { + x.getDmp().setId(null); + }); + } + + return itemMap; + } + + private Map> collectEntityDois(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", PublicEntityDoi.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(PublicEntityDoi._entityId)); + EntityDoiQuery query = this.queryFactory.query(EntityDoiQuery.class).authorize(this.authorize).types(EntityType.DMP).entityIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicEntityDoiBuilder.class).authorize(this.authorize).asMasterKey(query, clone, PublicEntityDoi::getEntityId); + + if (!fields.hasField(this.asIndexer(PublicEntityDoi._entityId))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getEntityId() != null).peek(x -> { + x.setEntityId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpDescriptionTemplateBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpDescriptionTemplateBuilder.java new file mode 100644 index 000000000..960b84031 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpDescriptionTemplateBuilder.java @@ -0,0 +1,100 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpDescriptionTemplateEntity; +import org.opencdmp.model.PublicDescriptionTemplate; +import org.opencdmp.model.PublicDmp; +import org.opencdmp.model.PublicDmpDescriptionTemplate; +import org.opencdmp.query.DescriptionTemplateQuery; +import org.opencdmp.query.DmpQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDmpDescriptionTemplateBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PublicDmpDescriptionTemplateBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PublicDmpDescriptionTemplateBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public PublicDmpDescriptionTemplateBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + + FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(PublicDmpDescriptionTemplate._dmp)); + Map dmpItemsMap = this.collectDmps(dmpFields, data); + + List models = new ArrayList<>(); + for (DmpDescriptionTemplateEntity d : data) { + PublicDmpDescriptionTemplate m = new PublicDmpDescriptionTemplate(); + if (fields.hasField(this.asIndexer(PublicDmpDescriptionTemplate._id))) m.setId(d.getId()); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) m.setDmp(dmpItemsMap.get(d.getDmpId())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectDmps(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", PublicDmp.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(PublicDmp._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpDescriptionTemplateEntity::getDmpId).distinct().collect(Collectors.toList()), + x -> { + PublicDmp item = new PublicDmp(); + item.setId(x); + return item; + }, + PublicDmp::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(PublicDmp._id); + DmpQuery q = this.queryFactory.query(DmpQuery.class).authorize(this.authorize).ids(data.stream().map(DmpDescriptionTemplateEntity::getDmpId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicDmpBuilder.class).authorize(this.authorize).asForeignKey(q, clone, PublicDmp::getId); + } + if (!fields.hasField(PublicDmp._id)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpReferenceBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpReferenceBuilder.java new file mode 100644 index 000000000..ea160e59a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpReferenceBuilder.java @@ -0,0 +1,132 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpReferenceEntity; +import org.opencdmp.model.PublicDmp; +import org.opencdmp.model.PublicDmpReference; +import org.opencdmp.model.PublicReference; +import org.opencdmp.query.DmpQuery; +import org.opencdmp.query.ReferenceQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDmpReferenceBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PublicDmpReferenceBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PublicDmpReferenceBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public PublicDmpReferenceBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet referenceFields = fields.extractPrefixed(this.asPrefix(PublicDmpReference._reference)); + Map referenceItemsMap = this.collectReferences(referenceFields, data); + + FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(PublicDmpReference._dmp)); + Map dmpItemsMap = this.collectDmps(dmpFields, data); + + List models = new ArrayList<>(); + for (DmpReferenceEntity d : data) { + PublicDmpReference m = new PublicDmpReference(); + if (fields.hasField(this.asIndexer(PublicDmpReference._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(PublicDmpReference._isActive))) m.setIsActive(d.getIsActive()); + if (!referenceFields.isEmpty() && referenceItemsMap != null && referenceItemsMap.containsKey(d.getReferenceId())) m.setReference(referenceItemsMap.get(d.getReferenceId())); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) m.setDmp(dmpItemsMap.get(d.getDmpId())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectReferences(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", PublicReference.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(PublicReference._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpReferenceEntity::getReferenceId).distinct().collect(Collectors.toList()), + x -> { + PublicReference item = new PublicReference(); + item.setId(x); + return item; + }, + PublicReference::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(PublicReference._id); + ReferenceQuery q = this.queryFactory.query(ReferenceQuery.class).authorize(this.authorize).isActive(IsActive.Active).ids(data.stream().map(DmpReferenceEntity::getReferenceId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicReferenceBuilder.class).authorize(this.authorize).asForeignKey(q, clone, PublicReference::getId); + } + if (!fields.hasField(PublicReference._id)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + } + + return itemMap; + } + + private Map collectDmps(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", PublicDmp.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(PublicDmp._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpReferenceEntity::getDmpId).distinct().collect(Collectors.toList()), + x -> { + PublicDmp item = new PublicDmp(); + item.setId(x); + return item; + }, + PublicDmp::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(PublicDmp._id); + DmpQuery q = this.queryFactory.query(DmpQuery.class).authorize(this.authorize).isActive(IsActive.Active).ids(data.stream().map(DmpReferenceEntity::getDmpId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicDmpBuilder.class).authorize(this.authorize).asForeignKey(q, clone, PublicDmp::getId); + } + if (!fields.hasField(PublicDmp._id)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpUserBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpUserBuilder.java new file mode 100644 index 000000000..6f6bc22a7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/PublicDmpUserBuilder.java @@ -0,0 +1,135 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpUserEntity; +import org.opencdmp.model.PublicDmp; +import org.opencdmp.model.PublicDmpUser; +import org.opencdmp.model.PublicUser; +import org.opencdmp.model.User; +import org.opencdmp.query.DmpQuery; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDmpUserBuilder extends BaseBuilder{ + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PublicDmpUserBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PublicDmpUserBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public PublicDmpUserBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(PublicDmpUser._user)); + Map userItemsMap = this.collectUsers(userFields, data); + + FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(PublicDmpUser._dmp)); + Map dmpItemsMap = this.collectDmps(dmpFields, data); + + List models = new ArrayList<>(); + for (DmpUserEntity d : data) { + PublicDmpUser m = new PublicDmpUser(); + if (fields.hasField(this.asIndexer(PublicDmpUser._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(PublicDmpUser._role))) m.setRole(d.getRole()); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getDmpId())) m.setDmp(dmpItemsMap.get(d.getDmpId())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(PublicUser._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpUserEntity::getUserId).distinct().collect(Collectors.toList()), + x -> { + PublicUser item = new PublicUser(); + item.setId(x); + return item; + }, + PublicUser::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(PublicUser._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(DmpUserEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicUserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, PublicUser::getId); + } + if (!fields.hasField(PublicUser._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectDmps(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", PublicDmp.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(PublicDmp._id))) { + itemMap = this.asEmpty( + data.stream().map(DmpUserEntity::getDmpId).distinct().collect(Collectors.toList()), + x -> { + PublicDmp item = new PublicDmp(); + item.setId(x); + return item; + }, + PublicDmp::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(PublicDmp._id); + DmpQuery q = this.queryFactory.query(DmpQuery.class).authorize(this.authorize).ids(data.stream().map(DmpUserEntity::getDmpId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicDmpBuilder.class).authorize(this.authorize).asForeignKey(q, clone, PublicDmp::getId); + } + if (!fields.hasField(PublicDmp._id)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/PublicEntityDoiBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/PublicEntityDoiBuilder.java new file mode 100644 index 000000000..2bbc35187 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/PublicEntityDoiBuilder.java @@ -0,0 +1,69 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.EntityDoiEntity; +import org.opencdmp.model.*; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicEntityDoiBuilder extends BaseBuilder { + + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PublicEntityDoiBuilder( + ConventionService conventionService, + QueryFactory queryFactory, + BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PublicEntityDoiBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + public PublicEntityDoiBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (EntityDoiEntity d : data) { + PublicEntityDoi m = new PublicEntityDoi(); + if (fields.hasField(this.asIndexer(PublicEntityDoi._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(PublicEntityDoi._entityType))) m.setEntityType(d.getEntityType()); + if (fields.hasField(this.asIndexer(PublicEntityDoi._repositoryId))) m.setRepositoryId(d.getRepositoryId()); + if (fields.hasField(this.asIndexer(PublicEntityDoi._doi))) m.setDoi(d.getDoi()); + if (fields.hasField(this.asIndexer(PublicEntityDoi._entityId))) m.setEntityId(d.getEntityId()); + + models.add(m); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/PublicReferenceBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/PublicReferenceBuilder.java new file mode 100644 index 000000000..7991737bd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/PublicReferenceBuilder.java @@ -0,0 +1,104 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpReferenceEntity; +import org.opencdmp.data.ReferenceEntity; +import org.opencdmp.model.PublicDmp; +import org.opencdmp.model.PublicDmpUser; +import org.opencdmp.model.PublicReference; +import org.opencdmp.model.PublicReferenceType; +import org.opencdmp.query.DmpQuery; +import org.opencdmp.query.ReferenceTypeQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicReferenceBuilder extends BaseBuilder{ + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PublicReferenceBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PublicReferenceBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public PublicReferenceBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + + FieldSet typeFields = fields.extractPrefixed(this.asPrefix(PublicReference._type)); + Map typeItemsMap = this.collectReferenceTypes(typeFields, data); + + List models = new ArrayList<>(); + for (ReferenceEntity d : data) { + PublicReference m = new PublicReference(); + if (fields.hasField(this.asIndexer(PublicReference._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(PublicReference._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(PublicReference._reference))) m.setReference(d.getReference()); + if (fields.hasField(this.asIndexer(PublicReference._description))) m.setDescription(d.getDescription()); + if (!typeFields.isEmpty() && typeItemsMap != null && typeItemsMap.containsKey(d.getTypeId())) m.setType(typeItemsMap.get(d.getTypeId())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + + + private Map collectReferenceTypes(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", PublicReferenceType.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(PublicReferenceType._id))) { + itemMap = this.asEmpty( + data.stream().map(ReferenceEntity::getTypeId).distinct().collect(Collectors.toList()), + x -> { + PublicReferenceType item = new PublicReferenceType(); + item.setId(x); + return item; + }, + PublicReferenceType::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(PublicReferenceType._id); + ReferenceTypeQuery q = this.queryFactory.query(ReferenceTypeQuery.class).authorize(this.authorize).isActive(IsActive.Active).ids(data.stream().map(ReferenceEntity::getTypeId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(PublicReferenceTypeBuilder.class).authorize(this.authorize).asForeignKey(q, clone, PublicReferenceType::getId); + } + if (!fields.hasField(PublicReferenceType._id)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + } + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/PublicReferenceTypeBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/PublicReferenceTypeBuilder.java new file mode 100644 index 000000000..250fba9d8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/PublicReferenceTypeBuilder.java @@ -0,0 +1,54 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.ReferenceTypeEntity; +import org.opencdmp.model.PublicReferenceType; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicReferenceTypeBuilder extends BaseBuilder{ + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PublicReferenceTypeBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PublicReferenceTypeBuilder.class))); + } + + public PublicReferenceTypeBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (ReferenceTypeEntity d : data) { + PublicReferenceType m = new PublicReferenceType(); + if (fields.hasField(this.asIndexer(PublicReferenceType._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(PublicReferenceType._name))) m.setName(d.getName()); + if (fields.hasField(this.asIndexer(PublicReferenceType._code))) m.setCode(d.getCode()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/PublicUserBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/PublicUserBuilder.java new file mode 100644 index 000000000..ceb608699 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/PublicUserBuilder.java @@ -0,0 +1,57 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.UserEntity; +import org.opencdmp.model.PublicUser; +import org.opencdmp.model.User; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicUserBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PublicUserBuilder(ConventionService conventionService + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PublicUserBuilder.class))); + } + + public PublicUserBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + + for (UserEntity d : data) { + PublicUser m = new PublicUser(); + if (fields.hasField(this.asIndexer(PublicUser._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(PublicUser._name))) m.setName(d.getName()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/RecentActivityItemBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/RecentActivityItemBuilder.java new file mode 100644 index 000000000..08e6358a4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/RecentActivityItemBuilder.java @@ -0,0 +1,132 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import org.opencdmp.commons.enums.RecentActivityItemType; +import org.opencdmp.commons.types.dashborad.RecentActivityItemEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.*; +import org.opencdmp.query.DescriptionQuery; +import org.opencdmp.query.DescriptionTemplateQuery; +import org.opencdmp.query.DmpQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class RecentActivityItemBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public RecentActivityItemBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(RecentActivityItemBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public RecentActivityItemBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet descriptionFields = fields.extractPrefixed(this.asPrefix(RecentActivityItem._description)); + Map descriptionItemsMap = this.collectDescriptions(descriptionFields, data); + + FieldSet dmpFields = fields.extractPrefixed(this.asPrefix(RecentActivityItem._dmp)); + Map dmpItemsMap = this.collectDmps(dmpFields, data); + + List models = new ArrayList<>(); + for (RecentActivityItemEntity d : data) { + RecentActivityItem m = new RecentActivityItem(); + if (fields.hasField(this.asIndexer(RecentActivityItem._type))) m.setType(d.getType()); + if (!descriptionFields.isEmpty() && descriptionItemsMap != null && descriptionItemsMap.containsKey(d.getId())) m.setDescription(descriptionItemsMap.get(d.getId())); + if (!dmpFields.isEmpty() && dmpItemsMap != null && dmpItemsMap.containsKey(d.getId())) m.setDmp(dmpItemsMap.get(d.getId())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + + private Map collectDmps(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Dmp.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Dmp._id))) { + itemMap = this.asEmpty( + data.stream().filter(x-> x.getType().equals(RecentActivityItemType.Dmp)).map(RecentActivityItemEntity::getId).distinct().collect(Collectors.toList()), + x -> { + Dmp item = new Dmp(); + item.setId(x); + return item; + }, + Dmp::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Dmp._id); + DmpQuery q = this.queryFactory.query(DmpQuery.class).authorize(this.authorize).ids(data.stream().filter(x-> x.getType().equals(RecentActivityItemType.Dmp)).map(RecentActivityItemEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Dmp::getId); + } + if (!fields.hasField(Dmp._id)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + } + + return itemMap; + } + + private Map collectDescriptions(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Description.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Description._id))) { + itemMap = this.asEmpty( + data.stream().filter(x-> x.getType().equals(RecentActivityItemType.Description)).map(RecentActivityItemEntity::getId).distinct().collect(Collectors.toList()), + x -> { + Description item = new Description(); + item.setId(x); + return item; + }, + Description::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Description._id); + DescriptionQuery q = this.queryFactory.query(DescriptionQuery.class).authorize(this.authorize).ids(data.stream().filter(x-> x.getType().equals(RecentActivityItemType.Description)).map(RecentActivityItemEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Description::getId); + } + if (!fields.hasField(Description._id)) { + itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/ReferenceBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/ReferenceBuilder.java new file mode 100644 index 000000000..6f6a2105e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/ReferenceBuilder.java @@ -0,0 +1,184 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.reference.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionEntity; +import org.opencdmp.data.ReferenceEntity; +import org.opencdmp.model.DmpReference; +import org.opencdmp.model.Reference; +import org.opencdmp.model.ReferenceType; +import org.opencdmp.model.User; +import org.opencdmp.model.builder.referencedefinition.DefinitionBuilder; +import org.opencdmp.query.DmpReferenceQuery; +import org.opencdmp.query.ReferenceTypeQuery; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceBuilder extends BaseBuilder{ + + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private final XmlHandlingService xmlHandlingService; + private final TenantScope tenantScope; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ReferenceBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory, XmlHandlingService xmlHandlingService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.xmlHandlingService = xmlHandlingService; + this.tenantScope = tenantScope; + } + + public ReferenceBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //ToDo FieldSet userInfoFields = fields.extractPrefixed(this.asPrefix(Reference._createdBy)); + FieldSet definitionFields = fields.extractPrefixed(this.asPrefix(Reference._definition)); + + FieldSet dmpReferencesFields = fields.extractPrefixed(this.asPrefix(Reference._dmpReferences)); + Map> dmpReferenceMap = this.collectDmpReferences(dmpReferencesFields, data); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(Reference._createdBy)); + Map userItemsMap = this.collectUsers(userFields, data); + + FieldSet typeFields = fields.extractPrefixed(this.asPrefix(Reference._type)); + Map typeItemsMap = this.collectReferenceTypes(typeFields, data); + + List models = new ArrayList<>(); + for (ReferenceEntity d : data) { + Reference m = new Reference(); + if (fields.hasField(this.asIndexer(Reference._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(Reference._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(Reference._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(Reference._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(Reference._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(Reference._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (!definitionFields.isEmpty() && d.getDefinition() != null){ + DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, d.getDefinition()); + m.setDefinition(this.builderFactory.builder(DefinitionBuilder.class).authorize(this.authorize).build(definitionFields, definition)); + } + if (fields.hasField(this.asIndexer(Reference._reference))) m.setReference(d.getReference()); + if (fields.hasField(this.asIndexer(Reference._abbreviation))) m.setAbbreviation(d.getAbbreviation()); + if (fields.hasField(this.asIndexer(Reference._description))) m.setDescription(d.getDescription()); + if (fields.hasField(this.asIndexer(Reference._source))) m.setSource(d.getSource()); + if (fields.hasField(this.asIndexer(Reference._sourceType))) m.setSourceType(d.getSourceType()); + if (!typeFields.isEmpty() && typeItemsMap != null && typeItemsMap.containsKey(d.getTypeId())) m.setType(typeItemsMap.get(d.getTypeId())); + if (dmpReferenceMap != null && !dmpReferenceMap.isEmpty() && dmpReferenceMap.containsKey(d.getId())) m.setDmpReferences(dmpReferenceMap.get(d.getId())); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getCreatedById())) m.setCreatedBy(userItemsMap.get(d.getCreatedById())); + if (fields.hasField(this.asIndexer(Reference._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectReferenceTypes(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", ReferenceType.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(ReferenceType._id))) { + itemMap = this.asEmpty( + data.stream().map(ReferenceEntity::getTypeId).distinct().collect(Collectors.toList()), + x -> { + ReferenceType item = new ReferenceType(); + item.setId(x); + return item; + }, + ReferenceType::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(ReferenceType._id); + ReferenceTypeQuery q = this.queryFactory.query(ReferenceTypeQuery.class).authorize(this.authorize).ids(data.stream().map(ReferenceEntity::getTypeId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(ReferenceTypeBuilder.class).authorize(this.authorize).asForeignKey(q, clone, ReferenceType::getId); + } + if (!fields.hasField(ReferenceType._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(ReferenceEntity::getCreatedById).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(ReferenceEntity::getCreatedById).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map> collectDmpReferences(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", DmpReference.class.getSimpleName()); + + Map> itemMap = null; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(DmpReference._reference, Reference._id)); + DmpReferenceQuery query = this.queryFactory.query(DmpReferenceQuery.class).authorize(this.authorize).referenceIds(data.stream().map(ReferenceEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpReferenceBuilder.class).authorize(this.authorize).authorize(this.authorize).asMasterKey(query, clone, x -> x.getReference().getId()); + + if (!fields.hasField(this.asIndexer(DmpReference._reference, Reference._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getReference() != null).map(x -> { + x.getReference().setId(null); + return x; + }).collect(Collectors.toList()); + } + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/ReferenceTypeBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/ReferenceTypeBuilder.java new file mode 100644 index 000000000..3eec29f4b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/ReferenceTypeBuilder.java @@ -0,0 +1,78 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.referencetype.ReferenceTypeDefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.ReferenceTypeEntity; +import org.opencdmp.model.ReferenceType; +import org.opencdmp.model.builder.referencetypedefinition.ReferenceTypeDefinitionBuilder; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeBuilder extends BaseBuilder{ + + private final BuilderFactory builderFactory; + private final XmlHandlingService xmlHandlingService; + private final TenantScope tenantScope; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ReferenceTypeBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, XmlHandlingService xmlHandlingService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceTypeBuilder.class))); + this.builderFactory = builderFactory; + this.tenantScope = tenantScope; + this.xmlHandlingService = xmlHandlingService; + } + + public ReferenceTypeBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet definitionFields = fields.extractPrefixed(this.asPrefix(ReferenceType._definition)); + + List models = new ArrayList<>(); + for (ReferenceTypeEntity d : data) { + ReferenceType m = new ReferenceType(); + if (fields.hasField(this.asIndexer(ReferenceType._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(ReferenceType._name))) m.setName(d.getName()); + if (fields.hasField(this.asIndexer(ReferenceType._code))) m.setCode(d.getCode()); + if (fields.hasField(this.asIndexer(ReferenceType._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(ReferenceType._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(ReferenceType._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(ReferenceType._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(ReferenceType._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!definitionFields.isEmpty() && d.getDefinition() != null){ + ReferenceTypeDefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(ReferenceTypeDefinitionEntity.class, d.getDefinition()); + m.setDefinition(this.builderFactory.builder(ReferenceTypeDefinitionBuilder.class).authorize(this.authorize).build(definitionFields, definition)); + } + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/StorageFileBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/StorageFileBuilder.java new file mode 100644 index 000000000..e6c29b7fb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/StorageFileBuilder.java @@ -0,0 +1,115 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.StorageFileEntity; +import org.opencdmp.model.*; +import org.opencdmp.query.*; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class StorageFileBuilder extends BaseBuilder { + + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + private final TenantScope tenantScope; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public StorageFileBuilder( + ConventionService conventionService, + QueryFactory queryFactory, + BuilderFactory builderFactory, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(StorageFileBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + this.tenantScope = tenantScope; + } + + public StorageFileBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(StorageFile._owner)); + Map userItemsMap = this.collectUsers(userFields, data); + + List models = new ArrayList<>(); + for (StorageFileEntity d : data) { + StorageFile m = new StorageFile(); + if (fields.hasField(this.asIndexer(StorageFile._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(StorageFile._name))) m.setName(d.getName()); + if (fields.hasField(this.asIndexer(StorageFile._fileRef))) m.setFileRef(d.getFileRef()); + if (fields.hasField(this.asIndexer(StorageFile._extension))) m.setExtension(d.getExtension()); + if (fields.hasField(this.asIndexer(StorageFile._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(StorageFile._mimeType))) m.setMimeType(d.getMimeType()); + if (fields.hasField(this.asIndexer(StorageFile._storageType))) m.setStorageType(d.getStorageType()); + if (fields.hasField(this.asIndexer(StorageFile._purgeAt))) m.setPurgeAt(d.getPurgeAt()); + if (fields.hasField(this.asIndexer(StorageFile._purgedAt))) m.setPurgedAt(d.getPurgedAt()); + if (fields.hasField(this.asIndexer(StorageFile._fullName))) m.setFullName(d.getName() + (d.getExtension().startsWith(".") ? "" : ".") + d.getExtension()); + if (fields.hasField(this.asIndexer(StorageFile._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getOwnerId())) m.setOwner(userItemsMap.get(d.getOwnerId())); + models.add(m); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(StorageFileEntity::getOwnerId).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(StorageFileEntity::getOwnerId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/SupportiveMaterialBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/SupportiveMaterialBuilder.java new file mode 100644 index 000000000..75a14d252 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/SupportiveMaterialBuilder.java @@ -0,0 +1,71 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpReferenceEntity; +import org.opencdmp.data.SupportiveMaterialEntity; +import org.opencdmp.model.*; +import org.opencdmp.query.DmpQuery; +import org.opencdmp.query.ReferenceQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SupportiveMaterialBuilder extends BaseBuilder{ + + private final TenantScope tenantScope; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public SupportiveMaterialBuilder( + ConventionService conventionService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(SupportiveMaterialBuilder.class))); + this.tenantScope = tenantScope; + } + + public SupportiveMaterialBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (SupportiveMaterialEntity d : data) { + SupportiveMaterial m = new SupportiveMaterial(); + if (fields.hasField(this.asIndexer(SupportiveMaterial._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(SupportiveMaterial._type))) m.setType(d.getType()); + if (fields.hasField(this.asIndexer(SupportiveMaterial._languageCode))) m.setLanguageCode(d.getLanguageCode()); + if (fields.hasField(this.asIndexer(SupportiveMaterial._payload))) m.setPayload(d.getPayload()); + if (fields.hasField(this.asIndexer(SupportiveMaterial._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(SupportiveMaterial._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(SupportiveMaterial._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(SupportiveMaterial._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(SupportiveMaterial._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/TagBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/TagBuilder.java new file mode 100644 index 000000000..df5cac30f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/TagBuilder.java @@ -0,0 +1,104 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.TagEntity; +import org.opencdmp.model.Tag; +import org.opencdmp.model.User; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TagBuilder extends BaseBuilder{ + + private final QueryFactory queryFactory; + private final BuilderFactory builderFactory; + private final TenantScope tenantScope; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public TagBuilder( + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(TagBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + this.tenantScope = tenantScope; + } + + public TagBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(Tag._createdBy)); + Map userItemsMap = this.collectUsers(userFields, data); + + List models = new ArrayList<>(); + for (TagEntity d : data) { + Tag m = new Tag(); + if (fields.hasField(this.asIndexer(Tag._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(Tag._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(Tag._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(Tag._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(Tag._isActive))) m.setIsActive(d.getIsActive()); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getCreatedById())) m.setCreatedBy(userItemsMap.get(d.getCreatedById())); + if (fields.hasField(this.asIndexer(Tag._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(TagEntity::getCreatedById).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(TagEntity::getCreatedById).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/TenantBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/TenantBuilder.java new file mode 100644 index 000000000..4b8b6f24e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/TenantBuilder.java @@ -0,0 +1,62 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.TenantEntity; +import org.opencdmp.model.Tenant; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private final XmlHandlingService xmlHandlingService; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public TenantBuilder(ConventionService conventionService, BuilderFactory builderFactory, XmlHandlingService xmlHandlingService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(TenantBuilder.class))); + this.builderFactory = builderFactory; + this.xmlHandlingService = xmlHandlingService; + } + + public TenantBuilder authorize(EnumSet values){ + this.authorize = values; + return this; + } + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0),Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size) .orElse(0)); + this.logger.trace(new DataLogEntry("requested fields",fields)); + if(fields == null || data == null || fields.isEmpty()) return new ArrayList<>(); + + + List models = new ArrayList<>(); + for(TenantEntity d : data){ + Tenant m = new Tenant(); + if(fields.hasField(this.asIndexer(Tenant._id))) m.setId(d.getId()); + if(fields.hasField(this.asIndexer(Tenant._code))) m.setCode(d.getCode()); + if(fields.hasField(this.asIndexer(Tenant._name))) m.setName(d.getName()); + if(fields.hasField(this.asIndexer(Tenant._description))) m.setDescription(d.getDescription()); + if(fields.hasField(this.asIndexer(Tenant._isActive))) m.setIsActive(d.getIsActive()); + if(fields.hasField(this.asIndexer(Tenant._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if(fields.hasField(this.asIndexer(Tenant._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if(fields.hasField(this.asIndexer(Tenant._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + models.add(m); + } + this.logger.debug("build {} items",Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/TenantUserBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/TenantUserBuilder.java new file mode 100644 index 000000000..a973db7bb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/TenantUserBuilder.java @@ -0,0 +1,142 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.TenantUserEntity; +import org.opencdmp.model.Tenant; +import org.opencdmp.model.TenantUser; +import org.opencdmp.model.User; +import org.opencdmp.query.TenantQuery; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantUserBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private final TenantScope tenantScope; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public TenantUserBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, + QueryFactory queryFactory, TenantScope tenantScope + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(TenantUserBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.tenantScope = tenantScope; + } + + public TenantUserBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List datas) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(datas).map(e -> e.size()).orElse(0), Optional.ofNullable(fields).map(e -> e.getFields()).map(e -> e.size()).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || fields.isEmpty()) return new ArrayList<>(); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(TenantUser._user)); + Map userMap = this.collectUsers(userFields, datas); + + FieldSet tenantFields = fields.extractPrefixed(this.asPrefix(TenantUser._tenant)); + Map tenantMap = this.collectTenants(tenantFields, datas); + + List models = new ArrayList<>(); + + for (TenantUserEntity d : datas) { + TenantUser m = new TenantUser(); + if (fields.hasField(this.asIndexer(TenantUser._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(TenantUser._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(TenantUser._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(TenantUser._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(TenantUser._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(TenantUser._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!userFields.isEmpty() && userMap != null && userMap.containsKey(d.getUserId())) m.setUser(userMap.get(d.getUserId())); + if (!tenantFields.isEmpty() && tenantMap != null && tenantMap.containsKey(d.getTenantId())) m.setTenant(tenantMap.get(d.getTenantId())); + models.add(m); + } + this.logger.debug("build {} items", Optional.ofNullable(models).map(e -> e.size()).orElse(0)); + return models; + } + + private Map collectUsers(FieldSet fields, List datas) throws MyApplicationException { + if (fields.isEmpty() || datas.isEmpty()) return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap = null; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + datas.stream().map(x -> x.getUserId()).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + x -> x.getId()); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(datas.stream().map(x -> x.getUserId()).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, x -> x.getId()); + } + if (!fields.hasField(User._id)) { + itemMap.values().stream().filter(x -> x != null).map(x -> { + x.setId(null); + return x; + }).collect(Collectors.toList()); + } + + return itemMap; + } + + private Map collectTenants(FieldSet fields, List datas) throws MyApplicationException { + if (fields.isEmpty() || datas.isEmpty()) return null; + this.logger.debug("checking related - {}", Tenant.class.getSimpleName()); + + Map itemMap = null; + if (!fields.hasOtherField(this.asIndexer(Tenant._id))) { + itemMap = this.asEmpty( + datas.stream().map(x -> x.getTenantId()).distinct().collect(Collectors.toList()), + x -> { + Tenant item = new Tenant(); + item.setId(x); + return item; + }, + x -> x.getId()); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Tenant._id); + TenantQuery q = this.queryFactory.query(TenantQuery.class).authorize(this.authorize).ids(datas.stream().map(x -> x.getTenantId()).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(TenantBuilder.class).authorize(this.authorize).asForeignKey(q, clone, x -> x.getId()); + } + if (!fields.hasField(Tenant._id)) { + itemMap.values().stream().filter(x -> x != null).map(x -> { + x.setId(null); + return x; + }).collect(Collectors.toList()); + } + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/UserAdditionalInfoBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/UserAdditionalInfoBuilder.java new file mode 100644 index 000000000..2c51db334 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/UserAdditionalInfoBuilder.java @@ -0,0 +1,109 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.user.AdditionalInfoEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionReferenceEntity; +import org.opencdmp.model.DescriptionReference; +import org.opencdmp.model.Reference; +import org.opencdmp.model.UserAdditionalInfo; +import org.opencdmp.query.ReferenceQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserAdditionalInfoBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public UserAdditionalInfoBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserAdditionalInfoBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public UserAdditionalInfoBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet referenceFields = fields.extractPrefixed(this.asPrefix(DescriptionReference._reference)); + Map referenceItemsMap = this.collectReferences(referenceFields, data); + + List models = new ArrayList<>(); + + for (AdditionalInfoEntity d : data) { + UserAdditionalInfo m = new UserAdditionalInfo(); + if (fields.hasField(this.asIndexer(UserAdditionalInfo._language))) m.setLanguage(d.getLanguage()); + if (fields.hasField(this.asIndexer(UserAdditionalInfo._culture))) m.setCulture(d.getCulture()); + if (fields.hasField(this.asIndexer(UserAdditionalInfo._avatarUrl))) m.setAvatarUrl(d.getAvatarUrl()); + if (fields.hasField(this.asIndexer(UserAdditionalInfo._timezone))) m.setTimezone(d.getTimezone()); + if (!referenceFields.isEmpty() && referenceItemsMap != null && referenceItemsMap.containsKey(d.getOrganizationId())) m.setOrganization(referenceItemsMap.get(d.getOrganizationId())); + if (fields.hasField(this.asIndexer(UserAdditionalInfo._roleOrganization))) m.setRoleOrganization(d.getRoleOrganization()); + + models.add(m); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + + + private Map collectReferences(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Reference.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Reference._id))) { + itemMap = this.asEmpty( + data.stream().map(AdditionalInfoEntity::getOrganizationId).filter(Objects::nonNull).distinct().collect(Collectors.toList()), + x -> { + Reference item = new Reference(); + item.setId(x); + return item; + }, + Reference::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Reference._id); + ReferenceQuery q = this.queryFactory.query(ReferenceQuery.class).authorize(this.authorize).ids(data.stream().map(AdditionalInfoEntity::getOrganizationId).filter(Objects::nonNull).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(ReferenceBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Reference::getId); + } + if (!fields.hasField(Reference._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/UserBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/UserBuilder.java new file mode 100644 index 000000000..08c053502 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/UserBuilder.java @@ -0,0 +1,220 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.authorization.AuthorizationProperties; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.user.AdditionalInfoEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.TenantEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.data.UserEntity; +import org.opencdmp.model.*; +import org.opencdmp.query.*; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.exception.MyForbiddenException; +import gr.cite.tools.exception.MyNotFoundException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Scope; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserBuilder extends BaseBuilder { + + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + private final JsonHandlingService jsonHandlingService; + private final AuthorizationProperties authorizationProperties; + private final TenantEntityManager tenantEntityManager; + private final TenantScope tenantScope; + + private final MessageSource messageSource; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public UserBuilder(ConventionService conventionService, + QueryFactory queryFactory, + BuilderFactory builderFactory, JsonHandlingService jsonHandlingService, AuthorizationProperties authorizationProperties, TenantEntityManager tenantEntityManager, TenantScope tenantScope, MessageSource messageSource) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + this.jsonHandlingService = jsonHandlingService; + this.authorizationProperties = authorizationProperties; + this.tenantEntityManager = tenantEntityManager; + this.tenantScope = tenantScope; + this.messageSource = messageSource; + } + + public UserBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + + FieldSet contactsFields = fields.extractPrefixed(this.asPrefix(User._contacts)); + Map> contactsMap = this.collectUserContactInfos(contactsFields, data); + + FieldSet globalRolesFields = fields.extractPrefixed(this.asPrefix(User._globalRoles)); + Map> globalRolesMap = this.collectUserGlobalRoles(globalRolesFields, data); + + FieldSet tenantRolesFields = fields.extractPrefixed(this.asPrefix(User._tenantRoles)); + Map> tenantRolesMap = this.collectUserTenantRoles(tenantRolesFields, data); + + FieldSet credentialsFields = fields.extractPrefixed(this.asPrefix(User._credentials)); + Map> credentialsMap = this.collectUserCredentials(credentialsFields, data); + + FieldSet additionalInfoFields = fields.extractPrefixed(this.asPrefix(User._additionalInfo)); + + FieldSet tenantUsersFields = fields.extractPrefixed(this.asPrefix(User._tenantUsers)); + Map> tenantUsersMap = this.collectTenantUsers(tenantUsersFields, data); + for (UserEntity d : data) { + User m = new User(); + if (fields.hasField(this.asIndexer(User._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(User._name))) m.setName(d.getName()); + if (fields.hasField(this.asIndexer(User._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(User._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(User._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(User._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (contactsMap != null && !contactsFields.isEmpty() && contactsMap.containsKey(d.getId())) m.setContacts(contactsMap.get(d.getId())); + if (globalRolesMap != null && !globalRolesFields.isEmpty() && globalRolesMap.containsKey(d.getId())) m.setGlobalRoles(globalRolesMap.get(d.getId())); + if (tenantRolesMap != null && !tenantRolesFields.isEmpty() && tenantRolesMap.containsKey(d.getId())) m.setTenantRoles(tenantRolesMap.get(d.getId())); + if (credentialsMap != null && !credentialsFields.isEmpty() && credentialsMap.containsKey(d.getId())) m.setCredentials(credentialsMap.get(d.getId())); + if (!additionalInfoFields.isEmpty() && d.getAdditionalInfo() != null){ + AdditionalInfoEntity definition = this.jsonHandlingService.fromJsonSafe(AdditionalInfoEntity.class, d.getAdditionalInfo()); + m.setAdditionalInfo(this.builderFactory.builder(UserAdditionalInfoBuilder.class).authorize(this.authorize).build(additionalInfoFields, definition)); + } + if (!tenantUsersFields.isEmpty() && tenantUsersMap != null && tenantUsersMap.containsKey(d.getId())) m.setTenantUsers(tenantUsersMap.get(d.getId())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map> collectUserContactInfos(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", UserContactInfo.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserContactInfo._user, User._id)); + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).authorize(this.authorize).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserContactInfoBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); + + if (!fields.hasField(this.asIndexer(UserContactInfo._user, User._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).peek(x -> { + x.getUser().setId(null); + }); + } + + return itemMap; + } + + private Map> collectUserGlobalRoles(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", UserRole.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserRole._user, User._id)); + UserRoleQuery query = this.queryFactory.query(UserRoleQuery.class).authorize(this.authorize).tenantIsSet(false).roles(this.authorizationProperties.getAllowedGlobalRoles()).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserRoleBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); + + if (!fields.hasField(this.asIndexer(UserRole._user, User._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).peek(x -> { + x.getUser().setId(null); + }); + } + + return itemMap; + } + + private Map> collectUserTenantRoles(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", UserRole.class.getSimpleName()); + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserRole._user, User._id)); + + if (!tenantScope.isSet()) throw new MyForbiddenException("tenant scope required"); + + UserRoleQuery query = this.queryFactory.query(UserRoleQuery.class).authorize(this.authorize).roles(this.authorizationProperties.getAllowedTenantRoles()).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); + if (tenantScope.isDefaultTenant()) query.tenantIsSet(false); + else { + try { + query.tenantIsSet(true).tenantIds(this.tenantScope.getTenant()); + } catch (InvalidApplicationException e) { + throw new RuntimeException(e); + } + } + + itemMap = this.builderFactory.builder(UserRoleBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); + + if (!fields.hasField(this.asIndexer(UserRole._user, User._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).peek(x -> { + x.getUser().setId(null); + }); + } + + return itemMap; + } + + private Map> collectUserCredentials(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", UserCredential.class.getSimpleName()); + + Map> itemMap; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(UserCredential._user, User._id)); + UserCredentialQuery query = this.queryFactory.query(UserCredentialQuery.class).authorize(this.authorize).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserCredentialBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); + + if (!fields.hasField(this.asIndexer(UserCredential._user, User._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).peek(x -> { + x.getUser().setId(null); + }); + } + + return itemMap; + } + + private Map> collectTenantUsers(FieldSet fields, List datas) throws MyApplicationException { + if (fields.isEmpty() || datas.isEmpty()) return null; + this.logger.debug("checking related - {}", TenantUser.class.getSimpleName()); + + Map> itemMap = null; + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(TenantUser._user, User._id)); + TenantUserQuery query = this.queryFactory.query(TenantUserQuery.class).authorize(this.authorize).userIds(datas.stream().map(x -> x.getId()).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(TenantUserBuilder.class).authorize(this.authorize).asMasterKey(query, clone, x -> x.getUser().getId()); + + if (!fields.hasField(this.asIndexer(TenantUser._user, User._id))) { + itemMap.values().stream().flatMap(List::stream).filter(x -> x != null && x.getUser() != null).map(x -> { + x.getUser().setId(null); + return x; + }).collect(Collectors.toList()); + } + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/UserContactInfoBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/UserContactInfoBuilder.java new file mode 100644 index 000000000..7b9f0de29 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/UserContactInfoBuilder.java @@ -0,0 +1,111 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.UserContactInfoEntity; +import org.opencdmp.model.Description; +import org.opencdmp.model.User; +import org.opencdmp.model.UserContactInfo; +import org.opencdmp.model.User; +import org.opencdmp.query.DescriptionQuery; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserContactInfoBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public UserContactInfoBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserContactInfoBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public UserContactInfoBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(UserContactInfo._user)); + Map userItemsMap = this.collectUsers(userFields, data); + + List models = new ArrayList<>(); + + for (UserContactInfoEntity d : data) { + UserContactInfo m = new UserContactInfo(); + if (fields.hasField(this.asIndexer(UserContactInfo._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(UserContactInfo._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(UserContactInfo._ordinal))) m.setOrdinal(d.getOrdinal()); + if (fields.hasField(this.asIndexer(UserContactInfo._value))) m.setValue(d.getValue()); + if (fields.hasField(this.asIndexer(UserContactInfo._type))) m.setType(d.getType()); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + + models.add(m); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(UserContactInfoEntity::getUserId).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(UserContactInfoEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/UserCredentialBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/UserCredentialBuilder.java new file mode 100644 index 000000000..5f465e943 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/UserCredentialBuilder.java @@ -0,0 +1,119 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.types.description.PropertyDefinitionEntity; +import org.opencdmp.commons.types.usercredential.UserCredentialDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.UserCredentialEntity; +import org.opencdmp.model.Description; +import org.opencdmp.model.User; +import org.opencdmp.model.UserCredential; +import org.opencdmp.model.builder.descriptionpropertiesdefinition.PropertyDefinitionBuilder; +import org.opencdmp.model.builder.usercredential.UserCredentialDataBuilder; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserCredentialBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + private final JsonHandlingService jsonHandlingService; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public UserCredentialBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory, JsonHandlingService jsonHandlingService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserCredentialBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.jsonHandlingService = jsonHandlingService; + } + + public UserCredentialBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(UserCredential._user)); + Map userItemsMap = this.collectUsers(userFields, data); + + FieldSet definitionPropertiesFields = fields.extractPrefixed(this.asPrefix(UserCredential._data)); + + List models = new ArrayList<>(); + + for (UserCredentialEntity d : data) { + UserCredential m = new UserCredential(); + if (fields.hasField(this.asIndexer(UserCredential._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(UserCredential._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(UserCredential._externalId))) m.setExternalId(d.getExternalId()); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + if (!definitionPropertiesFields.isEmpty() && d.getData() != null){ + UserCredentialDataEntity propertyDefinition = this.jsonHandlingService.fromJsonSafe(UserCredentialDataEntity.class, d.getData()); + m.setData(this.builderFactory.builder(UserCredentialDataBuilder.class).authorize(this.authorize).build(definitionPropertiesFields, propertyDefinition)); + } + models.add(m); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(UserCredentialEntity::getUserId).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(UserCredentialEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/UserDescriptionTemplateBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/UserDescriptionTemplateBuilder.java new file mode 100644 index 000000000..f40f0ba77 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/UserDescriptionTemplateBuilder.java @@ -0,0 +1,142 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.UserDescriptionTemplateEntity; +import org.opencdmp.model.Description; +import org.opencdmp.model.DescriptionTemplate; +import org.opencdmp.model.User; +import org.opencdmp.model.UserDescriptionTemplate; +import org.opencdmp.query.DescriptionTemplateQuery; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserDescriptionTemplateBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private final QueryFactory queryFactory; + private final BuilderFactory builderFactory; + private final TenantScope tenantScope; + + @Autowired + public UserDescriptionTemplateBuilder( + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserDescriptionTemplateBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + this.tenantScope = tenantScope; + } + + public UserDescriptionTemplateBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet descriptionTemplateFields = fields.extractPrefixed(this.asPrefix(UserDescriptionTemplate._descriptionTemplate)); + Map descriptionTemplateMap = this.collectDescriptionTemplates(descriptionTemplateFields, data); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(UserDescriptionTemplate._user)); + Map userItemsMap = this.collectUsers(userFields, data); + + List models = new ArrayList<>(); + for (UserDescriptionTemplateEntity d : data) { + UserDescriptionTemplate m = new UserDescriptionTemplate(); + if (fields.hasField(this.asIndexer(UserDescriptionTemplate._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(UserDescriptionTemplate._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(UserDescriptionTemplate._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(UserDescriptionTemplate._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(UserDescriptionTemplate._role))) m.setRole(d.getRole()); + if (fields.hasField(this.asIndexer(UserDescriptionTemplate._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(UserDescriptionTemplate._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!descriptionTemplateFields.isEmpty() && descriptionTemplateMap != null && descriptionTemplateMap.containsKey(d.getDescriptionTemplateId())) m.setDescriptionTemplate(descriptionTemplateMap.get(d.getDescriptionTemplateId())); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(UserDescriptionTemplateEntity::getUserId).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(UserDescriptionTemplateEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + + private Map collectDescriptionTemplates(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) return null; + this.logger.debug("checking related - {}", DescriptionTemplate.class.getSimpleName()); + + Map itemMap = null; + if (!fields.hasOtherField(this.asIndexer(DescriptionTemplate._id))) { + itemMap = this.asEmpty( + data.stream().map(UserDescriptionTemplateEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList()), + x -> { + DescriptionTemplate item = new DescriptionTemplate(); + item.setId(x); + return item; + }, + x -> x.getId()); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(DescriptionTemplate._id); + DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).ids(data.stream().map(UserDescriptionTemplateEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionTemplateBuilder.class).asForeignKey(q, clone, DescriptionTemplate::getId); + } + if (!fields.hasField(DescriptionTemplate._id)) { + itemMap.values().stream().filter(x -> x != null).map(x -> { + x.setId(null); + return x; + }).collect(Collectors.toList()); + } + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/UserRoleBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/UserRoleBuilder.java new file mode 100644 index 000000000..340994120 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/UserRoleBuilder.java @@ -0,0 +1,110 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.UserRoleEntity; +import org.opencdmp.model.User; +import org.opencdmp.model.UserRole; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserRoleBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + private final TenantScope tenantScope; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public UserRoleBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserRoleBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.tenantScope = tenantScope; + } + + public UserRoleBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet userFields = fields.extractPrefixed(this.asPrefix(UserRole._user)); + Map userItemsMap = this.collectUsers(userFields, data); + + List models = new ArrayList<>(); + + for (UserRoleEntity d : data) { + UserRole m = new UserRole(); + if (fields.hasField(this.asIndexer(UserRole._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(UserRole._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(UserRole._role))) m.setRole(d.getRole()); + if (fields.hasField(this.asIndexer(UserRole._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + + models.add(m); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(User._id))) { + itemMap = this.asEmpty( + data.stream().map(UserRoleEntity::getUserId).distinct().collect(Collectors.toList()), + x -> { + User item = new User(); + item.setId(x); + return item; + }, + User::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().map(UserRoleEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/UserSettingsBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/UserSettingsBuilder.java new file mode 100644 index 000000000..2b95d9035 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/UserSettingsBuilder.java @@ -0,0 +1,65 @@ +package org.opencdmp.model.builder; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.UserSettingsEntity; +import org.opencdmp.model.UserSettings; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.time.Instant; +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserSettingsBuilder extends BaseBuilder { + + private final TenantScope tenantScope; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + public UserSettingsBuilder(ConventionService conventionService, TenantScope tenantScope) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserSettingsBuilder.class))); + this.tenantScope = tenantScope; + } + + public UserSettingsBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) return new ArrayList<>(); + + List models = new ArrayList<>(); + + for (UserSettingsEntity d : data) { + UserSettings m = new UserSettings(); + if (fields.hasField(this.asIndexer(UserSettings._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(UserSettings._value))) m.setValue(d.getValue()); + if (fields.hasField(this.asIndexer(UserSettings._key))) m.setKey(d.getKey()); + if (fields.hasField(this.asIndexer(UserSettings._type))) m.setType(d.getType()); + if (fields.hasField(this.asIndexer(UserSettings._entityId))) m.setEntityId(d.getEntityId()); + if (fields.hasField(this.asIndexer(UserSettings._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(UserSettings._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(UserSettings._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + if (fields.hasField(this.asIndexer(UserSettings._hash))) m.setHash(this.hashValue(Instant.ofEpochMilli(d.getUpdatedAt().toEpochMilli()))); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/actionconfirmation/DmpInvitationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/actionconfirmation/DmpInvitationBuilder.java new file mode 100644 index 000000000..a0889e653 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/actionconfirmation/DmpInvitationBuilder.java @@ -0,0 +1,58 @@ +package org.opencdmp.model.builder.actionconfirmation; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.actionconfirmation.DmpInvitationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.actionconfirmation.DmpInvitation; +import org.opencdmp.model.builder.BaseBuilder; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpInvitationBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpInvitationBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpInvitationBuilder.class))); + } + + public DmpInvitationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + + List models = new ArrayList<>(); + for (DmpInvitationEntity d : data) { + DmpInvitation m = new DmpInvitation(); + if (fields.hasField(this.asIndexer(DmpInvitation._email))) m.setEmail(d.getEmail()); + if (fields.hasField(this.asIndexer(DmpInvitation._dmpId))) m.setDmpId(d.getDmpId()); + if (fields.hasField(this.asIndexer(DmpInvitation._role))) m.setRole(d.getRole()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/actionconfirmation/MergeAccountConfirmationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/actionconfirmation/MergeAccountConfirmationBuilder.java new file mode 100644 index 000000000..e0f6bf96e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/actionconfirmation/MergeAccountConfirmationBuilder.java @@ -0,0 +1,56 @@ +package org.opencdmp.model.builder.actionconfirmation; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.actionconfirmation.MergeAccountConfirmationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.actionconfirmation.MergeAccountConfirmation; +import org.opencdmp.model.builder.BaseBuilder; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class MergeAccountConfirmationBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public MergeAccountConfirmationBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(MergeAccountConfirmationBuilder.class))); + } + + public MergeAccountConfirmationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + + List models = new ArrayList<>(); + for (MergeAccountConfirmationEntity d : data) { + MergeAccountConfirmation m = new MergeAccountConfirmation(); + if (fields.hasField(this.asIndexer(MergeAccountConfirmation._email))) m.setEmail(d.getEmail()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/actionconfirmation/RemoveCredentialRequestBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/actionconfirmation/RemoveCredentialRequestBuilder.java new file mode 100644 index 000000000..ac5177c08 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/actionconfirmation/RemoveCredentialRequestBuilder.java @@ -0,0 +1,55 @@ +package org.opencdmp.model.builder.actionconfirmation; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.actionconfirmation.RemoveCredentialRequestEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.actionconfirmation.RemoveCredentialRequest; +import org.opencdmp.model.builder.BaseBuilder; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class RemoveCredentialRequestBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public RemoveCredentialRequestBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(RemoveCredentialRequestBuilder.class))); + } + + public RemoveCredentialRequestBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + + List models = new ArrayList<>(); + for (RemoveCredentialRequestEntity d : data) { + RemoveCredentialRequest m = new RemoveCredentialRequest(); + if (fields.hasField(this.asIndexer(RemoveCredentialRequest._credentialId))) m.setCredentialId(d.getCredentialId()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/BaseCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/BaseCommonModelBuilder.java new file mode 100644 index 000000000..2997feca6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/BaseCommonModelBuilder.java @@ -0,0 +1,77 @@ +package org.opencdmp.model.builder.commonmodels; + +import org.opencdmp.convention.ConventionService; +import gr.cite.tools.data.builder.Builder; +import gr.cite.tools.data.query.QueryBase; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; + +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +public abstract class BaseCommonModelBuilder implements Builder { + protected final LoggerService logger; + protected final ConventionService conventionService; + + public BaseCommonModelBuilder( + ConventionService conventionService, + LoggerService logger + ) { + this.conventionService = conventionService; + this.logger = logger; + } + + public M build(D data) throws MyApplicationException { + if (data == null) { + //this.logger.Debug(new MapLogEntry("requested build for null item requesting fields").And("fields", directives)); +// return default(M); + M model = null; + return null; //TODO + } + List> models = this.buildInternal(List.of(data)); + return models.stream().map(CommonModelBuilderItemResponse::getModel).findFirst().orElse(null); //TODO + } + + public List build(List data) throws MyApplicationException{ + List> models = this.buildInternal(data); + return models == null ? null : models.stream().map(CommonModelBuilderItemResponse::getModel).collect(Collectors.toList()); + } + + protected abstract List> buildInternal(List data) throws MyApplicationException; + + public Map asForeignKey(QueryBase query, Function keySelector) throws MyApplicationException { + this.logger.trace("Building references from query"); + List data = query.collect(); + this.logger.debug("collected {} items to build", Optional.ofNullable(data).map(List::size).orElse(0)); + return this.asForeignKey(data, keySelector); + } + + public Map asForeignKey(List data, Function keySelector) throws MyApplicationException { + this.logger.trace("building references"); + List> models = this.buildInternal(data); + this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(List::size).orElse(0), Optional.ofNullable(data).map(List::size).orElse(0)); + return models == null ? new HashMap<>() : models.stream().collect(Collectors.toMap(x-> keySelector.apply(x.getData()), CommonModelBuilderItemResponse::getModel)); + } + public Map> asMasterKey(QueryBase query,Function keySelector) throws MyApplicationException { + this.logger.trace("Building details from query"); + List data = query.collect(); + this.logger.debug("collected {} items to build", Optional.ofNullable(data).map(List::size).orElse(0)); + return this.asMasterKey(data, keySelector); + } + + public Map> asMasterKey(List data, Function keySelector) throws MyApplicationException { + this.logger.trace("building details"); + List> models = this.buildInternal(data); + this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(List::size).orElse(0), Optional.ofNullable(data).map(List::size).orElse(0)); + Map> map = new HashMap<>(); + if (models == null) return map; + for (CommonModelBuilderItemResponse model : models) { + K key = keySelector.apply(model.getData()); + if (!map.containsKey(key)) map.put(key, new ArrayList()); + map.get(key).add(model.getModel()); + } + return map; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/CommonModelBuilderItemResponse.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/CommonModelBuilderItemResponse.java new file mode 100644 index 000000000..afad0ad27 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/CommonModelBuilderItemResponse.java @@ -0,0 +1,19 @@ +package org.opencdmp.model.builder.commonmodels; + +public class CommonModelBuilderItemResponse{ + private final M model; + private final D data; + + public CommonModelBuilderItemResponse(M model, D data) { + this.model = model; + this.data = data; + } + + public D getData() { + return data; + } + + public M getModel() { + return model; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/DepositConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/DepositConfigurationBuilder.java new file mode 100644 index 000000000..6bdc20793 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/DepositConfigurationBuilder.java @@ -0,0 +1,58 @@ +package org.opencdmp.model.builder.commonmodels; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.deposit.DepositConfiguration; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DepositConfigurationBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DepositConfigurationBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DepositConfigurationBuilder.class))); + } + + public DepositConfigurationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (eu.eudat.depositinterface.repository.DepositConfiguration d : data) { + DepositConfiguration m = new DepositConfiguration(); + if (fields.hasField(this.asIndexer(DepositConfiguration._depositType))) m.setDepositType(d.getDepositType()); + if (fields.hasField(this.asIndexer(DepositConfiguration._redirectUri))) m.setRedirectUri(d.getRedirectUri()); + if (fields.hasField(this.asIndexer(DepositConfiguration._repositoryId))) m.setRepositoryId(d.getRepositoryId()); + if (fields.hasField(this.asIndexer(DepositConfiguration._repositoryAuthorizationUrl))) m.setRepositoryAuthorizationUrl(d.getRepositoryAuthorizationUrl()); + if (fields.hasField(this.asIndexer(DepositConfiguration._repositoryRecordUrl))) m.setRepositoryRecordUrl(d.getRepositoryRecordUrl()); + if (fields.hasField(this.asIndexer(DepositConfiguration._repositoryClientId))) m.setRepositoryClientId(d.getRepositoryClientId()); + if (fields.hasField(this.asIndexer(DepositConfiguration._hasLogo))) m.setHasLogo(d.isHasLogo()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/DescriptionTemplateTypeCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/DescriptionTemplateTypeCommonModelBuilder.java new file mode 100644 index 000000000..d832a8dc3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/DescriptionTemplateTypeCommonModelBuilder.java @@ -0,0 +1,52 @@ +package org.opencdmp.model.builder.commonmodels; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.DescriptionTemplateTypeModel; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionTemplateTypeEntity; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTemplateTypeCommonModelBuilder extends BaseCommonModelBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DescriptionTemplateTypeCommonModelBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeCommonModelBuilder.class))); + } + + public DescriptionTemplateTypeCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (DescriptionTemplateTypeEntity d : data) { + DescriptionTemplateTypeModel m = new DescriptionTemplateTypeModel(); + m.setId(d.getId()); + m.setName(d.getName()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/DmpUserCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/DmpUserCommonModelBuilder.java new file mode 100644 index 000000000..845b2fdc2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/DmpUserCommonModelBuilder.java @@ -0,0 +1,84 @@ +package org.opencdmp.model.builder.commonmodels; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.enums.DmpUserRole; +import eu.eudat.commonmodels.models.DmpUserModel; +import eu.eudat.commonmodels.models.UserModel; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpUserEntity; +import org.opencdmp.data.UserEntity; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpUserCommonModelBuilder extends BaseCommonModelBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpUserCommonModelBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpUserCommonModelBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public DmpUserCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {} items ", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null) + return new ArrayList<>(); + + + Map userItemsMap = this.collectUsers(data); + + List> models = new ArrayList<>(); + for (DmpUserEntity d : data) { + DmpUserModel m = new DmpUserModel(); + switch (d.getRole()){ + case User -> m.setRole(DmpUserRole.User); + case Owner -> m.setRole(DmpUserRole.Owner); + default -> throw new MyApplicationException("unrecognized type " + d.getRole().getValue()); + } + if (userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectUsers(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", UserModel.class.getSimpleName()); + + Map itemMap; + UserQuery q = this.queryFactory.query(UserQuery.class).isActive(IsActive.Active).authorize(this.authorize).ids(data.stream().map(DmpUserEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserCommonModelBuilder.class).authorize(this.authorize).asForeignKey(q, UserEntity::getId); + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/EntityDoiCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/EntityDoiCommonModelBuilder.java new file mode 100644 index 000000000..13fc68c78 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/EntityDoiCommonModelBuilder.java @@ -0,0 +1,53 @@ +package org.opencdmp.model.builder.commonmodels; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.EntityDoiModel; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.EntityDoiEntity; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class EntityDoiCommonModelBuilder extends BaseCommonModelBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public EntityDoiCommonModelBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(EntityDoiCommonModelBuilder.class))); + } + + public EntityDoiCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (EntityDoiEntity d : data) { + EntityDoiModel m = new EntityDoiModel(); + m.setId(d.getId()); + m.setDoi(d.getDoi()); + m.setRepositoryId(d.getRepositoryId()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/ReferenceTypeCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/ReferenceTypeCommonModelBuilder.java new file mode 100644 index 000000000..fc9bb3594 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/ReferenceTypeCommonModelBuilder.java @@ -0,0 +1,53 @@ +package org.opencdmp.model.builder.commonmodels; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.reference.ReferenceTypeModel; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.ReferenceTypeEntity; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeCommonModelBuilder extends BaseCommonModelBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ReferenceTypeCommonModelBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceTypeCommonModelBuilder.class))); + } + + public ReferenceTypeCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (ReferenceTypeEntity d : data) { + ReferenceTypeModel m = new ReferenceTypeModel(); + m.setId(d.getId()); + m.setCode(d.getCode()); + m.setName(d.getName()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/TagCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/TagCommonModelBuilder.java new file mode 100644 index 000000000..1cfabfbc7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/TagCommonModelBuilder.java @@ -0,0 +1,52 @@ +package org.opencdmp.model.builder.commonmodels; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.TagModel; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.TagEntity; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TagCommonModelBuilder extends BaseCommonModelBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public TagCommonModelBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(TagCommonModelBuilder.class))); + } + + public TagCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (TagEntity d : data) { + TagModel m = new TagModel(); + m.setId(d.getId()); + m.setLabel(d.getLabel()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/UserCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/UserCommonModelBuilder.java new file mode 100644 index 000000000..a2e853190 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/UserCommonModelBuilder.java @@ -0,0 +1,86 @@ +package org.opencdmp.model.builder.commonmodels; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.DmpUserModel; +import eu.eudat.commonmodels.models.UserContactInfoModel; +import eu.eudat.commonmodels.models.UserModel; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpEntity; +import org.opencdmp.data.DmpUserEntity; +import org.opencdmp.data.UserContactInfoEntity; +import org.opencdmp.data.UserEntity; +import org.opencdmp.model.DmpUser; +import org.opencdmp.model.UserContactInfo; +import org.opencdmp.query.DmpUserQuery; +import org.opencdmp.query.UserContactInfoQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserCommonModelBuilder extends BaseCommonModelBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private boolean disableContacts; + + @Autowired + public UserCommonModelBuilder(ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserCommonModelBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public UserCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + public UserCommonModelBuilder disableContacts(boolean values) { + this.disableContacts = disableContacts; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {} items ", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null) + return new ArrayList<>(); + Map> userContactInfoModelMap = this.disableContacts ? null : this.collectUserContactInfos(data); + + List> models = new ArrayList<>(); + for (UserEntity d : data) { + UserModel m = new UserModel(); + m.setId(d.getId()); + m.setName(d.getName()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + if (userContactInfoModelMap != null && d.getId() != null && userContactInfoModelMap.containsKey(d.getId())) m.setContacts(userContactInfoModelMap.get(d.getId())); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map> collectUserContactInfos(List data) throws MyApplicationException { + this.logger.debug("checking related - {}", UserContactInfo.class.getSimpleName()); + + Map> itemMap; + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).authorize(this.authorize).userIds(data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserContactInfoCommonModelBuilder.class).authorize(this.authorize).asMasterKey(query, UserContactInfoEntity::getUserId); + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/UserContactInfoCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/UserContactInfoCommonModelBuilder.java new file mode 100644 index 000000000..fd68330c0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/UserContactInfoCommonModelBuilder.java @@ -0,0 +1,58 @@ +package org.opencdmp.model.builder.commonmodels; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.enums.ContactInfoType; +import eu.eudat.commonmodels.models.UserContactInfoModel; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.UserContactInfoEntity; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserContactInfoCommonModelBuilder extends BaseCommonModelBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public UserContactInfoCommonModelBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserContactInfoCommonModelBuilder.class))); + } + + public UserContactInfoCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (UserContactInfoEntity d : data) { + UserContactInfoModel m = new UserContactInfoModel(); + m.setId(d.getId()); + m.setCreatedAt(d.getCreatedAt()); + m.setValue(d.getValue()); + switch (d.getType()){ + case Email -> m.setType(ContactInfoType.Email); + default -> throw new MyApplicationException("unrecognized type " + d.getType()); + } + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/DescriptionCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/DescriptionCommonModelBuilder.java new file mode 100644 index 000000000..6a80c66b9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/DescriptionCommonModelBuilder.java @@ -0,0 +1,180 @@ +package org.opencdmp.model.builder.commonmodels.description; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.enums.DescriptionStatus; +import eu.eudat.commonmodels.models.description.DescriptionModel; +import eu.eudat.commonmodels.models.descriptiotemplate.DescriptionTemplateModel; +import eu.eudat.commonmodels.models.dmp.DmpModel; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.types.description.PropertyDefinitionEntity; +import org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionEntity; +import org.opencdmp.data.DescriptionTemplateEntity; +import org.opencdmp.data.DmpDescriptionTemplateEntity; +import org.opencdmp.data.DmpEntity; +import org.opencdmp.model.DescriptionTemplate; +import org.opencdmp.model.DmpDescriptionTemplate; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.commonmodels.dmp.DmpCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.descriptiontemplate.DescriptionTemplateCommonModelBuilder; +import org.opencdmp.query.*; +import org.opencdmp.service.visibility.VisibilityService; +import org.opencdmp.service.visibility.VisibilityServiceImpl; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionCommonModelBuilder extends BaseCommonModelBuilder { + + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + private final JsonHandlingService jsonHandlingService; + private final XmlHandlingService xmlHandlingService; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private String repositoryId; + + @Autowired + public DescriptionCommonModelBuilder( + ConventionService conventionService, + QueryFactory queryFactory, + BuilderFactory builderFactory, JsonHandlingService jsonHandlingService, XmlHandlingService xmlHandlingService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionCommonModelBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + this.jsonHandlingService = jsonHandlingService; + this.xmlHandlingService = xmlHandlingService; + } + + public DescriptionCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + + private boolean useSharedStorage; + public DescriptionCommonModelBuilder useSharedStorage(boolean useSharedStorage) { + this.useSharedStorage = useSharedStorage; + return this; + } + + public DescriptionCommonModelBuilder setRepositoryId(String repositoryId) { + this.repositoryId = repositoryId; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + Map descriptionTemplates = this.collectDescriptionTemplates(data); + Map dmps = this.collectDmps(data); + + Map definitionEntityMap = this.collectDescriptionTemplateDefinitions(data); + Map dmpDescriptionTemplateSections = this.collectDmpDescriptionTemplateSections(data); + + List> models = new ArrayList<>(); + for (DescriptionEntity d : data) { + DescriptionModel m = new DescriptionModel(); + m.setId(d.getId()); + m.setLabel(d.getLabel()); + m.setDescription(d.getDescription()); + switch (d.getStatus()){ + case Finalized -> m.setStatus(DescriptionStatus.Finalized); + case Draft -> m.setStatus(DescriptionStatus.Draft); + case Canceled -> m.setStatus(DescriptionStatus.Canceled); + default -> throw new MyApplicationException("unrecognized type " + d.getStatus()); + } + m.setCreatedAt(d.getCreatedAt()); + m.setDescription(d.getDescription()); + if (dmps != null && d.getDmpId() != null && dmps.containsKey(d.getDmpId())) m.setDmp(dmps.get(d.getDmpId())); + if (dmpDescriptionTemplateSections != null && d.getDmpDescriptionTemplateId() != null && dmpDescriptionTemplateSections.containsKey(d.getDmpDescriptionTemplateId())) m.setSectionId(dmpDescriptionTemplateSections.get(d.getDmpDescriptionTemplateId())); + if (descriptionTemplates != null && d.getDescriptionTemplateId() != null && descriptionTemplates.containsKey(d.getDescriptionTemplateId())) m.setDescriptionTemplate(descriptionTemplates.get(d.getDescriptionTemplateId())); + if (d.getProperties() != null){ + PropertyDefinitionEntity propertyDefinition = this.jsonHandlingService.fromJsonSafe(PropertyDefinitionEntity.class, d.getProperties()); + DefinitionEntity definition = definitionEntityMap != null ? definitionEntityMap.getOrDefault(d.getDescriptionTemplateId(), null) : null; + m.setProperties(this.builderFactory.builder(PropertyDefinitionCommonModelBuilder.class).useSharedStorage(useSharedStorage).withDefinition(definition).authorize(this.authorize).build(propertyDefinition)); + VisibilityService visibilityService = new VisibilityServiceImpl(definition, propertyDefinition); + m.setVisibilityStates(this.builderFactory.builder(VisibilityStateModelBuilder.class).authorize(this.authorize).build(visibilityService.getVisibilityStates().entrySet().stream().toList())); + } + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private Map collectDescriptionTemplateDefinitions(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DefinitionEntity.class.getSimpleName()); + + Map itemMap = new HashMap<>(); + DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList())); + List items = q.collectAs(new BaseFieldSet().ensure(org.opencdmp.model.DescriptionTemplate._id).ensure(DescriptionTemplate._definition)); + for (DescriptionTemplateEntity item : items){ + DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, item.getDefinition()); + itemMap.put(item.getId(), definition); + } + + return itemMap; + } + + private Map collectDmpDescriptionTemplateSections(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DefinitionEntity.class.getSimpleName()); + + Map itemMap = new HashMap<>(); + DmpDescriptionTemplateQuery q = this.queryFactory.query(DmpDescriptionTemplateQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getDmpDescriptionTemplateId).distinct().collect(Collectors.toList())); + List items = q.collectAs(new BaseFieldSet().ensure(org.opencdmp.model.DmpDescriptionTemplate._id).ensure(DmpDescriptionTemplate._sectionId)); + for (DmpDescriptionTemplateEntity item : items){ + itemMap.put(item.getId(), item.getSectionId()); + } + + return itemMap; + } + + private Map collectDmps(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DmpModel.class.getSimpleName()); + + Map itemMap; + DmpQuery q = this.queryFactory.query(DmpQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getDmpId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpCommonModelBuilder.class).setRepositoryId(repositoryId).useSharedStorage(useSharedStorage).setDisableDescriptions(true).authorize(this.authorize).asForeignKey(q, DmpEntity::getId); + + return itemMap; + } + + private Map collectDescriptionTemplates(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DescriptionTemplateModel.class.getSimpleName()); + + Map itemMap; + DescriptionTemplateQuery q = this.queryFactory.query(DescriptionTemplateQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionEntity::getDescriptionTemplateId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionTemplateCommonModelBuilder.class).authorize(this.authorize).asForeignKey(q, DescriptionTemplateEntity::getId); + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/ExternalIdentifierCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/ExternalIdentifierCommonModelBuilder.java new file mode 100644 index 000000000..fe9b3b833 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/ExternalIdentifierCommonModelBuilder.java @@ -0,0 +1,56 @@ +package org.opencdmp.model.builder.commonmodels.description; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.description.ExternalIdentifierModel; +import org.opencdmp.commons.types.description.ExternalIdentifierEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ExternalIdentifierCommonModelBuilder extends BaseCommonModelBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public ExternalIdentifierCommonModelBuilder( + ConventionService conventionService + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ExternalIdentifierCommonModelBuilder.class))); + } + + public ExternalIdentifierCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (ExternalIdentifierEntity d : data) { + ExternalIdentifierModel m = new ExternalIdentifierModel(); + m.setIdentifier(d.getIdentifier()); + m.setType(d.getType()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/FieldCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/FieldCommonModelBuilder.java new file mode 100644 index 000000000..33317f8cf --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/FieldCommonModelBuilder.java @@ -0,0 +1,158 @@ +package org.opencdmp.model.builder.commonmodels.description; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.FileEnvelopeModel; +import eu.eudat.commonmodels.models.description.FieldModel; +import eu.eudat.commonmodels.models.reference.ReferenceModel; +import org.opencdmp.commons.enums.FieldType; +import org.opencdmp.commons.enums.StorageType; +import org.opencdmp.commons.scope.user.UserScope; +import org.opencdmp.commons.types.description.FieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.ReferenceEntity; +import org.opencdmp.data.StorageFileEntity; +import org.opencdmp.model.Reference; +import org.opencdmp.model.StorageFile; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.commonmodels.reference.ReferenceCommonModelBuilder; +import org.opencdmp.model.persist.StorageFilePersist; +import org.opencdmp.query.ReferenceQuery; +import org.opencdmp.query.StorageFileQuery; +import org.opencdmp.service.storage.StorageFileProperties; +import org.opencdmp.service.storage.StorageFileService; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.validation.ValidatorFactory; +import org.apache.commons.io.FilenameUtils; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.net.URLConnection; +import java.time.Duration; +import java.util.*; +import java.util.stream.Collectors; + +@Component("commonmodels.description") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private org.opencdmp.commons.types.descriptiontemplate.FieldEntity fieldEntity; + private final StorageFileService storageFileService; + private final UserScope userScope; + private final ValidatorFactory validatorFactory; + private final StorageFileProperties storageFileProperties; + @Autowired + public FieldCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory, StorageFileService storageFileService, UserScope userScope, ValidatorFactory validatorFactory, StorageFileProperties storageFileProperties + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldCommonModelBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.storageFileService = storageFileService; + this.userScope = userScope; + this.validatorFactory = validatorFactory; + this.storageFileProperties = storageFileProperties; + } + + public FieldCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + public FieldCommonModelBuilder withFieldEntity(org.opencdmp.commons.types.descriptiontemplate.FieldEntity fieldEntity) { + this.fieldEntity = fieldEntity; + return this; + } + + + private boolean useSharedStorage; + public FieldCommonModelBuilder useSharedStorage(boolean useSharedStorage) { + this.useSharedStorage = useSharedStorage; + return this; + } + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + FieldType fieldType = this.fieldEntity != null && this.fieldEntity.getData() != null ? this.fieldEntity.getData().getFieldType() : FieldType.FREE_TEXT; + + Map referenceItemsMap = FieldType.isReferenceType(fieldType) ? this.collectReferences(data) : null; + + List> models = new ArrayList<>(); + for (FieldEntity d : data) { + FieldModel m = new FieldModel(); + if (this.fieldEntity != null) m.setId(fieldEntity.getId()); + if (FieldType.isDateType(fieldType)) m.setDateValue(d.getDateValue()); + if (FieldType.isTextType(fieldType)) m.setTextValue(d.getTextValue()); + if (FieldType.isTextListType(fieldType)) m.setTextListValue(d.getTextListValue()); + if (FieldType.isReferenceType(fieldType) && referenceItemsMap != null && d.getTextListValue() != null && !d.getTextListValue().isEmpty()) { + m.setReferences(new ArrayList<>()); + for (UUID referenceId : d.getTextListValue().stream().map(UUID::fromString).toList()){ + if (referenceItemsMap.containsKey(referenceId)) m.getReferences().add(referenceItemsMap.get(referenceId)); + } + } + + if (FieldType.UPLOAD.equals(fieldType) && d.getTextValue() != null && !d.getTextValue().isEmpty()) { + try { + byte[] bytes = this.storageFileService.readAsBytesSafe(UUID.fromString(d.getTextValue())); + FileEnvelopeModel fileEnvelopeModel = new FileEnvelopeModel(); + StorageFileEntity storageFile = this.queryFactory.query(StorageFileQuery.class).ids(UUID.fromString(d.getTextValue())).first(); + fileEnvelopeModel.setFile(bytes); + fileEnvelopeModel.setFilename(storageFile.getName() + (storageFile.getExtension().startsWith(".") ? "" : ".") + storageFile.getExtension()); + fileEnvelopeModel.setMimeType(storageFile.getMimeType()); + if (!useSharedStorage){ + fileEnvelopeModel.setFile(bytes); + } else { + fileEnvelopeModel.setFileRef(this.addFileToSharedStorage(bytes, storageFile)); + } + }catch (Exception e){ + logger.error(e.getMessage()); + } + } + if (d.getExternalIdentifier() != null && FieldType.isExternalIdentifierType(fieldType)) m.setExternalIdentifier(this.builderFactory.builder(ExternalIdentifierCommonModelBuilder.class).authorize(this.authorize).build(d.getExternalIdentifier())); + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private String addFileToSharedStorage(byte[] bytes, StorageFileEntity storageFile) throws IOException { + StorageFilePersist storageFilePersist = new StorageFilePersist(); + storageFilePersist.setName(FilenameUtils.removeExtension(storageFile.getName())); + storageFilePersist.setExtension(FilenameUtils.getExtension(storageFile.getExtension())); + storageFilePersist.setMimeType(URLConnection.guessContentTypeFromName(storageFile.getName() + (storageFile.getExtension().startsWith(".") ? "" : ".") + storageFile.getExtension())); + storageFilePersist.setOwnerId(this.userScope.getUserIdSafe()); + storageFilePersist.setStorageType(StorageType.Temp); + storageFilePersist.setLifetime(Duration.ofSeconds(this.storageFileProperties.getTempStoreLifetimeSeconds())); //TODO + this.validatorFactory.validator(StorageFilePersist.StorageFilePersistValidator.class).validateForce(storageFilePersist); + StorageFile persisted = this.storageFileService.persistBytes(storageFilePersist, bytes, new BaseFieldSet(StorageFile._id, StorageFile._fileRef)); + return persisted.getFileRef(); + } + + private Map collectReferences(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Reference.class.getSimpleName()); + + Map itemMap; + + ReferenceQuery q = this.queryFactory.query(ReferenceQuery.class).authorize(this.authorize).ids(data.stream().filter(x-> x.getTextListValue() != null).map(FieldEntity::getTextListValue).flatMap(List::stream).filter(x-> !this.conventionService.isNullOrEmpty(x)).map(UUID::fromString).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(ReferenceCommonModelBuilder.class).authorize(this.authorize).asForeignKey(q, ReferenceEntity::getId); + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/PropertyDefinitionCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/PropertyDefinitionCommonModelBuilder.java new file mode 100644 index 000000000..a4751029e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/PropertyDefinitionCommonModelBuilder.java @@ -0,0 +1,72 @@ +package org.opencdmp.model.builder.commonmodels.description; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.description.PropertyDefinitionModel; +import org.opencdmp.commons.types.description.PropertyDefinitionEntity; +import org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity; +import org.opencdmp.commons.types.descriptiontemplate.FieldSetEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PropertyDefinitionCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private DefinitionEntity definition; + @Autowired + public PropertyDefinitionCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PropertyDefinitionCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public PropertyDefinitionCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + public PropertyDefinitionCommonModelBuilder withDefinition(DefinitionEntity definition) { + this.definition = definition; + return this; + } + + + private boolean useSharedStorage; + public PropertyDefinitionCommonModelBuilder useSharedStorage(boolean useSharedStorage) { + this.useSharedStorage = useSharedStorage; + return this; + } + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (PropertyDefinitionEntity d : data) { + PropertyDefinitionModel m = new PropertyDefinitionModel(); + m.setFieldSets(new HashMap<>()); + for (String key : d.getFieldSets().keySet()){ + FieldSetEntity fieldSetEntity = definition != null ? definition.getFieldSetById(key).stream().findFirst().orElse(null) : null; + m.getFieldSets().put(key, this.builderFactory.builder(PropertyDefinitionFieldSetCommonModelBuilder.class).useSharedStorage(useSharedStorage).authorize(this.authorize).withFieldSetEntity(fieldSetEntity).build(d.getFieldSets().get(key))); + } + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/PropertyDefinitionFieldSetCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/PropertyDefinitionFieldSetCommonModelBuilder.java new file mode 100644 index 000000000..1e5c0677e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/PropertyDefinitionFieldSetCommonModelBuilder.java @@ -0,0 +1,68 @@ +package org.opencdmp.model.builder.commonmodels.description; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.description.PropertyDefinitionFieldSetModel; +import org.opencdmp.commons.types.description.PropertyDefinitionFieldSetEntity; +import org.opencdmp.commons.types.descriptiontemplate.FieldSetEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PropertyDefinitionFieldSetCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private FieldSetEntity fieldSetEntity; + @Autowired + public PropertyDefinitionFieldSetCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PropertyDefinitionFieldSetCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public PropertyDefinitionFieldSetCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + + public PropertyDefinitionFieldSetCommonModelBuilder withFieldSetEntity(FieldSetEntity fieldSetEntity) { + this.fieldSetEntity = fieldSetEntity; + return this; + } + + + private boolean useSharedStorage; + public PropertyDefinitionFieldSetCommonModelBuilder useSharedStorage(boolean useSharedStorage) { + this.useSharedStorage = useSharedStorage; + return this; + } + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (PropertyDefinitionFieldSetEntity d : data) { + PropertyDefinitionFieldSetModel m = new PropertyDefinitionFieldSetModel(); + if (d.getItems() != null) m.setItems(this.builderFactory.builder(PropertyDefinitionFieldSetItemModelCommonModelBuilder.class).useSharedStorage(useSharedStorage).withFieldSetEntity(this.fieldSetEntity).authorize(this.authorize).build(d.getItems())); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/PropertyDefinitionFieldSetItemModelCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/PropertyDefinitionFieldSetItemModelCommonModelBuilder.java new file mode 100644 index 000000000..48a703ed3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/PropertyDefinitionFieldSetItemModelCommonModelBuilder.java @@ -0,0 +1,80 @@ +package org.opencdmp.model.builder.commonmodels.description; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.description.PropertyDefinitionFieldSetItemModel; +import org.opencdmp.commons.types.description.PropertyDefinitionFieldSetItemEntity; +import org.opencdmp.commons.types.descriptiontemplate.FieldEntity; +import org.opencdmp.commons.types.descriptiontemplate.FieldSetEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PropertyDefinitionFieldSetItemModelCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private FieldSetEntity fieldSetEntity; + @Autowired + public PropertyDefinitionFieldSetItemModelCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PropertyDefinitionFieldSetItemModelCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public PropertyDefinitionFieldSetItemModelCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + + public PropertyDefinitionFieldSetItemModelCommonModelBuilder withFieldSetEntity(FieldSetEntity fieldSetEntity) { + this.fieldSetEntity = fieldSetEntity; + return this; + } + + + private boolean useSharedStorage; + public PropertyDefinitionFieldSetItemModelCommonModelBuilder useSharedStorage(boolean useSharedStorage) { + this.useSharedStorage = useSharedStorage; + return this; + } + + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (PropertyDefinitionFieldSetItemEntity d : data) { + PropertyDefinitionFieldSetItemModel m = new PropertyDefinitionFieldSetItemModel(); + + m.setComment(d.getComment()); + m.setOrdinal(d.getOrdinal()); + if (d.getFields() != null && !d.getFields().isEmpty()) { + m.setFields(new HashMap<>()); + for (String key : d.getFields().keySet()){ + FieldEntity fieldEntity = fieldSetEntity != null ? fieldSetEntity.getFieldById(key).stream().findFirst().orElse(null) : null; + m.getFields().put(key, this.builderFactory.builder(FieldCommonModelBuilder.class).useSharedStorage(useSharedStorage).authorize(this.authorize).withFieldEntity(fieldEntity).build(d.getFields().get(key))); + } + } + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/VisibilityStateModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/VisibilityStateModelBuilder.java new file mode 100644 index 000000000..31b341ebb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/description/VisibilityStateModelBuilder.java @@ -0,0 +1,56 @@ +package org.opencdmp.model.builder.commonmodels.description; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.description.VisibilityStateModel; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.service.visibility.FieldKey; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("commonmodels.VisibilityStateModelBuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class VisibilityStateModelBuilder extends BaseCommonModelBuilder> { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public VisibilityStateModelBuilder( + ConventionService conventionService + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(VisibilityStateModelBuilder.class))); + } + + public VisibilityStateModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List>> buildInternal(List> data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List>> models = new ArrayList<>(); + for (Map.Entry d : data) { + VisibilityStateModel m = new VisibilityStateModel(); + if (d.getKey() != null) { + m.setFieldId(d.getKey().getFieldId()); + m.setOrdinal(d.getKey().getOrdinal()); + } + m.setVisible(d.getValue()); + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/DefinitionCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/DefinitionCommonModelBuilder.java new file mode 100644 index 000000000..67f58839f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/DefinitionCommonModelBuilder.java @@ -0,0 +1,59 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.descriptiotemplate.DefinitionModel; +import org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.descriptiontemplatedefinition.PageBuilder; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DefinitionCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public DefinitionCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DefinitionCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public DefinitionCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (DefinitionEntity d : data) { + DefinitionModel m = new DefinitionModel(); + if (d.getPages() != null) m.setPages(this.builderFactory.builder(PageCommonModelBuilder.class).authorize(this.authorize).build(d.getPages())); + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/DescriptionTemplateCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/DescriptionTemplateCommonModelBuilder.java new file mode 100644 index 000000000..a335f5446 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/DescriptionTemplateCommonModelBuilder.java @@ -0,0 +1,97 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.DescriptionTemplateTypeModel; +import eu.eudat.commonmodels.models.descriptiotemplate.DescriptionTemplateModel; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DescriptionTemplateEntity; +import org.opencdmp.data.DescriptionTemplateTypeEntity; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.commonmodels.DescriptionTemplateTypeCommonModelBuilder; +import org.opencdmp.query.DescriptionTemplateTypeQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTemplateCommonModelBuilder extends BaseCommonModelBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + private final XmlHandlingService xmlHandlingService; + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + @Autowired + public DescriptionTemplateCommonModelBuilder( + ConventionService conventionService, XmlHandlingService xmlHandlingService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionTemplateCommonModelBuilder.class))); + this.xmlHandlingService = xmlHandlingService; + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public DescriptionTemplateCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + Map typeMap = this.collectDescriptionTemplateTypes(data); + List> models = new ArrayList<>(); + for (DescriptionTemplateEntity d : data) { + DescriptionTemplateModel m = new DescriptionTemplateModel(); + m.setId(d.getId()); + m.setLabel(d.getLabel()); + m.setDescription(d.getDescription()); + m.setGroupId(d.getGroupId()); + m.setVersion(d.getVersion()); + m.setLanguage(d.getLanguage()); + if (d.getDefinition() != null){ + //TODO Update with the new logic of property definition + DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, d.getDefinition()); + m.setDefinition(this.builderFactory.builder(DefinitionCommonModelBuilder.class).authorize(this.authorize).build(definition)); + } + if (typeMap != null && d.getTypeId() != null && typeMap.containsKey(d.getTypeId())) m.setType(typeMap.get(d.getTypeId())); + + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + + + + private Map collectDescriptionTemplateTypes(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DescriptionTemplateTypeModel.class.getSimpleName()); + + Map itemMap; + DescriptionTemplateTypeQuery q = this.queryFactory.query(DescriptionTemplateTypeQuery.class).authorize(this.authorize).ids(data.stream().map(DescriptionTemplateEntity::getTypeId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionTemplateTypeCommonModelBuilder.class).authorize(this.authorize).asForeignKey(q, DescriptionTemplateTypeEntity::getId); + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/FieldCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/FieldCommonModelBuilder.java new file mode 100644 index 000000000..e4dc7dbe9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/FieldCommonModelBuilder.java @@ -0,0 +1,85 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.descriptiotemplate.FieldModel; +import org.opencdmp.commons.enums.FieldValidationType; +import org.opencdmp.commons.types.descriptiontemplate.FieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.service.fielddatahelper.FieldDataHelperService; +import org.opencdmp.service.fielddatahelper.FieldDataHelperServiceProvider; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component("commonmodels.descriptiontemplate") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private final FieldDataHelperServiceProvider fieldDataHelperServiceProvider; + @Autowired + public FieldCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory, FieldDataHelperServiceProvider fieldDataHelperServiceProvider + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldCommonModelBuilder.class))); + this.builderFactory = builderFactory; + this.fieldDataHelperServiceProvider = fieldDataHelperServiceProvider; + } + + public FieldCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (FieldEntity d : data) { + FieldModel m = new FieldModel(); + m.setId(d.getId()); + m.setOrdinal(d.getOrdinal()); + m.setNumbering(d.getNumbering()); + m.setSchematics(d.getSchematics()); + m.setDefaultValue(d.getDefaultValue()); + m.setIncludeInExport(d.getIncludeInExport()); + if (!this.conventionService.isListNullOrEmpty(d.getValidations())){ + m.setValidations(new ArrayList<>()); + for (FieldValidationType fieldValidationType : d.getValidations()) { + switch (fieldValidationType){ + case Url -> m.getValidations().add(eu.eudat.commonmodels.enums.FieldValidationType.Url); + case None -> m.getValidations().add(eu.eudat.commonmodels.enums.FieldValidationType.None); + case Required -> m.getValidations().add(eu.eudat.commonmodels.enums.FieldValidationType.Required); + default -> throw new MyApplicationException("unrecognized type " + fieldValidationType); + } + + } + } + m.setNumbering(d.getNumbering()); + m.setNumbering(d.getNumbering()); + if (d.getData() != null){ + FieldDataHelperService fieldDataHelperService = this.fieldDataHelperServiceProvider.get(d.getData().getFieldType()); + m.setData(fieldDataHelperService.buildCommonModelOne(d.getData(), this.authorize)); + } + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/FieldSetCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/FieldSetCommonModelBuilder.java new file mode 100644 index 000000000..c7493d023 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/FieldSetCommonModelBuilder.java @@ -0,0 +1,68 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.descriptiotemplate.FieldSetModel; +import org.opencdmp.commons.types.descriptiontemplate.FieldSetEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.descriptiontemplatedefinition.FieldBuilder; +import org.opencdmp.model.builder.descriptiontemplatedefinition.MultiplicityBuilder; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldSetCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public FieldSetCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldSetCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public FieldSetCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (FieldSetEntity d : data) { + FieldSetModel m = new FieldSetModel(); + m.setId(d.getId()); + m.setOrdinal(d.getOrdinal()); + m.setTitle(d.getTitle()); + m.setNumbering(d.getNumbering()); + m.setDescription(d.getDescription()); + m.setExtendedDescription(d.getExtendedDescription()); + m.setAdditionalInformation(d.getAdditionalInformation()); + m.setHasMultiplicity(d.getHasMultiplicity()); + if (d.getMultiplicity() != null) m.setMultiplicity(this.builderFactory.builder(MultiplicityCommonModelBuilder.class).authorize(this.authorize).build(d.getMultiplicity())); + if (d.getFields() != null) m.setFields(this.builderFactory.builder(FieldCommonModelBuilder.class).authorize(this.authorize).build(d.getFields())); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/MultiplicityCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/MultiplicityCommonModelBuilder.java new file mode 100644 index 000000000..bc0e0dd30 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/MultiplicityCommonModelBuilder.java @@ -0,0 +1,61 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.descriptiotemplate.MultiplicityModel; +import org.opencdmp.commons.types.descriptiontemplate.MultiplicityEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.descriptiontemplatedefinition.Multiplicity; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class MultiplicityCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public MultiplicityCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(MultiplicityCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public MultiplicityCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (MultiplicityEntity d : data) { + MultiplicityModel m = new MultiplicityModel(); + m.setMin(d.getMin()); + m.setMax(d.getMax()); + m.setPlaceholder(d.getPlaceholder()); + m.setTableView(d.getTableView()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/PageCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/PageCommonModelBuilder.java new file mode 100644 index 000000000..bfab0020f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/PageCommonModelBuilder.java @@ -0,0 +1,63 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.descriptiotemplate.PageModel; +import org.opencdmp.commons.types.descriptiontemplate.PageEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.descriptiontemplatedefinition.SectionBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.Page; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PageCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public PageCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PageCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public PageCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (PageEntity d : data) { + PageModel m = new PageModel(); + m.setId(d.getId()); + m.setOrdinal(d.getOrdinal()); + m.setTitle(d.getTitle()); + m.setSections(this.builderFactory.builder(SectionCommonModelBuilder.class).authorize(this.authorize).build(d.getSections())); + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/SectionCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/SectionCommonModelBuilder.java new file mode 100644 index 000000000..104b9bc89 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/SectionCommonModelBuilder.java @@ -0,0 +1,68 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.descriptiotemplate.SectionModel; +import org.opencdmp.commons.types.descriptiontemplate.SectionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.descriptiontemplatedefinition.FieldSetBuilder; +import org.opencdmp.model.builder.descriptiontemplatedefinition.SectionBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.Section; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SectionCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public SectionCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(SectionCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public SectionCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (SectionEntity d : data) { + SectionModel m = new SectionModel(); + m.setId(d.getId()); + m.setDescription(d.getDescription()); + m.setOrdinal(d.getOrdinal()); + m.setDefaultVisibility(d.isDefaultVisibility()); + m.setNumbering(d.getNumbering()); + m.setTitle(d.getTitle()); + m.setExtendedDescription(d.getExtendedDescription()); + if (d.getSections() != null) m.setSections(this.builderFactory.builder(SectionCommonModelBuilder.class).authorize(this.authorize).build(d.getSections())); + if (d.getFieldSets() != null) m.setFieldSets(this.builderFactory.builder(FieldSetCommonModelBuilder.class).authorize(this.authorize).build(d.getFieldSets())); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/BaseFieldDataCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/BaseFieldDataCommonModelBuilder.java new file mode 100644 index 000000000..c1a0111e2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/BaseFieldDataCommonModelBuilder.java @@ -0,0 +1,78 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate.fielddata; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.enums.FieldType; +import eu.eudat.commonmodels.models.descriptiotemplate.fielddata.BaseFieldDataModel; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.BaseFieldDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public abstract class BaseFieldDataCommonModelBuilder extends BaseCommonModelBuilder { + protected EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public BaseFieldDataCommonModelBuilder( + ConventionService conventionService, + LoggerService logger) { + super(conventionService, logger); + } + + public BaseFieldDataCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + protected abstract Model getInstance(); + + protected abstract void buildChild(Entity d, Model m); + + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (Entity d : data) { + Model m = this.getInstance(); + m.setLabel(d.getLabel()); + switch (d.getFieldType()){ + case SELECT -> m.setFieldType(FieldType.SELECT); + case BOOLEAN_DECISION -> m.setFieldType(FieldType.BOOLEAN_DECISION); + case RADIO_BOX -> m.setFieldType(FieldType.RADIO_BOX); + case INTERNAL_ENTRIES_DMPS -> m.setFieldType(FieldType.INTERNAL_ENTRIES_DMPS); + case INTERNAL_ENTRIES_DESCRIPTIONS -> m.setFieldType(FieldType.INTERNAL_ENTRIES_DESCRIPTIONS); + case CHECK_BOX -> m.setFieldType(FieldType.CHECK_BOX); + case FREE_TEXT -> m.setFieldType(FieldType.FREE_TEXT); + case TEXT_AREA -> m.setFieldType(FieldType.TEXT_AREA); + case RICH_TEXT_AREA -> m.setFieldType(FieldType.RICH_TEXT_AREA); + case UPLOAD -> m.setFieldType(FieldType.UPLOAD); + case DATE_PICKER -> m.setFieldType(FieldType.DATE_PICKER); + case TAGS -> m.setFieldType(FieldType.TAGS); + case REFERENCE_TYPES -> m.setFieldType(FieldType.REFERENCE_TYPES); + case DATASET_IDENTIFIER -> m.setFieldType(FieldType.DATASET_IDENTIFIER); + case VALIDATION -> m.setFieldType(FieldType.VALIDATION); + default -> throw new MyApplicationException("unrecognized type " + d.getFieldType()); + } + this.buildChild(d, m); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/LabelAndMultiplicityDataCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/LabelAndMultiplicityDataCommonModelBuilder.java new file mode 100644 index 000000000..72d24f952 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/LabelAndMultiplicityDataCommonModelBuilder.java @@ -0,0 +1,31 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate.fielddata; + +import eu.eudat.commonmodels.models.descriptiotemplate.fielddata.LabelAndMultiplicityDataModel; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.LabelAndMultiplicityDataEntity; +import org.opencdmp.convention.ConventionService; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LabelAndMultiplicityDataCommonModelBuilder extends BaseFieldDataCommonModelBuilder { + @Autowired + public LabelAndMultiplicityDataCommonModelBuilder( + ConventionService conventionService + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(LabelAndMultiplicityDataCommonModelBuilder.class))); + } + + protected LabelAndMultiplicityDataModel getInstance() { + return new LabelAndMultiplicityDataModel(); + } + + @Override + protected void buildChild(LabelAndMultiplicityDataEntity d, LabelAndMultiplicityDataModel m) { + m.setMultipleSelect(d.getMultipleSelect()); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/LabelDataCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/LabelDataCommonModelBuilder.java new file mode 100644 index 000000000..35e072034 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/LabelDataCommonModelBuilder.java @@ -0,0 +1,31 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate.fielddata; + +import eu.eudat.commonmodels.models.descriptiotemplate.fielddata.LabelDataModel; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.LabelDataEntity; +import org.opencdmp.convention.ConventionService; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LabelDataCommonModelBuilder extends BaseFieldDataCommonModelBuilder { + @Autowired + public LabelDataCommonModelBuilder( + ConventionService conventionService + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(LabelDataCommonModelBuilder.class))); + } + + protected LabelDataModel getInstance() { + return new LabelDataModel(); + } + + @Override + protected void buildChild(LabelDataEntity d, LabelDataModel m) { + + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/RadioBoxDataCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/RadioBoxDataCommonModelBuilder.java new file mode 100644 index 000000000..206c51959 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/RadioBoxDataCommonModelBuilder.java @@ -0,0 +1,80 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate.fielddata; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.descriptiotemplate.fielddata.RadioBoxDataModel; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.RadioBoxDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class RadioBoxDataCommonModelBuilder extends BaseFieldDataCommonModelBuilder { + private final BuilderFactory builderFactory; + @Autowired + public RadioBoxDataCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(RadioBoxDataCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + protected RadioBoxDataModel getInstance() { + return new RadioBoxDataModel(); + } + + @Override + protected void buildChild(RadioBoxDataEntity d, RadioBoxDataModel m) { + m.setOptions(this.builderFactory.builder(RadioBoxOptionCommonModelBuilder.class).authorize(this.authorize).build(d.getOptions())); + } + + @Component + @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public static class RadioBoxOptionCommonModelBuilder extends BaseCommonModelBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public RadioBoxOptionCommonModelBuilder( + ConventionService conventionService + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(RadioBoxOptionCommonModelBuilder.class))); + } + + public RadioBoxOptionCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (RadioBoxDataEntity.RadioBoxDataOptionEntity d : data) { + RadioBoxDataModel.RadioBoxOptionModel m = new RadioBoxDataModel.RadioBoxOptionModel(); + m.setLabel(d.getLabel()); + m.setValue(d.getValue()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/ReferenceTypeDataCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/ReferenceTypeDataCommonModelBuilder.java new file mode 100644 index 000000000..10a4b2e27 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/ReferenceTypeDataCommonModelBuilder.java @@ -0,0 +1,43 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate.fielddata; + +import eu.eudat.commonmodels.models.descriptiotemplate.fielddata.ReferenceTypeDataModel; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.ReferenceTypeDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.ReferenceTypeBuilder; +import org.opencdmp.model.builder.commonmodels.ReferenceTypeCommonModelBuilder; +import org.opencdmp.query.ReferenceTypeQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeDataCommonModelBuilder extends BaseFieldDataCommonModelBuilder { + + private final QueryFactory queryFactory; + private final BuilderFactory builderFactory; + @Autowired + public ReferenceTypeDataCommonModelBuilder( + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceTypeDataCommonModelBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + protected ReferenceTypeDataModel getInstance() { + return new ReferenceTypeDataModel(); + } + + @Override + protected void buildChild(ReferenceTypeDataEntity d, ReferenceTypeDataModel m) { + m.setMultipleSelect(d.getMultipleSelect()); + if (d.getReferenceTypeId() != null) m.setReferenceType(this.builderFactory.builder(ReferenceTypeCommonModelBuilder.class).build(this.queryFactory.query(ReferenceTypeQuery.class).ids(d.getReferenceTypeId()).first())); //TODO: Optimize + + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/SelectDataCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/SelectDataCommonModelBuilder.java new file mode 100644 index 000000000..c27bca1ae --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/SelectDataCommonModelBuilder.java @@ -0,0 +1,81 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate.fielddata; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.descriptiotemplate.fielddata.SelectDataModel; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.SelectDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SelectDataCommonModelBuilder extends BaseFieldDataCommonModelBuilder { + private final BuilderFactory builderFactory; + @Autowired + public SelectDataCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(SelectDataCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + protected SelectDataModel getInstance() { + return new SelectDataModel(); + } + + @Override + protected void buildChild(SelectDataEntity d, SelectDataModel m) { + m.setMultipleSelect(d.getMultipleSelect()); + m.setOptions(this.builderFactory.builder(SelectOptionCommonModelBuilder.class).authorize(this.authorize).build(d.getOptions())); + } + + @Component + @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public static class SelectOptionCommonModelBuilder extends BaseCommonModelBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public SelectOptionCommonModelBuilder( + ConventionService conventionService + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(SelectOptionCommonModelBuilder.class))); + } + + public SelectOptionCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (SelectDataEntity.OptionEntity d : data) { + SelectDataModel.OptionModel m = new SelectDataModel.OptionModel(); + m.setLabel(d.getLabel()); + m.setValue(d.getValue()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/UploadDataCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/UploadDataCommonModelBuilder.java new file mode 100644 index 000000000..95a93d84d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/descriptiontemplate/fielddata/UploadDataCommonModelBuilder.java @@ -0,0 +1,80 @@ +package org.opencdmp.model.builder.commonmodels.descriptiontemplate.fielddata; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.descriptiotemplate.fielddata.UploadDataModel; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.UploadDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UploadDataCommonModelBuilder extends BaseFieldDataCommonModelBuilder { + private final BuilderFactory builderFactory; + @Autowired + public UploadDataCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UploadDataCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + protected UploadDataModel getInstance() { + return new UploadDataModel(); + } + + @Override + protected void buildChild(UploadDataEntity d, UploadDataModel m) { + m.setTypes(this.builderFactory.builder(UploadOptionCommonModelBuilder.class).authorize(this.authorize).build(d.getTypes())); + } + + @Component + @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public static class UploadOptionCommonModelBuilder extends BaseCommonModelBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public UploadOptionCommonModelBuilder( + ConventionService conventionService + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UploadOptionCommonModelBuilder.class))); + } + + public UploadOptionCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (UploadDataEntity.UploadDataOptionEntity d : data) { + UploadDataModel.UploadOptionModel m = new UploadDataModel.UploadOptionModel(); + m.setLabel(d.getLabel()); + m.setValue(d.getValue()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpBlueprintValueCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpBlueprintValueCommonModelBuilder.java new file mode 100644 index 000000000..49571a24f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpBlueprintValueCommonModelBuilder.java @@ -0,0 +1,55 @@ +package org.opencdmp.model.builder.commonmodels.dmp; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.dmp.DmpBlueprintValueModel; +import org.opencdmp.commons.types.dmp.DmpBlueprintValueEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpBlueprintValueCommonModelBuilder extends BaseCommonModelBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public DmpBlueprintValueCommonModelBuilder( + ConventionService conventionService + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpBlueprintValueCommonModelBuilder.class))); + } + + public DmpBlueprintValueCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (DmpBlueprintValueEntity d : data) { + DmpBlueprintValueModel m = new DmpBlueprintValueModel(); + m.setValue(d.getValue()); + m.setFieldId(d.getFieldId()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpCommonModelBuilder.java new file mode 100644 index 000000000..11e07f5b3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpCommonModelBuilder.java @@ -0,0 +1,236 @@ +package org.opencdmp.model.builder.commonmodels.dmp; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.enums.DmpAccessType; +import eu.eudat.commonmodels.enums.DmpStatus; +import eu.eudat.commonmodels.models.DmpUserModel; +import eu.eudat.commonmodels.models.EntityDoiModel; +import eu.eudat.commonmodels.models.FileEnvelopeModel; +import eu.eudat.commonmodels.models.UserModel; +import eu.eudat.commonmodels.models.description.DescriptionModel; +import eu.eudat.commonmodels.models.dmp.DmpModel; +import eu.eudat.commonmodels.models.dmpblueprint.DmpBlueprintModel; +import eu.eudat.commonmodels.models.dmpreference.DmpReferenceModel; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.types.dmp.DmpPropertiesEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.*; +import org.opencdmp.model.*; +import org.opencdmp.model.builder.commonmodels.*; +import org.opencdmp.model.builder.commonmodels.description.DescriptionCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.dmpblueprint.DmpBlueprintCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.dmpreference.DmpReferenceCommonModelBuilder; +import org.opencdmp.query.*; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.Ordering; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpCommonModelBuilder extends BaseCommonModelBuilder { + + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + private final JsonHandlingService jsonHandlingService; + private FileEnvelopeModel pdfFile; + private FileEnvelopeModel rdaJsonFile; + private String repositoryId; + private boolean disableDescriptions; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpCommonModelBuilder(ConventionService conventionService, + QueryFactory queryFactory, + BuilderFactory builderFactory, JsonHandlingService jsonHandlingService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpCommonModelBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + this.jsonHandlingService = jsonHandlingService; + } + + public DmpCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + public DmpCommonModelBuilder setPdfFile(FileEnvelopeModel pdfFile) { + this.pdfFile = pdfFile; + return this; + } + + public DmpCommonModelBuilder setRdaJsonFile(FileEnvelopeModel rdaJsonFile) { + this.rdaJsonFile = rdaJsonFile; + return this; + } + + public DmpCommonModelBuilder setRepositoryId(String repositoryId) { + this.repositoryId = repositoryId; + return this; + } + + public DmpCommonModelBuilder setDisableDescriptions(boolean disableDescriptions) { + this.disableDescriptions = disableDescriptions; + return this; + } + + + private boolean useSharedStorage; + public DmpCommonModelBuilder useSharedStorage(boolean useSharedStorage) { + this.useSharedStorage = useSharedStorage; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + + Map> dmpReferencesMap = this.collectDmpReferences(data); + Map> dmpUsersMap = this.collectDmpUsers(data); + Map> descriptionsMap = this.disableDescriptions ? null : this.collectDmpDescriptions(data); + Map> entityDois = this.collectDmpEntityDois(data); + Map creators = this.collectCreators(data); + Map dmpBlueprints = this.collectDmpBlueprints(data); + + for (DmpEntity d : data) { + DmpModel m = new DmpModel(); + m.setId(d.getId()); + m.setLabel(d.getLabel()); + m.setVersion(d.getVersion()); + m.setDescription(d.getDescription()); + m.setFinalizedAt(d.getFinalizedAt()); + m.setCreatedAt(d.getCreatedAt()); + m.setLanguage(d.getLanguage()); + switch (d.getStatus()){ + case Finalized -> m.setStatus(DmpStatus.Finalized); + case Draft -> m.setStatus(DmpStatus.Draft); + default -> throw new MyApplicationException("unrecognized type " + d.getStatus()); + } + if (entityDois != null && !entityDois.isEmpty() && entityDois.containsKey(d.getId())) m.setEntityDois(entityDois.get(d.getId())); + if (creators != null && !creators.isEmpty() && d.getCreatorId() != null && creators.containsKey(d.getCreatorId())) m.setCreator(creators.get(d.getCreatorId())); + if (dmpBlueprints != null && !dmpBlueprints.isEmpty() && d.getBlueprintId() != null && dmpBlueprints.containsKey(d.getBlueprintId())) m.setDmpBlueprint(dmpBlueprints.get(d.getBlueprintId())); + if (d.getProperties() != null){ + //TODO Update with the new logic of property definition + DmpPropertiesEntity propertyDefinition = this.jsonHandlingService.fromJsonSafe(DmpPropertiesEntity.class, d.getProperties()); + m.setProperties(this.builderFactory.builder(DmpPropertiesCommonModelBuilder.class).authorize(this.authorize).build(propertyDefinition)); + } + m.setPublicAfter(d.getPublicAfter()); + m.setUpdatedAt(d.getUpdatedAt()); + m.setPdfFile(this.pdfFile); + m.setRdaJsonFile(this.rdaJsonFile); + if (d.getVersion() > (short)1) m.setPreviousDOI(this.getPreviousDOI(d.getGroupId(), d.getId())); + switch (d.getAccessType()){ + case Public -> m.setAccessType(DmpAccessType.Public); + case Restricted -> m.setAccessType(DmpAccessType.Restricted); + case null -> m.setAccessType(null); + default -> throw new MyApplicationException("unrecognized type " + d.getAccessType()); + } + + if (dmpReferencesMap != null && !dmpReferencesMap.isEmpty() && dmpReferencesMap.containsKey(d.getId())) m.setReferences(dmpReferencesMap.get(d.getId())); + if (dmpUsersMap != null && !dmpUsersMap.isEmpty() && dmpUsersMap.containsKey(d.getId())) m.setUsers(dmpUsersMap.get(d.getId())); + if (descriptionsMap != null && !descriptionsMap.isEmpty() && descriptionsMap.containsKey(d.getId())) m.setDescriptions(descriptionsMap.get(d.getId())); + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + + private String getPreviousDOI(UUID dmpGroup, UUID currentDmpId) { + if (repositoryId == null || repositoryId.isEmpty()) throw new MyApplicationException("repositoryId required"); + + //GK: Step one get the previous version of the Data management plan + DmpQuery dmpQuery = this.queryFactory.query(DmpQuery.class); + dmpQuery.setOrder(new Ordering().addDescending(Dmp._version)); + List dmpIds = dmpQuery.groupIds(dmpGroup).excludedIds(currentDmpId).isActive(IsActive.Active).collectAs(new BaseFieldSet().ensure(Dmp._id)).stream().map(DmpEntity::getId).toList(); + + //GK: Step two get it's doiEntity + List dois = this.queryFactory.query(EntityDoiQuery.class).repositoryIds(repositoryId).entityIds(dmpIds).isActive(IsActive.Active).collectAs(new BaseFieldSet().ensure(EntityDoi._entityId, EntityDoi._doi)); + for(UUID uuid: dmpIds) { + EntityDoiEntity doiEntity = dois.stream().filter(x -> x.getEntityId().equals(uuid)).findFirst().orElse(null); + if (doiEntity != null) return doiEntity.getDoi(); + } + return null; + } + + private Map> collectDmpUsers(List data) throws MyApplicationException { + this.logger.debug("checking related - {}", DmpUser.class.getSimpleName()); + + Map> itemMap; + DmpUserQuery query = this.queryFactory.query(DmpUserQuery.class).isActives(IsActive.Active).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpUserCommonModelBuilder.class).authorize(this.authorize).asMasterKey(query, DmpUserEntity::getDmpId); + + return itemMap; + } + + private Map> collectDmpReferences(List data) throws MyApplicationException { + this.logger.debug("checking related - {}", DmpReference.class.getSimpleName()); + + Map> itemMap; + DmpReferenceQuery query = this.queryFactory.query(DmpReferenceQuery.class).isActives(IsActive.Active).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpReferenceCommonModelBuilder.class).authorize(this.authorize).asMasterKey(query, DmpReferenceEntity::getDmpId); + + return itemMap; + } + + private Map> collectDmpDescriptions(List data) throws MyApplicationException { + if (data.isEmpty()) return null; + this.logger.debug("checking related - {}", Description.class.getSimpleName()); + + Map> itemMap; + DescriptionQuery query = this.queryFactory.query(DescriptionQuery.class).isActive(IsActive.Active).authorize(this.authorize).dmpIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DescriptionCommonModelBuilder.class).setRepositoryId(repositoryId).useSharedStorage(useSharedStorage).authorize(this.authorize).asMasterKey(query, DescriptionEntity::getDmpId); + + return itemMap; + } + + private Map> collectDmpEntityDois(List data) throws MyApplicationException { + if (data.isEmpty()) return null; + this.logger.debug("checking related - {}", EntityDoi.class.getSimpleName()); + + Map> itemMap; + EntityDoiQuery query = this.queryFactory.query(EntityDoiQuery.class).isActive(IsActive.Active).authorize(this.authorize).entityIds(data.stream().map(DmpEntity::getId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(EntityDoiCommonModelBuilder.class).authorize(this.authorize).asMasterKey(query, EntityDoiEntity::getEntityId); + + return itemMap; + } + + private Map collectCreators(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", UserModel.class.getSimpleName()); + + Map itemMap; + UserQuery q = this.queryFactory.query(UserQuery.class).isActive(IsActive.Active).authorize(this.authorize).ids(data.stream().filter(x-> x.getCreatorId() != null).map(DmpEntity::getCreatorId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserCommonModelBuilder.class).authorize(this.authorize).asForeignKey(q, UserEntity::getId); + return itemMap; + } + + private Map collectDmpBlueprints(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", DmpBlueprintModel.class.getSimpleName()); + + Map itemMap; + DmpBlueprintQuery q = this.queryFactory.query(DmpBlueprintQuery.class).isActive(IsActive.Active).authorize(this.authorize).ids(data.stream().filter(x-> x.getBlueprintId() != null).map(DmpEntity::getBlueprintId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpBlueprintCommonModelBuilder.class).authorize(this.authorize).asForeignKey(q, DmpBlueprintEntity::getId); + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpContactCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpContactCommonModelBuilder.java new file mode 100644 index 000000000..fb262a58e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpContactCommonModelBuilder.java @@ -0,0 +1,79 @@ +package org.opencdmp.model.builder.commonmodels.dmp; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.UserModel; +import eu.eudat.commonmodels.models.dmp.DmpContactModel; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.commons.types.dmp.DmpContactEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.UserEntity; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.commonmodels.UserCommonModelBuilder; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpContactCommonModelBuilder extends BaseCommonModelBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + + @Autowired + public DmpContactCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpContactCommonModelBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public DmpContactCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + Map userItemsMap = this.collectUsers(data); + + List> models = new ArrayList<>(); + for (DmpContactEntity d : data) { + DmpContactModel m = new DmpContactModel(); + m.setEmail(d.getEmail()); + m.setFirstName(d.getFirstName()); + m.setLastName(d.getLastName()); + if (userItemsMap != null && d.getUserId() != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectUsers(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", UserModel.class.getSimpleName()); + + Map itemMap; + UserQuery q = this.queryFactory.query(UserQuery.class).isActive(IsActive.Active).authorize(this.authorize).ids(data.stream().filter(x-> x.getUserId() != null).map(DmpContactEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(UserCommonModelBuilder.class).disableContacts(true).authorize(this.authorize).asForeignKey(q, UserEntity::getId); + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpPropertiesCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpPropertiesCommonModelBuilder.java new file mode 100644 index 000000000..9ec39c6b7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmp/DmpPropertiesCommonModelBuilder.java @@ -0,0 +1,60 @@ +package org.opencdmp.model.builder.commonmodels.dmp; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.dmp.DmpPropertiesModel; +import org.opencdmp.commons.types.dmp.DmpPropertiesEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.commonmodels.descriptiontemplate.PageCommonModelBuilder; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpPropertiesCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public DmpPropertiesCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpPropertiesCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public DmpPropertiesCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (DmpPropertiesEntity d : data) { + DmpPropertiesModel m = new DmpPropertiesModel(); + if (d.getDmpBlueprintValues() != null) m.setDmpBlueprintValues(this.builderFactory.builder(DmpBlueprintValueCommonModelBuilder.class).authorize(this.authorize).build(d.getDmpBlueprintValues())); + if (d.getContacts() != null) m.setContacts(this.builderFactory.builder(DmpContactCommonModelBuilder.class).authorize(this.authorize).build(d.getContacts())); + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/DefinitionCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/DefinitionCommonModelBuilder.java new file mode 100644 index 000000000..b92588d76 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/DefinitionCommonModelBuilder.java @@ -0,0 +1,59 @@ +package org.opencdmp.model.builder.commonmodels.dmpblueprint; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.dmpblueprint.DefinitionModel; +import org.opencdmp.commons.types.dmpblueprint.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.commonmodels.dmp.DmpBlueprintValueCommonModelBuilder; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component("dmpblueprint.DefinitionCommonModelBuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DefinitionCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public DefinitionCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DefinitionCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public DefinitionCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (DefinitionEntity d : data) { + DefinitionModel m = new DefinitionModel(); + if (d.getSections() != null) m.setSections(this.builderFactory.builder(SectionCommonModelBuilder.class).authorize(this.authorize).build(d.getSections())); + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/DmpBlueprintCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/DmpBlueprintCommonModelBuilder.java new file mode 100644 index 000000000..6ce222204 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/DmpBlueprintCommonModelBuilder.java @@ -0,0 +1,78 @@ +package org.opencdmp.model.builder.commonmodels.dmpblueprint; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.enums.DmpBlueprintStatus; +import eu.eudat.commonmodels.models.dmpblueprint.DmpBlueprintModel; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.types.dmpblueprint.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpBlueprintEntity; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpBlueprintCommonModelBuilder extends BaseCommonModelBuilder { + + private final BuilderFactory builderFactory; + private final XmlHandlingService xmlHandlingService; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpBlueprintCommonModelBuilder(ConventionService conventionService, + BuilderFactory builderFactory, XmlHandlingService xmlHandlingService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpBlueprintCommonModelBuilder.class))); + this.builderFactory = builderFactory; + this.xmlHandlingService = xmlHandlingService; + } + + public DmpBlueprintCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + + + for (DmpBlueprintEntity d : data) { + DmpBlueprintModel m = new DmpBlueprintModel(); + m.setId(d.getId()); + m.setLabel(d.getLabel()); + m.setGroupId(d.getGroupId()); + switch (d.getStatus()){ + case Finalized -> m.setStatus(DmpBlueprintStatus.Finalized); + case Draft -> m.setStatus(DmpBlueprintStatus.Draft); + default -> throw new MyApplicationException("unrecognized type " + d.getStatus()); + } + if (d.getDefinition() != null){ + //TODO Update with the new logic of property definition + DefinitionEntity propertyDefinition = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, d.getDefinition()); + m.setDefinition(this.builderFactory.builder(DefinitionCommonModelBuilder.class).authorize(this.authorize).build(propertyDefinition)); + } + + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/ExtraFieldCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/ExtraFieldCommonModelBuilder.java new file mode 100644 index 000000000..0f655540b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/ExtraFieldCommonModelBuilder.java @@ -0,0 +1,41 @@ +package org.opencdmp.model.builder.commonmodels.dmpblueprint; + +import eu.eudat.commonmodels.enums.DmpBlueprintExtraFieldDataType; +import eu.eudat.commonmodels.models.dmpblueprint.ExtraFieldModel; +import org.opencdmp.commons.types.dmpblueprint.ExtraFieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.dmpblueprintdefinition.ExtraField; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ExtraFieldCommonModelBuilder extends FieldCommonModelBuilder { + + @Autowired + public ExtraFieldCommonModelBuilder( + ConventionService conventionService) { + super(conventionService); + } + + protected ExtraFieldModel getInstance() { + return new ExtraFieldModel(); + } + + protected ExtraFieldModel buildChild(ExtraFieldEntity data, ExtraFieldModel model) { + switch (data.getType()){ + case Date -> model.setDataType(DmpBlueprintExtraFieldDataType.Date); + case Number -> model.setDataType(DmpBlueprintExtraFieldDataType.Number); + case RichTex -> model.setDataType(DmpBlueprintExtraFieldDataType.RichTex); + case Text -> model.setDataType(DmpBlueprintExtraFieldDataType.Text); + default -> throw new MyApplicationException("unrecognized type " + data.getType()); + } + return model; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/FieldCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/FieldCommonModelBuilder.java new file mode 100644 index 000000000..d8e6dab5b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/FieldCommonModelBuilder.java @@ -0,0 +1,77 @@ +package org.opencdmp.model.builder.commonmodels.dmpblueprint; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.enums.DmpBlueprintFieldCategory; +import eu.eudat.commonmodels.models.dmpblueprint.FieldModel; +import org.opencdmp.commons.types.dmpblueprint.FieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.commonmodels.dmp.DmpBlueprintValueCommonModelBuilder; +import org.opencdmp.model.dmpblueprintdefinition.Field; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component("dmpblueprint.FieldCommonModelBuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public abstract class FieldCommonModelBuilder extends BaseCommonModelBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public FieldCommonModelBuilder( + ConventionService conventionService + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldCommonModelBuilder.class))); + } + + public FieldCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + protected abstract Model getInstance(); + + protected abstract Model buildChild(Entity data, Model model); + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (Entity d : data) { + Model m = this.getInstance(); + m.setId(d.getId()); + m.setDescription(d.getDescription()); + switch (d.getCategory()){ + case System -> m.setCategory(DmpBlueprintFieldCategory.System); + case Extra -> m.setCategory(DmpBlueprintFieldCategory.Extra); + case ReferenceType -> m.setCategory(DmpBlueprintFieldCategory.ReferenceType); + default -> throw new MyApplicationException("unrecognized type " + d.getCategory()); + } + m.setPlaceholder(d.getPlaceholder()); + m.setDescription(d.getDescription()); + m.setSemantics(d.getSemantics()); + m.setRequired(d.isRequired()); + m.setLabel(d.getLabel()); + m.setOrdinal(d.getOrdinal()); + this.buildChild(d, m); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/ReferenceTypeFieldCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/ReferenceTypeFieldCommonModelBuilder.java new file mode 100644 index 000000000..c85820e8a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/ReferenceTypeFieldCommonModelBuilder.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.builder.commonmodels.dmpblueprint; + +import eu.eudat.commonmodels.models.dmpblueprint.ReferenceTypeFieldModel; +import org.opencdmp.commons.types.dmpblueprint.ReferenceTypeFieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.ReferenceTypeCommonModelBuilder; +import org.opencdmp.model.dmpblueprintdefinition.ReferenceTypeField; +import org.opencdmp.query.ReferenceTypeQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeFieldCommonModelBuilder extends FieldCommonModelBuilder { + private final QueryFactory queryFactory; + private final BuilderFactory builderFactory; + @Autowired + public ReferenceTypeFieldCommonModelBuilder( + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory) { + super(conventionService); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + protected ReferenceTypeFieldModel getInstance() { + return new ReferenceTypeFieldModel(); + } + + protected ReferenceTypeFieldModel buildChild(ReferenceTypeFieldEntity data, ReferenceTypeFieldModel model) { + if (data.getReferenceTypeId() != null ) model.setReferenceType(this.builderFactory.builder(ReferenceTypeCommonModelBuilder.class).build(this.queryFactory.query(ReferenceTypeQuery.class).ids(data.getReferenceTypeId()).first())); //TODO: Optimize + model.setMultipleSelect(data.getMultipleSelect()); + + return model; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/SectionCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/SectionCommonModelBuilder.java new file mode 100644 index 000000000..52922a726 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/SectionCommonModelBuilder.java @@ -0,0 +1,76 @@ +package org.opencdmp.model.builder.commonmodels.dmpblueprint; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.dmpblueprint.SectionModel; +import org.opencdmp.commons.enums.DmpBlueprintFieldCategory; +import org.opencdmp.commons.types.dmpblueprint.ExtraFieldEntity; +import org.opencdmp.commons.types.dmpblueprint.ReferenceTypeFieldEntity; +import org.opencdmp.commons.types.dmpblueprint.SectionEntity; +import org.opencdmp.commons.types.dmpblueprint.SystemFieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component("dmpblueprint.SectionCommonModelBuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SectionCommonModelBuilder extends BaseCommonModelBuilder { + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + @Autowired + public SectionCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory + ) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(SectionCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public SectionCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (SectionEntity d : data) { + SectionModel m = new SectionModel(); + m.setId(d.getId()); + m.setDescription(d.getDescription()); + m.setLabel(d.getLabel()); + m.setOrdinal(d.getOrdinal()); + m.setHasTemplates(d.getHasTemplates()); + + if ( d.getFields() != null) { + m.setFields(new ArrayList<>()); + List systemFieldEntities = d.getFields().stream().filter(x-> DmpBlueprintFieldCategory.System.equals(x.getCategory())).map(x-> (SystemFieldEntity)x).toList(); + m.getFields().addAll(this.builderFactory.builder(SystemFieldCommonModelBuilder.class).authorize(this.authorize).build(systemFieldEntities)); + List extraFieldEntities = d.getFields().stream().filter(x-> DmpBlueprintFieldCategory.Extra.equals(x.getCategory())).map(x-> (ExtraFieldEntity)x).toList(); + m.getFields().addAll(this.builderFactory.builder(ExtraFieldCommonModelBuilder.class).authorize(this.authorize).build(extraFieldEntities)); + List referenceFieldEntities = d.getFields().stream().filter(x-> DmpBlueprintFieldCategory.ReferenceType.equals(x.getCategory())).map(x-> (ReferenceTypeFieldEntity)x).toList(); + m.getFields().addAll(this.builderFactory.builder(ReferenceTypeFieldCommonModelBuilder.class).authorize(this.authorize).build(referenceFieldEntities)); + } + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/SystemFieldCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/SystemFieldCommonModelBuilder.java new file mode 100644 index 000000000..16bc763a1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpblueprint/SystemFieldCommonModelBuilder.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.builder.commonmodels.dmpblueprint; + +import eu.eudat.commonmodels.enums.DmpBlueprintSystemFieldType; +import eu.eudat.commonmodels.models.dmpblueprint.SystemFieldModel; +import org.opencdmp.commons.types.dmpblueprint.SystemFieldEntity; +import org.opencdmp.convention.ConventionService; +import gr.cite.tools.exception.MyApplicationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SystemFieldCommonModelBuilder extends FieldCommonModelBuilder { + + @Autowired + public SystemFieldCommonModelBuilder( + ConventionService conventionService) { + super(conventionService); + } + + protected SystemFieldModel getInstance() { + return new SystemFieldModel(); + } + + protected SystemFieldModel buildChild(SystemFieldEntity data, SystemFieldModel model) { + switch (data.getType()){ + case AccessRights -> model.setSystemFieldType(DmpBlueprintSystemFieldType.AccessRights); + case Contact -> model.setSystemFieldType(DmpBlueprintSystemFieldType.Contact); + case Description -> model.setSystemFieldType(DmpBlueprintSystemFieldType.Description); + case Language -> model.setSystemFieldType(DmpBlueprintSystemFieldType.Language); + case Title -> model.setSystemFieldType(DmpBlueprintSystemFieldType.Title); + case User -> model.setSystemFieldType(DmpBlueprintSystemFieldType.User); + default -> throw new MyApplicationException("unrecognized type " + data.getType()); + } + return model; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpreference/DmpReferenceCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpreference/DmpReferenceCommonModelBuilder.java new file mode 100644 index 000000000..dea5779d3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpreference/DmpReferenceCommonModelBuilder.java @@ -0,0 +1,86 @@ +package org.opencdmp.model.builder.commonmodels.dmpreference; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.dmpreference.DmpReferenceModel; +import eu.eudat.commonmodels.models.reference.ReferenceModel; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.types.dmpreference.DmpReferenceDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.DmpReferenceEntity; +import org.opencdmp.data.ReferenceEntity; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.commonmodels.reference.ReferenceCommonModelBuilder; +import org.opencdmp.query.ReferenceQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpReferenceCommonModelBuilder extends BaseCommonModelBuilder { + + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private final JsonHandlingService jsonHandlingService; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpReferenceCommonModelBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory, JsonHandlingService jsonHandlingService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpReferenceCommonModelBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.jsonHandlingService = jsonHandlingService; + } + + public DmpReferenceCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + Map referenceModelMap = this.collectReferences(data); + List> models = new ArrayList<>(); + for (DmpReferenceEntity d : data) { + DmpReferenceModel m = new DmpReferenceModel(); + m.setId(d.getId()); + if (d.getData() != null){ + DmpReferenceDataEntity definition = this.jsonHandlingService.fromJsonSafe(DmpReferenceDataEntity.class, d.getData()); + m.setData(this.builderFactory.builder(DmpReferenceDataCommonModelBuilder.class).authorize(this.authorize).build(definition)); + } + if (referenceModelMap != null && d.getReferenceId() != null && referenceModelMap.containsKey(d.getReferenceId())) m.setReference(referenceModelMap.get(d.getReferenceId())); + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + + private Map collectReferences(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", ReferenceModel.class.getSimpleName()); + + Map itemMap; + ReferenceQuery q = this.queryFactory.query(ReferenceQuery.class).authorize(this.authorize).ids(data.stream().map(DmpReferenceEntity::getReferenceId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(ReferenceCommonModelBuilder.class).authorize(this.authorize).asForeignKey(q, ReferenceEntity::getId); + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpreference/DmpReferenceDataCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpreference/DmpReferenceDataCommonModelBuilder.java new file mode 100644 index 000000000..1a8c52f16 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/dmpreference/DmpReferenceDataCommonModelBuilder.java @@ -0,0 +1,56 @@ +package org.opencdmp.model.builder.commonmodels.dmpreference; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.dmpreference.DmpReferenceDataModel; +import org.opencdmp.commons.types.dmpreference.DmpReferenceDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpReferenceDataCommonModelBuilder extends BaseCommonModelBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpReferenceDataCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpReferenceDataCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public DmpReferenceDataCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (DmpReferenceDataEntity d : data) { + DmpReferenceDataModel m = new DmpReferenceDataModel(); + m.setBlueprintFieldId(d.getBlueprintFieldId()); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/reference/ReferenceCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/reference/ReferenceCommonModelBuilder.java new file mode 100644 index 000000000..5882e48ed --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/reference/ReferenceCommonModelBuilder.java @@ -0,0 +1,97 @@ +package org.opencdmp.model.builder.commonmodels.reference; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.enums.ReferenceSourceType; +import eu.eudat.commonmodels.models.reference.ReferenceModel; +import eu.eudat.commonmodels.models.reference.ReferenceTypeModel; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.types.reference.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.ReferenceTypeEntity; +import org.opencdmp.data.ReferenceEntity; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import org.opencdmp.model.builder.commonmodels.ReferenceTypeCommonModelBuilder; +import org.opencdmp.query.ReferenceTypeQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceCommonModelBuilder extends BaseCommonModelBuilder { + + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private final XmlHandlingService xmlHandlingService; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ReferenceCommonModelBuilder( + ConventionService conventionService, + BuilderFactory builderFactory, QueryFactory queryFactory, XmlHandlingService xmlHandlingService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceCommonModelBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + this.xmlHandlingService = xmlHandlingService; + } + + public ReferenceCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + Map typeMap = this.collectReferenceTypes(data); + List> models = new ArrayList<>(); + for (ReferenceEntity d : data) { + ReferenceModel m = new ReferenceModel(); + m.setId(d.getId()); + m.setLabel(d.getLabel()); + if (d.getDefinition() != null){ + DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(DefinitionEntity.class, d.getDefinition()); + m.setDefinition(this.builderFactory.builder(ReferenceDefinitionCommonModelBuilder.class).authorize(this.authorize).build(definition)); + } + m.setReference(d.getReference()); + m.setAbbreviation(d.getAbbreviation()); + m.setDescription(d.getDescription()); + m.setSource(d.getSource()); + switch (d.getSourceType()){ + case Internal -> m.setSourceType(ReferenceSourceType.Internal); + case External -> m.setSourceType(ReferenceSourceType.External); + default -> throw new MyApplicationException("unrecognized type " + d.getSourceType().getValue()); + } + if (typeMap != null && d.getTypeId() != null && typeMap.containsKey(d.getTypeId())) m.setType(typeMap.get(d.getTypeId())); + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + + private Map collectReferenceTypes(List data) throws MyApplicationException { + if (data.isEmpty()) + return null; + this.logger.debug("checking related - {}", ReferenceTypeModel.class.getSimpleName()); + + Map itemMap; + ReferenceTypeQuery q = this.queryFactory.query(ReferenceTypeQuery.class).authorize(this.authorize).ids(data.stream().map(ReferenceEntity::getTypeId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(ReferenceTypeCommonModelBuilder.class).authorize(this.authorize).asForeignKey(q, ReferenceTypeEntity::getId); + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/reference/ReferenceDefinitionCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/reference/ReferenceDefinitionCommonModelBuilder.java new file mode 100644 index 000000000..2784d9e1c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/reference/ReferenceDefinitionCommonModelBuilder.java @@ -0,0 +1,53 @@ +package org.opencdmp.model.builder.commonmodels.reference; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.reference.ReferenceDefinitionModel; +import org.opencdmp.commons.types.reference.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceDefinitionCommonModelBuilder extends BaseCommonModelBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ReferenceDefinitionCommonModelBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceDefinitionCommonModelBuilder.class))); + this.builderFactory = builderFactory; + } + + public ReferenceDefinitionCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (DefinitionEntity d : data) { + ReferenceDefinitionModel m = new ReferenceDefinitionModel(); + if (d.getFields() != null) m.setFields(this.builderFactory.builder(ReferenceFieldCommonModelBuilder.class).authorize(this.authorize).build(d.getFields())); + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/reference/ReferenceFieldCommonModelBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/reference/ReferenceFieldCommonModelBuilder.java new file mode 100644 index 000000000..5128de187 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/commonmodels/reference/ReferenceFieldCommonModelBuilder.java @@ -0,0 +1,55 @@ +package org.opencdmp.model.builder.commonmodels.reference; + +import org.opencdmp.authorization.AuthorizationFlags; +import eu.eudat.commonmodels.models.reference.ReferenceFieldModel; +import org.opencdmp.commons.types.reference.FieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.commonmodels.BaseCommonModelBuilder; +import org.opencdmp.model.builder.commonmodels.CommonModelBuilderItemResponse; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceFieldCommonModelBuilder extends BaseCommonModelBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ReferenceFieldCommonModelBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceFieldCommonModelBuilder.class))); + } + + public ReferenceFieldCommonModelBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + protected List> buildInternal(List data) throws MyApplicationException { + this.logger.debug("building for {}", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) return new ArrayList<>(); + + List> models = new ArrayList<>(); + for (FieldEntity d : data) { + ReferenceFieldModel m = new ReferenceFieldModel(); + m.setCode(d.getCode()); + m.setValue(d.getValue()); + + models.add(new CommonModelBuilderItemResponse<>(m, d)); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/deposit/DepositSourceBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/deposit/DepositSourceBuilder.java new file mode 100644 index 000000000..8988cf295 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/deposit/DepositSourceBuilder.java @@ -0,0 +1,81 @@ +package org.opencdmp.model.builder.deposit; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.deposit.DepositSourceEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.deposit.DepositSource; +import org.opencdmp.service.encryption.EncryptionService; +import org.opencdmp.service.tenant.TenantProperties; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DepositSourceBuilder extends BaseBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private boolean encrypted; + private final EncryptionService encryptionService; + private final TenantProperties tenantProperties; + + @Autowired + public DepositSourceBuilder( + ConventionService conventionService, EncryptionService encryptionService, TenantProperties tenantProperties) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DepositSourceBuilder.class))); + this.encryptionService = encryptionService; + this.tenantProperties = tenantProperties; + } + + public DepositSourceBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + public DepositSourceBuilder encrypted(boolean encrypted) { + this.encrypted = encrypted; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (DepositSourceEntity d : data) { + DepositSource m = new DepositSource(); + if (fields.hasField(this.asIndexer(DepositSource._repositoryId))) m.setRepositoryId(d.getRepositoryId()); + if (fields.hasField(this.asIndexer(DepositSource._url))) m.setUrl(d.getUrl()); + if (fields.hasField(this.asIndexer(DepositSource._issuerUrl))) m.setIssuerUrl(d.getIssuerUrl()); + if (fields.hasField(this.asIndexer(DepositSource._clientId))) m.setClientId(d.getClientId()); + if (fields.hasField(this.asIndexer(DepositSource._clientSecret))) { + if (encrypted) { + try { + if (!this.conventionService.isNullOrEmpty(d.getClientSecret())) m.setClientSecret(this.encryptionService.decryptAES(d.getClientSecret(), tenantProperties.getConfigEncryptionAesKey(), tenantProperties.getConfigEncryptionAesIv())); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + m.setClientSecret(d.getClientSecret()); + } + } + if (fields.hasField(this.asIndexer(DepositSource._scope))) m.setScope(d.getScope()); + if (fields.hasField(this.asIndexer(DepositSource._pdfTransformerId))) m.setPdfTransformerId(d.getPdfTransformerId()); + if (fields.hasField(this.asIndexer(DepositSource._rdaTransformerId))) m.setRdaTransformerId(d.getRdaTransformerId()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/ExternalIdentifierBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/ExternalIdentifierBuilder.java new file mode 100644 index 000000000..4eda026ed --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/ExternalIdentifierBuilder.java @@ -0,0 +1,60 @@ +package org.opencdmp.model.builder.descriptionpropertiesdefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.description.ExternalIdentifierEntity; +import org.opencdmp.commons.types.description.FieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptionproperties.ExternalIdentifier; +import org.opencdmp.model.descriptionproperties.Field; +import org.opencdmp.service.fielddatahelper.FieldDataHelperServiceProvider; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("description.ExternalIdentifierBuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ExternalIdentifierBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ExternalIdentifierBuilder( + ConventionService conventionService, BuilderFactory builderFactory, FieldDataHelperServiceProvider fieldDataHelperServiceProvider) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ExternalIdentifierBuilder.class))); + } + + public ExternalIdentifierBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + + List models = new ArrayList<>(); + for (ExternalIdentifierEntity d : data) { + ExternalIdentifier m = new ExternalIdentifier(); + if (fields.hasField(this.asIndexer(ExternalIdentifier._identifier))) m.setIdentifier(d.getIdentifier()); + if (fields.hasField(this.asIndexer(ExternalIdentifier._type))) m.setType(d.getType()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/FieldBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/FieldBuilder.java new file mode 100644 index 000000000..d9f12bafe --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/FieldBuilder.java @@ -0,0 +1,142 @@ +package org.opencdmp.model.builder.descriptionpropertiesdefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.FieldType; +import org.opencdmp.commons.types.description.FieldEntity; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.LabelAndMultiplicityDataEntity; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.SelectDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Reference; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.builder.ReferenceBuilder; +import org.opencdmp.model.descriptionproperties.Field; +import org.opencdmp.query.ReferenceQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component("description.FieldBuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldBuilder extends BaseBuilder { + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + private org.opencdmp.commons.types.descriptiontemplate.FieldEntity fieldEntity; + + @Autowired + public FieldBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public FieldBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + public FieldBuilder withFieldEntity(org.opencdmp.commons.types.descriptiontemplate.FieldEntity fieldEntity) { + this.fieldEntity = fieldEntity; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + FieldSet externalIdentifierFields = fields.extractPrefixed(this.asPrefix(Field._externalIdentifier)); + + FieldType fieldType = this.fieldEntity != null && this.fieldEntity.getData() != null ? this.fieldEntity.getData().getFieldType() : FieldType.FREE_TEXT; + + FieldSet referenceFields = fields.extractPrefixed(this.asPrefix(Field._references)); + Map referenceItemsMap = FieldType.isReferenceType(fieldType) ? this.collectReferences(referenceFields, data) : null; + + List models = new ArrayList<>(); + for (FieldEntity d : data) { + Field m = new Field(); + if (fields.hasField(this.asIndexer(Field._dateValue)) && FieldType.isDateType(fieldType)) m.setDateValue(d.getDateValue()); + if (fields.hasField(this.asIndexer(Field._textValue)) && FieldType.isTextType(fieldType)) m.setTextValue(d.getTextValue()); + if (fields.hasField(this.asIndexer(Field._textListValue)) && FieldType.isTextListType(fieldType)) { + boolean isMultiSelect = true; + if(this.fieldEntity != null && this.fieldEntity.getData() != null && (this.fieldEntity.getData().getFieldType().equals(FieldType.SELECT) || this.fieldEntity.getData().getFieldType().equals(FieldType.INTERNAL_ENTRIES_DMPS) || this.fieldEntity.getData().getFieldType().equals(FieldType.INTERNAL_ENTRIES_DESCRIPTIONS))){ + if (this.fieldEntity.getData() instanceof SelectDataEntity) isMultiSelect = ((SelectDataEntity) this.fieldEntity.getData()).getMultipleSelect(); + else if (this.fieldEntity.getData() instanceof LabelAndMultiplicityDataEntity) isMultiSelect = ((LabelAndMultiplicityDataEntity) this.fieldEntity.getData()).getMultipleSelect(); + + if (!isMultiSelect && !this.conventionService.isListNullOrEmpty(d.getTextListValue())){ + m.setTextValue(d.getTextListValue().stream().findFirst().orElse(null)); + }else{ + m.setTextListValue(d.getTextListValue()); + } + } else{ + m.setTextListValue(d.getTextListValue()); + } + } + if (!referenceFields.isEmpty() && FieldType.isReferenceType(fieldType) && referenceItemsMap != null && d.getTextListValue() != null && !d.getTextListValue().isEmpty()) { + m.setReferences(new ArrayList<>()); + for (UUID referenceId : d.getTextListValue().stream().map(UUID::fromString).toList()){ + if (referenceItemsMap.containsKey(referenceId)) m.getReferences().add(referenceItemsMap.get(referenceId)); + } + } + if (!externalIdentifierFields.isEmpty() && d.getExternalIdentifier() != null && FieldType.isExternalIdentifierType(fieldType)) m.setExternalIdentifier(this.builderFactory.builder(ExternalIdentifierBuilder.class).authorize(this.authorize).build(externalIdentifierFields, d.getExternalIdentifier())); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectReferences(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Reference.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Reference._id))) { + itemMap = this.asEmpty( + data.stream().map(FieldEntity::getTextListValue).flatMap(List::stream).map(UUID::fromString).distinct().collect(Collectors.toList()), + x -> { + Reference item = new Reference(); + item.setId(x); + return item; + }, + Reference::getId); + } else { + List ids = new ArrayList<>(); + for (FieldEntity field: data) { + if (field.getTextListValue() != null) { + for (String value: field.getTextListValue()) { + if (value != null && !ids.contains(value)) ids.add(UUID.fromString(value)); + } + } + } + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Reference._id); + ReferenceQuery q = this.queryFactory.query(ReferenceQuery.class).authorize(this.authorize).ids(ids); + itemMap = this.builderFactory.builder(ReferenceBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Reference::getId);; + } + + if (!fields.hasField(Reference._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/PropertyDefinitionBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/PropertyDefinitionBuilder.java new file mode 100644 index 000000000..0df623c70 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/PropertyDefinitionBuilder.java @@ -0,0 +1,75 @@ +package org.opencdmp.model.builder.descriptionpropertiesdefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.description.PropertyDefinitionEntity; +import org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity; +import org.opencdmp.commons.types.descriptiontemplate.FieldSetEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.Definition; +import org.opencdmp.model.persist.descriptionproperties.PropertyDefinitionPersist; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; +import org.opencdmp.model.descriptionproperties.PropertyDefinition; + +import java.util.*; + +@Component("descriptionpropertiesdefinitionbuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PropertyDefinitionBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private DefinitionEntity definition; + + @Autowired + public PropertyDefinitionBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PropertyDefinitionBuilder.class))); + this.builderFactory = builderFactory; + } + + public PropertyDefinitionBuilder withDefinition(DefinitionEntity definition) { + this.definition = definition; + return this; + } + + public PropertyDefinitionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + FieldSet fieldsFields = fields.extractPrefixed(this.asPrefix(PropertyDefinition._fieldSets)); + + List models = new ArrayList<>(); + for (PropertyDefinitionEntity d : data) { + PropertyDefinition m = new PropertyDefinition(); + if (!fieldsFields.isEmpty() && d.getFieldSets() != null && !d.getFieldSets().isEmpty()) { + m.setFieldSets(new HashMap<>()); + for (String key : d.getFieldSets().keySet()){ + FieldSetEntity fieldSetEntity = definition != null ? definition.getFieldSetById(key).stream().findFirst().orElse(null) : null; + m.getFieldSets().put(key, this.builderFactory.builder(PropertyDefinitionFieldSetBuilder.class).authorize(this.authorize).withFieldSetEntity(fieldSetEntity).build(fieldsFields, d.getFieldSets().get(key))); + } + } + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/PropertyDefinitionFieldSetBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/PropertyDefinitionFieldSetBuilder.java new file mode 100644 index 000000000..975dfbcc0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/PropertyDefinitionFieldSetBuilder.java @@ -0,0 +1,67 @@ +package org.opencdmp.model.builder.descriptionpropertiesdefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.description.PropertyDefinitionFieldSetEntity; +import org.opencdmp.commons.types.descriptiontemplate.FieldSetEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptionproperties.PropertyDefinitionFieldSet; +import org.opencdmp.model.persist.descriptionproperties.PropertyDefinitionFieldSetPersist; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("description.PropertyDefinitionFieldSet") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PropertyDefinitionFieldSetBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private FieldSetEntity fieldSetEntity; + + @Autowired + public PropertyDefinitionFieldSetBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PropertyDefinitionFieldSetBuilder.class))); + this.builderFactory = builderFactory; + } + + public PropertyDefinitionFieldSetBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + public PropertyDefinitionFieldSetBuilder withFieldSetEntity(FieldSetEntity fieldSetEntity) { + this.fieldSetEntity = fieldSetEntity; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + FieldSet itemsFields = fields.extractPrefixed(this.asPrefix(PropertyDefinitionFieldSet._items)); + + List models = new ArrayList<>(); + for (PropertyDefinitionFieldSetEntity d : data) { + PropertyDefinitionFieldSet m = new PropertyDefinitionFieldSet(); + if (!itemsFields.isEmpty() && d.getItems() != null) m.setItems(this.builderFactory.builder(PropertyDefinitionFieldSetItemBuilder.class).withFieldSetEntity(this.fieldSetEntity).authorize(this.authorize).build(itemsFields, d.getItems())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/PropertyDefinitionFieldSetItemBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/PropertyDefinitionFieldSetItemBuilder.java new file mode 100644 index 000000000..b59f1716b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionpropertiesdefinition/PropertyDefinitionFieldSetItemBuilder.java @@ -0,0 +1,79 @@ +package org.opencdmp.model.builder.descriptionpropertiesdefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.description.PropertyDefinitionEntity; +import org.opencdmp.commons.types.description.PropertyDefinitionFieldSetItemEntity; +import org.opencdmp.commons.types.descriptiontemplate.FieldEntity; +import org.opencdmp.commons.types.descriptiontemplate.FieldSetEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DescriptionTemplate; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptionproperties.PropertyDefinition; +import org.opencdmp.model.descriptionproperties.PropertyDefinitionFieldSetItem; +import org.opencdmp.model.persist.descriptionproperties.PropertyDefinitionFieldSetItemPersist; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("description.PropertyDefinitionFieldSetItemBuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PropertyDefinitionFieldSetItemBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private FieldSetEntity fieldSetEntity; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PropertyDefinitionFieldSetItemBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PropertyDefinitionFieldSetItemBuilder.class))); + this.builderFactory = builderFactory; + } + + public PropertyDefinitionFieldSetItemBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + public PropertyDefinitionFieldSetItemBuilder withFieldSetEntity(FieldSetEntity fieldSetEntity) { + this.fieldSetEntity = fieldSetEntity; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + FieldSet fieldsFields = fields.extractPrefixed(this.asPrefix(PropertyDefinitionFieldSetItem._fields)); + + List models = new ArrayList<>(); + for (PropertyDefinitionFieldSetItemEntity d : data) { + PropertyDefinitionFieldSetItem m = new PropertyDefinitionFieldSetItem(); + if (fields.hasField(this.asIndexer(PropertyDefinitionFieldSetItem._comment))) m.setComment(d.getComment()); + if (fields.hasField(this.asIndexer(PropertyDefinitionFieldSetItem._ordinal))) m.setOrdinal(d.getOrdinal()); + if (!fieldsFields.isEmpty() && d.getFields() != null && !d.getFields().isEmpty()) { + m.setFields(new HashMap<>()); + for (String key : d.getFields().keySet()){ + FieldEntity fieldEntity = fieldSetEntity != null ? fieldSetEntity.getFieldById(key).stream().findFirst().orElse(null) : null; + m.getFields().put(key, this.builderFactory.builder(FieldBuilder.class).authorize(this.authorize).withFieldEntity(fieldEntity).build(fieldsFields, d.getFields().get(key))); + } + } + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptionreference/DescriptionReferenceDataBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionreference/DescriptionReferenceDataBuilder.java new file mode 100644 index 000000000..8a4deb1ac --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptionreference/DescriptionReferenceDataBuilder.java @@ -0,0 +1,55 @@ +package org.opencdmp.model.builder.descriptionreference; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptionreference.DescriptionReferenceDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptionreference.DescriptionReferenceData; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("referencedescriptionreferencedatabuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionReferenceDataBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DescriptionReferenceDataBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionReferenceDataBuilder.class))); + } + + public DescriptionReferenceDataBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + + List models = new ArrayList<>(); + for (DescriptionReferenceDataEntity d : data) { + DescriptionReferenceData m = new DescriptionReferenceData(); + if (fields.hasField(this.asIndexer(DescriptionReferenceData._fieldId))) m.setFieldId(d.getFieldId()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/DefinitionBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/DefinitionBuilder.java new file mode 100644 index 000000000..60bced0b0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/DefinitionBuilder.java @@ -0,0 +1,59 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptiontemplate.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.Definition; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("descriptiontemplatedefinitionbuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DefinitionBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DefinitionBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DefinitionBuilder.class))); + this.builderFactory = builderFactory; + } + + public DefinitionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + FieldSet pagesFields = fields.extractPrefixed(this.asPrefix(Definition._pages)); + + List models = new ArrayList<>(); + for (DefinitionEntity d : data) { + Definition m = new Definition(); + if (!pagesFields.isEmpty() && d.getPages() != null) m.setPages(this.builderFactory.builder(PageBuilder.class).authorize(this.authorize).build(pagesFields, d.getPages())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/ExternalIdentifierBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/ExternalIdentifierBuilder.java new file mode 100644 index 000000000..22440a434 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/ExternalIdentifierBuilder.java @@ -0,0 +1,58 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptiontemplate.ExternalIdentifierEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.ExternalIdentifier; +import org.opencdmp.service.fielddatahelper.FieldDataHelperServiceProvider; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("descriptiontemplatedefinition.ExternalIdentifierBuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ExternalIdentifierBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ExternalIdentifierBuilder( + ConventionService conventionService, BuilderFactory builderFactory, FieldDataHelperServiceProvider fieldDataHelperServiceProvider) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ExternalIdentifierBuilder.class))); + } + + public ExternalIdentifierBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + + List models = new ArrayList<>(); + for (ExternalIdentifierEntity d : data) { + ExternalIdentifier m = new ExternalIdentifier(); + if (fields.hasField(this.asIndexer(ExternalIdentifier._identifier))) m.setIdentifier(d.getIdentifier()); + if (fields.hasField(this.asIndexer(ExternalIdentifier._type))) m.setType(d.getType()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/FieldBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/FieldBuilder.java new file mode 100644 index 000000000..5172fe298 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/FieldBuilder.java @@ -0,0 +1,77 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptiontemplate.FieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.service.fielddatahelper.FieldDataHelperService; +import org.opencdmp.service.fielddatahelper.FieldDataHelperServiceProvider; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; +import org.opencdmp.model.descriptiontemplatedefinition.Field; +import java.util.*; + +@Component("descriptiontemplatedefinitionfieldbuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private final FieldDataHelperServiceProvider fieldDataHelperServiceProvider; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public FieldBuilder( + ConventionService conventionService, BuilderFactory builderFactory, FieldDataHelperServiceProvider fieldDataHelperServiceProvider) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldBuilder.class))); + this.builderFactory = builderFactory; + this.fieldDataHelperServiceProvider = fieldDataHelperServiceProvider; + } + + public FieldBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + FieldSet visibilityRulesFields = fields.extractPrefixed(this.asPrefix(Field._visibilityRules)); + FieldSet dataFields = fields.extractPrefixed(this.asPrefix(Field._data)); + + List models = new ArrayList<>(); + for (FieldEntity d : data) { + Field m = new Field(); + if (fields.hasField(this.asIndexer(Field._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(Field._ordinal))) m.setOrdinal(d.getOrdinal()); + if (fields.hasField(this.asIndexer(Field._numbering))) m.setNumbering(d.getNumbering()); + if (fields.hasField(this.asIndexer(Field._schematics))) m.setSchematics(d.getSchematics()); + if (fields.hasField(this.asIndexer(Field._defaultValue))) m.setDefaultValue(d.getDefaultValue()); + if (fields.hasField(this.asIndexer(Field._includeInExport))) m.setIncludeInExport(d.getIncludeInExport()); + if (fields.hasField(this.asIndexer(Field._validations))) m.setValidations(d.getValidations()); + if (fields.hasField(this.asIndexer(Field._numbering))) m.setNumbering(d.getNumbering()); + if (fields.hasField(this.asIndexer(Field._numbering))) m.setNumbering(d.getNumbering()); + if (!visibilityRulesFields.isEmpty() && d.getVisibilityRules() != null) m.setVisibilityRules(this.builderFactory.builder(RuleBuilder.class).withFieldEntity(d).authorize(this.authorize).build(visibilityRulesFields, d.getVisibilityRules())); + if (!dataFields.isEmpty() && d.getData() != null){ + FieldDataHelperService fieldDataHelperService = this.fieldDataHelperServiceProvider.get(d.getData().getFieldType()); + m.setData(fieldDataHelperService.buildOne(dataFields, d.getData(), this.authorize)); + } + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/FieldSetBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/FieldSetBuilder.java new file mode 100644 index 000000000..a153e5cf1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/FieldSetBuilder.java @@ -0,0 +1,68 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptiontemplate.FieldSetEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.Field; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldSetBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public FieldSetBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldSetBuilder.class))); + this.builderFactory = builderFactory; + } + + public FieldSetBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + FieldSet fieldsFields = fields.extractPrefixed(this.asPrefix(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._fields)); + FieldSet multiplicityFields = fields.extractPrefixed(this.asPrefix(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._multiplicity)); + + List models = new ArrayList<>(); + for (FieldSetEntity d : data) { + org.opencdmp.model.descriptiontemplatedefinition.FieldSet m = new org.opencdmp.model.descriptiontemplatedefinition.FieldSet(); + if (fields.hasField(this.asIndexer(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._ordinal))) m.setOrdinal(d.getOrdinal()); + if (fields.hasField(this.asIndexer(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._title))) m.setTitle(d.getTitle()); + if (fields.hasField(this.asIndexer(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._numbering))) m.setNumbering(d.getNumbering()); + if (fields.hasField(this.asIndexer(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._description))) m.setDescription(d.getDescription()); + if (fields.hasField(this.asIndexer(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._extendedDescription))) m.setExtendedDescription(d.getExtendedDescription()); + if (fields.hasField(this.asIndexer(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._additionalInformation))) m.setAdditionalInformation(d.getAdditionalInformation()); + if (fields.hasField(this.asIndexer(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._hasCommentField))) m.setHasCommentField(d.getHasCommentField()); + if (fields.hasField(this.asIndexer(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._hasMultiplicity))) m.setHasMultiplicity(d.getHasMultiplicity()); + if (!multiplicityFields.isEmpty() && d.getMultiplicity() != null) m.setMultiplicity(this.builderFactory.builder(MultiplicityBuilder.class).authorize(this.authorize).build(multiplicityFields, d.getMultiplicity())); + if (!fieldsFields.isEmpty() && d.getFields() != null) m.setFields(this.builderFactory.builder(FieldBuilder.class).authorize(this.authorize).build(fieldsFields, d.getFields())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/MultiplicityBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/MultiplicityBuilder.java new file mode 100644 index 000000000..bc7c8e251 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/MultiplicityBuilder.java @@ -0,0 +1,57 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptiontemplate.MultiplicityEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.Multiplicity; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("descriptiontemplatedefinitionmultiplicitybuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class MultiplicityBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public MultiplicityBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(MultiplicityBuilder.class))); + } + + public MultiplicityBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (MultiplicityEntity d : data) { + Multiplicity m = new Multiplicity(); + if (fields.hasField(this.asIndexer(Multiplicity._min))) m.setMin(d.getMin()); + if (fields.hasField(this.asIndexer(Multiplicity._max))) m.setMax(d.getMax()); + if (fields.hasField(this.asIndexer(Multiplicity._placeholder))) m.setPlaceholder(d.getPlaceholder()); + if (fields.hasField(this.asIndexer(Multiplicity._tableView))) m.setTableView(d.getTableView()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/PageBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/PageBuilder.java new file mode 100644 index 000000000..b08242320 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/PageBuilder.java @@ -0,0 +1,62 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptiontemplate.PageEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.Definition; +import org.opencdmp.model.descriptiontemplatedefinition.Page; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PageBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PageBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PageBuilder.class))); + this.builderFactory = builderFactory; + } + + public PageBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + FieldSet sectionsFields = fields.extractPrefixed(this.asPrefix(Page._sections)); + for (PageEntity d : data) { + Page m = new Page(); + if (fields.hasField(this.asIndexer(Page._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(Page._ordinal))) m.setOrdinal(d.getOrdinal()); + if (fields.hasField(this.asIndexer(Page._title))) m.setTitle(d.getTitle()); + if (!sectionsFields.isEmpty() && d.getSections() != null) m.setSections(this.builderFactory.builder(SectionBuilder.class).authorize(this.authorize).build(sectionsFields, d.getSections())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/RuleBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/RuleBuilder.java new file mode 100644 index 000000000..ddb465189 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/RuleBuilder.java @@ -0,0 +1,118 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.FieldType; +import org.opencdmp.commons.types.descriptiontemplate.RuleEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Reference; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.builder.ReferenceBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.Rule; +import org.opencdmp.query.ReferenceQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class RuleBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + private org.opencdmp.commons.types.descriptiontemplate.FieldEntity fieldEntity; + + @Autowired + public RuleBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(RuleBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public RuleBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + public RuleBuilder withFieldEntity(org.opencdmp.commons.types.descriptiontemplate.FieldEntity fieldEntity) { + this.fieldEntity = fieldEntity; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + FieldType fieldType = this.fieldEntity != null && this.fieldEntity.getData() != null ? this.fieldEntity.getData().getFieldType() : FieldType.FREE_TEXT; + + FieldSet externalIdentifierFields = fields.extractPrefixed(this.asPrefix(Rule._externalIdentifier)); + FieldSet referenceFields = fields.extractPrefixed(this.asPrefix(Rule._references)); + Map referenceItemsMap = FieldType.isReferenceType(fieldType) ? this.collectReferences(referenceFields, data) : null; + + List models = new ArrayList<>(); + for (RuleEntity d : data) { + Rule m = new Rule(); + if (fields.hasField(this.asIndexer(Rule._target))) m.setTarget(d.getTarget()); + if (fields.hasField(this.asIndexer(Rule._dateValue)) && FieldType.isDateType(fieldType)) m.setDateValue(d.getDateValue()); + if (fields.hasField(this.asIndexer(Rule._textValue)) && FieldType.isTextType(fieldType)) m.setTextValue(d.getTextValue()); + if (fields.hasField(this.asIndexer(Rule._textListValue)) && FieldType.isTextListType(fieldType)) m.setTextListValue(d.getTextListValue()); + if (!referenceFields.isEmpty() && FieldType.isReferenceType(fieldType) && referenceItemsMap != null && d.getTextListValue() != null && !d.getTextListValue().isEmpty()) { + m.setReferences(new ArrayList<>()); + for (UUID referenceId : d.getTextListValue().stream().map(UUID::fromString).toList()){ + if (referenceItemsMap.containsKey(referenceId)) m.getReferences().add(referenceItemsMap.get(referenceId)); + } + } + if (!externalIdentifierFields.isEmpty() && d.getExternalIdentifier() != null && FieldType.isExternalIdentifierType(fieldType)) m.setExternalIdentifier(this.builderFactory.builder(ExternalIdentifierBuilder.class).authorize(this.authorize).build(externalIdentifierFields, d.getExternalIdentifier())); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectReferences(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", Reference.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(Reference._id))) { + itemMap = this.asEmpty( + data.stream().map(RuleEntity::getTextListValue).flatMap(List::stream).map(UUID::fromString).distinct().collect(Collectors.toList()), + x -> { + Reference item = new Reference(); + item.setId(x); + return item; + }, + Reference::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Reference._id); + ReferenceQuery q = this.queryFactory.query(ReferenceQuery.class).authorize(this.authorize).ids(data.stream().map(RuleEntity::getTextListValue).flatMap(List::stream).map(UUID::fromString).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(ReferenceBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Reference::getId); + } + if (!fields.hasField(Reference._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/SectionBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/SectionBuilder.java new file mode 100644 index 000000000..5c8cc4981 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/SectionBuilder.java @@ -0,0 +1,67 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptiontemplate.SectionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.Section; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("descriptiontemplatedefinitionsectionbuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SectionBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public SectionBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(SectionBuilder.class))); + this.builderFactory = builderFactory; + } + + public SectionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List
build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + FieldSet fieldSetsFields = fields.extractPrefixed(this.asPrefix(Section._fieldSets)); + + List
models = new ArrayList<>(); + for (SectionEntity d : data) { + Section m = new Section(); + if (fields.hasField(this.asIndexer(Section._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(Section._description))) m.setDescription(d.getDescription()); + if (fields.hasField(this.asIndexer(Section._ordinal))) m.setOrdinal(d.getOrdinal()); + if (fields.hasField(this.asIndexer(Section._defaultVisibility))) m.setDefaultVisibility(d.isDefaultVisibility()); + if (fields.hasField(this.asIndexer(Section._numbering))) m.setNumbering(d.getNumbering()); + if (fields.hasField(this.asIndexer(Section._title))) m.setTitle(d.getTitle()); + if (fields.hasField(this.asIndexer(Section._extendedDescription))) m.setExtendedDescription(d.getExtendedDescription()); + if (d.getSections() != null) m.setSections(this.builderFactory.builder(SectionBuilder.class).authorize(this.authorize).build(fields, d.getSections())); + if (!fieldSetsFields.isEmpty() && d.getFieldSets() != null) m.setFieldSets(this.builderFactory.builder(FieldSetBuilder.class).authorize(this.authorize).build(fieldSetsFields, d.getFieldSets())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/BaseFieldDataBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/BaseFieldDataBuilder.java new file mode 100644 index 000000000..d896d8817 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/BaseFieldDataBuilder.java @@ -0,0 +1,54 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition.fielddata; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.BaseFieldDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.fielddata.BaseFieldData; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.*; + +public abstract class BaseFieldDataBuilder extends BaseBuilder { + + protected EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public BaseFieldDataBuilder( + ConventionService conventionService, + LoggerService logger) { + super(conventionService, logger); + } + + public BaseFieldDataBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + protected abstract Model getInstance(); + + protected abstract void buildChild(FieldSet fields, Entity d, Model m); + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (Entity d : data) { + Model m = this.getInstance(); + if (fields.hasField(this.asIndexer(Model._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(Model._fieldType))) m.setFieldType(d.getFieldType()); + this.buildChild(fields, d, m); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/LabelAndMultiplicityDataBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/LabelAndMultiplicityDataBuilder.java new file mode 100644 index 000000000..98a0a2f7f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/LabelAndMultiplicityDataBuilder.java @@ -0,0 +1,30 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition.fielddata; + +import org.opencdmp.commons.types.descriptiontemplate.fielddata.LabelAndMultiplicityDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.descriptiontemplatedefinition.fielddata.LabelAndMultiplicityData; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LabelAndMultiplicityDataBuilder extends BaseFieldDataBuilder { + + @Autowired + public LabelAndMultiplicityDataBuilder(ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(LabelAndMultiplicityDataBuilder.class))); + } + + protected LabelAndMultiplicityData getInstance() { + return new LabelAndMultiplicityData(); + } + @Override + protected void buildChild(FieldSet fields, LabelAndMultiplicityDataEntity d, LabelAndMultiplicityData m) { + if (fields.hasField(this.asIndexer(LabelAndMultiplicityData._multipleSelect))) m.setMultipleSelect(d.getMultipleSelect()); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/LabelDataBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/LabelDataBuilder.java new file mode 100644 index 000000000..9d6da2925 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/LabelDataBuilder.java @@ -0,0 +1,30 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition.fielddata; + +import org.opencdmp.commons.types.descriptiontemplate.fielddata.LabelDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.descriptiontemplatedefinition.fielddata.LabelData; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LabelDataBuilder extends BaseFieldDataBuilder { + + @Autowired + public LabelDataBuilder(ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(LabelDataBuilder.class))); + } + + protected LabelData getInstance() { + return new LabelData(); + } + + @Override + protected void buildChild(FieldSet fields, LabelDataEntity d, LabelData model) { + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/RadioBoxDataBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/RadioBoxDataBuilder.java new file mode 100644 index 000000000..541fc6f6e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/RadioBoxDataBuilder.java @@ -0,0 +1,76 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition.fielddata; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.RadioBoxDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.fielddata.RadioBoxData; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class RadioBoxDataBuilder extends BaseFieldDataBuilder { + private final BuilderFactory builderFactory; + + @Autowired + public RadioBoxDataBuilder(ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(RadioBoxDataBuilder.class))); + this.builderFactory = builderFactory; + } + + protected RadioBoxData getInstance() { + return new RadioBoxData(); + } + @Override + protected void buildChild(FieldSet fields, RadioBoxDataEntity d, RadioBoxData m) { + FieldSet optionsFields = fields.extractPrefixed(this.asPrefix(RadioBoxData._options)); + if (!optionsFields.isEmpty() && d.getOptions() != null) m.setOptions(this.builderFactory.builder(RadioBoxOptionBuilder.class).authorize(this.authorize).build(optionsFields, d.getOptions())); + } + + @Component + @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public static class RadioBoxOptionBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public RadioBoxOptionBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(RadioBoxOptionBuilder.class))); + } + + public RadioBoxOptionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (RadioBoxDataEntity.RadioBoxDataOptionEntity d : data) { + RadioBoxData.RadioBoxOption m = new RadioBoxData.RadioBoxOption(); + if (fields.hasField(this.asIndexer(RadioBoxData.RadioBoxOption._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(RadioBoxData.RadioBoxOption._value))) m.setValue(d.getValue()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/ReferenceTypeDataBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/ReferenceTypeDataBuilder.java new file mode 100644 index 000000000..fbdfedf66 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/ReferenceTypeDataBuilder.java @@ -0,0 +1,44 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition.fielddata; + +import org.opencdmp.commons.types.descriptiontemplate.fielddata.ReferenceTypeDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.ReferenceTypeBuilder; +import org.opencdmp.model.builder.dmpblueprintdefinition.ReferenceFieldBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.fielddata.ReferenceTypeData; +import org.opencdmp.model.dmpblueprintdefinition.ReferenceTypeField; +import org.opencdmp.query.ReferenceTypeQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeDataBuilder extends BaseFieldDataBuilder { + + private final QueryFactory queryFactory; + private final BuilderFactory builderFactory; + + @Autowired + public ReferenceTypeDataBuilder(ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceTypeDataBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + protected ReferenceTypeData getInstance() { + return new ReferenceTypeData(); + } + @Override + protected void buildChild(FieldSet fields, ReferenceTypeDataEntity d, ReferenceTypeData m) { + if (fields.hasField(this.asIndexer(ReferenceTypeData._multipleSelect))) m.setMultipleSelect(d.getMultipleSelect()); + + FieldSet referenceTypeFields = fields.extractPrefixed(this.asPrefix(ReferenceTypeData._referenceType)); + if (d.getReferenceTypeId() != null && !referenceTypeFields.isEmpty() ) m.setReferenceType(this.builderFactory.builder(ReferenceTypeBuilder.class).build(referenceTypeFields, this.queryFactory.query(ReferenceTypeQuery.class).ids(d.getReferenceTypeId()).first())); //TODO: Optimize + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/SelectDataBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/SelectDataBuilder.java new file mode 100644 index 000000000..51d65d6d0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/SelectDataBuilder.java @@ -0,0 +1,79 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition.fielddata; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.SelectDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.fielddata.SelectData; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SelectDataBuilder extends BaseFieldDataBuilder { + private final BuilderFactory builderFactory; + @Autowired + public SelectDataBuilder(ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(SelectDataBuilder.class))); + this.builderFactory = builderFactory; + } + + @Override + protected SelectData getInstance() { + return new SelectData(); + } + + @Override + protected void buildChild(FieldSet fields, SelectDataEntity d, SelectData m) { + FieldSet optionsFields = fields.extractPrefixed(this.asPrefix(SelectData._options)); + if (fields.hasField(this.asIndexer(SelectData._multipleSelect))) m.setMultipleSelect(d.getMultipleSelect()); + if (!optionsFields.isEmpty() && d.getOptions() != null) m.setOptions(this.builderFactory.builder(SelectOptionBuilder.class).authorize(this.authorize).build(optionsFields, d.getOptions())); + + } + + @Component + @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public static class SelectOptionBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public SelectOptionBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(SelectOptionBuilder.class))); + } + + public SelectOptionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (SelectDataEntity.OptionEntity d : data) { + SelectData.Option m = new SelectData.Option(); + if (fields.hasField(this.asIndexer(SelectData.Option._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(SelectData.Option._value))) m.setValue(d.getValue()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/UploadDataBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/UploadDataBuilder.java new file mode 100644 index 000000000..6f5e78f9e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/descriptiontemplatedefinition/fielddata/UploadDataBuilder.java @@ -0,0 +1,78 @@ +package org.opencdmp.model.builder.descriptiontemplatedefinition.fielddata; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.descriptiontemplate.fielddata.UploadDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.descriptiontemplatedefinition.fielddata.UploadData; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UploadDataBuilder extends BaseFieldDataBuilder { + private final BuilderFactory builderFactory; + + @Autowired + public UploadDataBuilder(ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UploadDataBuilder.class))); + this.builderFactory = builderFactory; + } + + protected UploadData getInstance() { + return new UploadData(); + } + @Override + protected void buildChild(FieldSet fields, UploadDataEntity d, UploadData m) { + FieldSet typesFields = fields.extractPrefixed(this.asPrefix(UploadData._types)); + + if (fields.hasField(this.asIndexer(UploadData._maxFileSizeInMB))) m.setMaxFileSizeInMB(d.getMaxFileSizeInMB()); + if (!typesFields.isEmpty() && d.getTypes() != null) m.setTypes(this.builderFactory.builder(UploadOptionBuilder.class).build(typesFields, d.getTypes())); + } + + @Component + @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public static class UploadOptionBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public UploadOptionBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UploadOptionBuilder.class))); + } + + public UploadOptionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (UploadDataEntity.UploadDataOptionEntity d : data) { + UploadData.UploadOption m = new UploadData.UploadOption(); + if (fields.hasField(this.asIndexer(UploadData.UploadOption._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(UploadData.UploadOption._value))) m.setValue(d.getValue()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/DefinitionBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/DefinitionBuilder.java new file mode 100644 index 000000000..9a40c352b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/DefinitionBuilder.java @@ -0,0 +1,59 @@ +package org.opencdmp.model.builder.dmpblueprintdefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.dmpblueprint.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.dmpblueprintdefinition.Definition; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("dmpblueprintdefinitionbuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DefinitionBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DefinitionBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DefinitionBuilder.class))); + this.builderFactory = builderFactory; + } + + public DefinitionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + FieldSet sectionsFields = fields.extractPrefixed(this.asPrefix(Definition._sections)); + + List models = new ArrayList<>(); + for (DefinitionEntity d : data) { + Definition m = new Definition(); + if (!sectionsFields.isEmpty() && d.getSections() != null) m.setSections(this.builderFactory.builder(SectionBuilder.class).authorize(this.authorize).build(sectionsFields, d.getSections())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/DescriptionTemplateBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/DescriptionTemplateBuilder.java new file mode 100644 index 000000000..3683be28f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/DescriptionTemplateBuilder.java @@ -0,0 +1,56 @@ +package org.opencdmp.model.builder.dmpblueprintdefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.dmpblueprint.DescriptionTemplateEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.dmpblueprintdefinition.DescriptionTemplate; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("dmpblueprintdefinitiondescriptiontemplatebuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTemplateBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DescriptionTemplateBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DescriptionTemplateBuilder.class))); + } + + public DescriptionTemplateBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (DescriptionTemplateEntity d : data) { + DescriptionTemplate m = new DescriptionTemplate(); + if (fields.hasField(this.asIndexer(DescriptionTemplate._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._descriptionTemplateGroupId))) m.setDescriptionTemplateGroupId(d.getDescriptionTemplateGroupId()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._maxMultiplicity))) m.setMaxMultiplicity(d.getMaxMultiplicity()); + if (fields.hasField(this.asIndexer(DescriptionTemplate._minMultiplicity))) m.setMinMultiplicity(d.getMinMultiplicity()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/ExtraFieldBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/ExtraFieldBuilder.java new file mode 100644 index 000000000..3653a03b7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/ExtraFieldBuilder.java @@ -0,0 +1,32 @@ +package org.opencdmp.model.builder.dmpblueprintdefinition; + +import org.opencdmp.commons.types.dmpblueprint.ExtraFieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.dmpblueprintdefinition.ExtraField; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ExtraFieldBuilder extends FieldBuilder { + + @Autowired + public ExtraFieldBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ExtraFieldBuilder.class))); + } + + protected ExtraField getInstance() { + return new ExtraField(); + } + + protected ExtraField buildChild(FieldSet fields, ExtraFieldEntity data, ExtraField model) { + if (fields.hasField(this.asIndexer(ExtraField._dataType))) model.setDataType(data.getType()); + return model; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/FieldBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/FieldBuilder.java new file mode 100644 index 000000000..6fa2a6b87 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/FieldBuilder.java @@ -0,0 +1,65 @@ +package org.opencdmp.model.builder.dmpblueprintdefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.dmpblueprint.FieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.dmpblueprintdefinition.Field; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("dmpblueprintdefinitionfieldbuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public abstract class FieldBuilder extends BaseBuilder { + + protected EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public FieldBuilder( + ConventionService conventionService, + LoggerService logger) { + super(conventionService, logger); + } + + public FieldBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + protected abstract Model getInstance(); + + protected abstract Model buildChild(FieldSet fields, Entity data, Model model); + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (Entity d : data) { + Model m = this.getInstance(); + if (fields.hasField(this.asIndexer(Model._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(Model._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(Model._category))) m.setCategory(d.getCategory()); + if (fields.hasField(this.asIndexer(Model._description))) m.setDescription(d.getDescription()); + if (fields.hasField(this.asIndexer(Model._semantics))) m.setSemantics(d.getSemantics()); + if (fields.hasField(this.asIndexer(Model._placeholder))) m.setPlaceholder(d.getPlaceholder()); + if (fields.hasField(this.asIndexer(Model._ordinal))) m.setOrdinal(d.getOrdinal()); + if (fields.hasField(this.asIndexer(Model._required))) m.setRequired(d.isRequired()); + this.buildChild(fields, d, m); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/ReferenceFieldBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/ReferenceFieldBuilder.java new file mode 100644 index 000000000..14977014d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/ReferenceFieldBuilder.java @@ -0,0 +1,48 @@ +package org.opencdmp.model.builder.dmpblueprintdefinition; + +import org.opencdmp.commons.types.dmpblueprint.ReferenceTypeFieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Dmp; +import org.opencdmp.model.PublicReferenceType; +import org.opencdmp.model.builder.PublicReferenceTypeBuilder; +import org.opencdmp.model.builder.ReferenceTypeBuilder; +import org.opencdmp.model.dmpblueprintdefinition.ReferenceTypeField; +import org.opencdmp.query.ReferenceTypeQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceFieldBuilder extends FieldBuilder { + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; + + @Autowired + public ReferenceFieldBuilder( + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceFieldBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; + } + + protected ReferenceTypeField getInstance() { + return new ReferenceTypeField(); + } + + protected ReferenceTypeField buildChild(FieldSet fields, ReferenceTypeFieldEntity data, ReferenceTypeField model) { + FieldSet referenceTypeFields = fields.extractPrefixed(this.asPrefix(ReferenceTypeField._referenceType)); + + if (data.getReferenceTypeId() != null && !referenceTypeFields.isEmpty() ) model.setReferenceType(this.builderFactory.builder(ReferenceTypeBuilder.class).build(referenceTypeFields, this.queryFactory.query(ReferenceTypeQuery.class).ids(data.getReferenceTypeId()).first())); //TODO: Optimize + if (fields.hasField(this.asIndexer(ReferenceTypeField._multipleSelect))) model.setMultipleSelect(data.getMultipleSelect()); + return model; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/SectionBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/SectionBuilder.java new file mode 100644 index 000000000..1f83fc599 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/SectionBuilder.java @@ -0,0 +1,86 @@ +package org.opencdmp.model.builder.dmpblueprintdefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.DmpBlueprintFieldCategory; +import org.opencdmp.commons.types.dmpblueprint.*; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.PrefillingSourceEntity; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.builder.PrefillingSourceBuilder; +import org.opencdmp.model.dmpblueprintdefinition.Section; +import org.opencdmp.query.PrefillingSourceQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("dmpblueprintdefinitionsectionbuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SectionBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public SectionBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(SectionBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public SectionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List
build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + FieldSet descriptionTemplatesFields = fields.extractPrefixed(this.asPrefix(Section._descriptionTemplates)); + FieldSet fieldsFields = fields.extractPrefixed(this.asPrefix(Section._fields)); + FieldSet prefillingSourcesFields = fields.extractPrefixed(this.asPrefix(Section._prefillingSources)); + + List
models = new ArrayList<>(); + for (SectionEntity d : data) { + Section m = new Section(); + if (fields.hasField(this.asIndexer(Section._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(Section._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(Section._description))) m.setDescription(d.getDescription()); + if (fields.hasField(this.asIndexer(Section._ordinal))) m.setOrdinal(d.getOrdinal()); + if (fields.hasField(this.asIndexer(Section._hasTemplates))) m.setHasTemplates(d.getHasTemplates()); + if (!descriptionTemplatesFields.isEmpty() && d.getDescriptionTemplates() != null) m.setDescriptionTemplates(this.builderFactory.builder(DescriptionTemplateBuilder.class).authorize(this.authorize).build(descriptionTemplatesFields, d.getDescriptionTemplates())); + if (!fieldsFields.isEmpty() && d.getFields() != null) { + m.setFields(new ArrayList<>()); + List systemFieldEntities = d.getFields().stream().filter(x-> DmpBlueprintFieldCategory.System.equals(x.getCategory())).map(x-> (SystemFieldEntity)x).toList(); + m.getFields().addAll(this.builderFactory.builder(SystemFieldBuilder.class).authorize(this.authorize).build(fieldsFields, systemFieldEntities)); + List extraFieldEntities = d.getFields().stream().filter(x-> DmpBlueprintFieldCategory.Extra.equals(x.getCategory())).map(x-> (ExtraFieldEntity)x).toList(); + m.getFields().addAll(this.builderFactory.builder(ExtraFieldBuilder.class).authorize(this.authorize).build(fieldsFields, extraFieldEntities)); + List referenceFieldEntities = d.getFields().stream().filter(x-> DmpBlueprintFieldCategory.ReferenceType.equals(x.getCategory())).map(x-> (ReferenceTypeFieldEntity)x).toList(); + m.getFields().addAll(this.builderFactory.builder(ReferenceFieldBuilder.class).authorize(this.authorize).build(fieldsFields, referenceFieldEntities)); + } + if (!prefillingSourcesFields.isEmpty() && d.getPrefillingSourcesIds() != null) { + List prefillingSourceEntities = this.queryFactory.query(PrefillingSourceQuery.class).authorize(this.authorize).ids(d.getPrefillingSourcesIds()).collectAs(prefillingSourcesFields); + m.setPrefillingSources(this.builderFactory.builder(PrefillingSourceBuilder.class).authorize(this.authorize).build(prefillingSourcesFields, prefillingSourceEntities)); + } + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/SystemFieldBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/SystemFieldBuilder.java new file mode 100644 index 000000000..c5705d139 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/dmpblueprintdefinition/SystemFieldBuilder.java @@ -0,0 +1,32 @@ +package org.opencdmp.model.builder.dmpblueprintdefinition; + +import org.opencdmp.commons.types.dmpblueprint.SystemFieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.dmpblueprintdefinition.SystemField; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SystemFieldBuilder extends FieldBuilder { + + @Autowired + public SystemFieldBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(SystemFieldBuilder.class))); + } + + protected SystemField getInstance() { + return new SystemField(); + } + + protected SystemField buildChild(FieldSet fields, SystemFieldEntity data, SystemField model) { + if (fields.hasField(this.asIndexer(SystemField._systemFieldType))) model.setSystemFieldType(data.getType()); + return model; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/dmpproperties/DmpBlueprintValueBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/dmpproperties/DmpBlueprintValueBuilder.java new file mode 100644 index 000000000..a119fa9fe --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/dmpproperties/DmpBlueprintValueBuilder.java @@ -0,0 +1,57 @@ +package org.opencdmp.model.builder.dmpproperties; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.dmp.DmpBlueprintValueEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.dmpproperties.DmpBlueprintValue; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("descriptionpropertiesdefinitionDmpBlueprintValuebuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpBlueprintValueBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpBlueprintValueBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpBlueprintValueBuilder.class))); + } + + public DmpBlueprintValueBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet DmpBlueprintValues, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} DmpBlueprintValues", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(DmpBlueprintValues).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested DmpBlueprintValues", DmpBlueprintValues)); + if (DmpBlueprintValues == null || data == null || DmpBlueprintValues.isEmpty()) + return new ArrayList<>(); + + + List models = new ArrayList<>(); + for (DmpBlueprintValueEntity d : data) { + DmpBlueprintValue m = new DmpBlueprintValue(); + if (DmpBlueprintValues.hasField(this.asIndexer(DmpBlueprintValue._fieldValue))) m.setFieldValue(d.getValue()); + if (DmpBlueprintValues.hasField(this.asIndexer(DmpBlueprintValue._fieldId))) m.setFieldId(d.getFieldId()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/dmpproperties/DmpContactBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/dmpproperties/DmpContactBuilder.java new file mode 100644 index 000000000..7bb227d96 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/dmpproperties/DmpContactBuilder.java @@ -0,0 +1,103 @@ +package org.opencdmp.model.builder.dmpproperties; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.dmp.DmpContactEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DmpAssociatedUser; +import org.opencdmp.model.User; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.builder.DmpAssociatedUserBuilder; +import org.opencdmp.model.dmpproperties.DmpContact; +import org.opencdmp.query.UserQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component("dmpcontactbuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpContactBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + + private final QueryFactory queryFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpContactBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpContactBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public DmpContactBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + FieldSet userFields = fields.extractPrefixed(this.asPrefix(DmpContact._user)); + Map userItemsMap = this.collectUsers(userFields, data); + + List models = new ArrayList<>(); + for (DmpContactEntity d : data) { + DmpContact m = new DmpContact(); + if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); + if (fields.hasField(this.asIndexer(DmpContact._email))) m.setEmail(d.getEmail()); + if (fields.hasField(this.asIndexer(DmpContact._firstName))) m.setFirstName(d.getFirstName()); + if (fields.hasField(this.asIndexer(DmpContact._lastName))) m.setLastName(d.getLastName()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", User.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(DmpAssociatedUser._id))) { + itemMap = this.asEmpty( + data.stream().filter(x-> x.getUserId() != null).map(DmpContactEntity::getUserId).distinct().collect(Collectors.toList()), + x -> { + DmpAssociatedUser item = new DmpAssociatedUser(); + item.setId(x); + return item; + }, + DmpAssociatedUser::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); + UserQuery q = this.queryFactory.query(UserQuery.class).authorize(this.authorize).ids(data.stream().filter(x-> x.getUserId() != null).map(DmpContactEntity::getUserId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(DmpAssociatedUserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, DmpAssociatedUser::getId); + } + if (!fields.hasField(User._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/dmpproperties/DmpPropertiesBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/dmpproperties/DmpPropertiesBuilder.java new file mode 100644 index 000000000..edd86213e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/dmpproperties/DmpPropertiesBuilder.java @@ -0,0 +1,61 @@ +package org.opencdmp.model.builder.dmpproperties; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.dmp.DmpPropertiesEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.dmpproperties.DmpProperties; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("dmppropertiesbuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpPropertiesBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpPropertiesBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpPropertiesBuilder.class))); + this.builderFactory = builderFactory; + } + + public DmpPropertiesBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + FieldSet dmpBlueprintValuesFields = fields.extractPrefixed(this.asPrefix(DmpProperties._dmpBlueprintValues)); + FieldSet contactsFields = fields.extractPrefixed(this.asPrefix(DmpProperties._contacts)); + + List models = new ArrayList<>(); + for (DmpPropertiesEntity d : data) { + DmpProperties m = new DmpProperties(); + if (!dmpBlueprintValuesFields.isEmpty() && d.getDmpBlueprintValues() != null) m.setDmpBlueprintValues(this.builderFactory.builder(DmpBlueprintValueBuilder.class).authorize(this.authorize).build(dmpBlueprintValuesFields, d.getDmpBlueprintValues())); + if (!contactsFields.isEmpty() && d.getContacts() != null) m.setContacts(this.builderFactory.builder(DmpContactBuilder.class).authorize(this.authorize).build(contactsFields, d.getContacts())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/dmpreference/DmpReferenceDataBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/dmpreference/DmpReferenceDataBuilder.java new file mode 100644 index 000000000..5e6e6a7e4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/dmpreference/DmpReferenceDataBuilder.java @@ -0,0 +1,56 @@ +package org.opencdmp.model.builder.dmpreference; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.dmpreference.DmpReferenceDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.dmpreference.DmpReferenceData; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("referencedmpreferencedatabuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpReferenceDataBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DmpReferenceDataBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DmpReferenceDataBuilder.class))); + } + + public DmpReferenceDataBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + + List models = new ArrayList<>(); + for (DmpReferenceDataEntity d : data) { + DmpReferenceData m = new DmpReferenceData(); + if (fields.hasField(this.asIndexer(DmpReferenceData._blueprintFieldId))) m.setBlueprintFieldId(d.getBlueprintFieldId()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/AuthenticationConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/AuthenticationConfigurationBuilder.java new file mode 100644 index 000000000..e1d94bbb0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/AuthenticationConfigurationBuilder.java @@ -0,0 +1,59 @@ +package org.opencdmp.model.builder.externalfetcher; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.externalfetcher.AuthenticationConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.externalfetcher.AuthenticationConfiguration; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class AuthenticationConfigurationBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public AuthenticationConfigurationBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(AuthenticationConfigurationBuilder.class))); + } + + public AuthenticationConfigurationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (AuthenticationConfigurationEntity d : data) { + AuthenticationConfiguration m = new AuthenticationConfiguration(); + if (fields.hasField(this.asIndexer(AuthenticationConfiguration._enabled))) m.setEnabled(d.getEnabled()); + if (fields.hasField(this.asIndexer(AuthenticationConfiguration._authUrl))) m.setAuthUrl(d.getAuthUrl()); + if (fields.hasField(this.asIndexer(AuthenticationConfiguration._authMethod))) m.setAuthMethod(d.getAuthMethod()); + if (fields.hasField(this.asIndexer(AuthenticationConfiguration._authTokenPath))) m.setAuthTokenPath(d.getAuthTokenPath()); + if (fields.hasField(this.asIndexer(AuthenticationConfiguration._authRequestBody))) m.setAuthRequestBody(d.getAuthRequestBody()); + if (fields.hasField(this.asIndexer(AuthenticationConfiguration._type))) m.setType(d.getType()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ExternalFetcherApiSourceConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ExternalFetcherApiSourceConfigurationBuilder.java new file mode 100644 index 000000000..4dabb00a1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ExternalFetcherApiSourceConfigurationBuilder.java @@ -0,0 +1,70 @@ +package org.opencdmp.model.builder.externalfetcher; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.authorization.Permission; +import org.opencdmp.commons.types.externalfetcher.ExternalFetcherApiSourceConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.externalfetcher.ExternalFetcherApiSourceConfiguration; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ExternalFetcherApiSourceConfigurationBuilder extends ExternalFetcherBaseSourceConfigurationBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private final AuthorizationService authorizationService; + + @Autowired + public ExternalFetcherApiSourceConfigurationBuilder( + ConventionService conventionService, BuilderFactory builderFactory, AuthorizationService authorizationService, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ExternalFetcherApiSourceConfigurationBuilder.class)), builderFactory, queryFactory); + this.builderFactory = builderFactory; + this.authorizationService = authorizationService; + } + + + @Override + protected ExternalFetcherApiSourceConfiguration getInstance() { + return new ExternalFetcherApiSourceConfiguration(); + } + + @Override + protected ExternalFetcherApiSourceConfiguration buildChild(FieldSet fields, ExternalFetcherApiSourceConfigurationEntity d, ExternalFetcherApiSourceConfiguration m) { + FieldSet resultsFields = fields.extractPrefixed(this.asPrefix(ExternalFetcherApiSourceConfiguration._results)); + FieldSet authFields = fields.extractPrefixed(this.asPrefix(ExternalFetcherApiSourceConfiguration._auth)); + FieldSet queriesFields = fields.extractPrefixed(this.asPrefix(ExternalFetcherApiSourceConfiguration._queries)); + if(!authorizationService.authorize(Permission.EditReferenceType)) return m; + + if (fields.hasField(this.asIndexer(ExternalFetcherApiSourceConfiguration._url))) m.setUrl(d.getUrl()); + if (!resultsFields.isEmpty() && d.getResults() != null) { + m.setResults(this.builderFactory.builder(ResultsConfigurationBuilder.class).authorize(this.authorize).build(resultsFields, d.getResults())); + } + if (fields.hasField(this.asIndexer(ExternalFetcherApiSourceConfiguration._type))) m.setType(d.getType()); + if (fields.hasField(this.asIndexer(ExternalFetcherApiSourceConfiguration._paginationPath))) m.setPaginationPath(d.getPaginationPath()); + if (fields.hasField(this.asIndexer(ExternalFetcherApiSourceConfiguration._contentType))) m.setContentType(d.getContentType()); + if (fields.hasField(this.asIndexer(ExternalFetcherApiSourceConfiguration._firstPage))) m.setFirstPage(d.getFirstPage()); + if (fields.hasField(this.asIndexer(ExternalFetcherApiSourceConfiguration._httpMethod))) m.setHttpMethod(d.getHttpMethod()); + if (fields.hasField(this.asIndexer(ExternalFetcherApiSourceConfiguration._requestBody))) m.setRequestBody(d.getRequestBody()); + if (fields.hasField(this.asIndexer(ExternalFetcherApiSourceConfiguration._filterType))) m.setFilterType(d.getFilterType()); + if (!authFields.isEmpty() && d.getAuth() != null) { + m.setAuth(this.builderFactory.builder(AuthenticationConfigurationBuilder.class).authorize(this.authorize).build(authFields, d.getAuth())); + } + if (!queriesFields.isEmpty() && d.getQueries() != null) { + m.setQueries(this.builderFactory.builder(QueryConfigBuilder.class).authorize(this.authorize).build(queriesFields, d.getQueries())); + } + + return m; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ExternalFetcherBaseSourceConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ExternalFetcherBaseSourceConfigurationBuilder.java new file mode 100644 index 000000000..a17d5de2f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ExternalFetcherBaseSourceConfigurationBuilder.java @@ -0,0 +1,113 @@ +package org.opencdmp.model.builder.externalfetcher; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.externalfetcher.ExternalFetcherBaseSourceConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.ReferenceType; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.builder.ReferenceTypeBuilder; +import org.opencdmp.model.externalfetcher.ExternalFetcherBaseSourceConfiguration; +import org.opencdmp.query.ReferenceTypeQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public abstract class ExternalFetcherBaseSourceConfigurationBuilder extends BaseBuilder { + + protected EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + protected final BuilderFactory builderFactory; + protected final QueryFactory queryFactory; + + @Autowired + public ExternalFetcherBaseSourceConfigurationBuilder( + ConventionService conventionService, + LoggerService logger, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, logger); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public ExternalFetcherBaseSourceConfigurationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + protected abstract Model getInstance(); + + protected abstract Model buildChild(FieldSet fields, Entity data, Model model); + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet referenceTypeDependenciesFields = fields.extractPrefixed(this.asPrefix(Model._referenceTypeDependencies)); + Map referenceTypeItemsMap = this.collectReferenceTypes(referenceTypeDependenciesFields, data); + + List models = new ArrayList<>(); + for (Entity d : data) { + Model m = this.getInstance(); + if (fields.hasField(this.asIndexer(Model._key))) m.setKey(d.getKey()); + if (fields.hasField(this.asIndexer(Model._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(Model._ordinal))) m.setOrdinal(d.getOrdinal()); + if (fields.hasField(this.asIndexer(Model._type))) m.setType(d.getType()); + if (!referenceTypeDependenciesFields.isEmpty() && referenceTypeItemsMap != null && d.getReferenceTypeDependencyIds() != null) { + List referenceTypes = new ArrayList<>(); + for (UUID referenceTypeId : d.getReferenceTypeDependencyIds()){ + if (referenceTypeItemsMap.containsKey(referenceTypeId)) referenceTypes.add(referenceTypeItemsMap.get(referenceTypeId)); + } + if (!referenceTypes.isEmpty()) m.setReferenceTypeDependencies(referenceTypes); + } + + this.buildChild(fields, d, m); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectReferenceTypes(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", ReferenceType.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(ReferenceType._id))) { + itemMap = this.asEmpty( + data.stream().filter(x-> x.getReferenceTypeDependencyIds() != null).map(ExternalFetcherBaseSourceConfigurationEntity::getReferenceTypeDependencyIds).flatMap(List::stream).distinct().collect(Collectors.toList()), + x -> { + ReferenceType item = new ReferenceType(); + item.setId(x); + return item; + }, + ReferenceType::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(ReferenceType._id); + ReferenceTypeQuery q = this.queryFactory.query(ReferenceTypeQuery.class).authorize(this.authorize).ids(data.stream().filter(x-> x.getReferenceTypeDependencyIds() != null).map(ExternalFetcherBaseSourceConfigurationEntity::getReferenceTypeDependencyIds).flatMap(List::stream).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(ReferenceTypeBuilder.class).authorize(this.authorize).asForeignKey(q, clone, ReferenceType::getId); + } + if (!fields.hasField(ReferenceType._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ExternalFetcherStaticOptionSourceConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ExternalFetcherStaticOptionSourceConfigurationBuilder.java new file mode 100644 index 000000000..222cc6658 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ExternalFetcherStaticOptionSourceConfigurationBuilder.java @@ -0,0 +1,56 @@ +package org.opencdmp.model.builder.externalfetcher; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.authorization.Permission; +import org.opencdmp.commons.types.externalfetcher.ExternalFetcherStaticOptionSourceConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.externalfetcher.ExternalFetcherStaticOptionSourceConfiguration; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.EnumSet; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ExternalFetcherStaticOptionSourceConfigurationBuilder extends ExternalFetcherBaseSourceConfigurationBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private final AuthorizationService authorizationService; + + @Autowired + public ExternalFetcherStaticOptionSourceConfigurationBuilder( + ConventionService conventionService, BuilderFactory builderFactory, AuthorizationService authorizationService, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ExternalFetcherStaticOptionSourceConfigurationBuilder.class)), builderFactory, queryFactory); + this.builderFactory = builderFactory; + this.authorizationService = authorizationService; + } + + + @Override + protected ExternalFetcherStaticOptionSourceConfiguration getInstance() { + return new ExternalFetcherStaticOptionSourceConfiguration(); + } + + @Override + protected ExternalFetcherStaticOptionSourceConfiguration buildChild(FieldSet fields, ExternalFetcherStaticOptionSourceConfigurationEntity d, ExternalFetcherStaticOptionSourceConfiguration m) { + FieldSet itemsFields = fields.extractPrefixed(this.asPrefix(ExternalFetcherStaticOptionSourceConfiguration._items)); + + if(!authorizationService.authorize(Permission.EditReferenceType)) return m; + + if (!itemsFields.isEmpty() && d.getItems() != null) { + m.setItems(this.builderFactory.builder(StaticBuilder.class).authorize(this.authorize).build(itemsFields, d.getItems())); + } + + return m; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/QueryCaseConfigBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/QueryCaseConfigBuilder.java new file mode 100644 index 000000000..1c3323e04 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/QueryCaseConfigBuilder.java @@ -0,0 +1,102 @@ +package org.opencdmp.model.builder.externalfetcher; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.externalfetcher.QueryCaseConfigEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.ReferenceType; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.builder.ReferenceTypeBuilder; +import org.opencdmp.model.externalfetcher.QueryCaseConfig; +import org.opencdmp.query.ReferenceTypeQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class QueryCaseConfigBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public QueryCaseConfigBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(QueryCaseConfigBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public QueryCaseConfigBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet referenceTypeFields = fields.extractPrefixed(this.asPrefix(QueryCaseConfig._referenceType)); + Map referenceTypeItemsMap = this.collectReferenceTypes(referenceTypeFields, data); + + List models = new ArrayList<>(); + for (QueryCaseConfigEntity d : data) { + QueryCaseConfig m = new QueryCaseConfig(); + if (fields.hasField(this.asIndexer(QueryCaseConfig._separator))) m.setSeparator(d.getSeparator()); + if (fields.hasField(this.asIndexer(QueryCaseConfig._value))) m.setValue(d.getValue()); + if (fields.hasField(this.asIndexer(QueryCaseConfig._likePattern))) m.setLikePattern(d.getLikePattern()); + if (fields.hasField(this.asIndexer(QueryCaseConfig._referenceTypeSourceKey))) m.setReferenceTypeSourceKey(d.getReferenceTypeSourceKey()); + if (!referenceTypeFields.isEmpty() && referenceTypeItemsMap != null && referenceTypeItemsMap.containsKey(d.getReferenceTypeId())) m.setReferenceType(referenceTypeItemsMap.get(d.getReferenceTypeId())); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + + private Map collectReferenceTypes(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", ReferenceType.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(ReferenceType._id))) { + itemMap = this.asEmpty( + data.stream().filter(x-> x.getReferenceTypeId() != null).map(QueryCaseConfigEntity::getReferenceTypeId).distinct().collect(Collectors.toList()), + x -> { + ReferenceType item = new ReferenceType(); + item.setId(x); + return item; + }, + ReferenceType::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(ReferenceType._id); + ReferenceTypeQuery q = this.queryFactory.query(ReferenceTypeQuery.class).authorize(this.authorize).ids(data.stream().filter(x-> x.getReferenceTypeId() != null).map(QueryCaseConfigEntity::getReferenceTypeId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(ReferenceTypeBuilder.class).authorize(this.authorize).asForeignKey(q, clone, ReferenceType::getId); + } + if (!fields.hasField(ReferenceType._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/QueryConfigBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/QueryConfigBuilder.java new file mode 100644 index 000000000..e70541a65 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/QueryConfigBuilder.java @@ -0,0 +1,63 @@ +package org.opencdmp.model.builder.externalfetcher; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.externalfetcher.QueryConfigEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.externalfetcher.QueryConfig; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class QueryConfigBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public QueryConfigBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(QueryConfigBuilder.class))); + this.builderFactory = builderFactory; + } + + public QueryConfigBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet casesFields = fields.extractPrefixed(this.asPrefix(QueryConfig._cases)); + + List models = new ArrayList<>(); + for (QueryConfigEntity d : data) { + QueryConfig m = new QueryConfig(); + if (fields.hasField(this.asIndexer(QueryConfig._defaultValue))) m.setDefaultValue(d.getDefaultValue()); + if (fields.hasField(this.asIndexer(QueryConfig._name))) m.setName(d.getName()); + if (!casesFields.isEmpty() && !this.conventionService.isListNullOrEmpty(d.getCases())){ + m.setCases(this.builderFactory.builder(QueryCaseConfigBuilder.class).authorize(this.authorize).build(casesFields, d.getCases())); + } + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ResultFieldsMappingConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ResultFieldsMappingConfigurationBuilder.java new file mode 100644 index 000000000..dadc90034 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ResultFieldsMappingConfigurationBuilder.java @@ -0,0 +1,58 @@ +package org.opencdmp.model.builder.externalfetcher; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.externalfetcher.ResultFieldsMappingConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.externalfetcher.ResultFieldsMappingConfiguration; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ResultFieldsMappingConfigurationBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ResultFieldsMappingConfigurationBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ResultFieldsMappingConfigurationBuilder.class))); + this.builderFactory = builderFactory; + } + + public ResultFieldsMappingConfigurationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (ResultFieldsMappingConfigurationEntity d : data) { + ResultFieldsMappingConfiguration m = new ResultFieldsMappingConfiguration(); + if (fields.hasField(this.asIndexer(ResultFieldsMappingConfiguration._code))) m.setCode(d.getCode()); + if (fields.hasField(this.asIndexer(ResultFieldsMappingConfiguration._responsePath))) m.setResponsePath(d.getResponsePath()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ResultsConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ResultsConfigurationBuilder.java new file mode 100644 index 000000000..43d607b42 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/ResultsConfigurationBuilder.java @@ -0,0 +1,62 @@ +package org.opencdmp.model.builder.externalfetcher; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.externalfetcher.ResultsConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.externalfetcher.ResultsConfiguration; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ResultsConfigurationBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ResultsConfigurationBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ResultsConfigurationBuilder.class))); + this.builderFactory = builderFactory; + } + + public ResultsConfigurationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet fieldsMappingFields = fields.extractPrefixed(this.asPrefix(ResultsConfiguration._fieldsMapping)); + + List models = new ArrayList<>(); + for (ResultsConfigurationEntity d : data) { + ResultsConfiguration m = new ResultsConfiguration(); + if (fields.hasField(this.asIndexer(ResultsConfiguration._resultsArrayPath))) m.setResultsArrayPath(d.getResultsArrayPath()); + if (!fieldsMappingFields.isEmpty() && d.getFieldsMapping() != null) { + m.setFieldsMapping(this.builderFactory.builder(ResultFieldsMappingConfigurationBuilder.class).authorize(this.authorize).build(fieldsMappingFields, d.getFieldsMapping())); + } + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/StaticBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/StaticBuilder.java new file mode 100644 index 000000000..5be15eb89 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/StaticBuilder.java @@ -0,0 +1,65 @@ +package org.opencdmp.model.builder.externalfetcher; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.externalfetcher.StaticEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.externalfetcher.Static; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class StaticBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public StaticBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(QueryCaseConfigBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public StaticBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet optionsFields = fields.extractPrefixed(this.asPrefix(Static._options)); + + List models = new ArrayList<>(); + for (StaticEntity d : data) { + Static m = new Static(); + if (!optionsFields.isEmpty() && d.getOptions() != null) { + m.setOptions(this.builderFactory.builder(StaticOptionBuilder.class).authorize(this.authorize).build(optionsFields, d.getOptions())); + } + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/StaticOptionBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/StaticOptionBuilder.java new file mode 100644 index 000000000..07c7bf0d2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/externalfetcher/StaticOptionBuilder.java @@ -0,0 +1,54 @@ +package org.opencdmp.model.builder.externalfetcher; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.externalfetcher.StaticOptionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.externalfetcher.StaticOption; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class StaticOptionBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public StaticOptionBuilder(ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(StaticOptionBuilder.class))); + } + + public StaticOptionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (StaticOptionEntity d : data) { + StaticOption m = new StaticOption(); + if (fields.hasField(this.asIndexer(StaticOption._code))) m.setCode(d.getCode()); + if (fields.hasField(this.asIndexer(StaticOption._value))) m.setValue(d.getValue()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/filetransformer/FileTransformerSourceBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/filetransformer/FileTransformerSourceBuilder.java new file mode 100644 index 000000000..3a5199714 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/filetransformer/FileTransformerSourceBuilder.java @@ -0,0 +1,84 @@ +package org.opencdmp.model.builder.filetransformer; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.filetransformer.FileTransformerSourceEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.filetransformer.FileTransformerSource; +import org.opencdmp.service.encryption.EncryptionService; +import org.opencdmp.service.tenant.TenantProperties; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FileTransformerSourceBuilder extends BaseBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + private final EncryptionService encryptionService; + private final TenantProperties tenantProperties; + private boolean encrypted; + @Autowired + public FileTransformerSourceBuilder( + ConventionService conventionService, EncryptionService encryptionService, TenantProperties tenantProperties) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(FileTransformerSourceBuilder.class))); + this.encryptionService = encryptionService; + this.tenantProperties = tenantProperties; + } + + public FileTransformerSourceBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + public FileTransformerSourceBuilder encrypted(boolean encrypted) { + this.encrypted = encrypted; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (FileTransformerSourceEntity d : data) { + FileTransformerSource m = new FileTransformerSource(); + if (fields.hasField(this.asIndexer(FileTransformerSource._transformerId))) m.setTransformerId(d.getTransformerId()); + if (fields.hasField(this.asIndexer(FileTransformerSource._url))) m.setUrl(d.getUrl()); + if (fields.hasField(this.asIndexer(FileTransformerSource._issuerUrl))) m.setIssuerUrl(d.getIssuerUrl()); + if (fields.hasField(this.asIndexer(FileTransformerSource._clientId))) m.setClientId(d.getClientId()); + if (fields.hasField(this.asIndexer(FileTransformerSource._clientSecret))){ + if (encrypted) { + try { + if (!this.conventionService.isNullOrEmpty(d.getClientSecret())) m.setClientSecret(this.encryptionService.decryptAES(d.getClientSecret(), tenantProperties.getConfigEncryptionAesKey(), tenantProperties.getConfigEncryptionAesIv())); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + m.setClientSecret(d.getClientSecret()); + } + } + if (fields.hasField(this.asIndexer(FileTransformerSource._scope))) m.setScope(d.getScope()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/prefillingsourcedefinition/PrefillingSourceDefinitionBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/prefillingsourcedefinition/PrefillingSourceDefinitionBuilder.java new file mode 100644 index 000000000..3850e98d4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/prefillingsourcedefinition/PrefillingSourceDefinitionBuilder.java @@ -0,0 +1,71 @@ +package org.opencdmp.model.builder.prefillingsourcedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.prefillingsource.PrefillingSourceDefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.builder.externalfetcher.ExternalFetcherApiSourceConfigurationBuilder; +import org.opencdmp.model.externalfetcher.ExternalFetcherApiSourceConfiguration; +import org.opencdmp.model.prefillingsourcedefinition.PrefillingSourceDefinition; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PrefillingSourceDefinitionBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PrefillingSourceDefinitionBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PrefillingSourceDefinitionBuilder.class))); + this.builderFactory = builderFactory; + } + + public PrefillingSourceDefinitionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet searchConfigurationFields = fields.extractPrefixed(this.asPrefix(PrefillingSourceDefinition._searchConfiguration)); + FieldSet getConfigurationFields = fields.extractPrefixed(this.asPrefix(PrefillingSourceDefinition._getConfiguration)); + FieldSet fieldsFields = fields.extractPrefixed(this.asPrefix(PrefillingSourceDefinition._fields)); + FieldSet fixedValueFieldsFields = fields.extractPrefixed(this.asPrefix(PrefillingSourceDefinition._fixedValueFields)); + + List models = new ArrayList<>(); + for (PrefillingSourceDefinitionEntity d : data) { + PrefillingSourceDefinition m = new PrefillingSourceDefinition(); + if (!fieldsFields.isEmpty() && d.getFields() != null) m.setFields(this.builderFactory.builder(PrefillingSourceDefinitionFieldBuilder.class).authorize(this.authorize).build(fieldsFields, d.getFields())); + if (!fixedValueFieldsFields.isEmpty() && d.getFixedValueFields() != null) m.setFixedValueFields(this.builderFactory.builder(PrefillingSourceDefinitionFixedValueFieldBuilder.class).authorize(this.authorize).build(fixedValueFieldsFields, d.getFixedValueFields())); + if (!searchConfigurationFields.isEmpty() && d.getSearchConfiguration() != null) { + m.setSearchConfiguration((ExternalFetcherApiSourceConfiguration) this.builderFactory.builder(ExternalFetcherApiSourceConfigurationBuilder.class).authorize(this.authorize).build(searchConfigurationFields, d.getSearchConfiguration())); + } + if (!getConfigurationFields.isEmpty() && d.getGetConfiguration() != null) { + m.setGetConfiguration((ExternalFetcherApiSourceConfiguration) this.builderFactory.builder(ExternalFetcherApiSourceConfigurationBuilder.class).authorize(this.authorize).build(searchConfigurationFields, d.getGetConfiguration())); + } + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/prefillingsourcedefinition/PrefillingSourceDefinitionFieldBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/prefillingsourcedefinition/PrefillingSourceDefinitionFieldBuilder.java new file mode 100644 index 000000000..4a5f4aa50 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/prefillingsourcedefinition/PrefillingSourceDefinitionFieldBuilder.java @@ -0,0 +1,60 @@ +package org.opencdmp.model.builder.prefillingsourcedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.prefillingsource.PrefillingSourceDefinitionFieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.prefillingsourcedefinition.PrefillingSourceDefinitionField; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PrefillingSourceDefinitionFieldBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PrefillingSourceDefinitionFieldBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PrefillingSourceDefinitionFieldBuilder.class))); + this.builderFactory = builderFactory; + } + + public PrefillingSourceDefinitionFieldBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (PrefillingSourceDefinitionFieldEntity d : data) { + PrefillingSourceDefinitionField m = new PrefillingSourceDefinitionField(); + if (fields.hasField(this.asIndexer(PrefillingSourceDefinitionField._code))) m.setCode(d.getCode()); + if (fields.hasField(this.asIndexer(PrefillingSourceDefinitionField._systemFieldTarget))) m.setSystemFieldTarget(d.getSystemFieldTarget()); + if (fields.hasField(this.asIndexer(PrefillingSourceDefinitionField._semanticTarget))) m.setSemanticTarget(d.getSemanticTarget()); + if (fields.hasField(this.asIndexer(PrefillingSourceDefinitionField._trimRegex))) m.setTrimRegex(d.getTrimRegex()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/prefillingsourcedefinition/PrefillingSourceDefinitionFixedValueFieldBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/prefillingsourcedefinition/PrefillingSourceDefinitionFixedValueFieldBuilder.java new file mode 100644 index 000000000..3483a99f7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/prefillingsourcedefinition/PrefillingSourceDefinitionFixedValueFieldBuilder.java @@ -0,0 +1,60 @@ +package org.opencdmp.model.builder.prefillingsourcedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.prefillingsource.PrefillingSourceDefinitionFixedValueFieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.prefillingsourcedefinition.PrefillingSourceDefinitionFixedValueField; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PrefillingSourceDefinitionFixedValueFieldBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public PrefillingSourceDefinitionFixedValueFieldBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(PrefillingSourceDefinitionFixedValueFieldBuilder.class))); + this.builderFactory = builderFactory; + } + + public PrefillingSourceDefinitionFixedValueFieldBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (PrefillingSourceDefinitionFixedValueFieldEntity d : data) { + PrefillingSourceDefinitionFixedValueField m = new PrefillingSourceDefinitionFixedValueField(); + if (fields.hasField(this.asIndexer(PrefillingSourceDefinitionFixedValueField._systemFieldTarget))) m.setSystemFieldTarget(d.getSystemFieldTarget()); + if (fields.hasField(this.asIndexer(PrefillingSourceDefinitionFixedValueField._semanticTarget))) m.setSemanticTarget(d.getSemanticTarget()); + if (fields.hasField(this.asIndexer(PrefillingSourceDefinitionFixedValueField._trimRegex))) m.setTrimRegex(d.getTrimRegex()); + if (fields.hasField(this.asIndexer(PrefillingSourceDefinitionFixedValueField._fixedValue))) m.setFixedValue(d.getFixedValue()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/referencedefinition/DefinitionBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/referencedefinition/DefinitionBuilder.java new file mode 100644 index 000000000..f82986672 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/referencedefinition/DefinitionBuilder.java @@ -0,0 +1,59 @@ +package org.opencdmp.model.builder.referencedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.reference.DefinitionEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.referencedefinition.Definition; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("referencedefinitionbuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DefinitionBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DefinitionBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DefinitionBuilder.class))); + this.builderFactory = builderFactory; + } + + public DefinitionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + FieldSet definitionFields = fields.extractPrefixed(this.asPrefix(Definition._fields)); + + List models = new ArrayList<>(); + for (DefinitionEntity d : data) { + Definition m = new Definition(); + if (!definitionFields.isEmpty() && d.getFields() != null) m.setFields(this.builderFactory.builder(FieldBuilder.class).authorize(this.authorize).build(definitionFields, d.getFields())); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/referencedefinition/FieldBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/referencedefinition/FieldBuilder.java new file mode 100644 index 000000000..dac1d4f71 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/referencedefinition/FieldBuilder.java @@ -0,0 +1,59 @@ +package org.opencdmp.model.builder.referencedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.reference.FieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.referencedefinition.Field; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component("referencedefinitionfieldbuilder") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public FieldBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldBuilder.class))); + this.builderFactory = builderFactory; + } + + public FieldBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (FieldEntity d : data) { + Field m = new Field(); + if (fields.hasField(this.asIndexer(Field._code))) m.setCode(d.getCode()); + if (fields.hasField(this.asIndexer(Field._dataType))) m.setDataType(d.getDataType()); + if (fields.hasField(this.asIndexer(Field._value))) m.setValue(d.getValue()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/referencetypedefinition/ReferenceTypeDefinitionBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/referencetypedefinition/ReferenceTypeDefinitionBuilder.java new file mode 100644 index 000000000..1b7771a26 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/referencetypedefinition/ReferenceTypeDefinitionBuilder.java @@ -0,0 +1,73 @@ +package org.opencdmp.model.builder.referencetypedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.ExternalFetcherSourceType; +import org.opencdmp.commons.types.referencetype.ReferenceTypeDefinitionEntity; +import org.opencdmp.commons.types.externalfetcher.ExternalFetcherApiSourceConfigurationEntity; +import org.opencdmp.commons.types.externalfetcher.ExternalFetcherStaticOptionSourceConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.builder.externalfetcher.ExternalFetcherApiSourceConfigurationBuilder; +import org.opencdmp.model.builder.externalfetcher.ExternalFetcherStaticOptionSourceConfigurationBuilder; +import org.opencdmp.model.referencetypedefinition.ReferenceTypeDefinition; +import org.opencdmp.model.externalfetcher.ExternalFetcherBaseSourceConfiguration; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeDefinitionBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ReferenceTypeDefinitionBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceTypeDefinitionBuilder.class))); + this.builderFactory = builderFactory; + } + + public ReferenceTypeDefinitionBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet fieldsFields = fields.extractPrefixed(this.asPrefix(ReferenceTypeDefinition._fields)); + FieldSet sourcesFields = fields.extractPrefixed(this.asPrefix(ReferenceTypeDefinition._sources)); + + List models = new ArrayList<>(); + for (ReferenceTypeDefinitionEntity d : data) { + ReferenceTypeDefinition m = new ReferenceTypeDefinition(); + if (!fieldsFields.isEmpty() && d.getFields() != null) m.setFields(this.builderFactory.builder(ReferenceTypeFieldBuilder.class).authorize(this.authorize).build(fieldsFields, d.getFields())); + if (!sourcesFields.isEmpty() && d.getSources() != null) { + List externalApiConfigEntities = d.getSources().stream().filter(x-> ExternalFetcherSourceType.API.equals(x.getType())).map(x-> (ExternalFetcherApiSourceConfigurationEntity)x).toList(); + List staticOptionConfigEntities = d.getSources().stream().filter(x-> ExternalFetcherSourceType.STATIC.equals(x.getType())).map(x-> (ExternalFetcherStaticOptionSourceConfigurationEntity)x).toList(); + m.setSources(new ArrayList<>()); + m.getSources().addAll(this.builderFactory.builder(ExternalFetcherApiSourceConfigurationBuilder.class).authorize(this.authorize).build(sourcesFields, externalApiConfigEntities)); + m.getSources().addAll(this.builderFactory.builder(ExternalFetcherStaticOptionSourceConfigurationBuilder.class).authorize(this.authorize).build(sourcesFields, staticOptionConfigEntities)); + m.getSources().sort(Comparator.comparing(x -> x.getOrdinal() == null ? 0 : x.getOrdinal())); + } + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/referencetypedefinition/ReferenceTypeFieldBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/referencetypedefinition/ReferenceTypeFieldBuilder.java new file mode 100644 index 000000000..a50defde7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/referencetypedefinition/ReferenceTypeFieldBuilder.java @@ -0,0 +1,60 @@ +package org.opencdmp.model.builder.referencetypedefinition; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.referencetype.ReferenceTypeFieldEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.referencetypedefinition.ReferenceTypeField; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeFieldBuilder extends BaseBuilder { + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public ReferenceTypeFieldBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceTypeFieldBuilder.class))); + this.builderFactory = builderFactory; + } + + public ReferenceTypeFieldBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (ReferenceTypeFieldEntity d : data) { + ReferenceTypeField m = new ReferenceTypeField(); + if (fields.hasField(this.asIndexer(ReferenceTypeField._code))) m.setCode(d.getCode()); + if (fields.hasField(this.asIndexer(ReferenceTypeField._label))) m.setLabel(d.getLabel()); + if (fields.hasField(this.asIndexer(ReferenceTypeField._description))) m.setDescription(d.getDescription()); + if (fields.hasField(this.asIndexer(ReferenceTypeField._dataType))) m.setDataType(d.getDataType()); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/CssColorsTenantConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/CssColorsTenantConfigurationBuilder.java new file mode 100644 index 000000000..6a129bc97 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/CssColorsTenantConfigurationBuilder.java @@ -0,0 +1,55 @@ +package org.opencdmp.model.builder.tenantconfiguration; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.tenantconfiguration.CssColorsTenantConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.tenantconfiguration.CssColorsTenantConfiguration; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class CssColorsTenantConfigurationBuilder extends BaseBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public CssColorsTenantConfigurationBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(CssColorsTenantConfigurationBuilder.class))); + } + + public CssColorsTenantConfigurationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (CssColorsTenantConfigurationEntity d : data) { + CssColorsTenantConfiguration m = new CssColorsTenantConfiguration(); + if (fields.hasField(this.asIndexer(CssColorsTenantConfiguration._primaryColor))) m.setPrimaryColor(d.getPrimaryColor()); + if (fields.hasField(this.asIndexer(CssColorsTenantConfiguration._primaryColor2))) m.setPrimaryColor2(d.getPrimaryColor2()); + if (fields.hasField(this.asIndexer(CssColorsTenantConfiguration._primaryColor3))) m.setPrimaryColor3(d.getPrimaryColor3()); + if (fields.hasField(this.asIndexer(CssColorsTenantConfiguration._secondaryColor))) m.setSecondaryColor(d.getSecondaryColor()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/DefaultUserLocaleTenantConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/DefaultUserLocaleTenantConfigurationBuilder.java new file mode 100644 index 000000000..d8e7d1beb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/DefaultUserLocaleTenantConfigurationBuilder.java @@ -0,0 +1,54 @@ +package org.opencdmp.model.builder.tenantconfiguration; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.tenantconfiguration.DefaultUserLocaleTenantConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.tenantconfiguration.DefaultUserLocaleTenantConfiguration; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DefaultUserLocaleTenantConfigurationBuilder extends BaseBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public DefaultUserLocaleTenantConfigurationBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DefaultUserLocaleTenantConfigurationBuilder.class))); + } + + public DefaultUserLocaleTenantConfigurationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + List models = new ArrayList<>(); + for (DefaultUserLocaleTenantConfigurationEntity d : data) { + DefaultUserLocaleTenantConfiguration m = new DefaultUserLocaleTenantConfiguration(); + if (fields.hasField(this.asIndexer(DefaultUserLocaleTenantConfiguration._culture))) m.setCulture(d.getCulture()); + if (fields.hasField(this.asIndexer(DefaultUserLocaleTenantConfiguration._timezone))) m.setTimezone(d.getTimezone()); + if (fields.hasField(this.asIndexer(DefaultUserLocaleTenantConfiguration._language))) m.setLanguage(d.getLanguage()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/DepositTenantConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/DepositTenantConfigurationBuilder.java new file mode 100644 index 000000000..d8025c59f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/DepositTenantConfigurationBuilder.java @@ -0,0 +1,62 @@ +package org.opencdmp.model.builder.tenantconfiguration; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.tenantconfiguration.DepositTenantConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.builder.deposit.DepositSourceBuilder; +import org.opencdmp.model.tenantconfiguration.DepositTenantConfiguration; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DepositTenantConfigurationBuilder extends BaseBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + private final BuilderFactory builderFactory; + + @Autowired + public DepositTenantConfigurationBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(DepositTenantConfigurationBuilder.class))); + this.builderFactory = builderFactory; + } + + public DepositTenantConfigurationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet sourcesFields = fields.extractPrefixed(this.asPrefix(DepositTenantConfiguration._sources)); + + List models = new ArrayList<>(); + for (DepositTenantConfigurationEntity d : data) { + DepositTenantConfiguration m = new DepositTenantConfiguration(); + if (!sourcesFields.isEmpty() && d.getSources() != null){ + if (fields.hasField(this.asIndexer(DepositTenantConfiguration._disableSystemSources))) m.setDisableSystemSources(d.getDisableSystemSources()); + m.setSources(this.builderFactory.builder(DepositSourceBuilder.class).encrypted(true).authorize(this.authorize).build(sourcesFields, d.getSources())); + } + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/FileTransformerTenantConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/FileTransformerTenantConfigurationBuilder.java new file mode 100644 index 000000000..f6017d9fb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/FileTransformerTenantConfigurationBuilder.java @@ -0,0 +1,62 @@ +package org.opencdmp.model.builder.tenantconfiguration; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.tenantconfiguration.FileTransformerTenantConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.builder.filetransformer.FileTransformerSourceBuilder; +import org.opencdmp.model.tenantconfiguration.FileTransformerTenantConfiguration; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FileTransformerTenantConfigurationBuilder extends BaseBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + private final BuilderFactory builderFactory; + + @Autowired + public FileTransformerTenantConfigurationBuilder( + ConventionService conventionService, BuilderFactory builderFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(FileTransformerTenantConfigurationBuilder.class))); + this.builderFactory = builderFactory; + } + + public FileTransformerTenantConfigurationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet sourcesFields = fields.extractPrefixed(this.asPrefix(FileTransformerTenantConfiguration._sources)); + + List models = new ArrayList<>(); + for (FileTransformerTenantConfigurationEntity d : data) { + FileTransformerTenantConfiguration m = new FileTransformerTenantConfiguration(); + if (!sourcesFields.isEmpty() && d.getSources() != null){ + if (fields.hasField(this.asIndexer(FileTransformerTenantConfiguration._disableSystemSources))) m.setDisableSystemSources(d.getDisableSystemSources()); + m.setSources(this.builderFactory.builder(FileTransformerSourceBuilder.class).encrypted(true).authorize(this.authorize).build(sourcesFields, d.getSources())); + } + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/LogoTenantConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/LogoTenantConfigurationBuilder.java new file mode 100644 index 000000000..2feca6dde --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/LogoTenantConfigurationBuilder.java @@ -0,0 +1,100 @@ +package org.opencdmp.model.builder.tenantconfiguration; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.tenantconfiguration.LogoTenantConfigurationEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.StorageFile; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.builder.StorageFileBuilder; +import org.opencdmp.model.tenantconfiguration.LogoTenantConfiguration; +import org.opencdmp.query.StorageFileQuery; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LogoTenantConfigurationBuilder extends BaseBuilder { + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + private final BuilderFactory builderFactory; + private final QueryFactory queryFactory; + + @Autowired + public LogoTenantConfigurationBuilder( + ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(LogoTenantConfigurationBuilder.class))); + this.builderFactory = builderFactory; + this.queryFactory = queryFactory; + } + + public LogoTenantConfigurationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + + FieldSet storageFileFields = fields.extractPrefixed(this.asPrefix(LogoTenantConfiguration._storageFile)); + Map storageFileItemsMap = this.collectStorageFiles(storageFileFields, data); + + + List models = new ArrayList<>(); + for (LogoTenantConfigurationEntity d : data) { + LogoTenantConfiguration m = new LogoTenantConfiguration(); + if (!storageFileFields.isEmpty() && storageFileItemsMap != null && storageFileItemsMap.containsKey(d.getStorageFileId())) m.setStorageFile(storageFileItemsMap.get(d.getStorageFileId())); + + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } + private Map collectStorageFiles(FieldSet fields, List data) throws MyApplicationException { + if (fields.isEmpty() || data.isEmpty()) + return null; + this.logger.debug("checking related - {}", StorageFile.class.getSimpleName()); + + Map itemMap; + if (!fields.hasOtherField(this.asIndexer(StorageFile._id))) { + itemMap = this.asEmpty( + data.stream().map(LogoTenantConfigurationEntity::getStorageFileId).distinct().collect(Collectors.toList()), + x -> { + StorageFile item = new StorageFile(); + item.setId(x); + return item; + }, + StorageFile::getId); + } else { + FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(StorageFile._id); + StorageFileQuery q = this.queryFactory.query(StorageFileQuery.class).authorize(this.authorize).ids(data.stream().map(LogoTenantConfigurationEntity::getStorageFileId).distinct().collect(Collectors.toList())); + itemMap = this.builderFactory.builder(StorageFileBuilder.class).authorize(this.authorize).asForeignKey(q, clone, StorageFile::getId); + } + if (!fields.hasField(StorageFile._id)) { + itemMap.forEach((id, item) -> { + if (item != null) + item.setId(null); + }); + } + + return itemMap; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/TenantConfigurationBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/TenantConfigurationBuilder.java new file mode 100644 index 000000000..cc07ec3c1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/tenantconfiguration/TenantConfigurationBuilder.java @@ -0,0 +1,100 @@ +package org.opencdmp.model.builder.tenantconfiguration; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.JsonHandlingService; +import org.opencdmp.commons.XmlHandlingService; +import org.opencdmp.commons.enums.TenantConfigurationType; +import org.opencdmp.commons.scope.tenant.TenantScope; +import org.opencdmp.commons.types.tenantconfiguration.*; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.data.TenantConfigurationEntity; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.tenantconfiguration.TenantConfiguration; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantConfigurationBuilder extends BaseBuilder { + private final TenantScope tenantScope; + private final JsonHandlingService jsonHandlingService; + + private final BuilderFactory builderFactory; + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public TenantConfigurationBuilder( + ConventionService conventionService, + TenantScope tenantScope, JsonHandlingService jsonHandlingService, BuilderFactory builderFactory1) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(TenantConfigurationBuilder.class))); + this.tenantScope = tenantScope; + this.jsonHandlingService = jsonHandlingService; + this.builderFactory = builderFactory1; + } + + public TenantConfigurationBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + FieldSet cssColorsFields = fields.extractPrefixed(this.asPrefix(TenantConfiguration._cssColors)); + FieldSet defaultUserLocaleFields = fields.extractPrefixed(this.asPrefix(TenantConfiguration._defaultUserLocale)); + FieldSet depositPluginsFields = fields.extractPrefixed(this.asPrefix(TenantConfiguration._depositPlugins)); + FieldSet fileTransformerPluginsFields = fields.extractPrefixed(this.asPrefix(TenantConfiguration._fileTransformerPlugins)); + FieldSet logoFields = fields.extractPrefixed(this.asPrefix(TenantConfiguration._logo)); + + + List models = new ArrayList<>(); + for (TenantConfigurationEntity d : data) { + TenantConfiguration m = new TenantConfiguration(); + if (fields.hasField(this.asIndexer(TenantConfiguration._id))) m.setId(d.getId()); + if (fields.hasField(this.asIndexer(TenantConfiguration._type))) m.setType(d.getType()); + if (!cssColorsFields.isEmpty() && !this.conventionService.isNullOrEmpty(d.getValue()) && TenantConfigurationType.CssColors.equals(d.getType())){ + CssColorsTenantConfigurationEntity valueTyped = this.jsonHandlingService.fromJsonSafe(CssColorsTenantConfigurationEntity.class, d.getValue()); + m.setCssColors(this.builderFactory.builder(CssColorsTenantConfigurationBuilder.class).authorize(this.authorize).build(cssColorsFields, valueTyped)); + } + if (!defaultUserLocaleFields.isEmpty() && !this.conventionService.isNullOrEmpty(d.getValue()) && TenantConfigurationType.DefaultUserLocale.equals(d.getType())){ + DefaultUserLocaleTenantConfigurationEntity valueTyped = this.jsonHandlingService.fromJsonSafe(DefaultUserLocaleTenantConfigurationEntity.class, d.getValue()); + m.setDefaultUserLocale(this.builderFactory.builder(DefaultUserLocaleTenantConfigurationBuilder.class).authorize(this.authorize).build(defaultUserLocaleFields, valueTyped)); + } + if (!depositPluginsFields.isEmpty() && !this.conventionService.isNullOrEmpty(d.getValue()) && TenantConfigurationType.DepositPlugins.equals(d.getType())){ + DepositTenantConfigurationEntity valueTyped = this.jsonHandlingService.fromJsonSafe(DepositTenantConfigurationEntity.class, d.getValue()); + m.setDepositPlugins(this.builderFactory.builder(DepositTenantConfigurationBuilder.class).authorize(this.authorize).build(depositPluginsFields, valueTyped)); + } + if (!fileTransformerPluginsFields.isEmpty() && !this.conventionService.isNullOrEmpty(d.getValue()) && TenantConfigurationType.FileTransformerPlugins.equals(d.getType())){ + FileTransformerTenantConfigurationEntity valueTyped = this.jsonHandlingService.fromJsonSafe(FileTransformerTenantConfigurationEntity.class, d.getValue()); + m.setFileTransformerPlugins(this.builderFactory.builder(FileTransformerTenantConfigurationBuilder.class).authorize(this.authorize).build(fileTransformerPluginsFields, valueTyped)); + } + if (!logoFields.isEmpty() && !this.conventionService.isNullOrEmpty(d.getValue()) && TenantConfigurationType.Logo.equals(d.getType())){ + LogoTenantConfigurationEntity valueTyped = this.jsonHandlingService.fromJsonSafe(LogoTenantConfigurationEntity.class, d.getValue()); + m.setLogo(this.builderFactory.builder(LogoTenantConfigurationBuilder.class).authorize(this.authorize).build(logoFields, valueTyped)); + } + if (fields.hasField(this.asIndexer(TenantConfiguration._createdAt))) m.setCreatedAt(d.getCreatedAt()); + if (fields.hasField(this.asIndexer(TenantConfiguration._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); + if (fields.hasField(this.asIndexer(TenantConfiguration._isActive))) m.setIsActive(d.getIsActive()); + if (fields.hasField(this.asIndexer(TenantConfiguration._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); + if (fields.hasField(this.asIndexer(TenantConfiguration._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/builder/usercredential/UserCredentialDataBuilder.java b/backend/core/src/main/java/org/opencdmp/model/builder/usercredential/UserCredentialDataBuilder.java new file mode 100644 index 000000000..55adc2ba5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/builder/usercredential/UserCredentialDataBuilder.java @@ -0,0 +1,56 @@ +package org.opencdmp.model.builder.usercredential; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.types.usercredential.UserCredentialDataEntity; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.builder.BaseBuilder; +import org.opencdmp.model.usercredential.UserCredentialData; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component() +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserCredentialDataBuilder extends BaseBuilder { + + private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); + + @Autowired + public UserCredentialDataBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(UserCredentialDataBuilder.class))); + } + + public UserCredentialDataBuilder authorize(EnumSet values) { + this.authorize = values; + return this; + } + + @Override + public List build(FieldSet fields, List data) throws MyApplicationException { + this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); + this.logger.trace(new DataLogEntry("requested fields", fields)); + if (fields == null || data == null || fields.isEmpty()) + return new ArrayList<>(); + + //Not Bulk Build because is XML no interaction with db + + List models = new ArrayList<>(); + for (UserCredentialDataEntity d : data) { + UserCredentialData m = new UserCredentialData(); + if (fields.hasField(this.asIndexer(UserCredentialData._email))) m.setEmail(d.getEmail()); + if (fields.hasField(this.asIndexer(UserCredentialData._externalProviderNames))) m.setExternalProviderNames(d.getExternalProviderNames()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/BaseCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/BaseCensor.java new file mode 100644 index 000000000..e4cb0a659 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/BaseCensor.java @@ -0,0 +1,23 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.convention.ConventionService; +import gr.cite.tools.data.censor.Censor; +import gr.cite.tools.fieldset.FieldSet; + +public class BaseCensor implements Censor { + + protected final ConventionService conventionService; + + public BaseCensor(ConventionService conventionService) { + this.conventionService = conventionService; + } + + protected Boolean isEmpty(FieldSet fields) { + return fields == null || fields.isEmpty(); + } + + protected String asIndexerPrefix(String part) { + return this.conventionService.asPrefix(part); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionCensor.java new file mode 100644 index 000000000..57a227fb9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionCensor.java @@ -0,0 +1,64 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Description; +import org.opencdmp.model.censorship.descriptionproperties.PropertyDefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public DescriptionCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescription, Permission.DeferredAffiliation); + + FieldSet descriptionReferenceFields = fields.extractPrefixed(this.asIndexerPrefix(Description._descriptionReferences)); + this.censorFactory.censor(DescriptionReferenceCensor.class).censor(descriptionReferenceFields, userId); + + FieldSet descriptionTagsFields = fields.extractPrefixed(this.asIndexerPrefix(Description._descriptionTags)); + this.censorFactory.censor(DescriptionTagCensor.class).censor(descriptionTagsFields, userId); + + FieldSet dmpDescriptionTemplateFields = fields.extractPrefixed(this.asIndexerPrefix(Description._dmpDescriptionTemplate)); + this.censorFactory.censor(DmpDescriptionTemplateCensor.class).censor(dmpDescriptionTemplateFields, userId); + + FieldSet descriptionTemplateFields = fields.extractPrefixed(this.asIndexerPrefix(Description._descriptionTemplate)); + this.censorFactory.censor(DescriptionTemplateCensor.class).censor(descriptionTemplateFields, userId); + + FieldSet dmpFields = fields.extractPrefixed(this.asIndexerPrefix(Description._dmp)); + this.censorFactory.censor(DmpCensor.class).censor(dmpFields, userId); + + FieldSet propertiesFields = fields.extractPrefixed(this.asIndexerPrefix(Description._properties)); + this.censorFactory.censor(PropertyDefinitionCensor.class).censor(propertiesFields, userId); + + FieldSet createdByFields = fields.extractPrefixed(this.asIndexerPrefix(Description._createdBy)); + this.censorFactory.censor(UserCensor.class).censor(createdByFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionReferenceCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionReferenceCensor.java new file mode 100644 index 000000000..b8f9168c5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionReferenceCensor.java @@ -0,0 +1,53 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DescriptionReference; +import org.opencdmp.model.censorship.descriptionreference.DescriptionReferenceDataCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionReferenceCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionReferenceCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + @Autowired + public DescriptionReferenceCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionReference, Permission.DeferredAffiliation); + FieldSet descriptionFields = fields.extractPrefixed(this.asIndexerPrefix(DescriptionReference._description)); + this.censorFactory.censor(DescriptionCensor.class).censor(descriptionFields, userId); + FieldSet referenceFields = fields.extractPrefixed(this.asIndexerPrefix(DescriptionReference._reference)); + this.censorFactory.censor(ReferenceCensor.class).censor(referenceFields, userId); + FieldSet dataFields = fields.extractPrefixed(this.asIndexerPrefix(DescriptionReference._data)); + this.censorFactory.censor(DescriptionReferenceDataCensor.class).censor(dataFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionTagCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionTagCensor.java new file mode 100644 index 000000000..5803da746 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionTagCensor.java @@ -0,0 +1,51 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DescriptionReference; +import org.opencdmp.model.DescriptionTag; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTagCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTagCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + @Autowired + public DescriptionTagCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTag, Permission.DeferredAffiliation); + FieldSet descriptionFields = fields.extractPrefixed(this.asIndexerPrefix(DescriptionTag._description)); + this.censorFactory.censor(DescriptionCensor.class).censor(descriptionFields, userId); + FieldSet tagFields = fields.extractPrefixed(this.asIndexerPrefix(DescriptionTag._tag)); + this.censorFactory.censor(TagCensor.class).censor(tagFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionTemplateCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionTemplateCensor.java new file mode 100644 index 000000000..8ff0ea9f5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionTemplateCensor.java @@ -0,0 +1,48 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DescriptionTemplate; +import org.opencdmp.model.censorship.descriptiontemplatedefinition.DefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTemplateCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public DescriptionTemplateCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTemplate); + FieldSet definitionFields = fields.extractPrefixed(this.asIndexerPrefix(DescriptionTemplate._definition)); + this.censorFactory.censor(DescriptionTemplateTypeCensor.class).censor(definitionFields, userId); + FieldSet typeFields = fields.extractPrefixed(this.asIndexerPrefix(DescriptionTemplate._type)); + this.censorFactory.censor(DefinitionCensor.class).censor(typeFields, userId); + FieldSet _usersFields = fields.extractPrefixed(this.asIndexerPrefix(DescriptionTemplate._users)); + this.censorFactory.censor(UserDescriptionTemplateCensor.class).censor(_usersFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionTemplateTypeCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionTemplateTypeCensor.java new file mode 100644 index 000000000..4b6d6638b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/DescriptionTemplateTypeCensor.java @@ -0,0 +1,37 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTemplateTypeCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeCensor.class)); + + protected final AuthorizationService authService; + + public DescriptionTemplateTypeCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTemplateType); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/DmpAssociatedUserCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpAssociatedUserCensor.java new file mode 100644 index 000000000..bd341b0c2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpAssociatedUserCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpAssociatedUserCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpAssociatedUserCensor.class)); + + protected final AuthorizationService authService; + + + public DmpAssociatedUserCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseDmpAssociatedUser, Permission.DeferredAffiliation); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/DmpBlueprintCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpBlueprintCensor.java new file mode 100644 index 000000000..5ffa6ccfb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpBlueprintCensor.java @@ -0,0 +1,46 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DmpBlueprint; +import org.opencdmp.model.censorship.dmpblueprintdefinition.DefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpBlueprintCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpBlueprintCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public DmpBlueprintCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmpBlueprint); + FieldSet definitionFields = fields.extractPrefixed(this.asIndexerPrefix(DmpBlueprint._definition)); + this.censorFactory.censor(DefinitionCensor.class).censor(definitionFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/DmpCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpCensor.java new file mode 100644 index 000000000..a28961bde --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpCensor.java @@ -0,0 +1,55 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Dmp; +import org.opencdmp.model.censorship.dmpproperties.DmpPropertiesCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public DmpCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmp, Permission.DeferredAffiliation); + + FieldSet dmpUsersFields = fields.extractPrefixed(this.asIndexerPrefix(Dmp._dmpUsers)); + this.censorFactory.censor(DmpUserCensor.class).censor(dmpUsersFields, userId); + FieldSet dmpReferencesFields = fields.extractPrefixed(this.asIndexerPrefix(Dmp._dmpReferences)); + this.censorFactory.censor(DmpReferenceCensor.class).censor(dmpReferencesFields, userId); + FieldSet creatorFields = fields.extractPrefixed(this.asIndexerPrefix(Dmp._creator)); + this.censorFactory.censor(UserCensor.class).censor(creatorFields, userId); + FieldSet doisFields = fields.extractPrefixed(this.asIndexerPrefix(Dmp._entityDois)); + this.censorFactory.censor(EntityDoiCensor.class).censor(doisFields, userId); + FieldSet propertiesFields = fields.extractPrefixed(this.asIndexerPrefix(Dmp._properties)); + this.censorFactory.censor(DmpPropertiesCensor.class).censor(propertiesFields, userId); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/DmpDescriptionTemplateCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpDescriptionTemplateCensor.java new file mode 100644 index 000000000..99b1c5a3d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpDescriptionTemplateCensor.java @@ -0,0 +1,51 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DmpDescriptionTemplate; +import org.opencdmp.model.DmpReference; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpDescriptionTemplateCensor extends BaseCensor{ + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpDescriptionTemplateCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public DmpDescriptionTemplateCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescription, Permission.DeferredAffiliation); + FieldSet dmpFields = fields.extractPrefixed(this.asIndexerPrefix(DmpDescriptionTemplate._dmp)); + this.censorFactory.censor(DmpCensor.class).censor(dmpFields, userId); + FieldSet descriptionTemplatesFields = fields.extractPrefixed(this.asIndexerPrefix(DmpDescriptionTemplate._descriptionTemplates)); + this.censorFactory.censor(DescriptionTemplateCensor.class).censor(descriptionTemplatesFields, userId); + FieldSet currentDescriptionTemplateFields = fields.extractPrefixed(this.asIndexerPrefix(DmpDescriptionTemplate._currentDescriptionTemplate)); + this.censorFactory.censor(DescriptionTemplateCensor.class).censor(currentDescriptionTemplateFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/DmpReferenceCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpReferenceCensor.java new file mode 100644 index 000000000..804ac363d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpReferenceCensor.java @@ -0,0 +1,50 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DmpReference; +import org.opencdmp.model.censorship.dmpreference.DmpReferenceDataCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpReferenceCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpReferenceCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public DmpReferenceCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmpDescriptionTemplate, Permission.DeferredAffiliation); + FieldSet dmpFields = fields.extractPrefixed(this.asIndexerPrefix(DmpReference._dmp)); + this.censorFactory.censor(DmpCensor.class).censor(dmpFields, userId); + FieldSet templateFields = fields.extractPrefixed(this.asIndexerPrefix(DmpReference._reference)); + this.censorFactory.censor(ReferenceCensor.class).censor(templateFields, userId); + FieldSet dataFields = fields.extractPrefixed(this.asIndexerPrefix(DmpReference._data)); + this.censorFactory.censor(DmpReferenceDataCensor.class).censor(dataFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/DmpUserCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpUserCensor.java new file mode 100644 index 000000000..6397e2776 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/DmpUserCensor.java @@ -0,0 +1,47 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DmpDescriptionTemplate; +import org.opencdmp.model.DmpUser; +import org.opencdmp.model.UserDescriptionTemplate; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpUserCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpUserCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public DmpUserCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmpUser, Permission.DeferredAffiliation); + FieldSet dmpFields = fields.extractPrefixed(this.asIndexerPrefix(DmpUser._dmp)); + this.censorFactory.censor(DmpCensor.class).censor(dmpFields, userId); + FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(DmpUser._user)); + this.censorFactory.censor(UserCensor.class).censor(userFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/EntityDoiCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/EntityDoiCensor.java new file mode 100644 index 000000000..2e1696a7d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/EntityDoiCensor.java @@ -0,0 +1,36 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class EntityDoiCensor extends BaseCensor{ + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(EntityDoiCensor.class)); + + protected final AuthorizationService authService; + + public EntityDoiCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseEntityDoi, Permission.DeferredAffiliation); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/LanguageCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/LanguageCensor.java new file mode 100644 index 000000000..2c5ff9215 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/LanguageCensor.java @@ -0,0 +1,42 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LanguageCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(LanguageCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public LanguageCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseLanguage); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/LockCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/LockCensor.java new file mode 100644 index 000000000..cd6eeda5f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/LockCensor.java @@ -0,0 +1,49 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Lock; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.exception.MyForbiddenException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LockCensor extends BaseCensor { + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(LockCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + @Autowired + public LockCensor( + ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory + ) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) throws MyForbiddenException { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (this.isEmpty(fields)) return; + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseLock); + FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(Lock._lockedBy)); + this.censorFactory.censor(UserCensor.class).censor(userFields, userId); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/MyDashboardStatisticsCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/MyDashboardStatisticsCensor.java new file mode 100644 index 000000000..e981abcb3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/MyDashboardStatisticsCensor.java @@ -0,0 +1,33 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.convention.ConventionService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class MyDashboardStatisticsCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(MyDashboardStatisticsCensor.class)); + + protected final AuthorizationService authService; + + + public MyDashboardStatisticsCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(UUID userId) { + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PrefillingCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PrefillingCensor.java new file mode 100644 index 000000000..71197f8e8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PrefillingCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PrefillingCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PrefillingCensor.class)); + + protected final AuthorizationService authService; + + + public PrefillingCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowsePrefilling); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PrefillingSourceCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PrefillingSourceCensor.java new file mode 100644 index 000000000..195e18e55 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PrefillingSourceCensor.java @@ -0,0 +1,46 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.PrefillingSource; +import org.opencdmp.model.censorship.referencetypedefinition.ReferenceTypeDefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PrefillingSourceCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PrefillingSourceCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public PrefillingSourceCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowsePrefillingSource); + FieldSet definitionFields = fields.extractPrefixed(this.asIndexerPrefix(PrefillingSource._definition)); + this.censorFactory.censor(ReferenceTypeDefinitionCensor.class).censor(definitionFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDashboardStatisticsCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDashboardStatisticsCensor.java new file mode 100644 index 000000000..7570dd462 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDashboardStatisticsCensor.java @@ -0,0 +1,34 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDashboardStatisticsCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PublicDashboardStatisticsCensor.class)); + + protected final AuthorizationService authService; + + + public PublicDashboardStatisticsCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(UUID userId) { + this.authService.authorizeForce(Permission.PublicBrowseDashboardStatistics); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDescriptionCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDescriptionCensor.java new file mode 100644 index 000000000..5a37835f1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDescriptionCensor.java @@ -0,0 +1,51 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Description; +import org.opencdmp.model.PublicDescription; +import org.opencdmp.model.censorship.descriptionproperties.PropertyDefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDescriptionCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PublicDescriptionCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public PublicDescriptionCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.PublicBrowseDescription); + + FieldSet dmpDescriptionTemplateFields = fields.extractPrefixed(this.asIndexerPrefix(PublicDescription._dmpDescriptionTemplate)); + this.censorFactory.censor(PublicDmpDescriptionTemplateCensor.class).censor(dmpDescriptionTemplateFields); + + FieldSet descriptionTemplateFields = fields.extractPrefixed(this.asIndexerPrefix(PublicDescription._descriptionTemplate)); + this.censorFactory.censor(PublicDescriptionTemplateCensor.class).censor(descriptionTemplateFields); + + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDescriptionTemplateCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDescriptionTemplateCensor.java new file mode 100644 index 000000000..6e35a4483 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDescriptionTemplateCensor.java @@ -0,0 +1,42 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.PublicDescriptionTemplate; +import org.opencdmp.model.censorship.descriptiontemplatedefinition.DefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDescriptionTemplateCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PublicDescriptionTemplateCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public PublicDescriptionTemplateCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.PublicBrowseDescriptionTemplate); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpCensor.java new file mode 100644 index 000000000..d0993170b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpCensor.java @@ -0,0 +1,49 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.PublicDmp; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDmpCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PublicDmpCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public PublicDmpCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.PublicBrowseDmp); + + FieldSet dmpDescriptionsFields = fields.extractPrefixed(this.asIndexerPrefix(PublicDmp._dmpUsers)); + this.censorFactory.censor(PublicDmpUserCensor.class).censor(dmpDescriptionsFields); + FieldSet dmpReferencesFields = fields.extractPrefixed(this.asIndexerPrefix(PublicDmp._dmpReferences)); + this.censorFactory.censor(PublicDmpReferenceCensor.class).censor(dmpReferencesFields); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpDescriptionTemplateCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpDescriptionTemplateCensor.java new file mode 100644 index 000000000..514cf8d55 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpDescriptionTemplateCensor.java @@ -0,0 +1,48 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DmpDescriptionTemplate; +import org.opencdmp.model.DmpReference; +import org.opencdmp.model.PublicDmpDescriptionTemplate; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDmpDescriptionTemplateCensor extends BaseCensor{ + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PublicDmpDescriptionTemplateCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public PublicDmpDescriptionTemplateCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.PublicBrowseDescription); + FieldSet dmpFields = fields.extractPrefixed(this.asIndexerPrefix(PublicDmpDescriptionTemplate._dmp)); + this.censorFactory.censor(PublicDmpCensor.class).censor(dmpFields); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpReferenceCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpReferenceCensor.java new file mode 100644 index 000000000..dbd5129dd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpReferenceCensor.java @@ -0,0 +1,49 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DmpDescriptionTemplate; +import org.opencdmp.model.PublicDmpDescriptionTemplate; +import org.opencdmp.model.PublicDmpReference; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDmpReferenceCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PublicDmpReferenceCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public PublicDmpReferenceCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.PublicBrowseDmpReference); + FieldSet dmpFields = fields.extractPrefixed(this.asIndexerPrefix(PublicDmpReference._dmp)); + this.censorFactory.censor(PublicDmpCensor.class).censor(dmpFields); + FieldSet templateFields = fields.extractPrefixed(this.asIndexerPrefix(PublicDmpReference._reference)); + this.censorFactory.censor(PublicReferenceCensor.class).censor(templateFields); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpUserCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpUserCensor.java new file mode 100644 index 000000000..cd65aa18e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicDmpUserCensor.java @@ -0,0 +1,43 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.PublicDmpUser; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicDmpUserCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PublicDmpUserCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public PublicDmpUserCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.PublicBrowseDmpUser); + FieldSet dmpFields = fields.extractPrefixed(this.asIndexerPrefix(PublicDmpUser._dmp)); + this.censorFactory.censor(PublicDmpCensor.class).censor(dmpFields); + FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(PublicDmpUser._user)); + this.censorFactory.censor(PublicUserCensor.class).censor(userFields); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PublicReferenceCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicReferenceCensor.java new file mode 100644 index 000000000..c773be935 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicReferenceCensor.java @@ -0,0 +1,48 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.PublicDmpUser; +import org.opencdmp.model.PublicReference; +import org.opencdmp.model.Reference; +import org.opencdmp.model.censorship.referencedefinition.DefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicReferenceCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PublicReferenceCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public PublicReferenceCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.PublicBrowseReference); + FieldSet typeFields = fields.extractPrefixed(this.asIndexerPrefix(PublicReference._type)); + this.censorFactory.censor(PublicReferenceCensor.class).censor(typeFields); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PublicReferenceTypeCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicReferenceTypeCensor.java new file mode 100644 index 000000000..f5ae8405d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicReferenceTypeCensor.java @@ -0,0 +1,41 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.PublicDmpUser; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicReferenceTypeCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PublicReferenceTypeCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public PublicReferenceTypeCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.PublicBrowseReferenceType); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/PublicUserCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicUserCensor.java new file mode 100644 index 000000000..994b4cbce --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/PublicUserCensor.java @@ -0,0 +1,40 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PublicUserCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PublicUserCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public PublicUserCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.PublicBrowseUser); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/RecentActivityItemCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/RecentActivityItemCensor.java new file mode 100644 index 000000000..ac21b57ea --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/RecentActivityItemCensor.java @@ -0,0 +1,45 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.RecentActivityItem; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class RecentActivityItemCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(RecentActivityItemCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public RecentActivityItemCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + FieldSet dmpFields = fields.extractPrefixed(this.asIndexerPrefix(RecentActivityItem._dmp)); + this.censorFactory.censor(DmpCensor.class).censor(dmpFields, userId); + + FieldSet descriptionFields = fields.extractPrefixed(this.asIndexerPrefix(RecentActivityItem._description)); + this.censorFactory.censor(DescriptionCensor.class).censor(descriptionFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/ReferenceCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/ReferenceCensor.java new file mode 100644 index 000000000..9f53d76df --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/ReferenceCensor.java @@ -0,0 +1,52 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Reference; +import org.opencdmp.model.censorship.referencedefinition.DefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public ReferenceCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReference, Permission.DeferredAffiliation); + FieldSet definitionFields = fields.extractPrefixed(this.asIndexerPrefix(Reference._definition)); + this.censorFactory.censor(DefinitionCensor.class).censor(definitionFields, userId); + FieldSet dmpReferencesFields = fields.extractPrefixed(this.asIndexerPrefix(Reference._dmpReferences)); + this.censorFactory.censor(DmpReferenceCensor.class).censor(dmpReferencesFields, userId); + FieldSet createdByFields = fields.extractPrefixed(this.asIndexerPrefix(Reference._createdBy)); + this.censorFactory.censor(UserCensor.class).censor(createdByFields, userId); + FieldSet typeFields = fields.extractPrefixed(this.asIndexerPrefix(Reference._type)); + this.censorFactory.censor(ReferenceTypeCensor.class).censor(typeFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/ReferenceTypeCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/ReferenceTypeCensor.java new file mode 100644 index 000000000..ce3bb8036 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/ReferenceTypeCensor.java @@ -0,0 +1,46 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.ReferenceType; +import org.opencdmp.model.censorship.referencetypedefinition.ReferenceTypeDefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceTypeCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public ReferenceTypeCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReferenceType, Permission.DeferredAffiliation); + FieldSet definitionFields = fields.extractPrefixed(this.asIndexerPrefix(ReferenceType._definition)); + this.censorFactory.censor(ReferenceTypeDefinitionCensor.class).censor(definitionFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/StorageFileCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/StorageFileCensor.java new file mode 100644 index 000000000..5a0fa07a6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/StorageFileCensor.java @@ -0,0 +1,45 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.StorageFile; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class StorageFileCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(StorageFileCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public StorageFileCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseStorageFile); + + FieldSet ownerFields = fields.extractPrefixed(this.asIndexerPrefix(StorageFile._owner)); + this.censorFactory.censor(UserCensor.class).censor(ownerFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/SupportiveMaterialCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/SupportiveMaterialCensor.java new file mode 100644 index 000000000..dbfb8884d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/SupportiveMaterialCensor.java @@ -0,0 +1,44 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DmpBlueprint; +import org.opencdmp.model.censorship.dmpblueprintdefinition.DefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SupportiveMaterialCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(SupportiveMaterialCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public SupportiveMaterialCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseSupportiveMaterial); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/TagCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/TagCensor.java new file mode 100644 index 000000000..a849b9d06 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/TagCensor.java @@ -0,0 +1,47 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Reference; +import org.opencdmp.model.Tag; +import org.opencdmp.model.censorship.referencedefinition.DefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TagCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TagCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public TagCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseTag, Permission.DeferredAffiliation); + FieldSet createdByFields = fields.extractPrefixed(this.asIndexerPrefix(Tag._createdBy)); + this.censorFactory.censor(UserCensor.class).censor(createdByFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/TenantCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/TenantCensor.java new file mode 100644 index 000000000..b5e4cdc39 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/TenantCensor.java @@ -0,0 +1,42 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public TenantCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseTenant); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/TenantUserCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/TenantUserCensor.java new file mode 100644 index 000000000..547080eec --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/TenantUserCensor.java @@ -0,0 +1,51 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.TenantUser; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.exception.MyForbiddenException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantUserCensor extends BaseCensor { + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantUserCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + @Autowired + public TenantUserCensor( + ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory + ) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) throws MyForbiddenException { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (this.isEmpty(fields)) return; + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseTenantUser); + FieldSet tenantFields = fields.extractPrefixed(this.asIndexerPrefix(TenantUser._tenant)); + this.censorFactory.censor(TenantCensor.class).censor(tenantFields, null); + FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(TenantUser._user)); + this.censorFactory.censor(UserCensor.class).censor(userFields, userId); + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/UserAdditionalInfoCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/UserAdditionalInfoCensor.java new file mode 100644 index 000000000..fd001f7b6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/UserAdditionalInfoCensor.java @@ -0,0 +1,47 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.UserAdditionalInfo; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserAdditionalInfoCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserAdditionalInfoCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + + public UserAdditionalInfoCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseUser); + + FieldSet descriptionReferenceFields = fields.extractPrefixed(this.asIndexerPrefix(UserAdditionalInfo._organization)); + this.censorFactory.censor(ReferenceCensor.class).censor(descriptionReferenceFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/UserCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/UserCensor.java new file mode 100644 index 000000000..bd47c1a44 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/UserCensor.java @@ -0,0 +1,61 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.User; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public UserCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseUser, Permission.DeferredAffiliation); + + FieldSet globalRolesFields = fields.extractPrefixed(this.asIndexerPrefix(User._globalRoles)); + this.censorFactory.censor(UserRoleCensor.class).censor(globalRolesFields, userId); + + FieldSet tenantRolesFields = fields.extractPrefixed(this.asIndexerPrefix(User._tenantRoles)); + this.censorFactory.censor(UserRoleCensor.class).censor(tenantRolesFields, userId); + + FieldSet contactsFields = fields.extractPrefixed(this.asIndexerPrefix(User._contacts)); + this.censorFactory.censor(UserContactInfoCensor.class).censor(contactsFields, userId); + + FieldSet credentialsFields = fields.extractPrefixed(this.asIndexerPrefix(User._credentials)); + this.censorFactory.censor(UserCredentialCensor.class).censor(credentialsFields, userId); + + FieldSet additionalInfoFields = fields.extractPrefixed(this.asIndexerPrefix(User._additionalInfo)); + this.censorFactory.censor(UserAdditionalInfoCensor.class).censor(additionalInfoFields, userId); + + FieldSet tenantUsersFields = fields.extractPrefixed(this.asIndexerPrefix(User._tenantUsers)); + this.censorFactory.censor(TenantUserCensor.class).censor(tenantUsersFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/UserContactInfoCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/UserContactInfoCensor.java new file mode 100644 index 000000000..dbf5e402c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/UserContactInfoCensor.java @@ -0,0 +1,46 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.UserContactInfo; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserContactInfoCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserContactInfoCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public UserContactInfoCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseUser); + + FieldSet descriptionReferenceFields = fields.extractPrefixed(this.asIndexerPrefix(UserContactInfo._user)); + this.censorFactory.censor(DescriptionReferenceCensor.class).censor(descriptionReferenceFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/UserCredentialCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/UserCredentialCensor.java new file mode 100644 index 000000000..97605fff9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/UserCredentialCensor.java @@ -0,0 +1,50 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.UserCredential; +import org.opencdmp.model.censorship.usercredential.UserCredentialDataCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserCredentialCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserCredentialCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public UserCredentialCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseUser); + + FieldSet descriptionReferenceFields = fields.extractPrefixed(this.asIndexerPrefix(UserCredential._user)); + this.censorFactory.censor(DescriptionReferenceCensor.class).censor(descriptionReferenceFields, userId); + + FieldSet dataFields = fields.extractPrefixed(this.asIndexerPrefix(UserCredential._data)); + this.censorFactory.censor(UserCredentialDataCensor.class).censor(dataFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/UserDescriptionTemplateCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/UserDescriptionTemplateCensor.java new file mode 100644 index 000000000..b63632725 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/UserDescriptionTemplateCensor.java @@ -0,0 +1,47 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.DescriptionTemplate; +import org.opencdmp.model.UserDescriptionTemplate; +import org.opencdmp.model.censorship.descriptiontemplatedefinition.DefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserDescriptionTemplateCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserDescriptionTemplateCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public UserDescriptionTemplateCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTemplate); + FieldSet descriptionTemplateFields = fields.extractPrefixed(this.asIndexerPrefix(UserDescriptionTemplate._descriptionTemplate)); + this.censorFactory.censor(DescriptionTemplateCensor.class).censor(descriptionTemplateFields, userId); + FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(UserDescriptionTemplate._user)); + this.censorFactory.censor(UserCensor.class).censor(userFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/UserRoleCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/UserRoleCensor.java new file mode 100644 index 000000000..1a6720e1a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/UserRoleCensor.java @@ -0,0 +1,48 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Description; +import org.opencdmp.model.censorship.descriptionproperties.PropertyDefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; +import org.opencdmp.model.UserRole; + +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserRoleCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserRoleCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public UserRoleCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseUser); + + FieldSet descriptionReferenceFields = fields.extractPrefixed(this.asIndexerPrefix(UserRole._user)); + this.censorFactory.censor(DescriptionReferenceCensor.class).censor(descriptionReferenceFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/UserSettingsCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/UserSettingsCensor.java new file mode 100644 index 000000000..1d7459aa2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/UserSettingsCensor.java @@ -0,0 +1,41 @@ +package org.opencdmp.model.censorship; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.exception.MyForbiddenException; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserSettingsCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserSettingsCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public UserSettingsCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) throws MyForbiddenException { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (this.isEmpty(fields)) return; + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseUserSettings); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/deposit/DepositConfigurationCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/deposit/DepositConfigurationCensor.java new file mode 100644 index 000000000..c09ad03fd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/deposit/DepositConfigurationCensor.java @@ -0,0 +1,43 @@ +package org.opencdmp.model.censorship.deposit; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Description; +import org.opencdmp.model.censorship.*; +import org.opencdmp.model.censorship.descriptionproperties.PropertyDefinitionCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DepositConfigurationCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DepositConfigurationCensor.class)); + + protected final AuthorizationService authService; + + + public DepositConfigurationCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDeposit, Permission.DeferredAffiliation); + + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/deposit/DepositSourceCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/deposit/DepositSourceCensor.java new file mode 100644 index 000000000..bad1abaa0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/deposit/DepositSourceCensor.java @@ -0,0 +1,38 @@ +package org.opencdmp.model.censorship.deposit; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DepositSourceCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DepositSourceCensor.class)); + + protected final AuthorizationService authService; + + + public DepositSourceCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorize(Permission.BrowseTenantConfiguration); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/FieldCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/FieldCensor.java new file mode 100644 index 000000000..fd2e0e147 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/FieldCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship.descriptionproperties; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("description.FieldCensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FieldCensor.class)); + + protected final AuthorizationService authService; + + public FieldCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescription, Permission.DeferredAffiliation); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/PropertyDefinitionCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/PropertyDefinitionCensor.java new file mode 100644 index 000000000..4b745d41b --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/PropertyDefinitionCensor.java @@ -0,0 +1,49 @@ +package org.opencdmp.model.censorship.descriptionproperties; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Description; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.censorship.dmpblueprintdefinition.SectionCensor; +import org.opencdmp.model.descriptionproperties.PropertyDefinition; +import org.opencdmp.model.dmpblueprintdefinition.Definition; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("description.PropertyDefinitionCensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PropertyDefinitionCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PropertyDefinitionCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public PropertyDefinitionCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescription, Permission.DeferredAffiliation); + FieldSet fieldSetFields = fields.extractPrefixed(this.asIndexerPrefix(PropertyDefinition._fieldSets)); + this.censorFactory.censor(PropertyDefinitionFieldSetCensor.class).censor(fieldSetFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/PropertyDefinitionFieldSetCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/PropertyDefinitionFieldSetCensor.java new file mode 100644 index 000000000..75d73c772 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/PropertyDefinitionFieldSetCensor.java @@ -0,0 +1,47 @@ +package org.opencdmp.model.censorship.descriptionproperties; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.descriptionproperties.PropertyDefinition; +import org.opencdmp.model.descriptionproperties.PropertyDefinitionFieldSet; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("description.PropertyDefinitionFieldSetCensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PropertyDefinitionFieldSetCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PropertyDefinitionFieldSetCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public PropertyDefinitionFieldSetCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescription, Permission.DeferredAffiliation); + FieldSet itemsFields = fields.extractPrefixed(this.asIndexerPrefix(PropertyDefinitionFieldSet._items)); + this.censorFactory.censor(PropertyDefinitionFieldSetItemCensor.class).censor(itemsFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/PropertyDefinitionFieldSetItemCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/PropertyDefinitionFieldSetItemCensor.java new file mode 100644 index 000000000..50e173d04 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionproperties/PropertyDefinitionFieldSetItemCensor.java @@ -0,0 +1,47 @@ +package org.opencdmp.model.censorship.descriptionproperties; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.descriptionproperties.PropertyDefinition; +import org.opencdmp.model.descriptionproperties.PropertyDefinitionFieldSetItem; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("description.PropertyDefinitionFieldSetItemCensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PropertyDefinitionFieldSetItemCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PropertyDefinitionFieldSetItemCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public PropertyDefinitionFieldSetItemCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescription, Permission.DeferredAffiliation); + FieldSet fieldFields = fields.extractPrefixed(this.asIndexerPrefix(PropertyDefinitionFieldSetItem._fields)); + this.censorFactory.censor(FieldCensor.class).censor(fieldFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionreference/DescriptionReferenceDataCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionreference/DescriptionReferenceDataCensor.java new file mode 100644 index 000000000..b791a3f72 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptionreference/DescriptionReferenceDataCensor.java @@ -0,0 +1,42 @@ +package org.opencdmp.model.censorship.descriptionreference; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionReferenceDataCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionReferenceDataCensor.class)); + + protected final AuthorizationService authService; + + + @Autowired + public DescriptionReferenceDataCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionReference, Permission.DeferredAffiliation); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/DefinitionCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/DefinitionCensor.java new file mode 100644 index 000000000..b487deb53 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/DefinitionCensor.java @@ -0,0 +1,46 @@ +package org.opencdmp.model.censorship.descriptiontemplatedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.descriptiontemplatedefinition.Definition; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("descriptiontemplatedefinitioncensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DefinitionCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DefinitionCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public DefinitionCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTemplate); + FieldSet pagesFields = fields.extractPrefixed(this.asIndexerPrefix(Definition._pages)); + this.censorFactory.censor(PageCensor.class).censor(pagesFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/FieldCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/FieldCensor.java new file mode 100644 index 000000000..e829f73f9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/FieldCensor.java @@ -0,0 +1,49 @@ +package org.opencdmp.model.censorship.descriptiontemplatedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; +import org.opencdmp.model.descriptiontemplatedefinition.Field; + +import java.util.UUID; + +@Component("descriptiontemplatedefinitionfieldcensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FieldCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public FieldCensor(ConventionService conventionService, + AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTemplate); + + FieldSet multiplicityFields = fields.extractPrefixed(this.asIndexerPrefix(Field._visibilityRules)); + this.censorFactory.censor(RuleCensor.class).censor(multiplicityFields, userId); + + FieldSet fieldFields = fields.extractPrefixed(this.asIndexerPrefix(Field._data)); + this.censorFactory.censor(FieldDataCensor.class).censor(fieldFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/FieldDataCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/FieldDataCensor.java new file mode 100644 index 000000000..196df4a6a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/FieldDataCensor.java @@ -0,0 +1,40 @@ +package org.opencdmp.model.censorship.descriptiontemplatedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldDataCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FieldDataCensor.class)); + + protected final AuthorizationService authService; + + public FieldDataCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTemplate); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/FieldSetCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/FieldSetCensor.java new file mode 100644 index 000000000..156ad8eaf --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/FieldSetCensor.java @@ -0,0 +1,48 @@ +package org.opencdmp.model.censorship.descriptiontemplatedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldSetCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FieldSetCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public FieldSetCensor(ConventionService conventionService, + AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTemplate); + + FieldSet multiplicityFields = fields.extractPrefixed(this.asIndexerPrefix(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._multiplicity)); + this.censorFactory.censor(MultiplicityCensor.class).censor(multiplicityFields, userId); + + FieldSet fieldsFields = fields.extractPrefixed(this.asIndexerPrefix(org.opencdmp.model.descriptiontemplatedefinition.FieldSet._fields)); + this.censorFactory.censor(FieldCensor.class).censor(fieldsFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/MultiplicityCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/MultiplicityCensor.java new file mode 100644 index 000000000..442ffede4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/MultiplicityCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship.descriptiontemplatedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class MultiplicityCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(MultiplicityCensor.class)); + + protected final AuthorizationService authService; + + public MultiplicityCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTemplate); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/PageCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/PageCensor.java new file mode 100644 index 000000000..9dc53fb07 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/PageCensor.java @@ -0,0 +1,47 @@ +package org.opencdmp.model.censorship.descriptiontemplatedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.descriptiontemplatedefinition.Definition; +import org.opencdmp.model.descriptiontemplatedefinition.Page; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PageCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PageCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public PageCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTemplate); + FieldSet sectionsFields = fields.extractPrefixed(this.asIndexerPrefix(Page._sections)); + this.censorFactory.censor(SectionCensor.class).censor(sectionsFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/RuleCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/RuleCensor.java new file mode 100644 index 000000000..771da7e8a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/RuleCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship.descriptiontemplatedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class RuleCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(RuleCensor.class)); + + protected final AuthorizationService authService; + + public RuleCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTemplate); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/SectionCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/SectionCensor.java new file mode 100644 index 000000000..36982a222 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/descriptiontemplatedefinition/SectionCensor.java @@ -0,0 +1,46 @@ +package org.opencdmp.model.censorship.descriptiontemplatedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.descriptiontemplatedefinition.Section; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("descriptiontemplatedefinitionsectioncensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SectionCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(SectionCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public SectionCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDescriptionTemplate); + FieldSet fieldsFields = fields.extractPrefixed(this.asIndexerPrefix(Section._fieldSets)); + this.censorFactory.censor(FieldSetCensor.class).censor(fieldsFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/DefinitionCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/DefinitionCensor.java new file mode 100644 index 000000000..7dd7634c9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/DefinitionCensor.java @@ -0,0 +1,46 @@ +package org.opencdmp.model.censorship.dmpblueprintdefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.dmpblueprintdefinition.Definition; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("dmpblueprintdefinitioncensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DefinitionCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DefinitionCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public DefinitionCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmpBlueprint); + FieldSet sectionsFields = fields.extractPrefixed(this.asIndexerPrefix(Definition._sections)); + this.censorFactory.censor(SectionCensor.class).censor(sectionsFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/DescriptionTemplatesCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/DescriptionTemplatesCensor.java new file mode 100644 index 000000000..af2eee758 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/DescriptionTemplatesCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship.dmpblueprintdefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("dmpblueprintdefinitiondescriptiontemplatecensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTemplatesCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplatesCensor.class)); + + protected final AuthorizationService authService; + + public DescriptionTemplatesCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmpBlueprint); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/FieldCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/FieldCensor.java new file mode 100644 index 000000000..7ae569354 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/FieldCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship.dmpblueprintdefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("dmpblueprintdefinitionfieldcensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FieldCensor.class)); + + protected final AuthorizationService authService; + + public FieldCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmpBlueprint); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/SectionCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/SectionCensor.java new file mode 100644 index 000000000..d553bf928 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpblueprintdefinition/SectionCensor.java @@ -0,0 +1,48 @@ +package org.opencdmp.model.censorship.dmpblueprintdefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.dmpblueprintdefinition.Section; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("dmpblueprintdefinitionsectioncensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SectionCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(SectionCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public SectionCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmpBlueprint); + FieldSet fieldsFields = fields.extractPrefixed(this.asIndexerPrefix(Section._fields)); + this.censorFactory.censor(FieldCensor.class).censor(fieldsFields, userId); + FieldSet descriptionTemplatesFields = fields.extractPrefixed(this.asIndexerPrefix(Section._descriptionTemplates)); + this.censorFactory.censor(DescriptionTemplatesCensor.class).censor(descriptionTemplatesFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/dmpproperties/DmpBlueprintValueCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpproperties/DmpBlueprintValueCensor.java new file mode 100644 index 000000000..d029c2095 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpproperties/DmpBlueprintValueCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship.dmpproperties; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("dmpblueprintvaluecensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpBlueprintValueCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpBlueprintValueCensor.class)); + + protected final AuthorizationService authService; + + public DmpBlueprintValueCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmp, Permission.DeferredAffiliation); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/dmpproperties/DmpContactCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpproperties/DmpContactCensor.java new file mode 100644 index 000000000..b060d4ae1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpproperties/DmpContactCensor.java @@ -0,0 +1,46 @@ +package org.opencdmp.model.censorship.dmpproperties; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.censorship.UserCensor; +import org.opencdmp.model.dmpproperties.DmpContact; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("dmpcontactcensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpContactCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpContactCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public DmpContactCensor(ConventionService conventionService, + AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmp, Permission.DeferredAffiliation); + FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(DmpContact._user)); + this.censorFactory.censor(UserCensor.class).censor(userFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/dmpproperties/DmpPropertiesCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpproperties/DmpPropertiesCensor.java new file mode 100644 index 000000000..c4a8612ba --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpproperties/DmpPropertiesCensor.java @@ -0,0 +1,48 @@ +package org.opencdmp.model.censorship.dmpproperties; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.dmpproperties.DmpProperties; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("dmppropertiescensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpPropertiesCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpPropertiesCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public DmpPropertiesCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmp, Permission.DeferredAffiliation); + FieldSet dmpBlueprintValuesFields = fields.extractPrefixed(this.asIndexerPrefix(DmpProperties._dmpBlueprintValues)); + this.censorFactory.censor(DmpBlueprintValueCensor.class).censor(dmpBlueprintValuesFields, userId); + FieldSet contactsFields = fields.extractPrefixed(this.asIndexerPrefix(DmpProperties._contacts)); + this.censorFactory.censor(DmpContactCensor.class).censor(contactsFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/dmpreference/DmpReferenceDataCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpreference/DmpReferenceDataCensor.java new file mode 100644 index 000000000..706b92ee4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/dmpreference/DmpReferenceDataCensor.java @@ -0,0 +1,42 @@ +package org.opencdmp.model.censorship.dmpreference; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpReferenceDataCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpReferenceDataCensor.class)); + + protected final AuthorizationService authService; + + + @Autowired + public DmpReferenceDataCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseDmpDescriptionTemplate, Permission.DeferredAffiliation); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/filetransformer/FileTransformerSourceCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/filetransformer/FileTransformerSourceCensor.java new file mode 100644 index 000000000..44e787b17 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/filetransformer/FileTransformerSourceCensor.java @@ -0,0 +1,40 @@ +package org.opencdmp.model.censorship.filetransformer; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.censorship.deposit.DepositSourceCensor; +import org.opencdmp.model.tenantconfiguration.DepositTenantConfiguration; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FileTransformerSourceCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FileTransformerSourceCensor.class)); + + protected final AuthorizationService authService; + + + public FileTransformerSourceCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorize(Permission.BrowseTenantConfiguration); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/referencedefinition/DefinitionCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/referencedefinition/DefinitionCensor.java new file mode 100644 index 000000000..300bb0e35 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/referencedefinition/DefinitionCensor.java @@ -0,0 +1,46 @@ +package org.opencdmp.model.censorship.referencedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.referencedefinition.Definition; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("referencedefinitioncensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DefinitionCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DefinitionCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public DefinitionCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReference, Permission.DeferredAffiliation); + FieldSet fieldsFields = fields.extractPrefixed(this.asIndexerPrefix(Definition._fields)); + this.censorFactory.censor(FieldCensor.class).censor(fieldsFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/referencedefinition/FieldCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/referencedefinition/FieldCensor.java new file mode 100644 index 000000000..a71978019 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/referencedefinition/FieldCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship.referencedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component("referencedefinitionfieldcensor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FieldCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FieldCensor.class)); + + protected final AuthorizationService authService; + + public FieldCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReference, Permission.DeferredAffiliation); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/AuthenticationConfigurationCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/AuthenticationConfigurationCensor.java new file mode 100644 index 000000000..392ef2234 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/AuthenticationConfigurationCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship.referencetypedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class AuthenticationConfigurationCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(AuthenticationConfigurationCensor.class)); + + protected final AuthorizationService authService; + + public AuthenticationConfigurationCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReferenceType); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/QueryCaseConfigCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/QueryCaseConfigCensor.java new file mode 100644 index 000000000..1414033e7 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/QueryCaseConfigCensor.java @@ -0,0 +1,46 @@ +package org.opencdmp.model.censorship.referencetypedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.censorship.ReferenceTypeCensor; +import org.opencdmp.model.externalfetcher.QueryCaseConfig; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class QueryCaseConfigCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(QueryCaseConfigCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public QueryCaseConfigCensor(ConventionService conventionService, + AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReferenceType); + FieldSet referenceTypeFields = fields.extractPrefixed(this.asIndexerPrefix(QueryCaseConfig._referenceType)); + this.censorFactory.censor(ReferenceTypeCensor.class).censor(referenceTypeFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/QueryConfigCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/QueryConfigCensor.java new file mode 100644 index 000000000..bb7b4ea40 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/QueryConfigCensor.java @@ -0,0 +1,45 @@ +package org.opencdmp.model.censorship.referencetypedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.externalfetcher.QueryConfig; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class QueryConfigCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(QueryConfigCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public QueryConfigCensor(ConventionService conventionService, + AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReferenceType); + FieldSet casesFields = fields.extractPrefixed(this.asIndexerPrefix(QueryConfig._cases)); + this.censorFactory.censor(QueryCaseConfigCensor.class).censor(casesFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeDefinitionCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeDefinitionCensor.java new file mode 100644 index 000000000..cd3711367 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeDefinitionCensor.java @@ -0,0 +1,49 @@ +package org.opencdmp.model.censorship.referencetypedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.referencetypedefinition.ReferenceTypeDefinition; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeDefinitionCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceTypeDefinitionCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public ReferenceTypeDefinitionCensor(ConventionService conventionService, + AuthorizationService authService, + CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReferenceType); + FieldSet fieldsFields = fields.extractPrefixed(this.asIndexerPrefix(ReferenceTypeDefinition._fields)); + this.censorFactory.censor(ReferenceTypeFieldCensor.class).censor(fieldsFields, userId); + + FieldSet sourcesFields = fields.extractPrefixed(this.asIndexerPrefix(ReferenceTypeDefinition._sources)); + this.censorFactory.censor(ReferenceTypeSourceBaseConfigurationCensor.class).censor(sourcesFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeFieldCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeFieldCensor.java new file mode 100644 index 000000000..b6018fe36 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeFieldCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship.referencetypedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeFieldCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceTypeFieldCensor.class)); + + protected final AuthorizationService authService; + + public ReferenceTypeFieldCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReferenceType); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeSourceBaseConfigurationCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeSourceBaseConfigurationCensor.java new file mode 100644 index 000000000..9d1563f85 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeSourceBaseConfigurationCensor.java @@ -0,0 +1,62 @@ +package org.opencdmp.model.censorship.referencetypedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.censorship.ReferenceTypeCensor; +import org.opencdmp.model.externalfetcher.ExternalFetcherBaseSourceConfiguration; +import org.opencdmp.model.externalfetcher.ExternalFetcherApiSourceConfiguration; +import org.opencdmp.model.externalfetcher.ExternalFetcherStaticOptionSourceConfiguration; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeSourceBaseConfigurationCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceTypeSourceBaseConfigurationCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public ReferenceTypeSourceBaseConfigurationCensor(ConventionService conventionService, + AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReferenceType); + FieldSet referenceTypeDependencyFields = fields.extractPrefixed(this.asIndexerPrefix(ExternalFetcherBaseSourceConfiguration._referenceTypeDependencies)); + this.censorFactory.censor(ReferenceTypeCensor.class).censor(referenceTypeDependencyFields, userId); + + FieldSet optionsFields = fields.extractPrefixed(this.asIndexerPrefix(ExternalFetcherStaticOptionSourceConfiguration._items)); + this.censorFactory.censor(ReferenceTypeStaticOptionCensor.class).censor(optionsFields, userId); + + FieldSet authFields = fields.extractPrefixed(this.asIndexerPrefix(ExternalFetcherApiSourceConfiguration._auth)); + this.censorFactory.censor(AuthenticationConfigurationCensor.class).censor(authFields, userId); + + FieldSet resultsFields = fields.extractPrefixed(this.asIndexerPrefix(ExternalFetcherApiSourceConfiguration._results)); + this.censorFactory.censor(ResultsConfigurationCensor.class).censor(resultsFields, userId); + + FieldSet queriesFields = fields.extractPrefixed(this.asIndexerPrefix(ExternalFetcherApiSourceConfiguration._queries)); + this.censorFactory.censor(QueryConfigCensor.class).censor(queriesFields, userId); + } + +} + + diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeStaticOptionCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeStaticOptionCensor.java new file mode 100644 index 000000000..09191a71d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ReferenceTypeStaticOptionCensor.java @@ -0,0 +1,40 @@ +package org.opencdmp.model.censorship.referencetypedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeStaticOptionCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceTypeStaticOptionCensor.class)); + + protected final AuthorizationService authService; + + public ReferenceTypeStaticOptionCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReferenceType); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ResultFieldsMappingConfigurationCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ResultFieldsMappingConfigurationCensor.java new file mode 100644 index 000000000..1237b8d0f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ResultFieldsMappingConfigurationCensor.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.censorship.referencetypedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ResultFieldsMappingConfigurationCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ResultFieldsMappingConfigurationCensor.class)); + + protected final AuthorizationService authService; + + public ResultFieldsMappingConfigurationCensor(ConventionService conventionService, + AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReferenceType); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ResultsConfigurationCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ResultsConfigurationCensor.java new file mode 100644 index 000000000..571db77bb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/referencetypedefinition/ResultsConfigurationCensor.java @@ -0,0 +1,45 @@ +package org.opencdmp.model.censorship.referencetypedefinition; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.externalfetcher.ResultsConfiguration; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ResultsConfigurationCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ResultsConfigurationCensor.class)); + + protected final AuthorizationService authService; + protected final CensorFactory censorFactory; + + public ResultsConfigurationCensor(ConventionService conventionService, + AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + + this.authService.authorizeForce(Permission.BrowseReferenceType); + FieldSet fieldsMappingFields = fields.extractPrefixed(this.asIndexerPrefix(ResultsConfiguration._fieldsMapping)); + this.censorFactory.censor(ResultFieldsMappingConfigurationCensor.class).censor(fieldsMappingFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/CssColorsTenantConfigurationCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/CssColorsTenantConfigurationCensor.java new file mode 100644 index 000000000..36fc841c3 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/CssColorsTenantConfigurationCensor.java @@ -0,0 +1,38 @@ +package org.opencdmp.model.censorship.tenantconfiguration; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class CssColorsTenantConfigurationCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(CssColorsTenantConfigurationCensor.class)); + + protected final AuthorizationService authService; + + + public CssColorsTenantConfigurationCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorize(Permission.BrowseTenantConfiguration); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/DefaultUserLocaleTenantConfigurationCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/DefaultUserLocaleTenantConfigurationCensor.java new file mode 100644 index 000000000..28cc12110 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/DefaultUserLocaleTenantConfigurationCensor.java @@ -0,0 +1,38 @@ +package org.opencdmp.model.censorship.tenantconfiguration; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DefaultUserLocaleTenantConfigurationCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DefaultUserLocaleTenantConfigurationCensor.class)); + + protected final AuthorizationService authService; + + + public DefaultUserLocaleTenantConfigurationCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorize(Permission.BrowseTenantConfiguration); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/DepositTenantConfigurationCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/DepositTenantConfigurationCensor.java new file mode 100644 index 000000000..0ce79f6ed --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/DepositTenantConfigurationCensor.java @@ -0,0 +1,47 @@ +package org.opencdmp.model.censorship.tenantconfiguration; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.censorship.deposit.DepositSourceCensor; +import org.opencdmp.model.tenantconfiguration.DepositTenantConfiguration; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DepositTenantConfigurationCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DepositTenantConfigurationCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + + public DepositTenantConfigurationCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorize(Permission.BrowseTenantConfiguration); + + FieldSet sourcesFields = fields.extractPrefixed(this.asIndexerPrefix(DepositTenantConfiguration._sources)); + this.censorFactory.censor(DepositSourceCensor.class).censor(sourcesFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/FileTransformerTenantConfigurationCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/FileTransformerTenantConfigurationCensor.java new file mode 100644 index 000000000..0c99d9f75 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/FileTransformerTenantConfigurationCensor.java @@ -0,0 +1,50 @@ +package org.opencdmp.model.censorship.tenantconfiguration; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.censorship.deposit.DepositSourceCensor; +import org.opencdmp.model.censorship.filetransformer.FileTransformerSourceCensor; +import org.opencdmp.model.filetransformer.FileTransformerSource; +import org.opencdmp.model.tenantconfiguration.DepositTenantConfiguration; +import org.opencdmp.model.tenantconfiguration.FileTransformerTenantConfiguration; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class FileTransformerTenantConfigurationCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FileTransformerTenantConfigurationCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + + public FileTransformerTenantConfigurationCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorize(Permission.BrowseTenantConfiguration); + + FieldSet sourcesFields = fields.extractPrefixed(this.asIndexerPrefix(FileTransformerTenantConfiguration._sources)); + this.censorFactory.censor(FileTransformerSourceCensor.class).censor(sourcesFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/LogoTenantConfigurationCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/LogoTenantConfigurationCensor.java new file mode 100644 index 000000000..5b328584a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/LogoTenantConfigurationCensor.java @@ -0,0 +1,38 @@ +package org.opencdmp.model.censorship.tenantconfiguration; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LogoTenantConfigurationCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(LogoTenantConfigurationCensor.class)); + + protected final AuthorizationService authService; + + + public LogoTenantConfigurationCensor(ConventionService conventionService, AuthorizationService authService) { + super(conventionService); + this.authService = authService; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorize(Permission.BrowseTenantConfiguration); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/TenantConfigurationCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/TenantConfigurationCensor.java new file mode 100644 index 000000000..4800a8b1c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/tenantconfiguration/TenantConfigurationCensor.java @@ -0,0 +1,60 @@ +package org.opencdmp.model.censorship.tenantconfiguration; + +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.Description; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.censorship.DescriptionReferenceCensor; +import org.opencdmp.model.tenantconfiguration.TenantConfiguration; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantConfigurationCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantConfigurationCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + + public TenantConfigurationCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorize(Permission.BrowseTenantConfiguration); + + FieldSet cssColorsFields = fields.extractPrefixed(this.asIndexerPrefix(TenantConfiguration._cssColors)); + this.censorFactory.censor(CssColorsTenantConfigurationCensor.class).censor(cssColorsFields, userId); + + FieldSet defaultUserLocaleFields = fields.extractPrefixed(this.asIndexerPrefix(TenantConfiguration._defaultUserLocale)); + this.censorFactory.censor(DefaultUserLocaleTenantConfigurationCensor.class).censor(defaultUserLocaleFields, userId); + + FieldSet depositPluginsFields = fields.extractPrefixed(this.asIndexerPrefix(TenantConfiguration._depositPlugins)); + this.censorFactory.censor(DepositTenantConfigurationCensor.class).censor(depositPluginsFields, userId); + + FieldSet fileTransformerPluginsFields = fields.extractPrefixed(this.asIndexerPrefix(TenantConfiguration._fileTransformerPlugins)); + this.censorFactory.censor(FileTransformerTenantConfigurationCensor.class).censor(fileTransformerPluginsFields, userId); + + FieldSet logoFields = fields.extractPrefixed(this.asIndexerPrefix(TenantConfiguration._logo)); + this.censorFactory.censor(LogoTenantConfigurationCensor.class).censor(logoFields, userId); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/censorship/usercredential/UserCredentialDataCensor.java b/backend/core/src/main/java/org/opencdmp/model/censorship/usercredential/UserCredentialDataCensor.java new file mode 100644 index 000000000..959aeeb9e --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/censorship/usercredential/UserCredentialDataCensor.java @@ -0,0 +1,44 @@ +package org.opencdmp.model.censorship.usercredential; + +import org.opencdmp.authorization.OwnedResource; +import org.opencdmp.authorization.Permission; +import org.opencdmp.convention.ConventionService; +import org.opencdmp.model.censorship.BaseCensor; +import org.opencdmp.model.censorship.DescriptionReferenceCensor; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.censor.CensorFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.DataLogEntry; +import gr.cite.tools.logging.LoggerService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserCredentialDataCensor extends BaseCensor { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserCredentialDataCensor.class)); + + protected final AuthorizationService authService; + + protected final CensorFactory censorFactory; + + public UserCredentialDataCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { + super(conventionService); + this.authService = authService; + this.censorFactory = censorFactory; + } + + public void censor(FieldSet fields, UUID userId) { + logger.debug(new DataLogEntry("censoring fields", fields)); + if (fields == null || fields.isEmpty()) + return; + this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseUser); + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/ActionConfirmationDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/ActionConfirmationDeleter.java new file mode 100644 index 000000000..8109318c1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/ActionConfirmationDeleter.java @@ -0,0 +1,78 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.ActionConfirmationEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.ActionConfirmationQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ActionConfirmationDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ActionConfirmationDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public ActionConfirmationDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(ActionConfirmationQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (ActionConfirmationEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionDeleter.java new file mode 100644 index 000000000..726258a48 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionDeleter.java @@ -0,0 +1,104 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DescriptionEntity; +import org.opencdmp.data.DescriptionReferenceEntity; +import org.opencdmp.data.DescriptionTagEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.DescriptionQuery; +import org.opencdmp.query.DescriptionReferenceQuery; +import org.opencdmp.query.DescriptionTagQuery; +import org.opencdmp.service.elastic.ElasticService; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + protected final ElasticService elasticService; + + @Autowired + public DescriptionDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory, + ElasticService elasticService) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + this.elasticService = elasticService; + } + + public void deleteAndSaveByIds(List ids, boolean disableElastic) throws InvalidApplicationException, IOException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DescriptionQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data, disableElastic); + } + + public void deleteAndSave(List data, boolean disableElastic) throws InvalidApplicationException, IOException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data, disableElastic); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data, boolean disableElastic) throws InvalidApplicationException, IOException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + List ids = data.stream().map(DescriptionEntity::getId).distinct().collect(Collectors.toList()); + { + logger.debug("checking related - {}", DescriptionReferenceEntity.class.getSimpleName()); + List items = this.queryFactory.query(DescriptionReferenceQuery.class).descriptionIds(ids).collect(); + DescriptionReferenceDeleter deleter = this.deleterFactory.deleter(DescriptionReferenceDeleter.class); + deleter.delete(items); + } + { + logger.debug("checking related - {}", DescriptionTagEntity.class.getSimpleName()); + List items = this.queryFactory.query(DescriptionTagQuery.class).descriptionIds(ids).collect(); + DescriptionTagDeleter deleter = this.deleterFactory.deleter(DescriptionTagDeleter.class); + deleter.delete(items); + } + + for (DescriptionEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + + if (!disableElastic) this.elasticService.deleteDescription(item); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionReferenceDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionReferenceDeleter.java new file mode 100644 index 000000000..6d0a18696 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionReferenceDeleter.java @@ -0,0 +1,79 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DescriptionReferenceEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.DescriptionReferenceQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionReferenceDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionReferenceDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public DescriptionReferenceDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DescriptionReferenceQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (DescriptionReferenceEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionTagDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionTagDeleter.java new file mode 100644 index 000000000..663a3f1cc --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionTagDeleter.java @@ -0,0 +1,79 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DescriptionTagEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.DescriptionTagQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTagDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTagDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public DescriptionTagDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DescriptionTagQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (DescriptionTagEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionTemplateDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionTemplateDeleter.java new file mode 100644 index 000000000..4e3caa37c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionTemplateDeleter.java @@ -0,0 +1,106 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.DescriptionTemplateVersionStatus; +import org.opencdmp.commons.enums.DmpVersionStatus; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DescriptionTemplateEntity; +import org.opencdmp.data.DmpDescriptionTemplateEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.data.UserDescriptionTemplateEntity; +import org.opencdmp.query.DescriptionQuery; +import org.opencdmp.query.DescriptionTemplateQuery; +import org.opencdmp.query.DmpDescriptionTemplateQuery; +import org.opencdmp.query.UserDescriptionTemplateQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTemplateDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public DescriptionTemplateDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DescriptionTemplateQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + List ids = data.stream().map(DescriptionTemplateEntity::getId).distinct().collect(Collectors.toList()); + List groupIds = data.stream().map(DescriptionTemplateEntity::getGroupId).distinct().collect(Collectors.toList()); + { + logger.debug("checking related - {}", UserDescriptionTemplateEntity.class.getSimpleName()); + List items = this.queryFactory.query(UserDescriptionTemplateQuery.class).descriptionTemplateIds(ids).collect(); + UserDescriptionTemplateDeleter deleter = this.deleterFactory.deleter(UserDescriptionTemplateDeleter.class); + deleter.delete(items); + } + { + logger.debug("checking related - {}", DmpDescriptionTemplateEntity.class.getSimpleName()); + List items = this.queryFactory.query(DmpDescriptionTemplateQuery.class).descriptionTemplateGroupIds(groupIds).collect(); + DmpDescriptionTemplateDeleter deleter = this.deleterFactory.deleter(DmpDescriptionTemplateDeleter.class); + deleter.delete(items); + } + + //TODO can not delete profile if has Datasets + + Instant now = Instant.now(); + + for (DescriptionTemplateEntity item : data) { + logger.trace("deleting item {}", item.getId()); + if(item.getVersionStatus().equals(DescriptionTemplateVersionStatus.Current)) throw new MyApplicationException("Description is current can not deleted"); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionTemplateTypeDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionTemplateTypeDeleter.java new file mode 100644 index 000000000..d627470d2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/DescriptionTemplateTypeDeleter.java @@ -0,0 +1,90 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DescriptionTemplateEntity; +import org.opencdmp.data.DescriptionTemplateTypeEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.DescriptionTemplateQuery; +import org.opencdmp.query.DescriptionTemplateTypeQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DescriptionTemplateTypeDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public DescriptionTemplateTypeDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DescriptionTemplateTypeQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + List ids = data.stream().map(DescriptionTemplateTypeEntity::getId).distinct().collect(Collectors.toList()); + { + logger.debug("checking related - {}", DescriptionTemplateEntity.class.getSimpleName()); + List items = this.queryFactory.query(DescriptionTemplateQuery.class).typeIds(ids).collect(); + DescriptionTemplateDeleter deleter = this.deleterFactory.deleter(DescriptionTemplateDeleter.class); + deleter.delete(items); + } + + Instant now = Instant.now(); + + for (DescriptionTemplateTypeEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/DmpBlueprintDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/DmpBlueprintDeleter.java new file mode 100644 index 000000000..e34007725 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/DmpBlueprintDeleter.java @@ -0,0 +1,79 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DmpBlueprintEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.DmpBlueprintQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpBlueprintDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpBlueprintDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public DmpBlueprintDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DmpBlueprintQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (DmpBlueprintEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/DmpDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/DmpDeleter.java new file mode 100644 index 000000000..365c5049c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/DmpDeleter.java @@ -0,0 +1,121 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.commons.enums.DmpStatus; +import org.opencdmp.commons.enums.DmpVersionStatus; +import org.opencdmp.commons.enums.EntityType; +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.*; +import org.opencdmp.model.Description; +import org.opencdmp.model.DmpDescriptionTemplate; +import org.opencdmp.model.DmpReference; +import org.opencdmp.query.*; +import org.opencdmp.service.elastic.ElasticService; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + protected final ElasticService elasticService; + + @Autowired + public DmpDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory, + ElasticService elasticService) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + this.elasticService = elasticService; + } + + public void deleteAndSaveByIds(List ids, boolean disableElastic) throws InvalidApplicationException, IOException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DmpQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data, disableElastic); + } + + public void deleteAndSave(List data, boolean disableElastic) throws InvalidApplicationException, IOException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data, disableElastic); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data, boolean disableElastic) throws InvalidApplicationException, IOException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + List ids = data.stream().map(DmpEntity::getId).distinct().toList(); + { + logger.debug("checking related - {}", DmpUserEntity.class.getSimpleName()); + List items = this.queryFactory.query(DmpUserQuery.class).dmpIds(ids).collect(); + DmpUserDeleter deleter = this.deleterFactory.deleter(DmpUserDeleter.class); + deleter.delete(items); + } + { + logger.debug("checking related - {}", DmpDescriptionTemplate.class.getSimpleName()); + List items = this.queryFactory.query(DmpDescriptionTemplateQuery.class).dmpIds(ids).collect(); + DmpDescriptionTemplateDeleter deleter = this.deleterFactory.deleter(DmpDescriptionTemplateDeleter.class); + deleter.delete(items); + } + { + logger.debug("checking related - {}", DmpReference.class.getSimpleName()); + List items = this.queryFactory.query(DmpReferenceQuery.class).dmpIds(ids).collect(); + DmpReferenceDeleter deleter = this.deleterFactory.deleter(DmpReferenceDeleter.class); + deleter.delete(items); + } + { + logger.debug("checking related - {}", Description.class.getSimpleName()); + List items = this.queryFactory.query(DescriptionQuery.class).dmpIds(ids).collect(); + DescriptionDeleter deleter = this.deleterFactory.deleter(DescriptionDeleter.class); + deleter.delete(items, false); //We delete elastic entities by bmp deleter + } + + Instant now = Instant.now(); + + for (DmpEntity item : data) { + logger.trace("deleting item {}", item.getId()); + EntityDoiQuery entityDoiQuery = this.queryFactory.query(EntityDoiQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermission).types(EntityType.DMP).entityIds(item.getId()); + if (entityDoiQuery.count() > 0) throw new MyApplicationException("DMP is deposited can not deleted"); + if(item.getVersionStatus().equals(DmpVersionStatus.Current)) throw new MyApplicationException("DMP is current can not deleted"); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + + if (!disableElastic) this.elasticService.deleteDmp(item); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/DmpDescriptionTemplateDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/DmpDescriptionTemplateDeleter.java new file mode 100644 index 000000000..84d16b7bb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/DmpDescriptionTemplateDeleter.java @@ -0,0 +1,76 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DmpDescriptionTemplateEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.DmpDescriptionTemplateQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpDescriptionTemplateDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpDescriptionTemplateDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public DmpDescriptionTemplateDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DmpDescriptionTemplateQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + for (DmpDescriptionTemplateEntity item : data) { + logger.trace("deleting item {}", item.getId()); + logger.trace("updating item"); + item.setUpdatedAt(Instant.now()); + item.setIsActive(IsActive.Inactive); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/DmpReferenceDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/DmpReferenceDeleter.java new file mode 100644 index 000000000..9b95d6a4d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/DmpReferenceDeleter.java @@ -0,0 +1,76 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DmpReferenceEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.DmpReferenceQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpReferenceDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpReferenceDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public DmpReferenceDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DmpReferenceQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + for (DmpReferenceEntity item : data) { + logger.trace("deleting item {}", item.getId()); + logger.trace("updating item"); + item.setUpdatedAt(Instant.now()); + item.setIsActive(IsActive.Inactive); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/DmpUserDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/DmpUserDeleter.java new file mode 100644 index 000000000..b71b9fd46 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/DmpUserDeleter.java @@ -0,0 +1,76 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DmpUserEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.DmpUserQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class DmpUserDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpUserDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public DmpUserDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DmpUserQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + for (DmpUserEntity item : data) { + logger.trace("deleting item {}", item.getId()); + logger.trace("updating item"); + item.setUpdatedAt(Instant.now()); + item.setIsActive(IsActive.Inactive); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/EntityDoiDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/EntityDoiDeleter.java new file mode 100644 index 000000000..6b5fcd454 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/EntityDoiDeleter.java @@ -0,0 +1,79 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DescriptionTemplateTypeEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.DescriptionTemplateTypeQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class EntityDoiDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DescriptionTemplateTypeDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public EntityDoiDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(DescriptionTemplateTypeQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (DescriptionTemplateTypeEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/LanguageDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/LanguageDeleter.java new file mode 100644 index 000000000..4c65335c2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/LanguageDeleter.java @@ -0,0 +1,78 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.LanguageEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.LanguageQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LanguageDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(LanguageDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public LanguageDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(LanguageQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (LanguageEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/LockDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/LockDeleter.java new file mode 100644 index 000000000..dec414cff --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/LockDeleter.java @@ -0,0 +1,71 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.data.LockEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.LockQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class LockDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(LockDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public LockDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(LockQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + for (LockEntity item : data) { + logger.trace("deleting item {}", item.getId()); + this.entityManager.remove(item); + logger.trace("removed item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/PrefillingSourceDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/PrefillingSourceDeleter.java new file mode 100644 index 000000000..03b112408 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/PrefillingSourceDeleter.java @@ -0,0 +1,78 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.PrefillingSourceEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.PrefillingSourceQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PrefillingSourceDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PrefillingSourceDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public PrefillingSourceDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(PrefillingSourceQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (PrefillingSourceEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/ReferenceDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/ReferenceDeleter.java new file mode 100644 index 000000000..f7990bda8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/ReferenceDeleter.java @@ -0,0 +1,93 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.*; +import org.opencdmp.query.DescriptionReferenceQuery; +import org.opencdmp.query.DmpReferenceQuery; +import org.opencdmp.query.ReferenceQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public ReferenceDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(ReferenceQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + List ids = data.stream().map(ReferenceEntity::getId).distinct().collect(Collectors.toList()); + { + logger.debug("checking related - {}", DescriptionReferenceEntity.class.getSimpleName()); + List items = this.queryFactory.query(DescriptionReferenceQuery.class).referenceIds(ids).collect(); + DescriptionReferenceDeleter deleter = this.deleterFactory.deleter(DescriptionReferenceDeleter.class); + deleter.delete(items); + } + { + logger.debug("checking related - {}", DmpReferenceEntity.class.getSimpleName()); + List items = this.queryFactory.query(DmpReferenceQuery.class).referenceIds(ids).collect(); + DmpReferenceDeleter deleter = this.deleterFactory.deleter(DmpReferenceDeleter.class); + deleter.delete(items); + } + Instant now = Instant.now(); + + for (ReferenceEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/ReferenceTypeDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/ReferenceTypeDeleter.java new file mode 100644 index 000000000..75a94f8a1 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/ReferenceTypeDeleter.java @@ -0,0 +1,78 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.ReferenceTypeEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.ReferenceTypeQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ReferenceTypeDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceTypeDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public ReferenceTypeDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(ReferenceTypeQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (ReferenceTypeEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/SupportiveMaterialDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/SupportiveMaterialDeleter.java new file mode 100644 index 000000000..cad5663f2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/SupportiveMaterialDeleter.java @@ -0,0 +1,79 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.SupportiveMaterialEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.SupportiveMaterialQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class SupportiveMaterialDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(SupportiveMaterialDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public SupportiveMaterialDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(SupportiveMaterialQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (SupportiveMaterialEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/TagDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/TagDeleter.java new file mode 100644 index 000000000..5e5310626 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/TagDeleter.java @@ -0,0 +1,87 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.DescriptionTagEntity; +import org.opencdmp.data.TagEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.DescriptionTagQuery; +import org.opencdmp.query.TagQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TagDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TagDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public TagDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(TagQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + List ids = data.stream().map(TagEntity::getId).distinct().collect(Collectors.toList()); + { + logger.debug("checking related - {}", DescriptionTagEntity.class.getSimpleName()); + List items = this.queryFactory.query(DescriptionTagQuery.class).tagIds(ids).collect(); + DescriptionTagDeleter deleter = this.deleterFactory.deleter(DescriptionTagDeleter.class); + deleter.delete(items); + } + Instant now = Instant.now(); + + for (TagEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/TenantConfigurationDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/TenantConfigurationDeleter.java new file mode 100644 index 000000000..26c7804e8 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/TenantConfigurationDeleter.java @@ -0,0 +1,81 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.TenantConfigurationEntity; +import org.opencdmp.data.TenantEntity; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.query.TenantConfigurationQuery; +import org.opencdmp.query.TenantQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantConfigurationDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantConfigurationDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public TenantConfigurationDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(TenantConfigurationQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (TenantConfigurationEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/TenantDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/TenantDeleter.java new file mode 100644 index 000000000..b4ef6bcde --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/TenantDeleter.java @@ -0,0 +1,89 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.*; +import org.opencdmp.query.DescriptionTagQuery; +import org.opencdmp.query.TenantConfigurationQuery; +import org.opencdmp.query.TenantQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public TenantDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(TenantQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + List ids = data.stream().map(TenantEntity::getId).distinct().collect(Collectors.toList()); + { + logger.debug("checking related - {}", TenantConfigurationEntity.class.getSimpleName()); + List items = this.queryFactory.query(TenantConfigurationQuery.class).tenantIds(ids).collect(); + TenantConfigurationDeleter deleter = this.deleterFactory.deleter(TenantConfigurationDeleter.class); + deleter.delete(items); + } + + Instant now = Instant.now(); + + for (TenantEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/TenantUserDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/TenantUserDeleter.java new file mode 100644 index 000000000..48db5daa2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/TenantUserDeleter.java @@ -0,0 +1,74 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.data.TenantUserEntity; +import org.opencdmp.query.TenantUserQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class TenantUserDeleter implements Deleter { + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantUserDeleter.class)); + + private final TenantEntityManager entityManager; + private final QueryFactory queryFactory; + private final DeleterFactory deleterFactory; + + @Autowired + public TenantUserDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(e -> e.size()).orElse(0)).And("ids", ids)); + List datas = this.queryFactory.query(TenantUserQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(datas).map(e -> e.size()).orElse(0)); + this.deleteAndSave(datas); + } + + public void deleteAndSave(List datas) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(datas).map(e -> e.size()).orElse(0)); + this.delete(datas); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List datas) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(datas).map(x -> x.size()).orElse(0)); + if (datas == null || datas.isEmpty()) return; + + Instant now = Instant.now(); + + for (TenantUserEntity item : datas) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/UserContactInfoDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/UserContactInfoDeleter.java new file mode 100644 index 000000000..de8497562 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/UserContactInfoDeleter.java @@ -0,0 +1,68 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.data.UserContactInfoEntity; +import org.opencdmp.query.UserContactInfoQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserContactInfoDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserContactInfoDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + + @Autowired + public UserContactInfoDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(UserContactInfoQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + for (UserContactInfoEntity item : data) { + logger.trace("deleting item {}", item.getId()); + logger.trace("deleting item"); + this.entityManager.remove(item); + logger.trace("deleted item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/UserCredentialDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/UserCredentialDeleter.java new file mode 100644 index 000000000..e849daae9 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/UserCredentialDeleter.java @@ -0,0 +1,68 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.data.UserCredentialEntity; +import org.opencdmp.query.UserCredentialQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserCredentialDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserCredentialDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + + @Autowired + public UserCredentialDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(UserCredentialQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + for (UserCredentialEntity item : data) { + logger.trace("deleting item {}", item.getId()); + logger.trace("deleting item"); + this.entityManager.remove(item); + logger.trace("deleted item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/UserDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/UserDeleter.java new file mode 100644 index 000000000..f8c6d8ec2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/UserDeleter.java @@ -0,0 +1,108 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.*; +import org.opencdmp.query.*; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public UserDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(UserQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + List ids = data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList()); + { + logger.debug("checking related - {}", UserRoleEntity.class.getSimpleName()); + List items = this.queryFactory.query(UserRoleQuery.class).userIds(ids).collect(); + UserRoleDeleter deleter = this.deleterFactory.deleter(UserRoleDeleter.class); + deleter.delete(items); + } + { + logger.debug("checking related - {}", UserCredentialEntity.class.getSimpleName()); + List items = this.queryFactory.query(UserCredentialQuery.class).userIds(ids).collect(); + UserCredentialDeleter deleter = this.deleterFactory.deleter(UserCredentialDeleter.class); + deleter.delete(items); + } + { + logger.debug("checking related - {}", UserContactInfoEntity.class.getSimpleName()); + List items = this.queryFactory.query(UserContactInfoQuery.class).userIds(ids).collect(); + UserContactInfoDeleter deleter = this.deleterFactory.deleter(UserContactInfoDeleter.class); + deleter.delete(items); + } + { + logger.debug("checking related - {}", TenantUserEntity.class.getSimpleName()); + List items = this.queryFactory.query(TenantUserQuery.class).userIds(ids).collect(); + TenantUserDeleter deleter = this.deleterFactory.deleter(TenantUserDeleter.class); + deleter.delete(items); + } +// { +// logger.debug("checking related - {}", DmpUserEntity.class.getSimpleName()); +// List items = this.queryFactory.query(DmpUserQuery.class).userIds(ids).collect(); +// DmpUserDeleter deleter = this.deleterFactory.deleter(DmpUserDeleter.class); +// deleter.delete(items); +// } + Instant now = Instant.now(); + + for (UserEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/UserDescriptionTemplateDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/UserDescriptionTemplateDeleter.java new file mode 100644 index 000000000..966ee1b8f --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/UserDescriptionTemplateDeleter.java @@ -0,0 +1,79 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.commons.enums.IsActive; +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.data.UserDescriptionTemplateEntity; +import org.opencdmp.query.UserDescriptionTemplateQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserDescriptionTemplateDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserDescriptionTemplateDeleter.class)); + + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + protected final DeleterFactory deleterFactory; + + @Autowired + public UserDescriptionTemplateDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory, + DeleterFactory deleterFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + this.deleterFactory = deleterFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(UserDescriptionTemplateQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + Instant now = Instant.now(); + + for (UserDescriptionTemplateEntity item : data) { + logger.trace("deleting item {}", item.getId()); + item.setIsActive(IsActive.Inactive); + item.setUpdatedAt(now); + logger.trace("updating item"); + this.entityManager.merge(item); + logger.trace("updated item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/UserRoleDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/UserRoleDeleter.java new file mode 100644 index 000000000..f4df98eb4 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/UserRoleDeleter.java @@ -0,0 +1,68 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.data.UserRoleEntity; +import org.opencdmp.query.UserRoleQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserRoleDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserRoleDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + + @Autowired + public UserRoleDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(UserRoleQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + for (UserRoleEntity item : data) { + logger.trace("deleting item {}", item.getId()); + logger.trace("deleting item"); + this.entityManager.remove(item); + logger.trace("deleted item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deleter/UserSettingsSettingsDeleter.java b/backend/core/src/main/java/org/opencdmp/model/deleter/UserSettingsSettingsDeleter.java new file mode 100644 index 000000000..b238185db --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deleter/UserSettingsSettingsDeleter.java @@ -0,0 +1,68 @@ +package org.opencdmp.model.deleter; + +import org.opencdmp.data.TenantEntityManager; +import org.opencdmp.data.UserSettingsEntity; +import org.opencdmp.query.UserSettingsQuery; +import gr.cite.tools.data.deleter.Deleter; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.management.InvalidApplicationException; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class UserSettingsSettingsDeleter implements Deleter { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserSettingsSettingsDeleter.class)); + private final TenantEntityManager entityManager; + + protected final QueryFactory queryFactory; + + + @Autowired + public UserSettingsSettingsDeleter( + TenantEntityManager entityManager, + QueryFactory queryFactory + ) { + this.entityManager = entityManager; + this.queryFactory = queryFactory; + } + + public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { + logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); + List data = this.queryFactory.query(UserSettingsQuery.class).ids(ids).collect(); + logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.deleteAndSave(data); + } + + public void deleteAndSave(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + this.delete(data); + logger.trace("saving changes"); + this.entityManager.flush(); + logger.trace("changes saved"); + } + + public void delete(List data) throws InvalidApplicationException { + logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); + if (data == null || data.isEmpty()) + return; + + for (UserSettingsEntity item : data) { + logger.trace("deleting item {}", item.getId()); + logger.trace("deleting item"); + this.entityManager.remove(item); + logger.trace("deleted item"); + } + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/deposit/DepositConfiguration.java b/backend/core/src/main/java/org/opencdmp/model/deposit/DepositConfiguration.java new file mode 100644 index 000000000..bfedb0542 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deposit/DepositConfiguration.java @@ -0,0 +1,71 @@ +package org.opencdmp.model.deposit; + +import eu.eudat.depositinterface.enums.DepositType; + +public class DepositConfiguration { + + private DepositType depositType; + public static final String _depositType = "depositType"; + private String repositoryId; + public static final String _repositoryId = "repositoryId"; + private String repositoryAuthorizationUrl; + public static final String _repositoryAuthorizationUrl = "repositoryAuthorizationUrl"; + private String repositoryRecordUrl; + public static final String _repositoryRecordUrl = "repositoryRecordUrl"; + private String repositoryClientId; + public static final String _repositoryClientId = "repositoryClientId"; + private String redirectUri; + public static final String _redirectUri = "redirectUri"; + private boolean hasLogo; + public static final String _hasLogo = "hasLogo"; + + public DepositType getDepositType() { + return depositType; + } + public void setDepositType(DepositType depositType) { + this.depositType = depositType; + } + + public String getRepositoryId() { + return repositoryId; + } + public void setRepositoryId(String repositoryId) { + this.repositoryId = repositoryId; + } + + public String getRepositoryAuthorizationUrl() { + return repositoryAuthorizationUrl; + } + public void setRepositoryAuthorizationUrl(String repositoryAuthorizationUrl) { + this.repositoryAuthorizationUrl = repositoryAuthorizationUrl; + } + + public String getRepositoryRecordUrl() { + return repositoryRecordUrl; + } + public void setRepositoryRecordUrl(String repositoryRecordUrl) { + this.repositoryRecordUrl = repositoryRecordUrl; + } + + public String getRepositoryClientId() { + return repositoryClientId; + } + public void setRepositoryClientId(String repositoryClientId) { + this.repositoryClientId = repositoryClientId; + } + + public String getRedirectUri() { + return redirectUri; + } + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } + + public boolean isHasLogo() { + return hasLogo; + } + public void setHasLogo(boolean hasLogo) { + this.hasLogo = hasLogo; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/model/deposit/DepositSource.java b/backend/core/src/main/java/org/opencdmp/model/deposit/DepositSource.java new file mode 100644 index 000000000..f66eef51c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/deposit/DepositSource.java @@ -0,0 +1,85 @@ +package org.opencdmp.model.deposit; + +public class DepositSource { + + private String repositoryId; + public static final String _repositoryId = "repositoryId"; + private String url; + public static final String _url = "url"; + private String issuerUrl; + public static final String _issuerUrl = "issuerUrl"; + private String clientId; + public static final String _clientId = "clientId"; + private String clientSecret; + public static final String _clientSecret = "clientSecret"; + private String scope; + public static final String _scope = "scope"; + private String pdfTransformerId; + public static final String _pdfTransformerId = "pdfTransformerId"; + private String rdaTransformerId; + public static final String _rdaTransformerId = "rdaTransformerId"; + + public String getRepositoryId() { + return repositoryId; + } + + public void setRepositoryId(String repositoryId) { + this.repositoryId = repositoryId; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getIssuerUrl() { + return issuerUrl; + } + + public void setIssuerUrl(String issuerUrl) { + this.issuerUrl = issuerUrl; + } + + 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 getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + public String getPdfTransformerId() { + return pdfTransformerId; + } + + public void setPdfTransformerId(String pdfTransformerId) { + this.pdfTransformerId = pdfTransformerId; + } + + public String getRdaTransformerId() { + return rdaTransformerId; + } + + public void setRdaTransformerId(String rdaTransformerId) { + this.rdaTransformerId = rdaTransformerId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/ExternalIdentifier.java b/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/ExternalIdentifier.java new file mode 100644 index 000000000..e647d6dfb --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/ExternalIdentifier.java @@ -0,0 +1,27 @@ +package org.opencdmp.model.descriptionproperties; + +public class ExternalIdentifier { + + private String identifier; + public static final String _identifier = "identifier"; + + private String type; + public static final String _type = "type"; + + public String getIdentifier() { + return identifier; + } + + public void setIdentifier(String identifier) { + this.identifier = identifier; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/Field.java b/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/Field.java new file mode 100644 index 000000000..81289551a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/Field.java @@ -0,0 +1,67 @@ +package org.opencdmp.model.descriptionproperties; + + +import org.opencdmp.commons.enums.FieldType; +import org.opencdmp.model.Reference; + +import java.time.Instant; +import java.util.List; + +public class Field { + + private String textValue; + public static final String _textValue = "textValue"; + + private List textListValue; + public static final String _textListValue = "textListValue"; + + private Instant dateValue; + public static final String _dateValue = "dateValue"; + + private List references; + public static final String _references = "references"; + + private ExternalIdentifier externalIdentifier; + public static final String _externalIdentifier = "externalIdentifier"; + + public String getTextValue() { + return textValue; + } + + public void setTextValue(String textValue) { + this.textValue = textValue; + } + + public List getTextListValue() { + return textListValue; + } + + public void setTextListValue(List textListValue) { + this.textListValue = textListValue; + } + + public Instant getDateValue() { + return dateValue; + } + + public void setDateValue(Instant dateValue) { + this.dateValue = dateValue; + } + + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + + public ExternalIdentifier getExternalIdentifier() { + return externalIdentifier; + } + + public void setExternalIdentifier(ExternalIdentifier externalIdentifier) { + this.externalIdentifier = externalIdentifier; + } +} + diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/PropertyDefinition.java b/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/PropertyDefinition.java new file mode 100644 index 000000000..361096999 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/PropertyDefinition.java @@ -0,0 +1,20 @@ +package org.opencdmp.model.descriptionproperties; + + +import java.util.List; +import java.util.Map; + +public class PropertyDefinition { + + public final static String _fieldSets = "fieldSets"; + + private Map fieldSets; + + public Map getFieldSets() { + return fieldSets; + } + + public void setFieldSets(Map fieldSets) { + this.fieldSets = fieldSets; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/PropertyDefinitionFieldSet.java b/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/PropertyDefinitionFieldSet.java new file mode 100644 index 000000000..2a35e284d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/PropertyDefinitionFieldSet.java @@ -0,0 +1,17 @@ +package org.opencdmp.model.descriptionproperties; + +import java.util.List; + +public class PropertyDefinitionFieldSet { + + public final static String _items = "items"; + private List items; + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/PropertyDefinitionFieldSetItem.java b/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/PropertyDefinitionFieldSetItem.java new file mode 100644 index 000000000..7e6c044b5 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptionproperties/PropertyDefinitionFieldSetItem.java @@ -0,0 +1,41 @@ +package org.opencdmp.model.descriptionproperties; + +import org.opencdmp.commons.types.description.FieldEntity; + +import java.util.Map; + +public class PropertyDefinitionFieldSetItem { + + public final static String _fields = "fields"; + private Map fields; + + public final static String _comment = "comment"; + private String comment; + + public final static String _ordinal = "ordinal"; + private Integer ordinal; + + public Map getFields() { + return fields; + } + + public void setFields(Map fields) { + this.fields = fields; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public Integer getOrdinal() { + return ordinal; + } + + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptionreference/DescriptionReferenceData.java b/backend/core/src/main/java/org/opencdmp/model/descriptionreference/DescriptionReferenceData.java new file mode 100644 index 000000000..a13987da2 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptionreference/DescriptionReferenceData.java @@ -0,0 +1,16 @@ +package org.opencdmp.model.descriptionreference; + +import java.util.UUID; + +public class DescriptionReferenceData { + private String fieldId; + public final static String _fieldId = "fieldId"; + + public String getFieldId() { + return fieldId; + } + + public void setFieldId(String fieldId) { + this.fieldId = fieldId; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Definition.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Definition.java new file mode 100644 index 000000000..867db4c2d --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Definition.java @@ -0,0 +1,17 @@ +package org.opencdmp.model.descriptiontemplatedefinition; + +import java.util.List; + +public class Definition { + + public final static String _pages = "pages"; + private List pages; + + public List getPages() { + return pages; + } + + public void setPages(List pages) { + this.pages = pages; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/ExternalIdentifier.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/ExternalIdentifier.java new file mode 100644 index 000000000..3f2e9ac6a --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/ExternalIdentifier.java @@ -0,0 +1,27 @@ +package org.opencdmp.model.descriptiontemplatedefinition; + +public class ExternalIdentifier { + + private String identifier; + public static final String _identifier = "identifier"; + + private String type; + public static final String _type = "type"; + + public String getIdentifier() { + return identifier; + } + + public void setIdentifier(String identifier) { + this.identifier = identifier; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Field.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Field.java new file mode 100644 index 000000000..0dc50b7a6 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Field.java @@ -0,0 +1,109 @@ +package org.opencdmp.model.descriptiontemplatedefinition; + +import org.opencdmp.commons.enums.FieldType; +import org.opencdmp.commons.enums.FieldValidationType; +import org.opencdmp.model.descriptiontemplatedefinition.fielddata.BaseFieldData; + +import java.util.List; + +public class Field { + + public final static String _id = "id"; + private String id; + + public final static String _ordinal = "ordinal"; + private Integer ordinal; + + public final static String _numbering = "numbering"; + private String numbering; //TODO maybe remove + + public final static String _schematics = "schematics"; + private List schematics; + + public final static String _defaultValue = "defaultValue"; + private String defaultValue; + + public final static String _visibilityRules = "visibilityRules"; + private List visibilityRules; + + public final static String _validations = "validations"; + private List validations; + + public final static String _includeInExport = "includeInExport"; + private Boolean includeInExport; + + public final static String _data = "data"; + private BaseFieldData data; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Integer getOrdinal() { + return ordinal; + } + + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } + + public String getNumbering() { + return numbering; + } + + public void setNumbering(String numbering) { + this.numbering = numbering; + } + + public List getSchematics() { + return schematics; + } + + public void setSchematics(List schematics) { + this.schematics = schematics; + } + + public String getDefaultValue() { + return defaultValue; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public List getVisibilityRules() { + return visibilityRules; + } + + public void setVisibilityRules(List visibilityRules) { + this.visibilityRules = visibilityRules; + } + + public List getValidations() { + return validations; + } + + public void setValidations(List validations) { + this.validations = validations; + } + + public Boolean getIncludeInExport() { + return includeInExport; + } + + public void setIncludeInExport(Boolean includeInExport) { + this.includeInExport = includeInExport; + } + + public BaseFieldData getData() { + return data; + } + + public void setData(BaseFieldData data) { + this.data = data; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/FieldSet.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/FieldSet.java new file mode 100644 index 000000000..c834f1546 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/FieldSet.java @@ -0,0 +1,127 @@ +package org.opencdmp.model.descriptiontemplatedefinition; + +import java.util.List; + +public class FieldSet { + + public final static String _id = "id"; + private String id; + + public final static String _ordinal = "ordinal"; + private Integer ordinal; + + public final static String _numbering = "numbering"; + private String numbering; + + public final static String _title = "title"; + private String title; + + public final static String _description = "description"; + private String description; + + public final static String _extendedDescription = "extendedDescription"; + private String extendedDescription; + + public final static String _additionalInformation = "additionalInformation"; + private String additionalInformation; + + public final static String _multiplicity = "multiplicity"; + private Multiplicity multiplicity; + + private Boolean hasMultiplicity; + public static final String _hasMultiplicity = "hasMultiplicity"; + + public final static String _hasCommentField = "hasCommentField"; + private Boolean hasCommentField; + + public final static String _fields = "fields"; + private List fields; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Integer getOrdinal() { + return ordinal; + } + + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } + + public String getNumbering() { + return numbering; + } + + public void setNumbering(String numbering) { + this.numbering = numbering; + } + + 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 String getAdditionalInformation() { + return additionalInformation; + } + + public void setAdditionalInformation(String additionalInformation) { + this.additionalInformation = additionalInformation; + } + + public Multiplicity getMultiplicity() { + return multiplicity; + } + + public void setMultiplicity(Multiplicity multiplicity) { + this.multiplicity = multiplicity; + } + + public Boolean getHasMultiplicity() { + return hasMultiplicity; + } + + public void setHasMultiplicity(Boolean hasMultiplicity) { + this.hasMultiplicity = hasMultiplicity; + } + + public Boolean getHasCommentField() { + return hasCommentField; + } + + public void setHasCommentField(Boolean hasCommentField) { + this.hasCommentField = hasCommentField; + } + + public List getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Multiplicity.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Multiplicity.java new file mode 100644 index 000000000..24b1b7b44 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Multiplicity.java @@ -0,0 +1,52 @@ +package org.opencdmp.model.descriptiontemplatedefinition; + +import org.opencdmp.commons.enums.DmpBlueprintFieldCategory; + +import java.util.UUID; + +public class Multiplicity { + + public final static String _min = "min"; + private Integer min; + + public final static String _max = "max"; + private Integer max; + + public final static String _placeholder = "placeholder"; + private String placeholder; + + public final static String _tableView = "tableView"; + private Boolean tableView; + + public Integer getMin() { + return min; + } + + public void setMin(Integer min) { + this.min = min; + } + + public Integer getMax() { + return max; + } + + public void setMax(Integer 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/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Page.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Page.java new file mode 100644 index 000000000..368722a14 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Page.java @@ -0,0 +1,57 @@ +package org.opencdmp.model.descriptiontemplatedefinition; + + +import java.util.List; + +public class Page { + + public final static String _id = "id"; + private String id; + + public final static String _ordinal = "ordinal"; + private Integer ordinal; + + public final static String _title = "title"; + private String title; + + public final static String _sections = "sections"; + private List
sections; + + 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; + } + + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } + + public List
getSections() { + return sections; + } + + public void setSections(List
sections) { + this.sections = sections; + } +} + + diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Rule.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Rule.java new file mode 100644 index 000000000..fdf06de67 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Rule.java @@ -0,0 +1,77 @@ +package org.opencdmp.model.descriptiontemplatedefinition; + +import org.opencdmp.model.Reference; + +import java.time.Instant; +import java.util.List; + +public class Rule { + + public final static String _target = "target"; + private String target; + + + private String textValue; + public static final String _textValue = "textValue"; + + private List textListValue; + public static final String _textListValue = "textListValue"; + + private Instant dateValue; + public static final String _dateValue = "dateValue"; + + private List references; + public static final String _references = "references"; + + private ExternalIdentifier externalIdentifier; + public static final String _externalIdentifier = "externalIdentifier"; + + + public String getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + public String getTextValue() { + return textValue; + } + + public void setTextValue(String textValue) { + this.textValue = textValue; + } + + public List getTextListValue() { + return textListValue; + } + + public void setTextListValue(List textListValue) { + this.textListValue = textListValue; + } + + public Instant getDateValue() { + return dateValue; + } + + public void setDateValue(Instant dateValue) { + this.dateValue = dateValue; + } + + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + + public ExternalIdentifier getExternalIdentifier() { + return externalIdentifier; + } + + public void setExternalIdentifier(ExternalIdentifier externalIdentifier) { + this.externalIdentifier = externalIdentifier; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Section.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Section.java new file mode 100644 index 000000000..b89bcac4c --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/Section.java @@ -0,0 +1,108 @@ +package org.opencdmp.model.descriptiontemplatedefinition; + + +import java.util.List; + +public class Section { + + public final static String _id = "id"; + private String id; + + public final static String _ordinal = "ordinal"; + private Integer ordinal; + + public final static String _defaultVisibility = "defaultVisibility"; + private Boolean defaultVisibility; + + public final static String _numbering = "numbering"; + private String numbering; //TODO maybe remove + + public final static String _title = "title"; + private String title; + + public final static String _description = "description"; + private String description; + + public final static String _extendedDescription = "extendedDescription"; + private String extendedDescription; //TODO maybe remove + + public final static String _sections = "sections"; + private List
sections; + + public final static String _fieldSets = "fieldSets"; + private List
fieldSets; + + 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 Boolean getDefaultVisibility() { + return defaultVisibility; + } + + public void setDefaultVisibility(Boolean defaultVisibility) { + this.defaultVisibility = defaultVisibility; + } + + public String getNumbering() { + return numbering; + } + + public void setNumbering(String numbering) { + this.numbering = numbering; + } + + 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 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; + } +} + + diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/BaseFieldData.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/BaseFieldData.java new file mode 100644 index 000000000..c085e69dd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/BaseFieldData.java @@ -0,0 +1,28 @@ +package org.opencdmp.model.descriptiontemplatedefinition.fielddata; + +import org.opencdmp.commons.enums.FieldType; + +public abstract class BaseFieldData { + + public final static String _label = "label"; + private String label; + + public final static String _fieldType = "fieldType"; + private FieldType fieldType; + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public FieldType getFieldType() { + return fieldType; + } + + public void setFieldType(FieldType fieldType) { + this.fieldType = fieldType; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/LabelAndMultiplicityData.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/LabelAndMultiplicityData.java new file mode 100644 index 000000000..d27b0f6bd --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/LabelAndMultiplicityData.java @@ -0,0 +1,13 @@ +package org.opencdmp.model.descriptiontemplatedefinition.fielddata; + +public class LabelAndMultiplicityData extends BaseFieldData { + public final static String _multipleSelect = "multipleSelect"; + private Boolean multipleSelect; + + public Boolean getMultipleSelect() { + return multipleSelect; + } + public void setMultipleSelect(Boolean multipleSelect) { + this.multipleSelect = multipleSelect; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/LabelData.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/LabelData.java new file mode 100644 index 000000000..7f9a44424 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/LabelData.java @@ -0,0 +1,7 @@ +package org.opencdmp.model.descriptiontemplatedefinition.fielddata; + + + +public class LabelData extends BaseFieldData { + +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/RadioBoxData.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/RadioBoxData.java new file mode 100644 index 000000000..792c46338 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/RadioBoxData.java @@ -0,0 +1,42 @@ +package org.opencdmp.model.descriptiontemplatedefinition.fielddata; + + +import java.util.List; + +public class RadioBoxData extends BaseFieldData { + + + public final static String _options = "options"; + private List options; + + public List getOptions() { + return options; + } + + public void setOptions(List options) { + this.options = options; + } + + public static class RadioBoxOption { + public final static String _label = "label"; + private String label; + public final static String _value = "value"; + private String value; + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/ReferenceTypeData.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/ReferenceTypeData.java new file mode 100644 index 000000000..703955520 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/ReferenceTypeData.java @@ -0,0 +1,27 @@ +package org.opencdmp.model.descriptiontemplatedefinition.fielddata; + +import org.opencdmp.model.ReferenceType; + +import java.util.UUID; + +public class ReferenceTypeData extends BaseFieldData { + private Boolean multipleSelect; + public final static String _multipleSelect = "multipleSelect"; + + private ReferenceType referenceType; + public final static String _referenceType = "referenceType"; + public Boolean getMultipleSelect() { + return multipleSelect; + } + public void setMultipleSelect(Boolean multipleSelect) { + this.multipleSelect = multipleSelect; + } + + public ReferenceType getReferenceType() { + return referenceType; + } + + public void setReferenceType(ReferenceType referenceType) { + this.referenceType = referenceType; + } +} diff --git a/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/SelectData.java b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/SelectData.java new file mode 100644 index 000000000..37dc35fa0 --- /dev/null +++ b/backend/core/src/main/java/org/opencdmp/model/descriptiontemplatedefinition/fielddata/SelectData.java @@ -0,0 +1,39 @@ +package org.opencdmp.model.descriptiontemplatedefinition.fielddata; + +import java.util.List; + +public class SelectData extends LabelAndMultiplicityData { + public final static String _options = "options"; + private List