From 4f1b05ab2042ee1f5c3dad07d4e96fb8d2ff29e4 Mon Sep 17 00:00:00 2001 From: sgiannopoulos Date: Thu, 8 Feb 2024 18:12:47 +0200 Subject: [PATCH 1/5] reference-type-refactor --- .../eu/eudat/authorization/Permission.java | 1 + .../enums/DmpBlueprintFieldCategory.java | 4 +- .../enums/DmpBlueprintSystemFieldType.java | 16 +- .../eu/eudat/commons/enums/FieldType.java | 42 +- .../eu/eudat/commons/enums/ReferenceType.java | 39 - .../descriptiontemplate/FieldEntity.java | 2 +- .../fielddata/ExternalSelectDataEntity.java | 171 --- .../fielddata/ReferenceTypeDataEntity.java | 33 + .../importexport/FieldImportExport.java | 2 +- .../fielddata/ExternalSelectImportExport.java | 174 --- .../LabelAndMultiplicityDataImportExport.java | 1 + .../ReferenceTypeDataImportExport.java | 34 + .../types/dmpblueprint/DefinitionEntity.java | 16 + .../dmpblueprint/ReferenceFieldEntity.java | 22 + .../types/dmpblueprint/SectionEntity.java | 6 + .../types/dmpblueprint/SystemFieldEntity.java | 2 + .../ReferenceFieldImportExport.java | 84 ++ .../importexport/SectionImportExport.java | 11 + .../java/eu/eudat/data/ReferenceEntity.java | 15 +- .../data/converters/DateToUTCConverter.java | 48 - .../enums/ReferenceTypeConverter.java | 11 - .../eudat/data/old/helpers/EntityBinder.java | 14 - .../DashboardReferenceTypeStatistics.java | 27 + .../eu/eudat/model/DashboardStatistics.java | 31 +- .../java/eu/eudat/model/PublicReference.java | 15 +- .../eu/eudat/model/PublicReferenceType.java | 30 + .../main/java/eu/eudat/model/Reference.java | 1 - .../model/builder/PublicReferenceBuilder.java | 52 +- .../builder/PublicReferenceTypeBuilder.java | 53 + .../eudat/model/builder/ReferenceBuilder.java | 37 +- .../DescriptionFieldDepositBuilder.java | 13 +- .../deposit/ReferenceDepositBuilder.java | 19 +- .../fielddata/ExternalSelectDataBuilder.java | 163 --- .../fielddata/ReferenceTypeDataBuilder.java | 31 + .../dmpblueprintdefinition/FieldBuilder.java | 5 - .../ReferenceFieldBuilder.java | 32 + .../SectionBuilder.java | 11 +- ...plateDefinitionFileTransformerBuilder.java | 52 +- .../DmpBlueprintFileTransformerBuilder.java | 6 +- .../ReferenceFileTransformerBuilder.java | 20 +- .../DefinitionSearchBuilder.java | 116 +- .../referencesearch/FieldSearchBuilder.java | 177 ++- .../ReferenceSearchBuilder.java | 199 ++- .../censorship/PublicReferenceCensor.java | 4 + .../censorship/PublicReferenceTypeCensor.java | 41 + .../model/censorship/ReferenceCensor.java | 2 + .../fielddata/ExternalSelectData.java | 164 --- .../fielddata/ReferenceTypeData.java | 25 + .../dmpblueprintdefinition/ExtraField.java | 2 + .../ReferenceField.java | 17 + ...iptionToPublicApiDatasetListingMapper.java | 5 +- .../DescriptionToPublicApiDatasetMapper.java | 11 +- .../DmpToPublicApiDmpListingMapper.java | 5 +- .../publicapi/DmpToPublicApiDmpMapper.java | 11 +- .../eudat/model/persist/ReferencePersist.java | 18 +- .../descriptionproperties/FieldPersist.java | 6 +- .../fielddata/BaseFieldDataPersist.java | 15 +- .../fielddata/ReferenceTypeDataPersist.java | 71 ++ .../ReferenceFieldPersist.java | 56 + .../SectionPersist.java | 16 +- .../SystemFieldPersist.java | 2 + .../DataRepositoryPublicModel.java | 10 +- .../ExternalDatasetPublicListingModel.java | 7 +- .../datasetwizard/RegistryPublicModel.java | 8 +- .../datasetwizard/ServicePublicModel.java | 7 +- .../grant/GrantPublicOverviewModel.java | 15 +- .../organisation/OrganizationPublicModel.java | 8 +- .../researcher/ResearcherPublicModel.java | 8 +- .../java/eu/eudat/query/ReferenceQuery.java | 45 +- .../ReferenceDefinitionSearchLookup.java | 2 +- .../eudat/query/lookup/ReferenceLookup.java | 13 +- .../query/lookup/ReferenceSearchLookup.java | 15 +- .../query/lookup/ReferenceTypeLookup.java | 4 - .../dashborad/DashboardServiceImpl.java | 95 +- .../dashborad/DashboardServiceProperties.java | 21 + .../dashborad/PublicApiConfiguration.java | 10 + .../description/DescriptionServiceImpl.java | 19 +- .../eu/eudat/service/dmp/DmpServiceImpl.java | 22 +- .../dmpblueprint/DmpBlueprintServiceImpl.java | 68 +- .../ExternalSelectFieldDataHelperService.java | 236 ---- .../FieldDataHelperServiceProvider.java | 19 +- .../ReferenceTypeFieldDataHelperService.java | 102 ++ .../prefilling/PrefillingServiceImpl.java | 267 ++--- .../publicapi/PublicApiConfiguration.java | 10 + .../publicapi/PublicApiProperties.java | 93 ++ .../service/reference/ReferenceService.java | 2 - .../reference/ReferenceServiceImpl.java | 61 +- .../remotefetcher/RemoteFetcherService.java | 43 +- .../RemoteFetcherServiceImpl.java | 1064 ++++++++--------- .../remotefetcher/RemoteFetcherUtils.java | 304 ++--- ...ublicDatasetsDescriptionDocumentation.java | 21 +- .../publicapi/PublicDmpsDocumentation.java | 23 +- .../controllers/v2/ReferenceController.java | 13 +- .../logic/managers/DatasetProfileManager.java | 6 +- .../logic/managers/ValidationManager.java | 11 +- .../services/ExternalValidationService.java | 11 +- .../src/main/resources/config/application.yml | 2 + .../src/main/resources/config/dashboard.yml | 4 + .../src/main/resources/config/permissions.yml | 5 + .../src/main/resources/config/public-api.yml | 10 + 100 files changed, 2376 insertions(+), 2617 deletions(-) delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/enums/ReferenceType.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/fielddata/ExternalSelectDataEntity.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/fielddata/ReferenceTypeDataEntity.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/ExternalSelectImportExport.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/ReferenceTypeDataImportExport.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/ReferenceFieldEntity.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/ReferenceFieldImportExport.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/converters/DateToUTCConverter.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/ReferenceTypeConverter.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/old/helpers/EntityBinder.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/DashboardReferenceTypeStatistics.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/PublicReferenceType.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicReferenceTypeBuilder.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/builder/descriptiontemplatedefinition/fielddata/ExternalSelectDataBuilder.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/builder/descriptiontemplatedefinition/fielddata/ReferenceTypeDataBuilder.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/ReferenceFieldBuilder.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/censorship/PublicReferenceTypeCensor.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/descriptiontemplatedefinition/fielddata/ExternalSelectData.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/descriptiontemplatedefinition/fielddata/ReferenceTypeData.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceField.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptiontemplatedefinition/fielddata/ReferenceTypeDataPersist.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/ReferenceFieldPersist.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/dashborad/DashboardServiceProperties.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/dashborad/PublicApiConfiguration.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/ExternalSelectFieldDataHelperService.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/ReferenceTypeFieldDataHelperService.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/publicapi/PublicApiConfiguration.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/publicapi/PublicApiProperties.java create mode 100644 dmp-backend/web/src/main/resources/config/dashboard.yml create mode 100644 dmp-backend/web/src/main/resources/config/public-api.yml diff --git a/dmp-backend/core/src/main/java/eu/eudat/authorization/Permission.java b/dmp-backend/core/src/main/java/eu/eudat/authorization/Permission.java index 754abd244..35d331bb7 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/authorization/Permission.java +++ b/dmp-backend/core/src/main/java/eu/eudat/authorization/Permission.java @@ -23,6 +23,7 @@ public final class Permission { 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"; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintFieldCategory.java b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintFieldCategory.java index 032d476e8..611b92281 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintFieldCategory.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintFieldCategory.java @@ -7,11 +7,13 @@ import java.util.Map; public enum DmpBlueprintFieldCategory implements DatabaseEnum { System((short) 0), - Extra((short) 1); + Extra((short) 1), + Reference((short) 1); public static class Names { public static final String System = "system"; public static final String Extra = "extra"; + public static final String Reference = "reference"; } private final Short value; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintSystemFieldType.java b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintSystemFieldType.java index 73a371059..1b24e93ce 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintSystemFieldType.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintSystemFieldType.java @@ -7,17 +7,11 @@ import java.util.Map; public enum DmpBlueprintSystemFieldType implements DatabaseEnum { - Text((short)0), //TODO: Rename to "Title" - HtmlText((short)1), //TODO: Rename to "Description" - Researchers((short)2), //TODO: replace by reference type - Organizations((short)3), //TODO: replace by reference type - Language((short)4), - Contact((short)5), - Funder((short)6), //TODO: replace by reference type - Grant((short)7), //TODO: replace by reference type - Project((short)8), //TODO: replace by reference type - License((short)9), //TODO: replace by reference type - AccessRights((short)10); + Title((short)0), + Description((short)1), + Language((short)2), + Contact((short)3), + AccessRights((short)4); private final Short value; DmpBlueprintSystemFieldType(Short value) { diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/FieldType.java b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/FieldType.java index 97324ed53..b0d68a715 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/FieldType.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/FieldType.java @@ -6,42 +6,29 @@ import eu.eudat.data.converters.enums.DatabaseEnum; import java.util.Map; public enum FieldType implements DatabaseEnum { - EXTERNAL_SELECT(Names.ExternalSelect), //TODO: remove SELECT(Names.Select), BOOLEAN_DECISION(Names.BooleanDecision), RADIO_BOX(Names.RadioBox), - INTERNAL_DMP_ENTRIES_RESEARCHERS(Names.InternalDmpResearchers), //TODO: remove INTERNAL_DMP_ENTRIES_DMPS(Names.InternalDmpDmps), //TODO: rename InternalEntitiesDmps - INTERNAL_DMP_ENTRIES_DATASETS(Names.InternalDmpDescriptions), + INTERNAL_DMP_ENTRIES_DATASETS(Names.InternalDmpDescriptions),//TODO: rename 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), - EXTERNAL_DATASETS(Names.ExternalDatasets), //TODO: replace with reference type - DATA_REPOSITORIES(Names.DataRepositories), //TODO: replace with reference type - JOURNAL_REPOSITORIES(Names.JournalRepositories), //TODO: replace with reference type - PUB_REPOSITORIES(Names.PubRepositories), //TODO: replace with reference type - LICENSES(Names.Licenses), //TODO: replace with reference type - TAXONOMIES(Names.Taxonomies), //TODO: replace with reference type - PUBLICATIONS(Names.Publications), //TODO: replace with reference type - REGISTRIES(Names.Registries), //TODO: replace with reference type - SERVICES(Names.Services), //TODO: replace with reference type TAGS(Names.Tags), - RESEARCHERS(Names.Researchers), //TODO: replace with reference type - ORGANIZATIONS(Names.Organizations), //TODO: replace with reference type + EXTERNAL_DATASETS(Names.ExternalDatasets), + REFERENCE_TYPES(Names.ReferenceTypes), DATASET_IDENTIFIER(Names.DatasetIdentifier), CURRENCY(Names.Currency), VALIDATION(Names.Validation); private final String value; public static class Names { - public static final String ExternalSelect = "externalSelect"; public static final String Select = "select"; public static final String BooleanDecision = "booleanDecision"; public static final String RadioBox = "radiobox"; - public static final String InternalDmpResearchers = "internalDmpResearchers"; public static final String InternalDmpDmps = "internalDmpDmps"; public static final String InternalDmpDescriptions = "internalDmpDatasets"; public static final String CheckBox = "checkBox"; @@ -50,21 +37,12 @@ public enum FieldType implements DatabaseEnum { public static final String RichTextarea = "richTextarea"; public static final String Upload = "upload"; public static final String DatePicker = "datePicker"; - public static final String ExternalDatasets = "externalDatasets"; - public static final String DataRepositories = "dataRepositories"; - public static final String JournalRepositories = "journalRepositories"; - public static final String PubRepositories = "pubRepositories"; - public static final String Licenses = "licenses"; - public static final String Taxonomies = "taxonomies"; - public static final String Publications = "publications"; - public static final String Registries = "registries"; - public static final String Services = "services"; public static final String Tags = "tags"; - public static final String Researchers = "researchers"; - public static final String Organizations = "organizations"; public static final String DatasetIdentifier = "datasetIdentifier"; public static final String Currency = "currency"; public static final String Validation = "validation"; + public static final String ReferenceTypes = "referenceTypes"; + public static final String ExternalDatasets = "externalDatasets"; } FieldType(String value) { @@ -82,15 +60,9 @@ public enum FieldType implements DatabaseEnum { return map.get(i); } - public static boolean isNotImplemented(FieldType fieldType){ - return fieldType.equals(FieldType.EXTERNAL_SELECT); - } public static boolean isReferenceType(FieldType fieldType){ - return fieldType.equals(FieldType.ORGANIZATIONS) || fieldType.equals(FieldType.RESEARCHERS) || fieldType.equals(FieldType.SERVICES) || - fieldType.equals(FieldType.REGISTRIES) || fieldType.equals(FieldType.PUBLICATIONS) || fieldType.equals(FieldType.TAXONOMIES)|| - fieldType.equals(FieldType.LICENSES) || fieldType.equals(FieldType.DATA_REPOSITORIES) || fieldType.equals(FieldType.PUB_REPOSITORIES)|| - fieldType.equals(FieldType.JOURNAL_REPOSITORIES) || fieldType.equals(FieldType.EXTERNAL_DATASETS); + return fieldType.equals(FieldType.REFERENCE_TYPES); } public static boolean isTextType(FieldType fieldType){ @@ -100,7 +72,7 @@ public enum FieldType implements DatabaseEnum { } public static boolean isTextListType(FieldType fieldType){ - return fieldType.equals(FieldType.SELECT) || fieldType.equals(FieldType.TAGS) || fieldType.equals(FieldType.INTERNAL_DMP_ENTRIES_RESEARCHERS) || fieldType.equals(FieldType.INTERNAL_DMP_ENTRIES_DMPS) || + return fieldType.equals(FieldType.SELECT) || fieldType.equals(FieldType.TAGS) || fieldType.equals(FieldType.INTERNAL_DMP_ENTRIES_DMPS) || fieldType.equals(FieldType.INTERNAL_DMP_ENTRIES_DATASETS); } diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/ReferenceType.java b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/ReferenceType.java deleted file mode 100644 index 89b79c5d7..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/ReferenceType.java +++ /dev/null @@ -1,39 +0,0 @@ -package eu.eudat.commons.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import eu.eudat.data.converters.enums.DatabaseEnum; - -import java.util.Map; - -public enum ReferenceType implements DatabaseEnum { - Taxonomies((short) 0), - Licenses((short) 1), - Publications((short) 2), - Journals((short) 3), - PubRepositories((short) 4), - DataRepositories((short) 5), - Registries((short) 6), - Services((short) 7), - Project((short) 8), - Funder((short) 9), - Datasets((short) 10), - Organizations((short) 11), - Grants((short) 12), - Researcher((short) 13); - private final Short value; - - ReferenceType(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(ReferenceType.class); - - public static ReferenceType of(Short i) { - return map.get(i); - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/FieldEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/FieldEntity.java index de5bf2d28..af80d187d 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/FieldEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/FieldEntity.java @@ -30,7 +30,7 @@ public class FieldEntity { @XmlElement(name = UploadDataEntity.XmlElementName, type = UploadDataEntity.class), @XmlElement(name = RadioBoxDataEntity.XmlElementName, type = RadioBoxDataEntity.class), @XmlElement(name = SelectDataEntity.XmlElementName, type = SelectDataEntity.class), - @XmlElement(name = ExternalSelectDataEntity.XmlElementName, type = ExternalSelectDataEntity.class), + @XmlElement(name = ReferenceTypeDataEntity.XmlElementName, type = ReferenceTypeDataEntity.class) }) private BaseFieldDataEntity data; @XmlElementWrapper(name = "validations") diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/fielddata/ExternalSelectDataEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/fielddata/ExternalSelectDataEntity.java deleted file mode 100644 index 82a95527a..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/fielddata/ExternalSelectDataEntity.java +++ /dev/null @@ -1,171 +0,0 @@ -package eu.eudat.commons.types.descriptiontemplate.fielddata; - -import jakarta.xml.bind.annotation.*; - -import java.util.List; - - -@XmlAccessorType(XmlAccessType.FIELD) -public class ExternalSelectDataEntity extends LabelAndMultiplicityDataEntity { - public static final String XmlElementName = "externalSelectData"; - - @XmlAccessorType(XmlAccessType.FIELD) - public static class ExternalSelectAuthDataEntity { - @XmlAttribute(name="url") - private String url; - @XmlAttribute(name="method") - private String method; - @XmlAttribute(name="body") - private String body; - @XmlAttribute(name="path") - private String path; - @XmlAttribute(name="type") - private String type; - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - } - - @XmlAccessorType(XmlAccessType.FIELD) - public static class ExternalSelectSourceBindingEntity { - @XmlAttribute(name="label") - private String label; - @XmlAttribute(name="value") - private String value; - @XmlAttribute(name="source") - private String source; - - 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; - } - - public String getSource() { - return source; - } - public void setSource(String source) { - this.source = source; - } - } - - @XmlAccessorType(XmlAccessType.FIELD) - public static class ExternalSelectSourceEntity { - @XmlAttribute(name="url") - private String url; - @XmlAttribute(name="method") - private String method; - @XmlAttribute(name="optionsRoot") - private String optionsRoot; - @XmlElement(name="sourceBinding") - private ExternalSelectSourceBindingEntity sourceBinding; - @XmlAttribute(name="hasAuth") - private Boolean hasAuth; - @XmlElement(name="auth") - private ExternalSelectAuthDataEntity auth; - - public String getOptionsRoot() { - return optionsRoot; - } - public void setOptionsRoot(String optionsRoot) { - this.optionsRoot = optionsRoot; - } - - public String getUrl() { - return url; - } - public void setUrl(String url) { - this.url = url; - } - - public Boolean getHasAuth() { - return hasAuth; - } - - public void setHasAuth(Boolean hasAuth) { - this.hasAuth = hasAuth; - } - - public ExternalSelectAuthDataEntity getAuth() { - return auth; - } - - public void setAuth(ExternalSelectAuthDataEntity auth) { - this.auth = auth; - } - - public ExternalSelectSourceBindingEntity getSourceBinding() { - return sourceBinding; - } - public void setSourceBinding(ExternalSelectSourceBindingEntity sourceBinding) { - this.sourceBinding = sourceBinding; - } - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - } - - @XmlElementWrapper(name = "sources") - @XmlElement(name = "source") - private List sources; - - public List getSources() { - return sources; - } - - public void setSources(List externalSelectSourceEntityList) { - this.sources = externalSelectSourceEntityList; - } -} - - diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/fielddata/ReferenceTypeDataEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/fielddata/ReferenceTypeDataEntity.java new file mode 100644 index 000000000..48d0ab695 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/fielddata/ReferenceTypeDataEntity.java @@ -0,0 +1,33 @@ +package eu.eudat.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/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/FieldImportExport.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/FieldImportExport.java index a501d046e..3064ac7aa 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/FieldImportExport.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/FieldImportExport.java @@ -40,7 +40,7 @@ public class FieldImportExport { @XmlElement(name = UploadDataImportExport.XmlElementName, type = UploadDataImportExport.class), @XmlElement(name = RadioBoxDataImportExport.XmlElementName, type = RadioBoxDataImportExport.class), @XmlElement(name = SelectDataImportExport.XmlElementName, type = SelectDataImportExport.class), - @XmlElement(name = ExternalSelectImportExport.XmlElementName, type = ExternalSelectImportExport.class), + @XmlElement(name = ReferenceTypeDataImportExport.XmlElementName, type = ReferenceTypeDataImportExport.class), }) private BaseFieldDataImportExport data; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/ExternalSelectImportExport.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/ExternalSelectImportExport.java deleted file mode 100644 index f691f5e26..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/ExternalSelectImportExport.java +++ /dev/null @@ -1,174 +0,0 @@ -package eu.eudat.commons.types.descriptiontemplate.importexport.fielddata; - -import jakarta.xml.bind.annotation.*; - -import java.util.List; - -@XmlAccessorType(XmlAccessType.FIELD) -public class ExternalSelectImportExport extends LabelAndMultiplicityDataImportExport { - public static final String XmlElementName = "externalSelectData"; - - - @XmlAccessorType(XmlAccessType.FIELD) - public static class ExternalSelectAuthImportExport { - @XmlAttribute(name="url") - private String url; - @XmlAttribute(name="method") - private String method; - @XmlAttribute(name="body") - private String body; - @XmlAttribute(name="path") - private String path; - @XmlAttribute(name="type") - private String type; - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - } - - @XmlAccessorType(XmlAccessType.FIELD) - public static class ExternalSelectSourceBindingImportExport { - @XmlAttribute(name="label") - private String label; - @XmlAttribute(name="value") - private String value; - @XmlAttribute(name="source") - private String source; - - 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; - } - - public String getSource() { - return source; - } - public void setSource(String source) { - this.source = source; - } - } - - @XmlAccessorType(XmlAccessType.FIELD) - public static class ExternalSelectSourceImportExport { - @XmlAttribute(name="url") - private String url; - @XmlAttribute(name="method") - private String method; - @XmlAttribute(name="optionsRoot") - private String optionsRoot; - @XmlElement(name="sourceBinding") - private ExternalSelectSourceBindingImportExport sourceBinding; - @XmlAttribute(name="hasAuth") - private Boolean hasAuth; - @XmlElement(name="auth") - private ExternalSelectAuthImportExport auth; - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - public String getOptionsRoot() { - return optionsRoot; - } - - public void setOptionsRoot(String optionsRoot) { - this.optionsRoot = optionsRoot; - } - - public ExternalSelectSourceBindingImportExport getSourceBinding() { - return sourceBinding; - } - - public void setSourceBinding(ExternalSelectSourceBindingImportExport sourceBinding) { - this.sourceBinding = sourceBinding; - } - - public Boolean getHasAuth() { - return hasAuth; - } - - public void setHasAuth(Boolean hasAuth) { - this.hasAuth = hasAuth; - } - - public ExternalSelectAuthImportExport getAuth() { - return auth; - } - - public void setAuth(ExternalSelectAuthImportExport auth) { - this.auth = auth; - } - } - @XmlElementWrapper(name = "sources") - @XmlElement(name = "source") - private List sources; - - public List getSources() { - return sources; - } - - public void setSources(List sources) { - this.sources = sources; - } - -} - - diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/LabelAndMultiplicityDataImportExport.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/LabelAndMultiplicityDataImportExport.java index a6905b7b7..c617eb135 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/LabelAndMultiplicityDataImportExport.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/LabelAndMultiplicityDataImportExport.java @@ -20,3 +20,4 @@ public class LabelAndMultiplicityDataImportExport extends BaseFieldDataImportExp } } + diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/ReferenceTypeDataImportExport.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/ReferenceTypeDataImportExport.java new file mode 100644 index 000000000..869eacb9f --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/descriptiontemplate/importexport/fielddata/ReferenceTypeDataImportExport.java @@ -0,0 +1,34 @@ +package eu.eudat.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/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/DefinitionEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/DefinitionEntity.java index 301927b11..996c8ae98 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/DefinitionEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/DefinitionEntity.java @@ -2,7 +2,9 @@ package eu.eudat.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) @@ -17,4 +19,18 @@ public class DefinitionEntity { 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/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/ReferenceFieldEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/ReferenceFieldEntity.java new file mode 100644 index 000000000..aff2ac1d2 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/ReferenceFieldEntity.java @@ -0,0 +1,22 @@ +package eu.eudat.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 ReferenceFieldEntity extends FieldEntity { + + @XmlAttribute(name="referenceTypeId") + private UUID referenceTypeId; + + public UUID getReferenceTypeId() { + return referenceTypeId; + } + + public void setReferenceTypeId(UUID referenceTypeId) { + this.referenceTypeId = referenceTypeId; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SectionEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SectionEntity.java index 8590c78d6..100266770 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SectionEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SectionEntity.java @@ -3,6 +3,7 @@ package eu.eudat.commons.types.dmpblueprint; import eu.eudat.commons.enums.DmpBlueprintFieldCategory; import jakarta.xml.bind.annotation.*; +import java.util.ArrayList; import java.util.List; import java.util.UUID; @@ -25,6 +26,7 @@ public class SectionEntity { @XmlElements({ @XmlElement(name = DmpBlueprintFieldCategory.Names.Extra, type = ExtraFieldEntity.class), @XmlElement(name = DmpBlueprintFieldCategory.Names.System, type = SystemFieldEntity.class), + @XmlElement(name = DmpBlueprintFieldCategory.Names.Reference, type = ReferenceFieldEntity.class), }) private List fields; @@ -84,4 +86,8 @@ public class SectionEntity { this.descriptionTemplates = descriptionTemplates; } + public List getAllField(){ + return this.getFields() != null ? this.getFields() : new ArrayList<>(); + } + } diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SystemFieldEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SystemFieldEntity.java index 104389902..cfba900eb 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SystemFieldEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SystemFieldEntity.java @@ -5,6 +5,8 @@ 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 { diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/ReferenceFieldImportExport.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/ReferenceFieldImportExport.java new file mode 100644 index 000000000..05ae2e63b --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/ReferenceFieldImportExport.java @@ -0,0 +1,84 @@ +package eu.eudat.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 ReferenceFieldImportExport { + + @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; + + 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; + } + + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/SectionImportExport.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/SectionImportExport.java index 44f208c6e..641405acf 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/SectionImportExport.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/SectionImportExport.java @@ -22,6 +22,9 @@ public class SectionImportExport { @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") @@ -76,6 +79,14 @@ public class SectionImportExport { this.extraFields = extraFields; } + public List getReferenceFields() { + return referenceFields; + } + + public void setReferenceFields(List referenceFields) { + this.referenceFields = referenceFields; + } + public boolean isHasTemplates() { return hasTemplates; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/ReferenceEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/ReferenceEntity.java index efb80df9f..c3dcda35c 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/data/ReferenceEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/data/ReferenceEntity.java @@ -2,10 +2,8 @@ package eu.eudat.data; import eu.eudat.commons.enums.IsActive; import eu.eudat.commons.enums.ReferenceSourceType; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.data.converters.enums.IsActiveConverter; import eu.eudat.data.converters.enums.ReferenceSourceTypeConverter; -import eu.eudat.data.converters.enums.ReferenceTypeConverter; import eu.eudat.data.tenant.TenantScopedBaseEntity; import jakarta.persistence.*; @@ -30,10 +28,9 @@ public class ReferenceEntity extends TenantScopedBaseEntity { public static final int _labelLength = 500; @Column(name = "type", nullable = false) - @Convert(converter = ReferenceTypeConverter.class) - private ReferenceType type; + private UUID typeId; - public static final String _type = "type"; + public static final String _typeId = "typeId"; @Column(name = "description") private String description; @@ -109,12 +106,12 @@ public class ReferenceEntity extends TenantScopedBaseEntity { this.label = label; } - public ReferenceType getType() { - return type; + public UUID getTypeId() { + return typeId; } - public void setType(ReferenceType type) { - this.type = type; + public void setTypeId(UUID typeId) { + this.typeId = typeId; } public String getDescription() { diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/converters/DateToUTCConverter.java b/dmp-backend/core/src/main/java/eu/eudat/data/converters/DateToUTCConverter.java deleted file mode 100644 index d261435d6..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/data/converters/DateToUTCConverter.java +++ /dev/null @@ -1,48 +0,0 @@ -package eu.eudat.data.converters; - -import jakarta.persistence.AttributeConverter; -import jakarta.persistence.Converter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -/** - * Created by ikalyvas on 9/25/2018. - */ -@Converter -public class DateToUTCConverter implements AttributeConverter { - private static final Logger logger = LoggerFactory.getLogger(DateToUTCConverter.class); - - @Override - public Date convertToDatabaseColumn(Date attribute) { - if(attribute == null) return null; - DateFormat formatterIST = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - formatterIST.setTimeZone(TimeZone.getTimeZone("UTC")); - try { - String date = formatterIST.format(attribute); - return formatterIST.parse(date); - } catch (ParseException e) { - logger.error(e.getMessage(), e); - } - return null; - } - - @Override - public Date convertToEntityAttribute(Date dbData) { - if(dbData == null) return null; - DateFormat formatterIST = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - formatterIST.setTimeZone(TimeZone.getTimeZone("UTC")); - try { - String date = formatterIST.format(dbData); - return formatterIST.parse(date); - } catch (ParseException e) { - logger.error(e.getMessage(), e); - } - return null; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/ReferenceTypeConverter.java b/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/ReferenceTypeConverter.java deleted file mode 100644 index a8adb12c7..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/ReferenceTypeConverter.java +++ /dev/null @@ -1,11 +0,0 @@ -package eu.eudat.data.converters.enums; - -import eu.eudat.commons.enums.ReferenceType; -import jakarta.persistence.Converter; - -@Converter -public class ReferenceTypeConverter extends DatabaseEnumConverter { - public ReferenceType of(Short i) { - return ReferenceType.of(i); - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/old/helpers/EntityBinder.java b/dmp-backend/core/src/main/java/eu/eudat/data/old/helpers/EntityBinder.java deleted file mode 100644 index 6a8148380..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/data/old/helpers/EntityBinder.java +++ /dev/null @@ -1,14 +0,0 @@ -package eu.eudat.data.old.helpers; - -import jakarta.persistence.Tuple; -import java.util.List; - -public class EntityBinder { - public static T fromTuple(List tuple, String path) { - try { - return (T) tuple.get(0).get(path); - }catch (IllegalArgumentException illegalArgument){ - return null; - } - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/DashboardReferenceTypeStatistics.java b/dmp-backend/core/src/main/java/eu/eudat/model/DashboardReferenceTypeStatistics.java new file mode 100644 index 000000000..cbca3cf66 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/DashboardReferenceTypeStatistics.java @@ -0,0 +1,27 @@ +package eu.eudat.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/dmp-backend/core/src/main/java/eu/eudat/model/DashboardStatistics.java b/dmp-backend/core/src/main/java/eu/eudat/model/DashboardStatistics.java index a288a7944..8a4ea7782 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/DashboardStatistics.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/DashboardStatistics.java @@ -1,5 +1,8 @@ package eu.eudat.model; +import java.util.List; +import java.util.UUID; + public class DashboardStatistics { private long dmpCount; @@ -7,16 +10,8 @@ public class DashboardStatistics { public static final String _dmpCount = "dmpCount"; private long descriptionCount; - - public static final String _descriptionCount = "descriptionCount"; - - private long organizationCount; - - public static final String _organizationCount = "organizationCount"; - - private long grantCount; - - public static final String _grantCount = "grantCount"; + + private List referenceTypeStatistics; public long getDmpCount() { return dmpCount; @@ -34,19 +29,11 @@ public class DashboardStatistics { this.descriptionCount = descriptionCount; } - public long getOrganizationCount() { - return organizationCount; + public List getReferenceTypeStatistics() { + return referenceTypeStatistics; } - public void setOrganizationCount(long organizationCount) { - this.organizationCount = organizationCount; - } - - public long getGrantCount() { - return grantCount; - } - - public void setGrantCount(long grantCount) { - this.grantCount = grantCount; + public void setReferenceTypeStatistics(List referenceTypeStatistics) { + this.referenceTypeStatistics = referenceTypeStatistics; } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/PublicReference.java b/dmp-backend/core/src/main/java/eu/eudat/model/PublicReference.java index 0eac64a25..83d885768 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/PublicReference.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/PublicReference.java @@ -1,12 +1,5 @@ package eu.eudat.model; -import eu.eudat.commons.enums.IsActive; -import eu.eudat.commons.enums.ReferenceSourceType; -import eu.eudat.commons.enums.ReferenceType; -import eu.eudat.model.referencedefinition.Definition; - -import java.time.Instant; -import java.util.List; import java.util.UUID; public class PublicReference { @@ -17,7 +10,7 @@ public class PublicReference { private String label; public static final String _label = "label"; - private ReferenceType type; + private PublicReferenceType type; public static final String _type = "type"; private String description; @@ -42,11 +35,11 @@ public class PublicReference { this.label = label; } - public ReferenceType getType() { + public PublicReferenceType getType() { return type; } - public void setType(ReferenceType type) { + public void setType(PublicReferenceType type) { this.type = type; } @@ -66,3 +59,5 @@ public class PublicReference { this.reference = reference; } } + + diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/PublicReferenceType.java b/dmp-backend/core/src/main/java/eu/eudat/model/PublicReferenceType.java new file mode 100644 index 000000000..0c3a8fac0 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/PublicReferenceType.java @@ -0,0 +1,30 @@ +package eu.eudat.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"; + + + 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/dmp-backend/core/src/main/java/eu/eudat/model/Reference.java b/dmp-backend/core/src/main/java/eu/eudat/model/Reference.java index a17a04d03..7cfd0081a 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/Reference.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/Reference.java @@ -1,6 +1,5 @@ package eu.eudat.model; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.commons.enums.IsActive; import eu.eudat.commons.enums.ReferenceSourceType; import eu.eudat.model.referencedefinition.Definition; diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicReferenceBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicReferenceBuilder.java index 66a63f521..9a89e59f6 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicReferenceBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicReferenceBuilder.java @@ -1,10 +1,20 @@ package eu.eudat.model.builder; import eu.eudat.authorization.AuthorizationFlags; +import eu.eudat.commons.enums.IsActive; import eu.eudat.convention.ConventionService; +import eu.eudat.data.DmpReferenceEntity; import eu.eudat.data.ReferenceEntity; +import eu.eudat.model.PublicDmp; +import eu.eudat.model.PublicDmpUser; import eu.eudat.model.PublicReference; +import eu.eudat.model.PublicReferenceType; +import eu.eudat.query.DmpQuery; +import eu.eudat.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; @@ -15,17 +25,22 @@ 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) { + 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) { @@ -40,6 +55,10 @@ public class PublicReferenceBuilder extends BaseBuilder(); + + 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(); @@ -47,10 +66,39 @@ public class PublicReferenceBuilder extends BaseBuilder 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/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicReferenceTypeBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicReferenceTypeBuilder.java new file mode 100644 index 000000000..e9cb821c3 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/PublicReferenceTypeBuilder.java @@ -0,0 +1,53 @@ +package eu.eudat.model.builder; + +import eu.eudat.authorization.AuthorizationFlags; +import eu.eudat.convention.ConventionService; +import eu.eudat.data.ReferenceTypeEntity; +import eu.eudat.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()); + models.add(m); + } + this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); + return models; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/ReferenceBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/ReferenceBuilder.java index 2174e6ed3..8d4585747 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/ReferenceBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/ReferenceBuilder.java @@ -8,9 +8,11 @@ import eu.eudat.data.DescriptionEntity; import eu.eudat.data.ReferenceEntity; import eu.eudat.model.DmpReference; import eu.eudat.model.Reference; +import eu.eudat.model.ReferenceType; import eu.eudat.model.User; import eu.eudat.model.builder.referencedefinition.DefinitionBuilder; import eu.eudat.query.DmpReferenceQuery; +import eu.eudat.query.ReferenceTypeQuery; import eu.eudat.query.UserQuery; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; @@ -68,6 +70,9 @@ public class ReferenceBuilder extends BaseBuilder{ 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(); @@ -86,7 +91,7 @@ public class ReferenceBuilder extends BaseBuilder{ 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 (fields.hasField(this.asIndexer(Reference._type))) m.setType(d.getType()); + 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())); models.add(m); @@ -95,6 +100,36 @@ public class ReferenceBuilder extends BaseBuilder{ 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; diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/deposit/DescriptionFieldDepositBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/deposit/DescriptionFieldDepositBuilder.java index ba146f952..e39864af1 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/deposit/DescriptionFieldDepositBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/deposit/DescriptionFieldDepositBuilder.java @@ -80,11 +80,9 @@ public class DescriptionFieldDepositBuilder extends BaseDepositBuilder m.setFieldType(FieldType.AUTO_COMPLETE); case SELECT -> m.setFieldType(FieldType.WORD_LIST); case BOOLEAN_DECISION -> m.setFieldType(FieldType.BOOLEAN_DECISION); case RADIO_BOX -> m.setFieldType(FieldType.RADIO_BOX); - case INTERNAL_DMP_ENTRIES_RESEARCHERS -> m.setFieldType(FieldType.INTERNAL_DMP_ENTRIES_RESEARCHERS); case INTERNAL_DMP_ENTRIES_DMPS -> m.setFieldType(FieldType.INTERNAL_DMP_ENTRIES_DMPS); case INTERNAL_DMP_ENTRIES_DATASETS -> m.setFieldType(FieldType.INTERNAL_DMP_ENTRIES_DATASETS); case CHECK_BOX -> m.setFieldType(FieldType.CHECK_BOX); @@ -94,20 +92,11 @@ public class DescriptionFieldDepositBuilder extends BaseDepositBuilder m.setFieldType(FieldType.UPLOAD); case DATE_PICKER -> m.setFieldType(FieldType.DATE_PICKER); case EXTERNAL_DATASETS -> m.setFieldType(FieldType.EXTERNAL_DATASETS); - case DATA_REPOSITORIES -> m.setFieldType(FieldType.DATA_REPOSITORIES); - case JOURNAL_REPOSITORIES -> m.setFieldType(FieldType.JOURNAL_REPOSITORIES); - case PUB_REPOSITORIES -> m.setFieldType(FieldType.PUB_REPOSITORIES); - case LICENSES -> m.setFieldType(FieldType.LICENSES); - case PUBLICATIONS -> m.setFieldType(FieldType.PUBLICATIONS); - case REGISTRIES -> m.setFieldType(FieldType.REGISTRIES); - case SERVICES -> m.setFieldType(FieldType.SERVICES); +// case REFERENCE_TYPES -> m.setFieldType(FieldType.REFERENCE_TYPES); //TODO new reference logic case TAGS -> m.setFieldType(FieldType.TAGS); - case RESEARCHERS -> m.setFieldType(FieldType.RESEARCHERS); - case ORGANIZATIONS -> m.setFieldType(FieldType.ORGANIZATIONS); case DATASET_IDENTIFIER -> m.setFieldType(FieldType.DATASET_IDENTIFIER); case CURRENCY -> m.setFieldType(FieldType.CURRENCY); case VALIDATION -> m.setFieldType(FieldType.VALIDATION); - case TAXONOMIES -> m.setFieldType(FieldType.TAXONOMIES); default -> throw new MyApplicationException("unrecognized type " + field.getData().getFieldType()); } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/deposit/ReferenceDepositBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/deposit/ReferenceDepositBuilder.java index 069392b9e..0c9896a89 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/deposit/ReferenceDepositBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/deposit/ReferenceDepositBuilder.java @@ -6,7 +6,6 @@ import eu.eudat.commons.types.reference.DefinitionEntity; import eu.eudat.convention.ConventionService; import eu.eudat.data.ReferenceEntity; import eu.eudat.depositinterface.enums.ReferenceSourceType; -import eu.eudat.depositinterface.enums.ReferenceType; import eu.eudat.depositinterface.models.ReferenceDepositModel; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.exception.MyApplicationException; @@ -67,23 +66,7 @@ public class ReferenceDepositBuilder extends BaseDepositBuilder m.setSourceType(ReferenceSourceType.External); default -> throw new MyApplicationException("unrecognized type " + d.getSourceType().getValue()); } - switch (d.getType()){ - case Taxonomies -> m.setType(ReferenceType.Taxonomies); - case Licenses -> m.setType(ReferenceType.Licenses); - case Publications -> m.setType(ReferenceType.Publications); - case Journals -> m.setType(ReferenceType.Journals); - case PubRepositories -> m.setType(ReferenceType.PubRepositories); - case DataRepositories -> m.setType(ReferenceType.DataRepositories); - case Registries -> m.setType(ReferenceType.Registries); - case Services -> m.setType(ReferenceType.Services); - case Project -> m.setType(ReferenceType.Project); - case Funder -> m.setType(ReferenceType.Funder); - case Datasets -> m.setType(ReferenceType.Datasets); - case Organizations -> m.setType(ReferenceType.Organizations); - case Grants -> m.setType(ReferenceType.Grants); - case Researcher -> m.setType(ReferenceType.Researcher); - default -> throw new MyApplicationException("unrecognized type " + d.getType().getValue()); - } +// m.setType(d.getTypeId()); //TODO new reference logic models.add(new DepositBuilderItemResponse<>(m, d)); } this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/descriptiontemplatedefinition/fielddata/ExternalSelectDataBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/descriptiontemplatedefinition/fielddata/ExternalSelectDataBuilder.java deleted file mode 100644 index a21820ce2..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/descriptiontemplatedefinition/fielddata/ExternalSelectDataBuilder.java +++ /dev/null @@ -1,163 +0,0 @@ -package eu.eudat.model.builder.descriptiontemplatedefinition.fielddata; - -import eu.eudat.authorization.AuthorizationFlags; -import eu.eudat.commons.types.descriptiontemplate.fielddata.ExternalSelectDataEntity; -import eu.eudat.convention.ConventionService; -import eu.eudat.model.builder.BaseBuilder; -import eu.eudat.model.descriptiontemplatedefinition.fielddata.ExternalSelectData; -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 ExternalSelectDataBuilder extends BaseFieldDataBuilder { - private final BuilderFactory builderFactory; - @Autowired - public ExternalSelectDataBuilder(ConventionService conventionService, BuilderFactory builderFactory) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(ExternalSelectDataBuilder.class))); - this.builderFactory = builderFactory; - } - - @Override - protected ExternalSelectData getInstance() { - return new ExternalSelectData(); - } - - @Override - protected void buildChild(FieldSet fields, ExternalSelectDataEntity d, ExternalSelectData m) { - FieldSet sourcesFields = fields.extractPrefixed(this.asPrefix(ExternalSelectData._sources)); - if (fields.hasField(this.asIndexer(ExternalSelectData._multipleSelect))) m.setMultipleSelect(d.getMultipleSelect()); - if (!sourcesFields.isEmpty() && d.getSources() != null) m.setSources(this.builderFactory.builder(ExternalSelectSourceBuilder.class).authorize(this.authorize).build(sourcesFields, d.getSources())); - - } - - @Component - @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class ExternalSelectSourceBindingBuilder extends BaseBuilder { - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public ExternalSelectSourceBindingBuilder( - ConventionService conventionService) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(SelectDataBuilder.SelectOptionBuilder.class))); - } - - public ExternalSelectSourceBindingBuilder 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 (ExternalSelectDataEntity.ExternalSelectSourceBindingEntity d : data) { - ExternalSelectData.ExternalSelectSourceBinding m = new ExternalSelectData.ExternalSelectSourceBinding(); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectSourceBinding._label))) m.setLabel(d.getLabel()); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectSourceBinding._value))) m.setValue(d.getValue()); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectSourceBinding._source))) m.setSource(d.getSource()); - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } - } - - @Component - @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class ExternalSelectSourceBuilder extends BaseBuilder { - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - private final BuilderFactory builderFactory; - - @Autowired - public ExternalSelectSourceBuilder( - ConventionService conventionService, BuilderFactory builderFactory) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(ExternalSelectSourceBuilder.class))); - this.builderFactory = builderFactory; - } - - public ExternalSelectSourceBuilder 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 sourceBindingFields = fields.extractPrefixed(this.asPrefix(ExternalSelectData.ExternalSelectSource._sourceBinding)); - FieldSet authFields = fields.extractPrefixed(this.asPrefix(ExternalSelectData.ExternalSelectSource._auth)); - List models = new ArrayList<>(); - for (ExternalSelectDataEntity.ExternalSelectSourceEntity d : data) { - ExternalSelectData.ExternalSelectSource m = new ExternalSelectData.ExternalSelectSource(); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectSource._url))) m.setUrl(d.getUrl()); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectSource._optionsRoot))) m.setOptionsRoot(d.getOptionsRoot()); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectSource._hasAuth))) m.setHasAuth(d.getHasAuth()); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectSource._method))) m.setMethod(d.getMethod()); - if (!sourceBindingFields.isEmpty() && d.getSourceBinding() != null) m.setSourceBinding(this.builderFactory.builder(ExternalSelectSourceBindingBuilder.class).authorize(this.authorize).build(sourceBindingFields, d.getSourceBinding())); - if (!authFields.isEmpty() && d.getAuth() != null) m.setAuth(this.builderFactory.builder(ExternalSelectAuthDataBuilder.class).authorize(this.authorize).build(authFields, d.getAuth())); - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } - } - - @Component - @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class ExternalSelectAuthDataBuilder extends BaseBuilder { - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public ExternalSelectAuthDataBuilder( - ConventionService conventionService) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(ExternalSelectAuthDataBuilder.class))); - } - - public ExternalSelectAuthDataBuilder 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 (ExternalSelectDataEntity.ExternalSelectAuthDataEntity d : data) { - ExternalSelectData.ExternalSelectAuthData m = new ExternalSelectData.ExternalSelectAuthData(); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectAuthData._url))) m.setUrl(d.getUrl()); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectAuthData._method))) m.setMethod(d.getMethod()); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectAuthData._body))) m.setBody(d.getBody()); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectAuthData._path))) m.setPath(d.getPath()); - if (fields.hasField(this.asIndexer(ExternalSelectData.ExternalSelectAuthData._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/dmp-backend/core/src/main/java/eu/eudat/model/builder/descriptiontemplatedefinition/fielddata/ReferenceTypeDataBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/descriptiontemplatedefinition/fielddata/ReferenceTypeDataBuilder.java new file mode 100644 index 000000000..b84a8826f --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/descriptiontemplatedefinition/fielddata/ReferenceTypeDataBuilder.java @@ -0,0 +1,31 @@ +package eu.eudat.model.builder.descriptiontemplatedefinition.fielddata; + +import eu.eudat.commons.types.descriptiontemplate.fielddata.ReferenceTypeDataEntity; +import eu.eudat.convention.ConventionService; +import eu.eudat.model.descriptiontemplatedefinition.fielddata.ReferenceTypeData; +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 { + + @Autowired + public ReferenceTypeDataBuilder(ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceTypeDataBuilder.class))); + } + + 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()); + if (fields.hasField(this.asIndexer(ReferenceTypeData._referenceTypeId))) m.setReferenceTypeId(d.getReferenceTypeId()); + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/FieldBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/FieldBuilder.java index 8241d19a1..db4492ef4 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/FieldBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/FieldBuilder.java @@ -1,19 +1,14 @@ package eu.eudat.model.builder.dmpblueprintdefinition; import eu.eudat.authorization.AuthorizationFlags; -import eu.eudat.commons.types.dmpblueprint.DescriptionTemplateEntity; -import eu.eudat.commons.types.dmpblueprint.ExtraFieldEntity; import eu.eudat.commons.types.dmpblueprint.FieldEntity; import eu.eudat.convention.ConventionService; import eu.eudat.model.builder.BaseBuilder; -import eu.eudat.model.dmpblueprintdefinition.DescriptionTemplate; -import eu.eudat.model.dmpblueprintdefinition.ExtraField; import eu.eudat.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.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/ReferenceFieldBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/ReferenceFieldBuilder.java new file mode 100644 index 000000000..bc7714d42 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/ReferenceFieldBuilder.java @@ -0,0 +1,32 @@ +package eu.eudat.model.builder.dmpblueprintdefinition; + +import eu.eudat.commons.types.dmpblueprint.ReferenceFieldEntity; +import eu.eudat.convention.ConventionService; +import eu.eudat.model.dmpblueprintdefinition.ReferenceField; +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 { + + @Autowired + public ReferenceFieldBuilder( + ConventionService conventionService) { + super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceFieldBuilder.class))); + } + + protected ReferenceField getInstance() { + return new ReferenceField(); + } + + protected ReferenceField buildChild(FieldSet fields, ReferenceFieldEntity data, ReferenceField model) { + if (fields.hasField(this.asIndexer(ReferenceField._referenceTypeId))) model.setReferenceTypeId(data.getReferenceTypeId()); + return model; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/SectionBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/SectionBuilder.java index 1b9f0ef29..3af4ee3b7 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/SectionBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/SectionBuilder.java @@ -2,10 +2,7 @@ package eu.eudat.model.builder.dmpblueprintdefinition; import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.commons.enums.DmpBlueprintFieldCategory; -import eu.eudat.commons.types.dmpblueprint.ExtraFieldEntity; -import eu.eudat.commons.types.dmpblueprint.FieldEntity; -import eu.eudat.commons.types.dmpblueprint.SectionEntity; -import eu.eudat.commons.types.dmpblueprint.SystemFieldEntity; +import eu.eudat.commons.types.dmpblueprint.*; import eu.eudat.convention.ConventionService; import eu.eudat.model.builder.BaseBuilder; import eu.eudat.model.dmpblueprintdefinition.Section; @@ -63,11 +60,13 @@ public class SectionBuilder extends BaseBuilder { 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) { - List systemFieldEntities = d.getFields().stream().filter(x-> DmpBlueprintFieldCategory.System.equals(x.getCategory())).map(x-> (SystemFieldEntity)x).toList(); - List extraFieldEntities = d.getFields().stream().filter(x-> DmpBlueprintFieldCategory.Extra.equals(x.getCategory())).map(x-> (ExtraFieldEntity)x).toList(); 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.Reference.equals(x.getCategory())).map(x-> (ReferenceFieldEntity)x).toList(); + m.getFields().addAll(this.builderFactory.builder(ReferenceFieldBuilder.class).authorize(this.authorize).build(fieldsFields, referenceFieldEntities)); } models.add(m); } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DescriptionTemplateDefinitionFileTransformerBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DescriptionTemplateDefinitionFileTransformerBuilder.java index cf0463d02..e5b07ea17 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DescriptionTemplateDefinitionFileTransformerBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DescriptionTemplateDefinitionFileTransformerBuilder.java @@ -161,14 +161,14 @@ public class DescriptionTemplateDefinitionFileTransformerBuilder extends BaseFil public BaseFieldDataFileTransformerModel convertData (BaseFieldDataEntity data) { BaseFieldDataFileTransformerModel m; - switch (data) { - case ExternalSelectDataEntity d -> { - m = new ExternalSelectDataFileTransformerModel(); - m.setLabel(d.getLabel()); - m.setFieldType(FieldType.of(d.getFieldType().getValue())); - ((ExternalSelectDataFileTransformerModel)m).setMultipleSelect(d.getMultipleSelect()); - ((ExternalSelectDataFileTransformerModel) m).setSources(convertAutoCompleteSingleData(d.getSources())); - } + switch (data) { //TODO new reference logic +// case ExternalSelectDataEntity d -> { +// m = new ExternalSelectDataFileTransformerModel(); +// m.setLabel(d.getLabel()); +// m.setFieldType(FieldType.of(d.getFieldType().getValue())); +// ((ExternalSelectDataFileTransformerModel)m).setMultipleSelect(d.getMultipleSelect()); +// ((ExternalSelectDataFileTransformerModel) m).setSources(convertAutoCompleteSingleData(d.getSources())); +// } case ExternalDatasetDataEntity d -> { m = new ExternalDatasetDataFileTransformerModel(); m.setLabel(d.getLabel()); @@ -221,42 +221,6 @@ public class DescriptionTemplateDefinitionFileTransformerBuilder extends BaseFil return result; } - private List convertAutoCompleteSingleData(List data) { - List result = new ArrayList<>(); - for (ExternalSelectDataEntity.ExternalSelectSourceEntity d : data) { - ExternalSelectDataFileTransformerModel.ExternalSelectSourceFileTransformerModel m = new ExternalSelectDataFileTransformerModel.ExternalSelectSourceFileTransformerModel(); - m.setUrl(d.getUrl()); - m.setMethod(d.getMethod()); - m.setHasAuth(d.getHasAuth()); - m.setOptionsRoot(d.getOptionsRoot()); - if (d.getAuth() != null) { - m.setAuth(convertAuthData(d.getAuth())); - } - m.setSourceBinding(convertComboBoxOption(d.getSourceBinding())); - result.add(m); - } - return result; - } - - private ExternalSelectDataFileTransformerModel.ExternalSelectSourceBindingFileTransformerModel convertComboBoxOption(ExternalSelectDataEntity.ExternalSelectSourceBindingEntity data) { - ExternalSelectDataFileTransformerModel.ExternalSelectSourceBindingFileTransformerModel m = new ExternalSelectDataFileTransformerModel.ExternalSelectSourceBindingFileTransformerModel(); -// m.setUri(data.getUri()); - m.setSource(data.getSource()); - m.setLabel(data.getLabel()); - m.setValue(data.getValue()); - return m; - } - - private ExternalSelectDataFileTransformerModel.ExternalSelectAuthDataFileTransformerModel convertAuthData(ExternalSelectDataEntity.ExternalSelectAuthDataEntity data) { - ExternalSelectDataFileTransformerModel.ExternalSelectAuthDataFileTransformerModel m = new ExternalSelectDataFileTransformerModel.ExternalSelectAuthDataFileTransformerModel(); - m.setMethod(data.getMethod()); - m.setUrl(data.getUrl()); - m.setType(data.getType()); - m.setBody(data.getBody()); - m.setPath(data.getPath()); - return m; - } - private SelectDataFileTransformerModel.OptionFileTransformerModel convertComboBoxOption(SelectDataEntity.OptionEntity data) { SelectDataFileTransformerModel.OptionFileTransformerModel m = new SelectDataFileTransformerModel.OptionFileTransformerModel(); m.setLabel(data.getLabel()); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DmpBlueprintFileTransformerBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DmpBlueprintFileTransformerBuilder.java index 7fe4e3580..f7099d02e 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DmpBlueprintFileTransformerBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DmpBlueprintFileTransformerBuilder.java @@ -21,6 +21,7 @@ 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.apache.commons.lang3.NotImplementedException; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; @@ -110,6 +111,8 @@ public class DmpBlueprintFileTransformerBuilder extends BaseFileTransformerBuild FieldFileTransformerModel m = switch (fieldEntity.getCategory()) { case System -> new SystemFieldFileTransformerModel(); case Extra -> new ExtraFieldFileTransformerModelFileTransformerModel(); + case Reference -> throw new NotImplementedException("ReferenceFieldFileTransformerModel"); + default -> throw new MyApplicationException("unrecognized type " + fieldEntity.getCategory()); }; m.setId(fieldEntity.getId()); m.setLabel(fieldEntity.getLabel()); @@ -120,7 +123,8 @@ public class DmpBlueprintFileTransformerBuilder extends BaseFileTransformerBuild switch (m) { case SystemFieldFileTransformerModel sm -> sm.setSystemFieldType(DmpBlueprintSystemFieldType.of(((SystemFieldEntity)fieldEntity).getType().getValue())); case ExtraFieldFileTransformerModelFileTransformerModel sm -> sm.setDataType(DmpBlueprintExtraFieldDataType.of(((ExtraFieldEntity)fieldEntity).getType().getValue())); - default -> {} +// case ReferenceFieldFileTransformerModelFileTransformerModel sm -> sm.setReferenceTypeId(((ReferenceFieldEntity)fieldEntity).getReferenceTypeId()); + default -> throw new MyApplicationException("unrecognized type " + fieldEntity.getCategory()); } result.add(m); }); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/ReferenceFileTransformerBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/ReferenceFileTransformerBuilder.java index 9c5bda7f7..072870999 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/ReferenceFileTransformerBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/ReferenceFileTransformerBuilder.java @@ -69,23 +69,9 @@ public class ReferenceFileTransformerBuilder extends BaseFileTransformerBuilder< case External -> m.setSourceType(ReferenceSourceType.External); default -> throw new MyApplicationException("unrecognized type " + d.getSourceType().getValue()); } - switch (d.getType()){ - case Taxonomies -> m.setType(ReferenceType.Taxonomies); - case Licenses -> m.setType(ReferenceType.Licenses); - case Publications -> m.setType(ReferenceType.Publications); - case Journals -> m.setType(ReferenceType.Journals); - case PubRepositories -> m.setType(ReferenceType.PubRepositories); - case DataRepositories -> m.setType(ReferenceType.DataRepositories); - case Registries -> m.setType(ReferenceType.Registries); - case Services -> m.setType(ReferenceType.Services); - case Project -> m.setType(ReferenceType.Project); - case Funder -> m.setType(ReferenceType.Funder); - case Datasets -> m.setType(ReferenceType.Datasets); - case Organizations -> m.setType(ReferenceType.Organizations); - case Grants -> m.setType(ReferenceType.Grants); - case Researcher -> m.setType(ReferenceType.Researcher); - default -> throw new MyApplicationException("unrecognized type " + d.getType().getValue()); - } + + //m.setType(d.getTypeId()); //TODO new reference logic + models.add(new FileTransformerBuilderItemResponse<>(m, d)); } this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/DefinitionSearchBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/DefinitionSearchBuilder.java index 0a7515b7d..b66a528d1 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/DefinitionSearchBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/DefinitionSearchBuilder.java @@ -1,58 +1,58 @@ -package eu.eudat.model.builder.referencesearch; - -import eu.eudat.authorization.AuthorizationFlags; -import eu.eudat.configurations.referencetype.ReferenceTypeProperties; -import eu.eudat.convention.ConventionService; -import eu.eudat.model.builder.BaseBuilder; -import eu.eudat.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 -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class DefinitionSearchBuilder extends BaseBuilder> { - - private final BuilderFactory builderFactory; - private final ReferenceTypeProperties properties; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public DefinitionSearchBuilder( - ConventionService conventionService, BuilderFactory builderFactory, ReferenceTypeProperties properties) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(DefinitionSearchBuilder.class))); - this.builderFactory = builderFactory; - this.properties = properties; - } - - public DefinitionSearchBuilder 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 (data == null) - return new ArrayList<>(); - - List models = new ArrayList<>(); - //for (Map d : data) { - Definition m = new Definition(); - m.setFields(this.builderFactory.builder(FieldSearchBuilder.class).authorize(this.authorize).build(null, data)); - models.add(m); - //} - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } -} +//package eu.eudat.model.builder.referencesearch; +// +//import eu.eudat.authorization.AuthorizationFlags; +//import eu.eudat.configurations.referencetype.ReferenceTypeProperties; +//import eu.eudat.convention.ConventionService; +//import eu.eudat.model.builder.BaseBuilder; +//import eu.eudat.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 +//@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +//public class DefinitionSearchBuilder extends BaseBuilder> { +// +// private final BuilderFactory builderFactory; +// private final ReferenceTypeProperties properties; +// private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); +// +// @Autowired +// public DefinitionSearchBuilder( +// ConventionService conventionService, BuilderFactory builderFactory, ReferenceTypeProperties properties) { +// super(conventionService, new LoggerService(LoggerFactory.getLogger(DefinitionSearchBuilder.class))); +// this.builderFactory = builderFactory; +// this.properties = properties; +// } +// +// public DefinitionSearchBuilder 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 (data == null) +// return new ArrayList<>(); +// +// List models = new ArrayList<>(); +// //for (Map d : data) { +// Definition m = new Definition(); +// m.setFields(this.builderFactory.builder(FieldSearchBuilder.class).authorize(this.authorize).build(null, data)); +// models.add(m); +// //} +// this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); +// return models; +// } +//} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/FieldSearchBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/FieldSearchBuilder.java index 36399d472..5480bcec2 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/FieldSearchBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/FieldSearchBuilder.java @@ -1,89 +1,88 @@ -package eu.eudat.model.builder.referencesearch; - -import eu.eudat.authorization.AuthorizationFlags; -import eu.eudat.commons.enums.ReferenceFieldDataType; -import eu.eudat.commons.enums.ReferenceType; -import eu.eudat.configurations.referencetype.ReferenceTypeField; -import eu.eudat.configurations.referencetype.ReferenceTypeProperties; -import eu.eudat.convention.ConventionService; -import eu.eudat.model.builder.BaseBuilder; -import eu.eudat.model.referencedefinition.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.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 FieldSearchBuilder extends BaseBuilder> { - - private final ReferenceTypeProperties properties; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public FieldSearchBuilder( - ConventionService conventionService, ReferenceTypeProperties properties) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldSearchBuilder.class))); - this.properties = properties; - } - - public FieldSearchBuilder authorize(EnumSet values) { - this.authorize = values; - return this; - } - - @Override - public List build(FieldSet fields, List< Map> 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 (data == null) - return new ArrayList<>(); - - List models = new ArrayList<>(); - for (Map d : data) { - - ReferenceType referenceType = ReferenceType.valueOf(d.getOrDefault("referenceType", null)); - List typeFields = this.getPropertiesFields(referenceType); - if (typeFields.isEmpty()){ - return new ArrayList<>(); - } - - for (ReferenceTypeField typeField: typeFields){ - Field m = new Field(); - m.setCode(typeField.getCode()); - m.setDataType(ReferenceFieldDataType.valueOf(typeField.getDataType())); - m.setValue(d.getOrDefault(typeField.getCode(), null)); - models.add(m); - } - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } - - private List getPropertiesFields(ReferenceType referenceType){ - switch (referenceType) { - case Taxonomies: return properties.getTaxonomy().get("fields"); - case Licenses: return properties.getLicence().get("fields"); - case Publications: return properties.getPublication().get("fields"); - case Journals: return properties.getJournal().get("fields"); - case PubRepositories: return properties.getPubRepository().get("fields"); - case DataRepositories: return properties.getDataRepository().get("fields"); - case Registries: return properties.getRegistry().get("fields"); - case Services: return properties.getService().get("fields"); - case Organizations: return properties.getOrganisation().get("fields"); - case Datasets: return properties.getDataset().get("fields"); - case Funder: return properties.getFunder().get("fields"); - case Grants: return properties.getGrant().get("fields"); - case Project: return properties.getProject().get("fields"); - case Researcher: return properties.getResearcher().get("fields"); - default: return null; - } - } -} +//package eu.eudat.model.builder.referencesearch; +// +//import eu.eudat.authorization.AuthorizationFlags; +//import eu.eudat.commons.enums.ReferenceFieldDataType; +//import eu.eudat.configurations.referencetype.ReferenceTypeField; +//import eu.eudat.configurations.referencetype.ReferenceTypeProperties; +//import eu.eudat.convention.ConventionService; +//import eu.eudat.model.builder.BaseBuilder; +//import eu.eudat.model.referencedefinition.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.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 FieldSearchBuilder extends BaseBuilder> { +// +// private final ReferenceTypeProperties properties; +// private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); +// +// @Autowired +// public FieldSearchBuilder( +// ConventionService conventionService, ReferenceTypeProperties properties) { +// super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldSearchBuilder.class))); +// this.properties = properties; +// } +// +// public FieldSearchBuilder authorize(EnumSet values) { +// this.authorize = values; +// return this; +// } +// +// @Override +// public List build(FieldSet fields, List< Map> 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 (data == null) +// return new ArrayList<>(); +// +// List models = new ArrayList<>(); +// for (Map d : data) { +// +// ReferenceType referenceType = ReferenceType.valueOf(d.getOrDefault("referenceType", null)); +// List typeFields = this.getPropertiesFields(referenceType); +// if (typeFields.isEmpty()){ +// return new ArrayList<>(); +// } +// +// for (ReferenceTypeField typeField: typeFields){ +// Field m = new Field(); +// m.setCode(typeField.getCode()); +// m.setDataType(ReferenceFieldDataType.valueOf(typeField.getDataType())); +// m.setValue(d.getOrDefault(typeField.getCode(), null)); +// models.add(m); +// } +// } +// this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); +// return models; +// } +// +// private List getPropertiesFields(ReferenceType referenceType){ +// switch (referenceType) { +// case Taxonomies: return properties.getTaxonomy().get("fields"); +// case Licenses: return properties.getLicence().get("fields"); +// case Publications: return properties.getPublication().get("fields"); +// case Journals: return properties.getJournal().get("fields"); +// case PubRepositories: return properties.getPubRepository().get("fields"); +// case DataRepositories: return properties.getDataRepository().get("fields"); +// case Registries: return properties.getRegistry().get("fields"); +// case Services: return properties.getService().get("fields"); +// case Organizations: return properties.getOrganisation().get("fields"); +// case Datasets: return properties.getDataset().get("fields"); +// case Funder: return properties.getFunder().get("fields"); +// case Grants: return properties.getGrant().get("fields"); +// case Project: return properties.getProject().get("fields"); +// case Researcher: return properties.getResearcher().get("fields"); +// default: return null; +// } +// } +//} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/ReferenceSearchBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/ReferenceSearchBuilder.java index cdb9cd8a7..734feccd7 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/ReferenceSearchBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/ReferenceSearchBuilder.java @@ -1,103 +1,96 @@ -package eu.eudat.model.builder.referencesearch; - -import eu.eudat.authorization.AuthorizationFlags; -import eu.eudat.commons.XmlHandlingService; -import eu.eudat.commons.enums.ReferenceSourceType; -import eu.eudat.commons.enums.ReferenceType; -import eu.eudat.convention.ConventionService; -import eu.eudat.model.Reference; -import eu.eudat.model.builder.BaseBuilder; -import eu.eudat.model.referencedefinition.Definition; -import eu.eudat.model.referencedefinition.Field; -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 ReferenceSearchBuilder extends BaseBuilder> { - - private final BuilderFactory builderFactory; - private final QueryFactory queryFactory; - private final XmlHandlingService xmlHandlingService; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public ReferenceSearchBuilder( - ConventionService conventionService, - BuilderFactory builderFactory, QueryFactory queryFactory, XmlHandlingService xmlHandlingService) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceSearchBuilder.class))); - this.builderFactory = builderFactory; - this.queryFactory = queryFactory; - this.xmlHandlingService = xmlHandlingService; - } - - public ReferenceSearchBuilder 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 (data == null) - return new ArrayList<>(); - - List models = new ArrayList<>(); - for (Map d : data) { - Reference m = new Reference(); - if (d.containsKey("id")) m.setId(UUID.fromString(d.getOrDefault("id", null))); - m.setLabel(d.getOrDefault("name", null)); - m.setSourceType(ReferenceSourceType.External); - String type = d.getOrDefault("referenceType", null); - if (type != null) m.setType(ReferenceType.valueOf(type)); - - Definition definition = this.builderFactory.builder(DefinitionSearchBuilder.class).authorize(this.authorize).build(null, d); - m.setDefinition(definition); - - switch (m.getType()){ - case Researcher: - case Organizations: - case Funder: - case Grants: - case DataRepositories: - case PubRepositories: - case Journals: - case Datasets: - case Registries: - case Services:{ - for (Field field : definition.getFields()) { - if (field.getCode().equals("pid") && field.getValue() != null) { - if (d.containsKey("key")) { - m.setReference(d.get("key") + ":" + field.getValue()); - } - } - if (field.getCode().equals("tag") && field.getValue() != null){ - m.setSource(field.getValue()); - } - } - } - } - - m.setDescription(d.getOrDefault("description", null)); - m.setAbbreviation(d.getOrDefault("abbreviation", null)); - - models.add(m); - - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } - -} +//package eu.eudat.model.builder.referencesearch; +// +//import eu.eudat.authorization.AuthorizationFlags; +//import eu.eudat.commons.enums.ReferenceSourceType; +//import eu.eudat.convention.ConventionService; +//import eu.eudat.model.Reference; +//import eu.eudat.model.builder.BaseBuilder; +//import eu.eudat.model.referencedefinition.Definition; +//import eu.eudat.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 +//@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +//public class ReferenceSearchBuilder extends BaseBuilder> { +// +// private final BuilderFactory builderFactory; +// private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); +// +// @Autowired +// public ReferenceSearchBuilder( +// ConventionService conventionService, +// BuilderFactory builderFactory) { +// super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceSearchBuilder.class))); +// this.builderFactory = builderFactory; +// } +// +// public ReferenceSearchBuilder 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 (data == null) +// return new ArrayList<>(); +// +// List models = new ArrayList<>(); +// for (Map d : data) { +// Reference m = new Reference(); +// if (d.containsKey("id")) m.setId(UUID.fromString(d.getOrDefault("id", null))); +// m.setLabel(d.getOrDefault("name", null)); +// m.setSourceType(ReferenceSourceType.External); +// String type = d.getOrDefault("referenceType", null); +// if (type != null) m.setType(ReferenceType.valueOf(type)); +// +// Definition definition = this.builderFactory.builder(DefinitionSearchBuilder.class).authorize(this.authorize).build(null, d); +// m.setDefinition(definition); +// +// switch (m.getType()){ +// case Researcher: +// case Organizations: +// case Funder: +// case Grants: +// case DataRepositories: +// case PubRepositories: +// case Journals: +// case Datasets: +// case Registries: +// case Services:{ +// for (Field field : definition.getFields()) { +// if (field.getCode().equals("pid") && field.getValue() != null) { +// if (d.containsKey("key")) { +// m.setReference(d.get("key") + ":" + field.getValue()); +// } +// } +// if (field.getCode().equals("tag") && field.getValue() != null){ +// m.setSource(field.getValue()); +// } +// } +// } +// } +// +// m.setDescription(d.getOrDefault("description", null)); +// m.setAbbreviation(d.getOrDefault("abbreviation", null)); +// +// models.add(m); +// +// } +// this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); +// return models; +// } +// +//} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/censorship/PublicReferenceCensor.java b/dmp-backend/core/src/main/java/eu/eudat/model/censorship/PublicReferenceCensor.java index 84cc4b6cc..9d81ea1a3 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/censorship/PublicReferenceCensor.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/censorship/PublicReferenceCensor.java @@ -2,6 +2,8 @@ package eu.eudat.model.censorship; import eu.eudat.authorization.Permission; import eu.eudat.convention.ConventionService; +import eu.eudat.model.PublicDmpUser; +import eu.eudat.model.PublicReference; import eu.eudat.model.Reference; import eu.eudat.model.censorship.referencedefinition.DefinitionCensor; import gr.cite.commons.web.authz.service.AuthorizationService; @@ -39,6 +41,8 @@ public class PublicReferenceCensor extends BaseCensor { return; this.authService.authorizeForce(Permission.PublicBrowseReference); + FieldSet typeFields = fields.extractPrefixed(this.asIndexerPrefix(PublicReference._type)); + this.censorFactory.censor(PublicReferenceCensor.class).censor(typeFields); } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/censorship/PublicReferenceTypeCensor.java b/dmp-backend/core/src/main/java/eu/eudat/model/censorship/PublicReferenceTypeCensor.java new file mode 100644 index 000000000..aabbe14de --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/censorship/PublicReferenceTypeCensor.java @@ -0,0 +1,41 @@ +package eu.eudat.model.censorship; + +import eu.eudat.authorization.Permission; +import eu.eudat.convention.ConventionService; +import eu.eudat.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/dmp-backend/core/src/main/java/eu/eudat/model/censorship/ReferenceCensor.java b/dmp-backend/core/src/main/java/eu/eudat/model/censorship/ReferenceCensor.java index 9d711e310..859d38b2f 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/censorship/ReferenceCensor.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/censorship/ReferenceCensor.java @@ -45,6 +45,8 @@ public class ReferenceCensor extends BaseCensor { 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/dmp-backend/core/src/main/java/eu/eudat/model/descriptiontemplatedefinition/fielddata/ExternalSelectData.java b/dmp-backend/core/src/main/java/eu/eudat/model/descriptiontemplatedefinition/fielddata/ExternalSelectData.java deleted file mode 100644 index b0ac1d0a5..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/model/descriptiontemplatedefinition/fielddata/ExternalSelectData.java +++ /dev/null @@ -1,164 +0,0 @@ -package eu.eudat.model.descriptiontemplatedefinition.fielddata; - -import java.util.List; - -public class ExternalSelectData extends LabelAndMultiplicityData { - private List sources; - - public final static String _sources = "sources"; - - public List getSources() { - return sources; - } - - public void setSources(List sources) { - this.sources = sources; - } - - public static class ExternalSelectSource { - private String url; - public final static String _url = "url"; - - private String method; - public final static String _method = "method"; - private String optionsRoot; - public final static String _optionsRoot = "optionsRoot"; - private ExternalSelectSourceBinding sourceBinding; - public final static String _sourceBinding = "sourceBinding"; - private Boolean hasAuth; - public final static String _hasAuth = "hasAuth"; - private ExternalSelectAuthData auth; - public final static String _auth = "auth"; - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - public String getOptionsRoot() { - return optionsRoot; - } - - public void setOptionsRoot(String optionsRoot) { - this.optionsRoot = optionsRoot; - } - - public ExternalSelectSourceBinding getSourceBinding() { - return sourceBinding; - } - - public void setSourceBinding(ExternalSelectSourceBinding sourceBinding) { - this.sourceBinding = sourceBinding; - } - - public Boolean getHasAuth() { - return hasAuth; - } - - public void setHasAuth(Boolean hasAuth) { - this.hasAuth = hasAuth; - } - - public ExternalSelectAuthData getAuth() { - return auth; - } - - public void setAuth(ExternalSelectAuthData auth) { - this.auth = auth; - } - } - - public static class ExternalSelectSourceBinding { - private String label; - public final static String _label = "label"; - private String value; - public final static String _value = "value"; - private String source; - public final static String _source = "source"; - - 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; - } - - public String getSource() { - return source; - } - public void setSource(String source) { - this.source = source; - } - } - - public static class ExternalSelectAuthData { - private String url; - public final static String _url = "url"; - private String method; - public final static String _method = "method"; - private String body; - public final static String _body = "body"; - private String path; - public final static String _path = "path"; - private String type; - public final static String _type = "type"; - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/descriptiontemplatedefinition/fielddata/ReferenceTypeData.java b/dmp-backend/core/src/main/java/eu/eudat/model/descriptiontemplatedefinition/fielddata/ReferenceTypeData.java new file mode 100644 index 000000000..18607bad1 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/descriptiontemplatedefinition/fielddata/ReferenceTypeData.java @@ -0,0 +1,25 @@ +package eu.eudat.model.descriptiontemplatedefinition.fielddata; + +import java.util.UUID; + +public class ReferenceTypeData extends BaseFieldData { + private Boolean multipleSelect; + public final static String _multipleSelect = "multipleSelect"; + + private UUID referenceTypeId; + public final static String _referenceTypeId = "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/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ExtraField.java b/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ExtraField.java index 8bd1b4e52..23ea79320 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ExtraField.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ExtraField.java @@ -2,6 +2,7 @@ package eu.eudat.model.dmpblueprintdefinition; import eu.eudat.commons.enums.DmpBlueprintExtraFieldDataType; + public class ExtraField extends Field { public final static String _dataType = "dataType"; @@ -15,3 +16,4 @@ public class ExtraField extends Field { this.dataType = dataType; } } + diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceField.java b/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceField.java new file mode 100644 index 000000000..51ba03a06 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceField.java @@ -0,0 +1,17 @@ +package eu.eudat.model.dmpblueprintdefinition; + +import java.util.UUID; + +public class ReferenceField extends Field { + + public final static String _referenceTypeId = "referenceTypeId"; + private UUID referenceTypeId; + + public UUID getReferenceTypeId() { + return referenceTypeId; + } + + public void setReferenceTypeId(UUID referenceTypeId) { + this.referenceTypeId = referenceTypeId; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DescriptionToPublicApiDatasetListingMapper.java b/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DescriptionToPublicApiDatasetListingMapper.java index 308202031..688baaecd 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DescriptionToPublicApiDatasetListingMapper.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DescriptionToPublicApiDatasetListingMapper.java @@ -5,6 +5,7 @@ import eu.eudat.model.publicapi.datasetprofile.DatasetProfilePublicModel; import eu.eudat.model.publicapi.grant.GrantPublicOverviewModel; import eu.eudat.model.publicapi.listingmodels.DatasetPublicListingModel; import eu.eudat.model.publicapi.user.UserInfoPublicModel; +import eu.eudat.service.publicapi.PublicApiProperties; import org.springframework.stereotype.Component; import java.sql.Date; @@ -13,7 +14,7 @@ import java.util.List; @Component public class DescriptionToPublicApiDatasetListingMapper { - public DatasetPublicListingModel toPublicListingModel(Description description) { + public DatasetPublicListingModel toPublicListingModel(Description description, PublicApiProperties.ReferenceTypeMapConfig config) { DatasetPublicListingModel model = new DatasetPublicListingModel(); model.setId(description.getId().toString()); model.setLabel(description.getLabel()); @@ -24,7 +25,7 @@ public class DescriptionToPublicApiDatasetListingMapper { model.setDmpId(description.getDmp().getId().toString()); model.setUsers(List.of(UserInfoPublicModel.fromDescriptionCreator(description.getCreatedBy()))); model.setProfile(DatasetProfilePublicModel.fromDataModel(description.getDescriptionTemplate())); - model.setGrant(GrantPublicOverviewModel.fromDescriptionReference(description.getDescriptionReferences())); + model.setGrant(GrantPublicOverviewModel.fromDescriptionReference(description.getDescriptionReferences(), config)); model.setCreatedAt(Date.from(description.getCreatedAt())); model.setModifiedAt(Date.from(description.getUpdatedAt())); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DescriptionToPublicApiDatasetMapper.java b/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DescriptionToPublicApiDatasetMapper.java index a242fce3a..d7339700e 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DescriptionToPublicApiDatasetMapper.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DescriptionToPublicApiDatasetMapper.java @@ -8,6 +8,7 @@ import eu.eudat.model.publicapi.datasetwizard.RegistryPublicModel; import eu.eudat.model.publicapi.datasetwizard.ServicePublicModel; import eu.eudat.model.publicapi.listingmodels.DataManagementPlanPublicListingModel; import eu.eudat.model.publicapi.overviewmodels.DatasetPublicModel; +import eu.eudat.service.publicapi.PublicApiProperties; import org.springframework.stereotype.Component; import java.sql.Date; @@ -22,7 +23,7 @@ public class DescriptionToPublicApiDatasetMapper { this.descriptionTemplateToPublicApiDatasetProfileMapper = descriptionTemplateToPublicApiDatasetProfileMapper; } - public DatasetPublicModel toPublicModel(Description description, DataManagementPlanPublicListingModel dmp) { + public DatasetPublicModel toPublicModel(Description description, DataManagementPlanPublicListingModel dmp, PublicApiProperties.ReferenceTypeMapConfig config) { DatasetPublicModel model = new DatasetPublicModel(); model.setId(description.getId()); model.setLabel(description.getLabel()); @@ -36,10 +37,10 @@ public class DescriptionToPublicApiDatasetMapper { model.setProfile(DatasetProfilePublicModel.fromDataModel(description.getDescriptionTemplate())); if (description.getDescriptionReferences() != null) { - model.setRegistries(description.getDescriptionReferences().stream().map(RegistryPublicModel::fromDescriptionReference).filter(Objects::nonNull).toList()); - model.setServices(description.getDescriptionReferences().stream().map(ServicePublicModel::fromDescriptionReference).filter(Objects::nonNull).toList()); - model.setDataRepositories(description.getDescriptionReferences().stream().map(DataRepositoryPublicModel::fromDescriptionReference).filter(Objects::nonNull).toList()); - model.setExternalDatasets(description.getDescriptionReferences().stream().map(ExternalDatasetPublicListingModel::fromDescriptionReference).filter(Objects::nonNull).toList()); + model.setRegistries(description.getDescriptionReferences().stream().map(x-> RegistryPublicModel.fromDescriptionReference(x, config)).filter(Objects::nonNull).toList()); + model.setServices(description.getDescriptionReferences().stream().map(x-> ServicePublicModel.fromDescriptionReference(x, config)).filter(Objects::nonNull).toList()); + model.setDataRepositories(description.getDescriptionReferences().stream().map(x-> DataRepositoryPublicModel.fromDescriptionReference(x, config)).filter(Objects::nonNull).toList()); + model.setExternalDatasets(description.getDescriptionReferences().stream().map(x-> ExternalDatasetPublicListingModel.fromDescriptionReference(x, config)).filter(Objects::nonNull).toList()); } model.setCreatedAt(Date.from(description.getCreatedAt())); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DmpToPublicApiDmpListingMapper.java b/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DmpToPublicApiDmpListingMapper.java index 87ab68932..31a6e82b5 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DmpToPublicApiDmpListingMapper.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DmpToPublicApiDmpListingMapper.java @@ -4,6 +4,7 @@ import eu.eudat.model.Dmp; import eu.eudat.model.publicapi.listingmodels.DataManagementPlanPublicListingModel; import eu.eudat.model.publicapi.researcher.ResearcherPublicModel; import eu.eudat.model.publicapi.user.UserInfoPublicModel; +import eu.eudat.service.publicapi.PublicApiProperties; import org.springframework.stereotype.Component; import java.sql.Date; @@ -12,7 +13,7 @@ import java.util.Objects; @Component public class DmpToPublicApiDmpListingMapper { - public DataManagementPlanPublicListingModel toPublicListingModel(Dmp dmp) { + public DataManagementPlanPublicListingModel toPublicListingModel(Dmp dmp, PublicApiProperties.ReferenceTypeMapConfig config) { DataManagementPlanPublicListingModel model = new DataManagementPlanPublicListingModel(); model.setId(dmp.getId().toString()); model.setLabel(dmp.getLabel()); @@ -20,7 +21,7 @@ public class DmpToPublicApiDmpListingMapper { model.setGroupId(dmp.getGroupId()); model.setUsers(dmp.getDmpUsers().stream().map(UserInfoPublicModel::fromDmpUser).toList()); - model.setResearchers(dmp.getDmpReferences().stream().map(ResearcherPublicModel::fromDmpReference).filter(Objects::nonNull).toList()); + model.setResearchers(dmp.getDmpReferences().stream().map(x-> ResearcherPublicModel.fromDmpReference(x, config)).filter(Objects::nonNull).toList()); model.setCreatedAt(Date.from(dmp.getCreatedAt())); model.setModifiedAt(Date.from(dmp.getUpdatedAt())); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DmpToPublicApiDmpMapper.java b/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DmpToPublicApiDmpMapper.java index 088612c21..145484c8f 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DmpToPublicApiDmpMapper.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/mapper/publicapi/DmpToPublicApiDmpMapper.java @@ -11,6 +11,7 @@ import eu.eudat.model.publicapi.organisation.OrganizationPublicModel; import eu.eudat.model.publicapi.overviewmodels.DataManagementPlanPublicModel; import eu.eudat.model.publicapi.researcher.ResearcherPublicModel; import eu.eudat.model.publicapi.user.UserInfoPublicModel; +import eu.eudat.service.publicapi.PublicApiProperties; import org.springframework.stereotype.Component; import java.sql.Date; @@ -26,7 +27,7 @@ public class DmpToPublicApiDmpMapper { this.descriptionToPublicApiDatasetMapper = descriptionToPublicApiDatasetMapper; } - public DataManagementPlanPublicModel toPublicModel(Dmp dmp, List doiEntities, List descriptionTemplates) { + public DataManagementPlanPublicModel toPublicModel(Dmp dmp, List doiEntities, List descriptionTemplates, PublicApiProperties.ReferenceTypeMapConfig config) { DataManagementPlanPublicModel model = new DataManagementPlanPublicModel(); model.setId(dmp.getId().toString()); model.setLabel(dmp.getLabel()); @@ -38,13 +39,13 @@ public class DmpToPublicApiDmpMapper { if (dmp.getDescriptions() != null) { DataManagementPlanPublicListingModel publicListingModel = new DataManagementPlanPublicListingModel(); publicListingModel.setId(model.getId()); - model.setDatasets(dmp.getDescriptions().stream().map(x -> descriptionToPublicApiDatasetMapper.toPublicModel(x, publicListingModel)).toList()); + model.setDatasets(dmp.getDescriptions().stream().map(x -> descriptionToPublicApiDatasetMapper.toPublicModel(x, publicListingModel, config)).toList()); } model.setUsers(dmp.getDmpUsers().stream().map(UserInfoPublicModel::fromDmpUser).toList()); - model.setResearchers(dmp.getDmpReferences().stream().map(ResearcherPublicModel::fromDmpReference).filter(Objects::nonNull).toList()); - model.setGrant(GrantPublicOverviewModel.fromDmpReferences(dmp.getDmpReferences())); - model.setOrganisations(dmp.getDmpReferences().stream().map(OrganizationPublicModel::fromDmpReference).filter(Objects::nonNull).toList()); + model.setResearchers(dmp.getDmpReferences().stream().map(x-> ResearcherPublicModel.fromDmpReference(x, config)).filter(Objects::nonNull).toList()); + model.setGrant(GrantPublicOverviewModel.fromDmpReferences(dmp.getDmpReferences(), config)); + model.setOrganisations(dmp.getDmpReferences().stream().map(x-> OrganizationPublicModel.fromDmpReference(x, config)).filter(Objects::nonNull).toList()); model.setDois(doiEntities.stream().map(DoiPublicModel::fromDataModel).toList()); model.setAssociatedProfiles(descriptionTemplates.stream().map(x -> AssociatedProfilePublicModel.fromDmpDescriptionTemplate(x, dmp.getBlueprint())).toList()); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/ReferencePersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/ReferencePersist.java index fa81ef4aa..1a383ada3 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/persist/ReferencePersist.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/ReferencePersist.java @@ -1,7 +1,6 @@ package eu.eudat.model.persist; import eu.eudat.commons.enums.ReferenceSourceType; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.commons.validation.BaseValidator; import gr.cite.tools.validation.ValidatorFactory; import gr.cite.tools.validation.specification.Specification; @@ -27,9 +26,9 @@ public class ReferencePersist { public static final String _label = "label"; - private ReferenceType type; + private UUID typeId; - public static final String _type = "type"; + public static final String _typeId = "typeId"; private String description; @@ -73,12 +72,12 @@ public class ReferencePersist { this.label = label; } - public ReferenceType getType() { - return type; + public UUID getTypeId() { + return typeId; } - public void setType(ReferenceType type) { - this.type = type; + public void setTypeId(UUID typeId) { + this.typeId = typeId; } public String getDescription() { @@ -177,8 +176,8 @@ public class ReferencePersist { .must(() -> this.lessEqualLength(item.getLabel(), ReferenceEntity._labelLength)) .failOn(ReferencePersist._label).failWith(messageSource.getMessage("Validation_MaxLength", new Object[]{ReferencePersist._label}, LocaleContextHolder.getLocale())), this.spec() - .must(() -> !this.isNull(item.getType())) - .failOn(ReferencePersist._type).failWith(messageSource.getMessage("Validation_Required", new Object[]{ReferencePersist._type}, LocaleContextHolder.getLocale())), + .must(() -> this.isValidGuid(item.getTypeId())) + .failOn(ReferencePersist._typeId).failWith(messageSource.getMessage("Validation_Required", new Object[]{ReferencePersist._typeId}, LocaleContextHolder.getLocale())), this.spec() .must(() -> !this.isEmpty(item.getReference())) .failOn(ReferencePersist._reference).failWith(messageSource.getMessage("Validation_Required", new Object[]{ReferencePersist._reference}, LocaleContextHolder.getLocale())), @@ -200,7 +199,6 @@ public class ReferencePersist { this.spec() .must(() -> !this.isNull(item.getSourceType())) .failOn(ReferencePersist._sourceType).failWith(messageSource.getMessage("Validation_Required", new Object[]{ReferencePersist._sourceType}, LocaleContextHolder.getLocale())), - this.refSpec() .iff(() -> !this.isNull(item.getDefinition())) .on(ReferencePersist._definition) diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptionproperties/FieldPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptionproperties/FieldPersist.java index b4937bb3a..caaada642 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptionproperties/FieldPersist.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptionproperties/FieldPersist.java @@ -97,10 +97,6 @@ public class FieldPersist { protected List specifications(FieldPersist item) { FieldType fieldType = this.fieldEntity != null && this.fieldEntity.getData() != null ? this.fieldEntity.getData().getFieldType() : FieldType.FREE_TEXT; return Arrays.asList( - this.spec() - .iff(()-> FieldType.isNotImplemented(fieldType)) - .must(() -> false) - .failOn(FieldPersist._textValue).failWith("Field Not implemented yet!!"), this.spec() .iff(()-> FieldType.isTextType(fieldType)) .must(() -> !this.isEmpty(item.getTextValue())) @@ -130,7 +126,7 @@ public class FieldPersist { .must(() -> this.isUUID(item.getTextValue())) .failOn(FieldPersist._textValue).failWith(messageSource.getMessage("Validation_UnexpectedValue", new Object[]{FieldPersist._textValue}, LocaleContextHolder.getLocale())), this.spec() - .iff(()-> !this.isNull(item.getTextListValue()) && (fieldType.equals(FieldType.INTERNAL_DMP_ENTRIES_DMPS) || fieldType.equals(FieldType.INTERNAL_DMP_ENTRIES_RESEARCHERS) || fieldType.equals(FieldType.INTERNAL_DMP_ENTRIES_DATASETS))) + .iff(()-> !this.isNull(item.getTextListValue()) && (fieldType.equals(FieldType.INTERNAL_DMP_ENTRIES_DMPS) || fieldType.equals(FieldType.INTERNAL_DMP_ENTRIES_DATASETS))) .must(() -> item.getTextListValue().stream().allMatch(this::isUUID)) .failOn(FieldPersist._textListValue).failWith(messageSource.getMessage("Validation_UnexpectedValue", new Object[]{FieldPersist._textListValue}, LocaleContextHolder.getLocale())), this.navSpec() diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptiontemplatedefinition/fielddata/BaseFieldDataPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptiontemplatedefinition/fielddata/BaseFieldDataPersist.java index d6ec01609..88cfb0a6f 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptiontemplatedefinition/fielddata/BaseFieldDataPersist.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptiontemplatedefinition/fielddata/BaseFieldDataPersist.java @@ -21,7 +21,6 @@ import java.util.List; visible = true, defaultImpl = LabelDataPersist.class) @JsonSubTypes({ - @JsonSubTypes.Type(value = ExternalSelectDataPersist.class, name = FieldType.Names.ExternalSelect), @JsonSubTypes.Type(value = LabelDataPersist.class, name = FieldType.Names.BooleanDecision), @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.InternalDmpDescriptions), @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.InternalDmpDmps), @@ -29,26 +28,16 @@ import java.util.List; @JsonSubTypes.Type(value = LabelDataPersist.class, name = FieldType.Names.DatePicker), @JsonSubTypes.Type(value = ExternalDatasetDataPersist.class, name = FieldType.Names.ExternalDatasets), @JsonSubTypes.Type(value = LabelDataPersist.class, name = FieldType.Names.FreeText), - @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.Licenses), - @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.Organizations), - @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.Publications), + @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.ReferenceTypes), @JsonSubTypes.Type(value = RadioBoxDataPersist.class, name = FieldType.Names.RadioBox), - @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.Registries), - @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.InternalDmpResearchers), - @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.Researchers), @JsonSubTypes.Type(value = LabelDataPersist.class, name = FieldType.Names.RichTextarea), - @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.Services), @JsonSubTypes.Type(value = LabelDataPersist.class, name = FieldType.Names.Tags), - @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.Taxonomies), @JsonSubTypes.Type(value = LabelDataPersist.class, name = FieldType.Names.TextArea), @JsonSubTypes.Type(value = UploadDataPersist.class, name = FieldType.Names.Upload), @JsonSubTypes.Type(value = LabelDataPersist.class, name = FieldType.Names.Validation), @JsonSubTypes.Type(value = LabelDataPersist.class, name = FieldType.Names.DatasetIdentifier), @JsonSubTypes.Type(value = LabelDataPersist.class, name = FieldType.Names.Currency), - @JsonSubTypes.Type(value = SelectDataPersist.class, name = FieldType.Names.Select), - @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.DataRepositories), - @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.JournalRepositories), - @JsonSubTypes.Type(value = LabelAndMultiplicityDataPersist.class, name = FieldType.Names.PubRepositories), + @JsonSubTypes.Type(value = SelectDataPersist.class, name = FieldType.Names.Select) }) public abstract class BaseFieldDataPersist { diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptiontemplatedefinition/fielddata/ReferenceTypeDataPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptiontemplatedefinition/fielddata/ReferenceTypeDataPersist.java new file mode 100644 index 000000000..1cc7729d7 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/descriptiontemplatedefinition/fielddata/ReferenceTypeDataPersist.java @@ -0,0 +1,71 @@ +package eu.eudat.model.persist.descriptiontemplatedefinition.fielddata; + +import eu.eudat.convention.ConventionService; +import eu.eudat.errorcode.ErrorThesaurusProperties; +import gr.cite.tools.validation.specification.Specification; +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 ReferenceTypeDataPersist extends BaseFieldDataPersist { + + private Boolean multipleSelect; + + public static final String _multipleSelect = "multipleSelect"; + + private UUID referenceTypeId; + public final static String _referenceTypeId = "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; + } + + @Component(ReferenceTypeDataPersist.ReferenceTypeDataPersistValidator.ValidatorName) + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public static class ReferenceTypeDataPersistValidator extends BaseFieldDataPersistValidator { + + public static final String ValidatorName = "DescriptionTemplate.ReferenceTypeDataPersistValidator"; + + protected ReferenceTypeDataPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { + super(conventionService, errors, messageSource); + } + + @Override + protected Class modelClass() { + return ReferenceTypeDataPersist.class; + } + + @Override + protected List specifications(ReferenceTypeDataPersist item) { + List specifications = getBaseSpecifications(item); + specifications.addAll(Arrays.asList( + this.spec() + .must(() -> this.isValidGuid(item.getReferenceTypeId())) + .failOn(ReferenceTypeDataPersist._referenceTypeId).failWith(messageSource.getMessage("Validation_Required", new Object[]{ReferenceTypeDataPersist._referenceTypeId}, LocaleContextHolder.getLocale())), + this.spec() + .must(() -> !this.isNull(item.getMultipleSelect())) + .failOn(ReferenceTypeDataPersist._multipleSelect).failWith(messageSource.getMessage("Validation_Required", new Object[]{ReferenceTypeDataPersist._multipleSelect}, LocaleContextHolder.getLocale())) + )); + return specifications; + } + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/ReferenceFieldPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/ReferenceFieldPersist.java new file mode 100644 index 000000000..0c3bb02d9 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/ReferenceFieldPersist.java @@ -0,0 +1,56 @@ +package eu.eudat.model.persist.dmpblueprintdefinition; + +import eu.eudat.convention.ConventionService; +import eu.eudat.errorcode.ErrorThesaurusProperties; +import gr.cite.tools.validation.specification.Specification; +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.List; +import java.util.UUID; + +public class ReferenceFieldPersist extends FieldPersist { + + private UUID referenceTypeId; + + public static final String _referenceTypeId = "referenceTypeId"; + + public UUID getReferenceTypeId() { + return referenceTypeId; + } + + public void setReferenceTypeId(UUID referenceTypeId) { + this.referenceTypeId = referenceTypeId; + } + + @Component(ReferenceFieldPersistPersistValidator.ValidatorName) + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public static class ReferenceFieldPersistPersistValidator extends BaseFieldPersistValidator { + + public static final String ValidatorName = "DmpBlueprint.ReferenceFieldPersistPersistValidator"; + + protected ReferenceFieldPersistPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { + super(conventionService, errors, messageSource); + } + + @Override + protected Class modelClass() { + return ReferenceFieldPersist.class; + } + + @Override + protected List specifications(ReferenceFieldPersist item) { + List specifications = getBaseSpecifications(item); + specifications.add( + this.spec() + .must(() -> !this.isNull(item.getReferenceTypeId())) + .failOn(ReferenceFieldPersist._referenceTypeId).failWith(messageSource.getMessage("Validation_Required", new Object[]{ReferenceFieldPersist._referenceTypeId}, LocaleContextHolder.getLocale())) + ); + return specifications; + } + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SectionPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SectionPersist.java index 533dc2ad7..84fa1c41b 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SectionPersist.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SectionPersist.java @@ -2,6 +2,7 @@ package eu.eudat.model.persist.dmpblueprintdefinition; import eu.eudat.commons.enums.DmpBlueprintFieldCategory; import eu.eudat.commons.validation.BaseValidator; +import gr.cite.tools.exception.MyApplicationException; import gr.cite.tools.validation.ValidatorFactory; import gr.cite.tools.validation.specification.Specification; import eu.eudat.convention.ConventionService; @@ -145,7 +146,20 @@ public class SectionPersist { .iff(() -> !this.isListNullOrEmpty(item.getFields())) .on(SectionPersist._fields) .over(item.getFields()) - .using((itm) -> ((FieldPersist) itm).getCategory() == DmpBlueprintFieldCategory.Extra ? this.validatorFactory.validator(ExtraFieldPersist.ExtraFieldPersistValidator.class) : this.validatorFactory.validator(SystemFieldPersist.SystemFieldPersistValidator.class)), + .using((itm) -> { + switch (((FieldPersist) itm).getCategory()){ + case Extra -> { + return this.validatorFactory.validator(ExtraFieldPersist.ExtraFieldPersistValidator.class); + } + case System -> { + return this.validatorFactory.validator(SystemFieldPersist.SystemFieldPersistValidator.class); + } + case Reference -> { + return this.validatorFactory.validator(ReferenceFieldPersist.ReferenceFieldPersistPersistValidator.class); + } + default -> throw new MyApplicationException("unrecognized type " + ((FieldPersist) itm).getCategory()); + } + }), this.navSpec() .iff(() -> !this.isListNullOrEmpty(item.getDescriptionTemplates())) .on(SectionPersist._descriptionTemplates) diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SystemFieldPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SystemFieldPersist.java index 68efc88f3..000d99ff7 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SystemFieldPersist.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SystemFieldPersist.java @@ -11,6 +11,7 @@ import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Component; import java.util.List; +import java.util.UUID; public class SystemFieldPersist extends FieldPersist { @@ -54,3 +55,4 @@ public class SystemFieldPersist extends FieldPersist { } } + diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/DataRepositoryPublicModel.java b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/DataRepositoryPublicModel.java index 29c146c8d..910f89214 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/DataRepositoryPublicModel.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/DataRepositoryPublicModel.java @@ -1,12 +1,12 @@ package eu.eudat.model.publicapi.datasetwizard; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.model.DescriptionReference; import eu.eudat.model.Reference; import eu.eudat.model.referencedefinition.Field; +import eu.eudat.service.publicapi.PublicApiProperties; + +import java.util.Objects; -import java.util.Date; -import java.util.UUID; public class DataRepositoryPublicModel { private String id; @@ -90,8 +90,8 @@ public class DataRepositoryPublicModel { return null; } - public static DataRepositoryPublicModel fromDescriptionReference(DescriptionReference descriptionReference) { - if (descriptionReference.getReference().getType() != ReferenceType.DataRepositories) + public static DataRepositoryPublicModel fromDescriptionReference(DescriptionReference descriptionReference, PublicApiProperties.ReferenceTypeMapConfig config) { + if (!Objects.equals(descriptionReference.getReference().getType().getId(), config.getDataRepositoryTypeId())) return null; DataRepositoryPublicModel model = new DataRepositoryPublicModel(); Reference reference = descriptionReference.getReference(); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/ExternalDatasetPublicListingModel.java b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/ExternalDatasetPublicListingModel.java index 9ab04c895..68d619ceb 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/ExternalDatasetPublicListingModel.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/ExternalDatasetPublicListingModel.java @@ -1,11 +1,12 @@ package eu.eudat.model.publicapi.datasetwizard; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.model.DescriptionReference; import eu.eudat.model.Reference; import eu.eudat.model.referencedefinition.Field; +import eu.eudat.service.publicapi.PublicApiProperties; import java.util.Date; +import java.util.Objects; import java.util.UUID; public class ExternalDatasetPublicListingModel { @@ -106,8 +107,8 @@ public class ExternalDatasetPublicListingModel { this.source = source; } - public static ExternalDatasetPublicListingModel fromDescriptionReference(DescriptionReference descriptionReference) { - if (descriptionReference.getReference().getType() != ReferenceType.Datasets) + public static ExternalDatasetPublicListingModel fromDescriptionReference(DescriptionReference descriptionReference, PublicApiProperties.ReferenceTypeMapConfig config) { + if (!Objects.equals(descriptionReference.getReference().getType().getId(), config.getDatasetTypeId())) return null; ExternalDatasetPublicListingModel model = new ExternalDatasetPublicListingModel(); Reference reference = descriptionReference.getReference(); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/RegistryPublicModel.java b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/RegistryPublicModel.java index 521a3a8cf..b0d15e14d 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/RegistryPublicModel.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/RegistryPublicModel.java @@ -1,11 +1,11 @@ package eu.eudat.model.publicapi.datasetwizard; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.model.DescriptionReference; import eu.eudat.model.Reference; import eu.eudat.model.referencedefinition.Field; +import eu.eudat.service.publicapi.PublicApiProperties; -import java.util.Date; +import java.util.Objects; import java.util.UUID; public class RegistryPublicModel { @@ -74,8 +74,8 @@ public class RegistryPublicModel { return null; } - public static RegistryPublicModel fromDescriptionReference(DescriptionReference descriptionReference) { - if (descriptionReference.getReference().getType() != ReferenceType.Registries) + public static RegistryPublicModel fromDescriptionReference(DescriptionReference descriptionReference, PublicApiProperties.ReferenceTypeMapConfig config) { + if (!Objects.equals(descriptionReference.getReference().getType().getId(), config.getRegistryTypeId())) return null; RegistryPublicModel model = new RegistryPublicModel(); Reference reference = descriptionReference.getReference(); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/ServicePublicModel.java b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/ServicePublicModel.java index 20564d363..08d6925ac 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/ServicePublicModel.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/datasetwizard/ServicePublicModel.java @@ -1,11 +1,12 @@ package eu.eudat.model.publicapi.datasetwizard; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.model.DescriptionReference; import eu.eudat.model.Reference; import eu.eudat.model.referencedefinition.Field; +import eu.eudat.service.publicapi.PublicApiProperties; import java.util.Date; +import java.util.Objects; import java.util.UUID; public class ServicePublicModel { @@ -74,8 +75,8 @@ public class ServicePublicModel { return null; } - public static ServicePublicModel fromDescriptionReference(DescriptionReference descriptionReference) { - if (descriptionReference.getReference().getType() != ReferenceType.Services) + public static ServicePublicModel fromDescriptionReference(DescriptionReference descriptionReference, PublicApiProperties.ReferenceTypeMapConfig config) { + if (!Objects.equals(descriptionReference.getReference().getType().getId(), config.getServiceTypeId())) return null; ServicePublicModel model = new ServicePublicModel(); Reference reference = descriptionReference.getReference(); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/grant/GrantPublicOverviewModel.java b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/grant/GrantPublicOverviewModel.java index fb90d86a5..31d508176 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/grant/GrantPublicOverviewModel.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/grant/GrantPublicOverviewModel.java @@ -1,15 +1,16 @@ package eu.eudat.model.publicapi.grant; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.model.DescriptionReference; import eu.eudat.model.DmpReference; import eu.eudat.model.Reference; import eu.eudat.model.publicapi.funder.FunderPublicOverviewModel; import eu.eudat.model.referencedefinition.Field; +import eu.eudat.service.publicapi.PublicApiProperties; import java.time.Instant; import java.util.Date; import java.util.List; +import java.util.Objects; import java.util.UUID; public class GrantPublicOverviewModel { @@ -78,17 +79,17 @@ public class GrantPublicOverviewModel { this.funder = funder; } - public static GrantPublicOverviewModel fromDmpReferences(List references) { + public static GrantPublicOverviewModel fromDmpReferences(List references, PublicApiProperties.ReferenceTypeMapConfig config) { FunderPublicOverviewModel funder = null; for (DmpReference dmpReference : references) { - if (dmpReference.getReference().getType() == ReferenceType.Funder) { + if (!Objects.equals(dmpReference.getReference().getType().getId(), config.getFunderTypeId())) { funder = new FunderPublicOverviewModel(); Reference reference = dmpReference.getReference(); funder.setId(reference.getId()); funder.setLabel(reference.getLabel()); continue; } - if (dmpReference.getReference().getType() != ReferenceType.Grants) + if (!Objects.equals(dmpReference.getReference().getType().getId(), config.getGrantTypeId())) continue; GrantPublicOverviewModel model = new GrantPublicOverviewModel(); Reference reference = dmpReference.getReference(); @@ -110,17 +111,17 @@ public class GrantPublicOverviewModel { return null; } - public static GrantPublicOverviewModel fromDescriptionReference(List references) { + public static GrantPublicOverviewModel fromDescriptionReference(List references, PublicApiProperties.ReferenceTypeMapConfig config) { FunderPublicOverviewModel funder = null; for (DescriptionReference descriptionReference : references) { - if (descriptionReference.getReference().getType() == ReferenceType.Funder) { + if (Objects.equals(descriptionReference.getReference().getType().getId(), config.getFunderTypeId())) { funder = new FunderPublicOverviewModel(); Reference reference = descriptionReference.getReference(); funder.setId(reference.getId()); funder.setLabel(reference.getLabel()); continue; } - if (descriptionReference.getReference().getType() != ReferenceType.Grants) + if (Objects.equals(descriptionReference.getReference().getType().getId(), config.getGrantTypeId())) continue; GrantPublicOverviewModel model = new GrantPublicOverviewModel(); Reference reference = descriptionReference.getReference(); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/organisation/OrganizationPublicModel.java b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/organisation/OrganizationPublicModel.java index abb837b90..cd2cd2bfc 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/organisation/OrganizationPublicModel.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/organisation/OrganizationPublicModel.java @@ -1,8 +1,10 @@ package eu.eudat.model.publicapi.organisation; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.model.DmpReference; import eu.eudat.model.Reference; +import eu.eudat.service.publicapi.PublicApiProperties; + +import java.util.Objects; public class OrganizationPublicModel { private String label; @@ -46,8 +48,8 @@ public class OrganizationPublicModel { this.key = key; } - public static OrganizationPublicModel fromDmpReference(DmpReference dmpReference) { - if (dmpReference.getReference().getType() != ReferenceType.Organizations) + public static OrganizationPublicModel fromDmpReference(DmpReference dmpReference, PublicApiProperties.ReferenceTypeMapConfig config) { + if (!Objects.equals(dmpReference.getReference().getType().getId(), config.getOrganizationTypeId())) return null; OrganizationPublicModel model = new OrganizationPublicModel(); Reference reference = dmpReference.getReference(); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/researcher/ResearcherPublicModel.java b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/researcher/ResearcherPublicModel.java index cfe57f736..4b11a6e72 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/researcher/ResearcherPublicModel.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/publicapi/researcher/ResearcherPublicModel.java @@ -1,12 +1,14 @@ package eu.eudat.model.publicapi.researcher; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.model.DmpReference; import eu.eudat.model.Reference; +import eu.eudat.service.publicapi.PublicApiProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Objects; + @JsonIgnoreProperties(ignoreUnknown = true) public class ResearcherPublicModel { private static final Logger logger = LoggerFactory.getLogger(ResearcherPublicModel.class); @@ -51,8 +53,8 @@ public class ResearcherPublicModel { this.key = key; } - public static ResearcherPublicModel fromDmpReference(DmpReference dmpReference) { - if (dmpReference.getReference().getType() != ReferenceType.Researcher) + public static ResearcherPublicModel fromDmpReference(DmpReference dmpReference, PublicApiProperties.ReferenceTypeMapConfig config) { + if (!Objects.equals(dmpReference.getReference().getType().getId(), config.getRegistryTypeId())) return null; ResearcherPublicModel model = new ResearcherPublicModel(); Reference reference = dmpReference.getReference(); diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceQuery.java b/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceQuery.java index 91bce6f5d..76f220d97 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceQuery.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/ReferenceQuery.java @@ -1,7 +1,6 @@ package eu.eudat.query; import eu.eudat.authorization.AuthorizationFlags; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.commons.enums.IsActive; import eu.eudat.commons.enums.ReferenceSourceType; import eu.eudat.data.DmpReferenceEntity; @@ -33,17 +32,15 @@ public class ReferenceQuery extends QueryBase { private Collection referenceSourceTypes; - private Collection referenceTypes; + private Collection typeIds; private Collection references; private Collection sources; private Collection excludedIds; - private DmpReferenceQuery dmpReferenceQuery; - private Collection referenceTypeIds; private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); @@ -82,18 +79,18 @@ public class ReferenceQuery extends QueryBase { return this; } - public ReferenceQuery types(ReferenceType value) { - this.referenceTypes = List.of(value); + public ReferenceQuery typeIds(UUID value) { + this.typeIds = List.of(value); return this; } - public ReferenceQuery types(ReferenceType... value) { - this.referenceTypes = Arrays.asList(value); + public ReferenceQuery typeIds(UUID... value) { + this.typeIds = Arrays.asList(value); return this; } - public ReferenceQuery types(Collection values) { - this.referenceTypes = values; + public ReferenceQuery typeIds(Collection values) { + this.typeIds = values; return this; } @@ -157,21 +154,6 @@ public class ReferenceQuery extends QueryBase { return this; } - public ReferenceQuery referenceTypeIds(UUID value) { - this.referenceTypeIds = List.of(value); - return this; - } - - public ReferenceQuery referenceTypeIds(UUID... value) { - this.referenceTypeIds = Arrays.asList(value); - return this; - } - - public ReferenceQuery referenceTypeIds(Collection values) { - this.referenceTypeIds = values; - return this; - } - public ReferenceQuery dmpReferenceSubQuery(DmpReferenceQuery value) { this.dmpReferenceQuery = value; return this; @@ -193,7 +175,7 @@ public class ReferenceQuery extends QueryBase { @Override protected Boolean isFalseQuery() { - return this.isEmpty(this.ids) || this.isEmpty(this.isActives) || this.isEmpty(this.sources) ||this.isEmpty(this.excludedIds) || this.isEmpty(this.referenceTypes) || this.isEmpty(this.referenceSourceTypes)|| this.isFalseQuery(this.dmpReferenceQuery); + return this.isEmpty(this.ids) || this.isEmpty(this.isActives) || this.isEmpty(this.sources) ||this.isEmpty(this.excludedIds) || this.isEmpty(this.typeIds) || this.isEmpty(this.referenceSourceTypes)|| this.isFalseQuery(this.dmpReferenceQuery); } @Override @@ -223,9 +205,9 @@ public class ReferenceQuery extends QueryBase { inClause.value(item); predicates.add(inClause); } - if (this.referenceTypes != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(ReferenceEntity._type)); - for (ReferenceType item : this.referenceTypes) + if (this.typeIds != null) { + CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(ReferenceEntity._typeId)); + for (UUID item : this.typeIds) inClause.value(item); predicates.add(inClause); } @@ -273,7 +255,7 @@ public class ReferenceQuery extends QueryBase { item.setReference(QueryBase.convertSafe(tuple, columns, ReferenceEntity._reference, String.class)); item.setSource(QueryBase.convertSafe(tuple, columns, ReferenceEntity._source, String.class)); item.setSourceType(QueryBase.convertSafe(tuple, columns, ReferenceEntity._sourceType, ReferenceSourceType.class)); - item.setType(QueryBase.convertSafe(tuple, columns, ReferenceEntity._type, ReferenceType.class)); + item.setTypeId(QueryBase.convertSafe(tuple, columns, ReferenceEntity._typeId, UUID.class)); item.setCreatedById(QueryBase.convertSafe(tuple, columns, ReferenceEntity._createdById, UUID.class)); return item; } @@ -292,7 +274,8 @@ public class ReferenceQuery extends QueryBase { else if (item.match(Reference._reference) || item.match(PublicReference._reference)) return ReferenceEntity._reference; else if (item.match(Reference._source)) return ReferenceEntity._source; else if (item.match(Reference._sourceType)) return ReferenceEntity._sourceType; - else if (item.match(Reference._type) || item.match(PublicReference._type)) return ReferenceEntity._type; + else if (item.match(Reference._type) || item.match(PublicReference._type)) return ReferenceEntity._typeId; + else if (item.prefix(Reference._type) || item.prefix(PublicReference._type)) return ReferenceEntity._typeId; else if (item.prefix(Reference._createdBy)) return ReferenceEntity._createdById; else return null; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceDefinitionSearchLookup.java b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceDefinitionSearchLookup.java index d68d4811f..37f21a0f4 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceDefinitionSearchLookup.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceDefinitionSearchLookup.java @@ -40,7 +40,7 @@ public class ReferenceDefinitionSearchLookup extends Lookup { public ReferenceQuery enrich(QueryFactory queryFactory) { ReferenceQuery query = queryFactory.query(ReferenceQuery.class); - if (this.referenceTypeId != null) query.referenceTypeIds(this.referenceTypeId); + if (this.referenceTypeId != null) query.typeIds(this.referenceTypeId); this.enrichCommon(query); diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceLookup.java b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceLookup.java index 5891d734c..0b1c6de12 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceLookup.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceLookup.java @@ -1,6 +1,5 @@ package eu.eudat.query.lookup; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.commons.enums.IsActive; import eu.eudat.commons.enums.ReferenceSourceType; import eu.eudat.query.ReferenceQuery; @@ -19,7 +18,7 @@ public class ReferenceLookup extends Lookup { private Collection sourceTypes; - private Collection types; + private Collection typeIds; private List ids; @@ -65,19 +64,19 @@ public class ReferenceLookup extends Lookup { this.sourceTypes = sourceTypes; } - public Collection getTypes() { - return types; + public Collection getTypeIds() { + return typeIds; } - public void setTypes(Collection types) { - this.types = types; + public void setTypeIds(Collection typeIds) { + this.typeIds = typeIds; } public ReferenceQuery enrich(QueryFactory queryFactory) { ReferenceQuery query = queryFactory.query(ReferenceQuery.class); if (this.like != null) query.like(this.like); if (this.isActive != null) query.isActive(this.isActive); - if (this.types != null) query.types(this.types); + if (this.typeIds != null) query.typeIds(this.typeIds); if (this.sourceTypes != null) query.sourceTypes(this.sourceTypes); if (this.ids != null) query.ids(this.ids); if (this.excludedIds != null) query.excludedIds(this.excludedIds); diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceSearchLookup.java b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceSearchLookup.java index 947f3c7e8..727998400 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceSearchLookup.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceSearchLookup.java @@ -1,15 +1,16 @@ package eu.eudat.query.lookup; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.query.ReferenceQuery; import gr.cite.tools.data.query.Lookup; import gr.cite.tools.data.query.QueryFactory; +import java.util.UUID; + public class ReferenceSearchLookup extends Lookup { private String like; - private ReferenceType type; + private UUID typeId; private String key; @@ -21,12 +22,12 @@ public class ReferenceSearchLookup extends Lookup { this.like = like; } - public ReferenceType getType() { - return type; + public UUID getTypeId() { + return typeId; } - public void setType(ReferenceType type) { - this.type = type; + public void setTypeId(UUID typeId) { + this.typeId = typeId; } public String getKey() { @@ -39,7 +40,7 @@ public class ReferenceSearchLookup extends Lookup { public ReferenceQuery enrich(QueryFactory queryFactory) { ReferenceQuery query = queryFactory.query(ReferenceQuery.class); - if (this.type != null) query.types(this.type); + if (this.typeId != null) query.typeIds(this.typeId); this.enrichCommon(query); diff --git a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceTypeLookup.java b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceTypeLookup.java index 756fbf294..b1ebd93e7 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceTypeLookup.java +++ b/dmp-backend/core/src/main/java/eu/eudat/query/lookup/ReferenceTypeLookup.java @@ -1,14 +1,10 @@ package eu.eudat.query.lookup; import eu.eudat.commons.enums.IsActive; -import eu.eudat.commons.enums.ReferenceSourceType; -import eu.eudat.commons.enums.ReferenceType; -import eu.eudat.query.ReferenceQuery; import eu.eudat.query.ReferenceTypeQuery; import gr.cite.tools.data.query.Lookup; import gr.cite.tools.data.query.QueryFactory; -import java.util.Collection; import java.util.List; import java.util.UUID; diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/DashboardServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/DashboardServiceImpl.java index a4ae6b90e..ae7dea1ec 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/DashboardServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/DashboardServiceImpl.java @@ -6,13 +6,13 @@ import eu.eudat.authorization.Permission; import eu.eudat.commons.JsonHandlingService; import eu.eudat.commons.XmlHandlingService; import eu.eudat.commons.enums.*; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.commons.scope.user.UserScope; import eu.eudat.commons.types.dashborad.RecentActivityItemEntity; import eu.eudat.convention.ConventionService; import eu.eudat.errorcode.ErrorThesaurusProperties; import eu.eudat.event.EventBroker; import eu.eudat.model.*; +import eu.eudat.model.builder.PublicReferenceTypeBuilder; import eu.eudat.model.builder.RecentActivityItemBuilder; import eu.eudat.model.result.QueryResult; import eu.eudat.query.*; @@ -43,59 +43,28 @@ public class DashboardServiceImpl implements DashboardService { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DashboardServiceImpl.class)); - private final EntityManager entityManager; - - private final AuthorizationService authorizationService; - - private final DeleterFactory deleterFactory; - - private final BuilderFactory builderFactory; - private final ConventionService conventionService; - - private final ErrorThesaurusProperties errors; - - private final MessageSource messageSource; - - private final EventBroker eventBroker; - + private final AuthorizationService authorizationService; + private final BuilderFactory builderFactory; private final QueryFactory queryFactory; - - private final JsonHandlingService jsonHandlingService; - private final UserScope userScope; - private final XmlHandlingService xmlHandlingService; - + private final DashboardServiceProperties config; private final ElasticQueryHelperService elasticQueryHelperService; - private final DashboardStatisticsCacheService dashboardStatisticsCacheService; @Autowired public DashboardServiceImpl( - EntityManager entityManager, - AuthorizationService authorizationService, - DeleterFactory deleterFactory, - BuilderFactory builderFactory, - ConventionService conventionService, - ErrorThesaurusProperties errors, - MessageSource messageSource, - EventBroker eventBroker, - QueryFactory queryFactory, - JsonHandlingService jsonHandlingService, - UserScope userScope, - XmlHandlingService xmlHandlingService, ElasticQueryHelperService elasticQueryHelperService, DashboardStatisticsCacheService dashboardStatisticsCacheService) { - this.entityManager = entityManager; - this.authorizationService = authorizationService; - this.deleterFactory = deleterFactory; + ConventionService conventionService, AuthorizationService authorizationService, + BuilderFactory builderFactory, + QueryFactory queryFactory, + UserScope userScope, + DashboardServiceProperties config, ElasticQueryHelperService elasticQueryHelperService, DashboardStatisticsCacheService dashboardStatisticsCacheService) { + this.conventionService = conventionService; + this.authorizationService = authorizationService; this.builderFactory = builderFactory; - this.conventionService = conventionService; - this.errors = errors; - this.messageSource = messageSource; - this.eventBroker = eventBroker; this.queryFactory = queryFactory; - this.jsonHandlingService = jsonHandlingService; this.userScope = userScope; - this.xmlHandlingService = xmlHandlingService; - this.elasticQueryHelperService = elasticQueryHelperService; + this.config = config; + this.elasticQueryHelperService = elasticQueryHelperService; this.dashboardStatisticsCacheService = dashboardStatisticsCacheService; } @@ -146,12 +115,19 @@ public class DashboardServiceImpl implements DashboardService { DashboardStatistics statistics = new DashboardStatistics(); statistics.setDmpCount(dmpQuery.authorize(EnumSet.of(Public)).count()); statistics.setDescriptionCount(this.queryFactory.query(DescriptionQuery.class).isActive(IsActive.Active).dmpSubQuery(dmpQuery).statuses(DescriptionStatus.Finalized).authorize(EnumSet.of(Public)).count()); - statistics.setOrganizationCount(this.queryFactory.query(ReferenceQuery.class).isActive(IsActive.Active).types(ReferenceType.Organizations).authorize(EnumSet.of(Public)) - .dmpReferenceSubQuery(this.queryFactory.query(DmpReferenceQuery.class).isActives(IsActive.Active) - .dmpSubQuery(dmpQuery)).count()); - statistics.setGrantCount(this.queryFactory.query(ReferenceQuery.class).isActive(IsActive.Active).types(ReferenceType.Grants).authorize(EnumSet.of(Public)) - .dmpReferenceSubQuery(this.queryFactory.query(DmpReferenceQuery.class).isActives(IsActive.Active) - .dmpSubQuery(dmpQuery)).count()); + + statistics.setReferenceTypeStatistics(new ArrayList<>()); + if (!this.conventionService.isListNullOrEmpty(this.config.getReferenceTypeCounters())){ + for (UUID typeId : this.config.getReferenceTypeCounters()){ + DashboardReferenceTypeStatistics referenceTypeStatistics = new DashboardReferenceTypeStatistics(); + referenceTypeStatistics.setCount(this.queryFactory.query(ReferenceQuery.class).isActive(IsActive.Active).typeIds(typeId).authorize(EnumSet.of(Public)) + .dmpReferenceSubQuery(this.queryFactory.query(DmpReferenceQuery.class).isActives(IsActive.Active) + .dmpSubQuery(dmpQuery)).count()); + referenceTypeStatistics.setReferenceType(this.builderFactory.builder(PublicReferenceTypeBuilder.class).build(new BaseFieldSet().ensure(PublicReferenceType._name), this.queryFactory.query(ReferenceTypeQuery.class).ids(typeId).first())); + statistics.getReferenceTypeStatistics().add(referenceTypeStatistics); + } + } + cacheValue = new DashboardStatisticsCacheService.DashboardStatisticsCacheValue(); cacheValue.setPublic(true); cacheValue.setDashboardStatistics(statistics); @@ -175,13 +151,18 @@ public class DashboardServiceImpl implements DashboardService { DashboardStatistics statistics = new DashboardStatistics(); statistics.setDmpCount(dmpQuery.authorize(EnumSet.of(AuthorizationFlags.DmpAssociated)).count()); statistics.setDescriptionCount(this.queryFactory.query(DescriptionQuery.class).isActive(IsActive.Active).dmpSubQuery(dmpQuery).statuses(DescriptionStatus.Finalized).authorize(EnumSet.of(AuthorizationFlags.DmpAssociated)).count()); - statistics.setOrganizationCount(this.queryFactory.query(ReferenceQuery.class).isActive(IsActive.Active).types(ReferenceType.Organizations).authorize(EnumSet.of(Owner)) - .dmpReferenceSubQuery(this.queryFactory.query(DmpReferenceQuery.class).isActives(IsActive.Active) - .dmpSubQuery(dmpQuery)).count()); - statistics.setGrantCount(this.queryFactory.query(ReferenceQuery.class).isActive(IsActive.Active).types(ReferenceType.Grants).authorize(EnumSet.of(Owner)) - .dmpReferenceSubQuery(this.queryFactory.query(DmpReferenceQuery.class).isActives(IsActive.Active) - .dmpSubQuery(dmpQuery)).count()); - + + statistics.setReferenceTypeStatistics(new ArrayList<>()); + if (!this.conventionService.isListNullOrEmpty(this.config.getReferenceTypeCounters())){ + for (UUID typeId : this.config.getReferenceTypeCounters()){ + DashboardReferenceTypeStatistics referenceTypeStatistics = new DashboardReferenceTypeStatistics(); + referenceTypeStatistics.setCount(this.queryFactory.query(ReferenceQuery.class).isActive(IsActive.Active).typeIds(typeId).authorize(EnumSet.of(Owner)) + .dmpReferenceSubQuery(this.queryFactory.query(DmpReferenceQuery.class).isActives(IsActive.Active) + .dmpSubQuery(dmpQuery)).count()); + referenceTypeStatistics.setReferenceType(this.builderFactory.builder(PublicReferenceTypeBuilder.class).build(new BaseFieldSet().ensure(PublicReferenceType._name), this.queryFactory.query(ReferenceTypeQuery.class).ids(typeId).first())); + statistics.getReferenceTypeStatistics().add(referenceTypeStatistics); + } + } cacheValue = new DashboardStatisticsCacheService.DashboardStatisticsCacheValue(this.userScope.getUserId()); cacheValue.setPublic(false); cacheValue.setDashboardStatistics(statistics); diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/DashboardServiceProperties.java b/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/DashboardServiceProperties.java new file mode 100644 index 000000000..692b06eee --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/DashboardServiceProperties.java @@ -0,0 +1,21 @@ +package eu.eudat.service.dashborad; + + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.List; +import java.util.UUID; + +@ConfigurationProperties(prefix = "dashboard") +public class DashboardServiceProperties { + private List referenceTypeCounters; + + public List getReferenceTypeCounters() { + return referenceTypeCounters; + } + + public void setReferenceTypeCounters(List referenceTypeCounters) { + this.referenceTypeCounters = referenceTypeCounters; + } +} + diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/PublicApiConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/PublicApiConfiguration.java new file mode 100644 index 000000000..19984991e --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/PublicApiConfiguration.java @@ -0,0 +1,10 @@ +package eu.eudat.service.dashborad; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties(DashboardServiceProperties.class) +public class PublicApiConfiguration { + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/description/DescriptionServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/description/DescriptionServiceImpl.java index 2d416db90..5d384c28e 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/description/DescriptionServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/description/DescriptionServiceImpl.java @@ -5,12 +5,12 @@ import eu.eudat.authorization.Permission; import eu.eudat.commons.JsonHandlingService; import eu.eudat.commons.XmlHandlingService; import eu.eudat.commons.enums.*; -import eu.eudat.commons.enums.ReferenceType; import eu.eudat.commons.enums.notification.NotificationContactType; import eu.eudat.commons.scope.user.UserScope; import eu.eudat.commons.types.description.*; import eu.eudat.commons.types.descriptionreference.DescriptionReferenceDataEntity; import eu.eudat.commons.types.descriptiontemplate.FieldSetEntity; +import eu.eudat.commons.types.descriptiontemplate.fielddata.ReferenceTypeDataEntity; import eu.eudat.commons.types.descriptiontemplate.fielddata.UploadDataEntity; import eu.eudat.commons.types.notification.*; import eu.eudat.commons.types.reference.DefinitionEntity; @@ -184,7 +184,7 @@ public class DescriptionServiceImpl implements DescriptionService { this.entityManager.flush(); eu.eudat.commons.types.descriptiontemplate.DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(eu.eudat.commons.types.descriptiontemplate.DefinitionEntity.class, descriptionTemplateEntity.getDefinition()); - Map> fieldToReferenceMap = this.patchAndSaveReferences(this.buildDescriptionReferencePersists(model.getProperties()), data.getId()); + Map> fieldToReferenceMap = this.patchAndSaveReferences(this.buildDescriptionReferencePersists(model.getProperties()), data.getId(), definition); this.entityManager.flush(); @@ -424,12 +424,6 @@ public class DescriptionServiceImpl implements DescriptionService { for (UUID id : ids){ if (!existingIds.contains(id)) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, Description.class.getSimpleName()}, LocaleContextHolder.getLocale())); } - } if (FieldType.INTERNAL_DMP_ENTRIES_RESEARCHERS.equals(fieldType) && !this.conventionService.isListNullOrEmpty(persist.getTextListValue())){ - List ids = persist.getTextListValue().stream().map(UUID::fromString).toList(); - Set existingIds = this.queryFactory.query(ReferenceQuery.class).ids(ids).types(ReferenceType.Researcher).isActive(IsActive.Active).collectAs(new BaseFieldSet().ensure(Reference._id)).stream().map(ReferenceEntity::getId).collect(Collectors.toSet()); - for (UUID id : ids){ - if (!existingIds.contains(id)) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, Reference.class.getSimpleName()}, LocaleContextHolder.getLocale())); - } } data.setTextListValue(persist.getTextListValue()); } @@ -483,7 +477,7 @@ public class DescriptionServiceImpl implements DescriptionService { } } - private Map> patchAndSaveReferences(List models, UUID descriptionId) throws InvalidApplicationException { + private Map> patchAndSaveReferences(List models, UUID descriptionId, eu.eudat.commons.types.descriptiontemplate.DefinitionEntity definition) throws InvalidApplicationException { if (models == null) models = new ArrayList<>(); Map> fieldToReferenceMap = new HashMap<>(); @@ -512,13 +506,16 @@ public class DescriptionServiceImpl implements DescriptionService { referenceEntity = this.entityManager.find(ReferenceEntity.class, referencePersist.getId()); if (referenceEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{referencePersist.getId(), Reference.class.getSimpleName()}, LocaleContextHolder.getLocale())); } else { - referenceEntity = this.queryFactory.query(ReferenceQuery.class).sourceTypes(referencePersist.getSourceType()).sources(referencePersist.getSource()).isActive(IsActive.Active).references(referencePersist.getReference()).first(); + ReferenceTypeDataEntity fieldEntity = definition.getFieldById(model.getData().getFieldId()).stream().filter(x-> x.getData() != null && x.getData().getFieldType().equals(FieldType.REFERENCE_TYPES)).map(x-> (ReferenceTypeDataEntity)x.getData()).findFirst().orElse(null); + if (fieldEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getData().getFieldId(), ReferenceTypeDataEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); + + referenceEntity = this.queryFactory.query(ReferenceQuery.class).sourceTypes(referencePersist.getSourceType()).typeIds(fieldEntity.getReferenceTypeId()).sources(referencePersist.getSource()).isActive(IsActive.Active).references(referencePersist.getReference()).first(); if (referenceEntity == null){ referenceEntity = new ReferenceEntity(); referenceEntity.setId(UUID.randomUUID()); referenceEntity.setIsActive(IsActive.Active); referenceEntity.setCreatedAt(Instant.now()); - referenceEntity.setType(referencePersist.getType()); + referenceEntity.setTypeId(fieldEntity.getReferenceTypeId()); referenceEntity.setDefinition(this.xmlHandlingService.toXmlSafe(this.buildDefinitionEntity(referencePersist.getDefinition()))); referenceEntity.setUpdatedAt(Instant.now()); diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java index 37fd26d96..90ddefd11 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java @@ -12,6 +12,7 @@ import eu.eudat.commons.types.actionconfirmation.DmpInvitationEntity; import eu.eudat.commons.types.dmp.DmpBlueprintValueEntity; import eu.eudat.commons.types.dmp.DmpContactEntity; import eu.eudat.commons.types.dmp.DmpPropertiesEntity; +import eu.eudat.commons.types.dmpblueprint.ReferenceFieldEntity; import eu.eudat.commons.types.dmpreference.DmpReferenceDataEntity; import eu.eudat.commons.types.notification.*; import eu.eudat.commons.types.reference.DefinitionEntity; @@ -24,10 +25,7 @@ import eu.eudat.event.DmpTouchedEvent; import eu.eudat.event.EventBroker; import eu.eudat.integrationevent.outbox.notification.NotifyIntegrationEvent; import eu.eudat.integrationevent.outbox.notification.NotifyIntegrationEventHandler; -import eu.eudat.model.Dmp; -import eu.eudat.model.DmpUser; -import eu.eudat.model.Reference; -import eu.eudat.model.UserContactInfo; +import eu.eudat.model.*; import eu.eudat.model.builder.DmpBuilder; import eu.eudat.model.builder.DmpUserBuilder; import eu.eudat.model.deleter.*; @@ -169,7 +167,12 @@ public class DmpServiceImpl implements DmpService { DmpEntity data = this.patchAndSave(model); - this.patchAndSaveReferences(this.buildDmpReferencePersists(model.getProperties()), data.getId()); + DmpBlueprintEntity blueprintEntity = this.entityManager.find(DmpBlueprintEntity.class, data.getBlueprintId()); + if (blueprintEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{data.getBlueprintId(), DmpBlueprint.class.getSimpleName()}, LocaleContextHolder.getLocale())); + eu.eudat.commons.types.dmpblueprint.DefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(eu.eudat.commons.types.dmpblueprint.DefinitionEntity.class, blueprintEntity.getDefinition()); + if (definition == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{data.getBlueprintId(), eu.eudat.commons.types.dmpblueprint.DefinitionEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); + + this.patchAndSaveReferences(this.buildDmpReferencePersists(model.getProperties()), data.getId(), definition); this.patchAndSaveTemplates(data.getId(), model.getDescriptionTemplates()); @@ -620,7 +623,7 @@ public class DmpServiceImpl implements DmpService { return dmpReferencePersists; } - private void patchAndSaveReferences(List models, UUID dmpId) throws InvalidApplicationException { + private void patchAndSaveReferences(List models, UUID dmpId, eu.eudat.commons.types.dmpblueprint.DefinitionEntity blueprintDefinition) throws InvalidApplicationException { if (models == null) models = new ArrayList<>(); List dmpReferences = this.queryFactory.query(DmpReferenceQuery.class).dmpIds(dmpId).collect(); @@ -647,13 +650,16 @@ public class DmpServiceImpl implements DmpService { referenceEntity = this.entityManager.find(ReferenceEntity.class, referencePersist.getId()); if (referenceEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{referencePersist.getId(), Reference.class.getSimpleName()}, LocaleContextHolder.getLocale())); } else { - referenceEntity = this.queryFactory.query(ReferenceQuery.class).sourceTypes(referencePersist.getSourceType()).sources(referencePersist.getSource()).isActive(IsActive.Active).references(referencePersist.getReference()).first(); + ReferenceFieldEntity fieldEntity = blueprintDefinition.getFieldById(model.getData().getBlueprintFieldId()).stream().filter(x-> x.getCategory().equals(DmpBlueprintFieldCategory.Reference)).map(x-> (ReferenceFieldEntity)x).findFirst().orElse(null); + if (fieldEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getData().getBlueprintFieldId(), ReferenceFieldEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); + + referenceEntity = this.queryFactory.query(ReferenceQuery.class).sourceTypes(referencePersist.getSourceType()).typeIds(fieldEntity.getReferenceTypeId()).sources(referencePersist.getSource()).isActive(IsActive.Active).references(referencePersist.getReference()).first(); if (referenceEntity == null){ referenceEntity = new ReferenceEntity(); referenceEntity.setId(UUID.randomUUID()); referenceEntity.setIsActive(IsActive.Active); referenceEntity.setCreatedAt(Instant.now()); - referenceEntity.setType(referencePersist.getType()); + referenceEntity.setTypeId(fieldEntity.getReferenceTypeId()); referenceEntity.setDefinition(this.xmlHandlingService.toXmlSafe(this.buildDefinitionEntity(referencePersist.getDefinition()))); referenceEntity.setUpdatedAt(Instant.now()); diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/dmpblueprint/DmpBlueprintServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/dmpblueprint/DmpBlueprintServiceImpl.java index 0ce353028..19d07b834 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/dmpblueprint/DmpBlueprintServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/dmpblueprint/DmpBlueprintServiceImpl.java @@ -19,7 +19,6 @@ import eu.eudat.model.dmpblueprintdefinition.Section; import eu.eudat.model.persist.DmpBlueprintPersist; import eu.eudat.model.persist.NewVersionDmpBlueprintPersist; import eu.eudat.model.persist.dmpblueprintdefinition.*; -import eu.eudat.query.DescriptionTemplateQuery; import eu.eudat.query.DmpBlueprintQuery; import eu.eudat.service.responseutils.ResponseUtilsService; import gr.cite.commons.web.authz.service.AuthorizationService; @@ -37,7 +36,6 @@ import gr.cite.tools.logging.MapLogEntry; import gr.cite.tools.validation.ValidatorFactory; import jakarta.persistence.EntityManager; import jakarta.xml.bind.JAXBException; -import org.apache.bcel.generic.DADD; import org.jetbrains.annotations.NotNull; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -252,15 +250,26 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService { if (persist == null) return new ExtraFieldEntity(); FieldEntity data; - if (DmpBlueprintFieldCategory.Extra.equals(persist.getCategory())) { - ExtraFieldEntity dataTyped = new ExtraFieldEntity(); - dataTyped.setType(((ExtraFieldPersist) persist).getDataType()); - data = dataTyped; - } else { - SystemFieldEntity dataTyped = new SystemFieldEntity(); - dataTyped.setType(((SystemFieldPersist) persist).getSystemFieldType()); - data = dataTyped; + + switch (persist.getCategory()){ + case Extra -> { + ExtraFieldEntity dataTyped = new ExtraFieldEntity(); + dataTyped.setType(((ExtraFieldPersist) persist).getDataType()); + data = dataTyped; + } + case System -> { + SystemFieldEntity dataTyped = new SystemFieldEntity(); + dataTyped.setType(((SystemFieldPersist) persist).getSystemFieldType()); + data = dataTyped; + } + case Reference -> { + ReferenceFieldEntity dataTyped = new ReferenceFieldEntity(); + dataTyped.setReferenceTypeId(((ReferenceFieldPersist) persist).getReferenceTypeId()); + data = dataTyped; + } + default -> throw new InternalError("unknown type: " + persist.getCategory()); } + data.setId(persist.getId()); data.setCategory(persist.getCategory()); data.setLabel(persist.getLabel()); @@ -472,6 +481,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService { } } xml.setSystemFields(dmpBlueprintSystemFieldModels); + List dmpBlueprintExtraFieldModels = new LinkedList<>(); if (!this.conventionService.isListNullOrEmpty(entity.getFields())) { for (ExtraFieldEntity systemField : entity.getFields().stream().filter(x -> x.getCategory() == DmpBlueprintFieldCategory.Extra).map(x -> (ExtraFieldEntity) x).toList()) { @@ -480,6 +490,14 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService { } xml.setExtraFields(dmpBlueprintExtraFieldModels); + List dmpBlueprintReferenceFieldModels = new LinkedList<>(); + if (!this.conventionService.isListNullOrEmpty(entity.getFields())) { + for (ReferenceFieldEntity referenceFieldEntity : entity.getFields().stream().filter(x -> x.getCategory() == DmpBlueprintFieldCategory.Reference).map(x -> (ReferenceFieldEntity) x).toList()) { + dmpBlueprintReferenceFieldModels.add(this.referenceFieldXmlToExport(referenceFieldEntity)); + } + } + xml.setReferenceFields(dmpBlueprintReferenceFieldModels); + List dmpBlueprintDescriptionTemplates = new LinkedList<>(); if (!this.conventionService.isListNullOrEmpty(entity.getDescriptionTemplates())) { for (DescriptionTemplateEntity descriptionTemplate : entity.getDescriptionTemplates()) { @@ -511,6 +529,18 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService { return xml; } + private ReferenceFieldImportExport referenceFieldXmlToExport(ReferenceFieldEntity entity) { + ReferenceFieldImportExport xml = new ReferenceFieldImportExport(); + xml.setId(entity.getId()); + xml.setReferenceTypeId(entity.getReferenceTypeId()); + xml.setLabel(entity.getLabel()); + xml.setPlaceholder(entity.getPlaceholder()); + xml.setDescription(entity.getDescription()); + xml.setOrdinal(entity.getOrdinal()); + xml.setRequired(entity.isRequired()); + return xml; + } + private SystemFieldImportExport systemFieldXmlToExport(SystemFieldEntity entity) { SystemFieldImportExport xml = new SystemFieldImportExport(); xml.setId(entity.getId()); @@ -572,6 +602,11 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService { dmpBlueprintFieldModels.add(this.xmlSystemFieldToPersist(systemField)); } } + if (!this.conventionService.isListNullOrEmpty(importXml.getReferenceFields())) { + for (ReferenceFieldImportExport referenceField : importXml.getReferenceFields()) { + dmpBlueprintFieldModels.add(this.xmlReferenceFieldToPersist(referenceField)); + } + } if (!this.conventionService.isListNullOrEmpty(importXml.getExtraFields())) { for (ExtraFieldImportExport extraField : importXml.getExtraFields()) { dmpBlueprintFieldModels.add(this.xmlExtraFieldToPersist(extraField)); @@ -623,6 +658,19 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService { return persist; } + private FieldPersist xmlReferenceFieldToPersist(ReferenceFieldImportExport importXml) { + ReferenceFieldPersist persist = new ReferenceFieldPersist(); + persist.setId(importXml.getId()); + persist.setCategory(DmpBlueprintFieldCategory.Reference); + persist.setReferenceTypeId(importXml.getReferenceTypeId()); + persist.setLabel(importXml.getLabel()); + persist.setPlaceholder(importXml.getPlaceholder()); + persist.setDescription(importXml.getDescription()); + persist.setOrdinal(importXml.getOrdinal()); + persist.setRequired(importXml.isRequired()); + return persist; + } + //endregion } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/ExternalSelectFieldDataHelperService.java b/dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/ExternalSelectFieldDataHelperService.java deleted file mode 100644 index a456ca250..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/ExternalSelectFieldDataHelperService.java +++ /dev/null @@ -1,236 +0,0 @@ -package eu.eudat.service.fielddatahelper; - -import eu.eudat.authorization.AuthorizationFlags; -import eu.eudat.commons.types.descriptiontemplate.fielddata.ExternalSelectDataEntity; -import eu.eudat.commons.types.descriptiontemplate.importexport.fielddata.*; -import eu.eudat.convention.ConventionService; -import eu.eudat.model.builder.descriptiontemplatedefinition.fielddata.ExternalSelectDataBuilder; -import eu.eudat.model.descriptiontemplatedefinition.fielddata.ExternalSelectData; -import eu.eudat.model.persist.descriptiontemplatedefinition.fielddata.*; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.validation.Validator; -import gr.cite.tools.validation.ValidatorFactory; -import org.jetbrains.annotations.NotNull; -import org.springframework.stereotype.Component; - -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; - -@Component -public class ExternalSelectFieldDataHelperService extends BaseFieldDataHelperService { - private final ConventionService conventionService; - private final BuilderFactory builderFactory; - private final ValidatorFactory validatorFactory; - - public ExternalSelectFieldDataHelperService(ConventionService conventionService, BuilderFactory builderFactory, ValidatorFactory validatorFactory) { - this.conventionService = conventionService; - this.builderFactory = builderFactory; - this.validatorFactory = validatorFactory; - } - - - @Override - public ExternalSelectDataEntity newDataInstanceInternal() { - return new ExternalSelectDataEntity(); - } - - @Override - public ExternalSelectData newModelInstanceInternal() { - return new ExternalSelectData(); - } - - @Override - public ExternalSelectDataPersist newPersistModelInstanceInternal() { - return new ExternalSelectDataPersist(); - } - - @Override - protected ExternalSelectImportExport newImportExportInstanceInternal() { - return new ExternalSelectImportExport(); - } - - @Override - public Class getDataClass() { - return ExternalSelectDataEntity.class; - } - @Override - public Class getModelClass() { - return ExternalSelectData.class; - } - @Override - public Class getPersistModelClass() { - return ExternalSelectDataPersist.class; - } - - @Override - public Class getImportExportClass() { - return ExternalSelectImportExport.class; - } - - @Override - public Validator getPersistModelValidator() { - return this.validatorFactory.validator(ExternalSelectDataPersist.AutoCompleteDataPersistValidator.class); - } - - @Override - public List buildInternal(FieldSet fieldSet, List data, EnumSet authorizationFlags){ - return this.builderFactory.builder(ExternalSelectDataBuilder.class).authorize(authorizationFlags).build(fieldSet, data); - } - - @Override - protected ExternalSelectDataEntity applyPersistInternal(ExternalSelectDataPersist persist, ExternalSelectDataEntity data) { - data.setMultipleSelect(persist.getMultipleSelect()); - if (!this.conventionService.isListNullOrEmpty(persist.getSources())){ - data.setSources(new ArrayList<>()); - for (ExternalSelectDataPersist.ExternalSelectSourcePersist sourcePersist: persist.getSources()) { - data.getSources().add(this.buildAutoCompleteSingleData(sourcePersist)); - } - } - return data; - } - - private @NotNull ExternalSelectDataEntity.ExternalSelectSourceEntity buildAutoCompleteSingleData(ExternalSelectDataPersist.ExternalSelectSourcePersist persist){ - ExternalSelectDataEntity.ExternalSelectSourceEntity data = new ExternalSelectDataEntity.ExternalSelectSourceEntity(); - if (persist == null) return data; - - data.setUrl(persist.getUrl()); - data.setOptionsRoot(persist.getOptionsRoot()); - data.setHasAuth(persist.getHasAuth()); - if(persist.getSourceBinding() != null) data.setSourceBinding(this.buildOption(persist.getSourceBinding())); - if(persist.getAuth() != null) data.setAuth(this.buildAuthAutoCompleteData(persist.getAuth())); - data.setMethod(persist.getMethod()); - - return data; - } - - private @NotNull ExternalSelectDataEntity.ExternalSelectSourceBindingEntity buildOption(ExternalSelectDataPersist.ExternalSelectSourceBindingPersist persist){ - ExternalSelectDataEntity.ExternalSelectSourceBindingEntity data = new ExternalSelectDataEntity.ExternalSelectSourceBindingEntity(); - if (persist == null) return data; - - data.setLabel(persist.getLabel()); - data.setValue(persist.getValue()); - data.setSource(persist.getSource()); - - return data; - } - - private @NotNull ExternalSelectDataEntity.ExternalSelectAuthDataEntity buildAuthAutoCompleteData(ExternalSelectDataPersist.ExternalSelectAuthDataPersist persist){ - ExternalSelectDataEntity.ExternalSelectAuthDataEntity data = new ExternalSelectDataEntity.ExternalSelectAuthDataEntity(); - if (persist == null) return data; - - data.setBody(persist.getBody()); - data.setUrl(persist.getUrl()); - data.setMethod(persist.getMethod()); - data.setPath(persist.getPath()); - data.setType(persist.getType()); - - return data; - } - - @Override - protected ExternalSelectDataPersist importExportMapDataToPersistInternal(ExternalSelectImportExport data, ExternalSelectDataPersist persist) { - persist.setMultipleSelect(data.getMultipleSelect()); - if (!this.conventionService.isListNullOrEmpty(data.getSources())){ - persist.setSources(new ArrayList<>()); - for (ExternalSelectImportExport.ExternalSelectSourceImportExport autoCompleteSingleData: data.getSources()) { - persist.getSources().add(this.buildAutoCompleteSingleData(autoCompleteSingleData)); - } - } - return persist; - } - - private @NotNull ExternalSelectDataPersist.ExternalSelectSourcePersist buildAutoCompleteSingleData(ExternalSelectImportExport.ExternalSelectSourceImportExport data){ - ExternalSelectDataPersist.ExternalSelectSourcePersist persist = new ExternalSelectDataPersist.ExternalSelectSourcePersist(); - if (data == null) return persist; - - persist.setUrl(data.getUrl()); - persist.setOptionsRoot(data.getOptionsRoot()); - persist.setHasAuth(data.getHasAuth()); - if(data.getSourceBinding() != null) persist.setSourceBinding(this.buildOption(data.getSourceBinding())); - if(data.getAuth() != null) persist.setAuth(this.buildAuthAutoCompleteData(data.getAuth())); - persist.setMethod(data.getMethod()); - - return persist; - } - - private @NotNull ExternalSelectDataPersist.ExternalSelectSourceBindingPersist buildOption(ExternalSelectImportExport.ExternalSelectSourceBindingImportExport data){ - ExternalSelectDataPersist.ExternalSelectSourceBindingPersist persist = new ExternalSelectDataPersist.ExternalSelectSourceBindingPersist(); - if (data == null) return persist; - - persist.setLabel(data.getLabel()); - persist.setValue(data.getValue()); - persist.setSource(data.getSource()); - - return persist; - } - - private @NotNull ExternalSelectDataPersist.ExternalSelectAuthDataPersist buildAuthAutoCompleteData(ExternalSelectImportExport.ExternalSelectAuthImportExport data){ - ExternalSelectDataPersist.ExternalSelectAuthDataPersist persist = new ExternalSelectDataPersist.ExternalSelectAuthDataPersist(); - if (data == null) return persist; - - persist.setBody(data.getBody()); - persist.setUrl(data.getUrl()); - persist.setMethod(data.getMethod()); - persist.setPath(data.getPath()); - persist.setType(data.getType()); - - return persist; - } - - @Override - protected ExternalSelectImportExport dataToImportExportXmlInternal(ExternalSelectDataEntity data, ExternalSelectImportExport xml) { - xml.setMultipleSelect(data.getMultipleSelect()); - if (!this.conventionService.isListNullOrEmpty(data.getSources())){ - xml.setSources(new ArrayList<>()); - for (ExternalSelectDataEntity.ExternalSelectSourceEntity externalSelectSourceEntity : data.getSources()) { - xml.getSources().add(this.buildAutoCompleteSingleData(externalSelectSourceEntity)); - } - } - return xml; - } - - @Override - protected boolean isMultiValueInternal(ExternalSelectDataEntity data) { - return data.getMultipleSelect(); - } - - private @NotNull ExternalSelectImportExport.ExternalSelectSourceImportExport buildAutoCompleteSingleData(ExternalSelectDataEntity.ExternalSelectSourceEntity data){ - ExternalSelectImportExport.ExternalSelectSourceImportExport xml = new ExternalSelectImportExport.ExternalSelectSourceImportExport(); - if (data == null) return xml; - - xml.setUrl(data.getUrl()); - xml.setOptionsRoot(data.getOptionsRoot()); - xml.setHasAuth(data.getHasAuth()); - if(data.getSourceBinding() != null) xml.setSourceBinding(this.buildOption(data.getSourceBinding())); - if(data.getAuth() != null) xml.setAuth(this.buildAuthAutoCompleteData(data.getAuth())); - xml.setMethod(data.getMethod()); - - return xml; - } - - private @NotNull ExternalSelectImportExport.ExternalSelectSourceBindingImportExport buildOption(ExternalSelectDataEntity.ExternalSelectSourceBindingEntity data){ - ExternalSelectImportExport.ExternalSelectSourceBindingImportExport xml = new ExternalSelectImportExport.ExternalSelectSourceBindingImportExport(); - if (data == null) return xml; - - xml.setLabel(data.getLabel()); - xml.setValue(data.getValue()); - xml.setSource(data.getSource()); - - return xml; - } - - private @NotNull ExternalSelectImportExport.ExternalSelectAuthImportExport buildAuthAutoCompleteData(ExternalSelectDataEntity.ExternalSelectAuthDataEntity data){ - ExternalSelectImportExport.ExternalSelectAuthImportExport xml = new ExternalSelectImportExport.ExternalSelectAuthImportExport(); - if (data == null) return xml; - - xml.setBody(data.getBody()); - xml.setUrl(data.getUrl()); - xml.setMethod(data.getMethod()); - xml.setPath(data.getPath()); - xml.setType(data.getType()); - - return xml; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/FieldDataHelperServiceProvider.java b/dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/FieldDataHelperServiceProvider.java index 570b9c7f3..e2526ee3a 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/FieldDataHelperServiceProvider.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/FieldDataHelperServiceProvider.java @@ -15,19 +15,8 @@ public class FieldDataHelperServiceProvider { BaseFieldDataHelperService item = null; switch (type) { - case DATA_REPOSITORIES: - case PUB_REPOSITORIES: - case JOURNAL_REPOSITORIES: - case TAXONOMIES: - case LICENSES: - case PUBLICATIONS: - case REGISTRIES: - case SERVICES: - case RESEARCHERS: case INTERNAL_DMP_ENTRIES_DATASETS: - case INTERNAL_DMP_ENTRIES_DMPS: - case INTERNAL_DMP_ENTRIES_RESEARCHERS: - case ORGANIZATIONS: { + case INTERNAL_DMP_ENTRIES_DMPS: { item = this.applicationContext.getBean(LabelAndMultiplicityFieldDataHelperService.class); break; } @@ -60,10 +49,10 @@ public class FieldDataHelperServiceProvider { item = this.applicationContext.getBean(SelectFieldDataHelperService.class); break; } - case EXTERNAL_SELECT: { - item = this.applicationContext.getBean(ExternalSelectFieldDataHelperService.class); + case REFERENCE_TYPES:{ + item = this.applicationContext.getBean(ReferenceTypeFieldDataHelperService.class); break; - } + } default: throw new RuntimeException("unrecognized builder " + type.getValue()); } item.setFieldType(type); diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/ReferenceTypeFieldDataHelperService.java b/dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/ReferenceTypeFieldDataHelperService.java new file mode 100644 index 000000000..aa9bfca35 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/fielddatahelper/ReferenceTypeFieldDataHelperService.java @@ -0,0 +1,102 @@ +package eu.eudat.service.fielddatahelper; + +import eu.eudat.authorization.AuthorizationFlags; +import eu.eudat.commons.types.descriptiontemplate.fielddata.ReferenceTypeDataEntity; +import eu.eudat.commons.types.descriptiontemplate.importexport.fielddata.ReferenceTypeDataImportExport; +import eu.eudat.model.builder.descriptiontemplatedefinition.fielddata.ReferenceTypeDataBuilder; +import eu.eudat.model.descriptiontemplatedefinition.fielddata.ReferenceTypeData; +import eu.eudat.model.persist.descriptiontemplatedefinition.fielddata.ReferenceTypeDataPersist; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.validation.Validator; +import gr.cite.tools.validation.ValidatorFactory; +import org.springframework.stereotype.Component; + +import java.util.EnumSet; +import java.util.List; + +@Component +public class ReferenceTypeFieldDataHelperService extends BaseFieldDataHelperService { + + private final BuilderFactory builderFactory; + + private final ValidatorFactory validatorFactory; + public ReferenceTypeFieldDataHelperService(BuilderFactory builderFactory, ValidatorFactory validatorFactory) { + this.builderFactory = builderFactory; + this.validatorFactory = validatorFactory; + } + + @Override + public ReferenceTypeDataEntity newDataInstanceInternal() { + return new ReferenceTypeDataEntity(); + } + + @Override + public ReferenceTypeData newModelInstanceInternal() { + return new ReferenceTypeData(); + } + + @Override + public ReferenceTypeDataPersist newPersistModelInstanceInternal() { + return new ReferenceTypeDataPersist(); + } + + @Override + protected ReferenceTypeDataImportExport newImportExportInstanceInternal() { + return new ReferenceTypeDataImportExport(); + } + + @Override + public Class getDataClass() { + return ReferenceTypeDataEntity.class; + } + @Override + public Class getModelClass() { + return ReferenceTypeData.class; + } + @Override + public Class getPersistModelClass() { + return ReferenceTypeDataPersist.class; + } + + @Override + public Class getImportExportClass() { + return ReferenceTypeDataImportExport.class; + } + + @Override + public Validator getPersistModelValidator() { + return this.validatorFactory.validator(ReferenceTypeDataPersist.ReferenceTypeDataPersistValidator.class); + } + + @Override + public List buildInternal(FieldSet fieldSet, List data, EnumSet authorizationFlags){ + return this.builderFactory.builder(ReferenceTypeDataBuilder.class).authorize(authorizationFlags).build(fieldSet, data); + } + + @Override + protected ReferenceTypeDataEntity applyPersistInternal(ReferenceTypeDataPersist persist, ReferenceTypeDataEntity data) { + data.setMultipleSelect(persist.getMultipleSelect()); + data.setReferenceTypeId(persist.getReferenceTypeId()); + return data; + } + + @Override + protected ReferenceTypeDataPersist importExportMapDataToPersistInternal(ReferenceTypeDataImportExport data, ReferenceTypeDataPersist persist){ + persist.setMultipleSelect(data.getMultipleSelect()); + persist.setReferenceTypeId(data.getReferenceTypeId()); + return persist; + } + + @Override + protected ReferenceTypeDataImportExport dataToImportExportXmlInternal(ReferenceTypeDataEntity data, ReferenceTypeDataImportExport xml) { + xml.setMultipleSelect(data.getMultipleSelect()); + xml.setReferenceTypeId(data.getReferenceTypeId()); + return xml; + } + + @Override + protected boolean isMultiValueInternal(ReferenceTypeDataEntity data) { + return data.getMultipleSelect(); + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/prefilling/PrefillingServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/prefilling/PrefillingServiceImpl.java index 13559dd4a..9c7d89303 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/prefilling/PrefillingServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/prefilling/PrefillingServiceImpl.java @@ -5,38 +5,23 @@ import com.fasterxml.jackson.databind.ObjectMapper; import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.commons.JsonHandlingService; import eu.eudat.commons.XmlHandlingService; -import eu.eudat.commons.enums.FieldType; import eu.eudat.commons.types.descriptiontemplate.FieldEntity; import eu.eudat.commons.types.descriptiontemplate.FieldSetEntity; -import eu.eudat.commons.types.descriptiontemplate.fielddata.ExternalSelectDataEntity; -import eu.eudat.commons.types.descriptiontemplate.fielddata.LabelAndMultiplicityDataEntity; -import eu.eudat.commons.types.descriptiontemplate.fielddata.SelectDataEntity; import eu.eudat.commons.types.prefilling.PrefillingEntity; import eu.eudat.convention.ConventionService; import eu.eudat.data.DescriptionTemplateEntity; -import eu.eudat.data.ReferenceEntity; import eu.eudat.model.*; import eu.eudat.model.builder.DescriptionTemplateBuilder; import eu.eudat.model.builder.PrefillingBuilder; -import eu.eudat.model.builder.ReferenceBuilder; import eu.eudat.model.descriptionproperties.Field; import eu.eudat.model.descriptionproperties.PropertyDefinition; import eu.eudat.model.descriptionproperties.PropertyDefinitionFieldSet; import eu.eudat.model.descriptionproperties.PropertyDefinitionFieldSetItem; import eu.eudat.model.persist.DescriptionProfilingRequest; import eu.eudat.model.persist.DescriptionProfilingWithDataRequest; -import eu.eudat.query.ReferenceQuery; import eu.eudat.service.remotefetcher.ExternalUrlConfigProvider; -import eu.eudat.service.remotefetcher.RemoteFetcherService; -import eu.eudat.service.remotefetcher.config.AuthenticationConfiguration; -import eu.eudat.service.remotefetcher.config.DataFieldsUrlConfiguration; -import eu.eudat.service.remotefetcher.config.DataUrlConfiguration; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; import eu.eudat.service.remotefetcher.config.entities.*; import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.models.ExternalAutocompleteFieldResult; -import eu.eudat.utilities.helpers.StreamDistinctBy; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.exception.MyApplicationException; @@ -47,7 +32,6 @@ import gr.cite.tools.logging.MapLogEntry; import gr.cite.tools.validation.ValidatorFactory; import jakarta.persistence.EntityManager; import jakarta.xml.bind.JAXBException; -import org.json.JSONObject; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; @@ -62,8 +46,6 @@ import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; @@ -80,7 +62,6 @@ public class PrefillingServiceImpl implements PrefillingService { private final QueryFactory queryFactory; private final ConventionService conventionService; private final MessageSource messageSource; - private final RemoteFetcherService remoteFetcherService; private final JsonHandlingService jsonHandlingService; private final ExternalUrlConfigProvider externalUrlConfigProvider; private final XmlHandlingService xmlHandlingService; @@ -92,7 +73,6 @@ public class PrefillingServiceImpl implements PrefillingService { QueryFactory queryFactory, ConventionService conventionService, MessageSource messageSource, - RemoteFetcherService remoteFetcherService, JsonHandlingService jsonHandlingService, ExternalUrlConfigProvider externalUrlConfigProvider, XmlHandlingService xmlHandlingService, @@ -102,7 +82,6 @@ public class PrefillingServiceImpl implements PrefillingService { this.queryFactory = queryFactory; this.conventionService = conventionService; this.messageSource = messageSource; - this.remoteFetcherService = remoteFetcherService; this.jsonHandlingService = jsonHandlingService; this.externalUrlConfigProvider = externalUrlConfigProvider; this.xmlHandlingService = xmlHandlingService; @@ -118,17 +97,17 @@ public class PrefillingServiceImpl implements PrefillingService { List prefillings = new ArrayList<>(); List> map; Map prefillingConfigs = this.externalUrlConfigProvider.getExternalUrls().getPrefillings(); - for (PrefillingConfig prefillingConfig: prefillingConfigs.values()) { - map = remoteFetcherService.getExternalGeneric(externalReferenceCriteria, prefillingConfig.getPrefillingSearch()); - prefillings.addAll(map.stream().map(submap -> PrefillingEntity.build(submap, this.jsonHandlingService)).toList()); - if (prefillingConfig.getPrefillingSearch().getUrlConfig().isDataInListing()) { - List> mapData = remoteFetcherService.getExternalGenericWithData(externalReferenceCriteria, prefillingConfig.getPrefillingSearch()); - for (int i = 0; i < mapData.size(); i++) { - prefillings.get(i).setData(mapData.get(i)); - } - prefillings = prefillings.stream().filter(prefilling -> prefilling.getData() != null).collect(Collectors.toList()); - } - } +// for (PrefillingConfig prefillingConfig: prefillingConfigs.values()) {//TODO new reference logic +// map = remoteFetcherService.getExternalGeneric(externalReferenceCriteria, prefillingConfig.getPrefillingSearch()); +// prefillings.addAll(map.stream().map(submap -> PrefillingEntity.build(submap, this.jsonHandlingService)).toList()); +// if (prefillingConfig.getPrefillingSearch().getUrlConfig().isDataInListing()) { +// List> mapData = remoteFetcherService.getExternalGenericWithData(externalReferenceCriteria, prefillingConfig.getPrefillingSearch()); +// for (int i = 0; i < mapData.size(); i++) { +// prefillings.get(i).setData(mapData.get(i)); +// } +// prefillings = prefillings.stream().filter(prefilling -> prefilling.getData() != null).collect(Collectors.toList()); +// } +// } return this.builderFactory.builder(PrefillingBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(BaseFieldSet.build(lookup.getProject(), Prefilling._pid), prefillings); } @@ -381,49 +360,49 @@ public class PrefillingServiceImpl implements PrefillingService { return parsedValues.isEmpty() ? null : String.join(", ", parsedValues); } - private Object parseComboBoxValues(FieldEntity fieldEntity, List parsedValues) { - List normalizedValues = new ArrayList<>(); - boolean isMultiSelect; - if(fieldEntity.getData().getFieldType().equals(FieldType.EXTERNAL_SELECT)) { - ExternalSelectDataEntity autoCompleteData = (ExternalSelectDataEntity)fieldEntity.getData(); - isMultiSelect = autoCompleteData.getMultipleSelect(); - for (String format : parsedValues) { - List result = new ArrayList<>(); - try { - result = this.getAutocomplete(autoCompleteData, format); - } - catch (Exception e) { - logger.error(e.getMessage(), e); - } - result = result.stream().filter(StreamDistinctBy.distinctByKey(ExternalAutocompleteFieldResult::getId)).collect(Collectors.toList()); - if(!result.isEmpty()){ - List tempValues = new LinkedList<>(); - for (ExternalAutocompleteFieldResult f : result) { - if (format.equals(f.getId()) || f.getLabel().toUpperCase(Locale.ROOT).contains(format.toUpperCase(Locale.ROOT))) - tempValues.add(this.jsonHandlingService.toJsonSafe(f)); - } - if (isMultiSelect) - normalizedValues.addAll(tempValues); - else if (!tempValues.isEmpty()) - normalizedValues.add(tempValues.get(0)); - } - } - return !normalizedValues.isEmpty() ? (isMultiSelect ? normalizedValues : normalizedValues.getFirst()) : null; - } else { - SelectDataEntity selectDataEntity = (SelectDataEntity)fieldEntity.getData(); - isMultiSelect = selectDataEntity.getMultipleSelect(); - if (selectDataEntity.getOptions() != null) { - for (SelectDataEntity.OptionEntity option : selectDataEntity.getOptions()) { - if (parsedValues.contains(option.getValue())) { - normalizedValues.add(option.getValue()); - } - } - } - List normalizedStringValues = normalizedValues.stream().map(Object::toString).collect(Collectors.toList()); - - return !normalizedValues.isEmpty() ? (isMultiSelect ? String.join(", ", normalizedStringValues) : normalizedValues.getFirst()) : null; - } - } +// private Object parseComboBoxValues(FieldEntity fieldEntity, List parsedValues) { +// List normalizedValues = new ArrayList<>(); +// boolean isMultiSelect; +// if(fieldEntity.getData().getFieldType().equals(FieldType.EXTERNAL_SELECT)) { +// ExternalSelectDataEntity autoCompleteData = (ExternalSelectDataEntity)fieldEntity.getData(); +// isMultiSelect = autoCompleteData.getMultipleSelect(); +// for (String format : parsedValues) { +// List result = new ArrayList<>(); +// try { +// result = this.getAutocomplete(autoCompleteData, format); +// } +// catch (Exception e) { +// logger.error(e.getMessage(), e); +// } +// result = result.stream().filter(StreamDistinctBy.distinctByKey(ExternalAutocompleteFieldResult::getId)).collect(Collectors.toList()); +// if(!result.isEmpty()){ +// List tempValues = new LinkedList<>(); +// for (ExternalAutocompleteFieldResult f : result) { +// if (format.equals(f.getId()) || f.getLabel().toUpperCase(Locale.ROOT).contains(format.toUpperCase(Locale.ROOT))) +// tempValues.add(this.jsonHandlingService.toJsonSafe(f)); +// } +// if (isMultiSelect) +// normalizedValues.addAll(tempValues); +// else if (!tempValues.isEmpty()) +// normalizedValues.add(tempValues.get(0)); +// } +// } +// return !normalizedValues.isEmpty() ? (isMultiSelect ? normalizedValues : normalizedValues.getFirst()) : null; +// } else { +// SelectDataEntity selectDataEntity = (SelectDataEntity)fieldEntity.getData(); +// isMultiSelect = selectDataEntity.getMultipleSelect(); +// if (selectDataEntity.getOptions() != null) { +// for (SelectDataEntity.OptionEntity option : selectDataEntity.getOptions()) { +// if (parsedValues.contains(option.getValue())) { +// normalizedValues.add(option.getValue()); +// } +// } +// } +// List normalizedStringValues = normalizedValues.stream().map(Object::toString).collect(Collectors.toList()); +// +// return !normalizedValues.isEmpty() ? (isMultiSelect ? String.join(", ", normalizedStringValues) : normalizedValues.getFirst()) : null; +// } +// } private static List parseTags(String value) { if (value == null || value.isEmpty()) @@ -438,75 +417,75 @@ public class PrefillingServiceImpl implements PrefillingService { return parsedTags; } - public List getAutocomplete(ExternalSelectDataEntity data, String like) throws URISyntaxException { - - List result = new LinkedList<>(); - ExternalReferenceCriteria urlCriteria = new ExternalReferenceCriteria(); - GeneralUrls genericUrls = new GeneralUrls(); - int ordinal = 1; - List> rawResults = new ArrayList<>(); - genericUrls.setFetchMode(FetchStrategy.FIRST); - urlCriteria.setLike(like); - for (ExternalSelectDataEntity.ExternalSelectSourceEntity singleData : data.getSources()) { - UrlConfiguration urlConfiguration = new UrlConfiguration(); - try { - URI uri; - if (singleData.getUrl().contains("?")) { - uri = new URI(singleData.getUrl().substring(0, singleData.getUrl().lastIndexOf("?"))); - } else { - uri = new URI(singleData.getUrl()); - } - String source = singleData.getSourceBinding().getSource(); - source = source != null && !source.isEmpty() ? source : uri.getHost(); -// String uriString = singleData.getSourceBinding().getUrl(); -// uriString = uriString != null && !uriString.isEmpty() ? uriString : "uri"; - String uriString = "uri"; - String parsedUrl = singleData.getUrl(); - parsedUrl = parsedUrl.replace("%20", " "); - parsedUrl = parsedUrl.replace("%22", "\""); - while (parsedUrl.contains("&")) { - parsedUrl = parsedUrl.replace("&", "&"); - } - urlConfiguration.setUrl(parsedUrl); - urlConfiguration.setOrdinal(ordinal); - urlConfiguration.setType("External"); - urlConfiguration.setContentType(MediaType.APPLICATION_JSON_VALUE); - urlConfiguration.setFirstpage("1"); - urlConfiguration.setRequestType(singleData.getMethod() != null ? singleData.getMethod() : "GET"); - DataUrlConfiguration dataUrlConfiguration = new DataUrlConfiguration(); - dataUrlConfiguration.setPath(singleData.getOptionsRoot()); - DataFieldsUrlConfiguration fieldsUrlConfiguration = new DataFieldsUrlConfiguration(); - fieldsUrlConfiguration.setId(singleData.getSourceBinding().getValue()); - fieldsUrlConfiguration.setName(singleData.getSourceBinding().getLabel()); - fieldsUrlConfiguration.setSource(singleData.getSourceBinding().getSource().isEmpty()? null : singleData.getSourceBinding().getSource()); - fieldsUrlConfiguration.setUri(uriString); - dataUrlConfiguration.setFieldsUrlConfiguration(fieldsUrlConfiguration); - urlConfiguration.setKey(source); - urlConfiguration.setLabel(source); - urlConfiguration.setData(dataUrlConfiguration); - if (singleData.getHasAuth()) { - AuthenticationConfiguration authenticationConfiguration = new AuthenticationConfiguration(); - authenticationConfiguration.setAuthUrl(singleData.getAuth().getUrl()); - authenticationConfiguration.setAuthMethod(singleData.getAuth().getMethod()); - authenticationConfiguration.setAuthTokenPath(singleData.getAuth().getPath()); - authenticationConfiguration.setAuthRequestBody(singleData.getAuth().getBody()); - authenticationConfiguration.setType(singleData.getAuth().getType()); - urlConfiguration.setAuth(authenticationConfiguration); - } - genericUrls.getUrls().add(urlConfiguration); - List> singleResults = this.remoteFetcherService.getExternalGeneric(urlCriteria, genericUrls); - if (!singleResults.isEmpty() && !singleResults.get(0).containsKey("source") && !singleData.getSourceBinding().getSource().isEmpty()) { - singleResults.forEach(singleResult -> singleResult.put("source", singleData.getSourceBinding().getSource())); - } - rawResults.addAll(singleResults); - genericUrls.getUrls().clear(); - } catch (URISyntaxException e) { - logger.error(e.getMessage(), e); - } - } - rawResults.forEach(item -> result.add(new ExternalAutocompleteFieldResult(parseItem(item.get("pid")), parseItem(item.get("name")), parseItem(item.get("source")), parseItem(item.get("uri"))))); - return result; - } +// public List getAutocomplete(ExternalSelectDataEntity data, String like) throws URISyntaxException { +// +// List result = new LinkedList<>(); +// ExternalReferenceCriteria urlCriteria = new ExternalReferenceCriteria(); +// GeneralUrls genericUrls = new GeneralUrls(); +// int ordinal = 1; +// List> rawResults = new ArrayList<>(); +// genericUrls.setFetchMode(FetchStrategy.FIRST); +// urlCriteria.setLike(like); +// for (ExternalSelectDataEntity.ExternalSelectSourceEntity singleData : data.getSources()) { +// UrlConfiguration urlConfiguration = new UrlConfiguration(); +// try { +// URI uri; +// if (singleData.getUrl().contains("?")) { +// uri = new URI(singleData.getUrl().substring(0, singleData.getUrl().lastIndexOf("?"))); +// } else { +// uri = new URI(singleData.getUrl()); +// } +// String source = singleData.getSourceBinding().getSource(); +// source = source != null && !source.isEmpty() ? source : uri.getHost(); +//// String uriString = singleData.getSourceBinding().getUrl(); +//// uriString = uriString != null && !uriString.isEmpty() ? uriString : "uri"; +// String uriString = "uri"; +// String parsedUrl = singleData.getUrl(); +// parsedUrl = parsedUrl.replace("%20", " "); +// parsedUrl = parsedUrl.replace("%22", "\""); +// while (parsedUrl.contains("&")) { +// parsedUrl = parsedUrl.replace("&", "&"); +// } +// urlConfiguration.setUrl(parsedUrl); +// urlConfiguration.setOrdinal(ordinal); +// urlConfiguration.setType("External"); +// urlConfiguration.setContentType(MediaType.APPLICATION_JSON_VALUE); +// urlConfiguration.setFirstpage("1"); +// urlConfiguration.setRequestType(singleData.getMethod() != null ? singleData.getMethod() : "GET"); +// DataUrlConfiguration dataUrlConfiguration = new DataUrlConfiguration(); +// dataUrlConfiguration.setPath(singleData.getOptionsRoot()); +// DataFieldsUrlConfiguration fieldsUrlConfiguration = new DataFieldsUrlConfiguration(); +// fieldsUrlConfiguration.setId(singleData.getSourceBinding().getValue()); +// fieldsUrlConfiguration.setName(singleData.getSourceBinding().getLabel()); +// fieldsUrlConfiguration.setSource(singleData.getSourceBinding().getSource().isEmpty()? null : singleData.getSourceBinding().getSource()); +// fieldsUrlConfiguration.setUri(uriString); +// dataUrlConfiguration.setFieldsUrlConfiguration(fieldsUrlConfiguration); +// urlConfiguration.setKey(source); +// urlConfiguration.setLabel(source); +// urlConfiguration.setData(dataUrlConfiguration); +// if (singleData.getHasAuth()) { +// AuthenticationConfiguration authenticationConfiguration = new AuthenticationConfiguration(); +// authenticationConfiguration.setAuthUrl(singleData.getAuth().getUrl()); +// authenticationConfiguration.setAuthMethod(singleData.getAuth().getMethod()); +// authenticationConfiguration.setAuthTokenPath(singleData.getAuth().getPath()); +// authenticationConfiguration.setAuthRequestBody(singleData.getAuth().getBody()); +// authenticationConfiguration.setType(singleData.getAuth().getType()); +// urlConfiguration.setAuth(authenticationConfiguration); +// } +// genericUrls.getUrls().add(urlConfiguration); +// List> singleResults = this.remoteFetcherService.getExternalGeneric(urlCriteria, genericUrls); +// if (!singleResults.isEmpty() && !singleResults.get(0).containsKey("source") && !singleData.getSourceBinding().getSource().isEmpty()) { +// singleResults.forEach(singleResult -> singleResult.put("source", singleData.getSourceBinding().getSource())); +// } +// rawResults.addAll(singleResults); +// genericUrls.getUrls().clear(); +// } catch (URISyntaxException e) { +// logger.error(e.getMessage(), e); +// } +// } +// rawResults.forEach(item -> result.add(new ExternalAutocompleteFieldResult(parseItem(item.get("pid")), parseItem(item.get("name")), parseItem(item.get("source")), parseItem(item.get("uri"))))); +// return result; +// } private static String parseItem(Object item) { if (item instanceof String) { diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/publicapi/PublicApiConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/publicapi/PublicApiConfiguration.java new file mode 100644 index 000000000..ebecfd83a --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/publicapi/PublicApiConfiguration.java @@ -0,0 +1,10 @@ +package eu.eudat.service.publicapi; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties(PublicApiProperties.class) +public class PublicApiConfiguration { + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/publicapi/PublicApiProperties.java b/dmp-backend/core/src/main/java/eu/eudat/service/publicapi/PublicApiProperties.java new file mode 100644 index 000000000..54a969d95 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/publicapi/PublicApiProperties.java @@ -0,0 +1,93 @@ +package eu.eudat.service.publicapi; + + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.UUID; + +@ConfigurationProperties(prefix = "public-api") +public class PublicApiProperties { + private ReferenceTypeMapConfig referenceTypeMap; + public ReferenceTypeMapConfig getReferenceTypeMap() { + return referenceTypeMap; + } + + public void setReferenceTypeMap(ReferenceTypeMapConfig referenceTypeMap) { + this.referenceTypeMap = referenceTypeMap; + } + + public static class ReferenceTypeMapConfig{ + private UUID funderTypeId; + private UUID grantTypeId; + private UUID registryTypeId; + private UUID serviceTypeId; + private UUID dataRepositoryTypeId; + private UUID datasetTypeId; + private UUID researcherTypeId; + private UUID organizationTypeId; + public UUID getFunderTypeId() { + return funderTypeId; + } + + public void setFunderTypeId(UUID funderTypeId) { + this.funderTypeId = funderTypeId; + } + + public UUID getGrantTypeId() { + return grantTypeId; + } + + public void setGrantTypeId(UUID grantTypeId) { + this.grantTypeId = grantTypeId; + } + + public UUID getRegistryTypeId() { + return registryTypeId; + } + + public void setRegistryTypeId(UUID registryTypeId) { + this.registryTypeId = registryTypeId; + } + + public UUID getServiceTypeId() { + return serviceTypeId; + } + + public void setServiceTypeId(UUID serviceTypeId) { + this.serviceTypeId = serviceTypeId; + } + + public UUID getDataRepositoryTypeId() { + return dataRepositoryTypeId; + } + + public void setDataRepositoryTypeId(UUID dataRepositoryTypeId) { + this.dataRepositoryTypeId = dataRepositoryTypeId; + } + + public UUID getDatasetTypeId() { + return datasetTypeId; + } + + public void setDatasetTypeId(UUID datasetTypeId) { + this.datasetTypeId = datasetTypeId; + } + + public UUID getResearcherTypeId() { + return researcherTypeId; + } + + public void setResearcherTypeId(UUID researcherTypeId) { + this.researcherTypeId = researcherTypeId; + } + + public UUID getOrganizationTypeId() { + return organizationTypeId; + } + + public void setOrganizationTypeId(UUID organizationTypeId) { + this.organizationTypeId = organizationTypeId; + } + } +} + diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceService.java b/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceService.java index e88fb955f..9ec36e969 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceService.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceService.java @@ -24,7 +24,5 @@ public interface ReferenceService { void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException; - List searchReference(ReferenceSearchLookup lookup) throws HugeResultSetException, MyNotFoundException, InvalidApplicationException; - List searchReferenceWithDefinition(ReferenceDefinitionSearchLookup lookup) throws HugeResultSetException, MyNotFoundException, InvalidApplicationException; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceServiceImpl.java index a988d6187..790412ecf 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceServiceImpl.java @@ -21,7 +21,6 @@ import eu.eudat.data.ReferenceEntity; import eu.eudat.data.ReferenceTypeEntity; import eu.eudat.model.Reference; import eu.eudat.model.builder.ReferenceBuilder; -import eu.eudat.model.builder.referencesearch.ReferenceSearchBuilder; import eu.eudat.model.deleter.ReferenceDeleter; import eu.eudat.model.persist.ReferencePersist; import eu.eudat.model.persist.referencedefinition.DefinitionPersist; @@ -30,8 +29,6 @@ import eu.eudat.query.ReferenceQuery; import eu.eudat.query.ReferenceTypeQuery; import eu.eudat.query.lookup.ReferenceDefinitionSearchLookup; import eu.eudat.query.lookup.ReferenceSearchLookup; -import eu.eudat.service.remotefetcher.RemoteFetcherService; -import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; import eu.eudat.service.remotefetcher.criteria.FetchStrategy; import eu.eudat.service.remotefetcher.models.ExternalRefernceResult; import gr.cite.commons.web.authz.service.AuthorizationService; @@ -75,7 +72,6 @@ import java.util.stream.Collectors; public class ReferenceServiceImpl implements ReferenceService { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ReferenceServiceImpl.class)); - private final RemoteFetcherService remoteFetcherService; private final EntityManager entityManager; private final AuthorizationService authorizationService; private final DeleterFactory deleterFactory; @@ -87,7 +83,7 @@ public class ReferenceServiceImpl implements ReferenceService { private final WebClient client; - public ReferenceServiceImpl(RemoteFetcherService remoteFetcherService, + public ReferenceServiceImpl( EntityManager entityManager, AuthorizationService authorizationService, DeleterFactory deleterFactory, @@ -96,7 +92,6 @@ public class ReferenceServiceImpl implements ReferenceService { MessageSource messageSource, QueryFactory queryFactory, XmlHandlingService xmlHandlingService) { - this.remoteFetcherService = remoteFetcherService; this.entityManager = entityManager; this.authorizationService = authorizationService; this.deleterFactory = deleterFactory; @@ -133,7 +128,7 @@ public class ReferenceServiceImpl implements ReferenceService { } data.setLabel(model.getLabel()); - data.setType(model.getType()); + data.setTypeId(model.getTypeId()); data.setDescription(model.getDescription()); data.setDefinition(this.xmlHandlingService.toXmlSafe(this.buildDefinitionEntity(model.getDefinition()))); data.setUpdatedAt(Instant.now()); @@ -196,32 +191,32 @@ public class ReferenceServiceImpl implements ReferenceService { // return list; // } - @Override - public List searchReference(ReferenceSearchLookup lookup) throws HugeResultSetException, MyNotFoundException, InvalidApplicationException { - int initialOffset = 0; - if (lookup.getPage() != null && !lookup.getPage().isEmpty()){ - initialOffset = lookup.getPage().getOffset(); - lookup.getPage().setOffset(0); - } - - ExternalReferenceCriteria externalReferenceCriteria = new ExternalReferenceCriteria(lookup.getLike()); - - List> remoteRepos = remoteFetcherService.getReferences(lookup.getType(), externalReferenceCriteria, lookup.getKey()); - - List externalModels = this.builderFactory.builder(ReferenceSearchBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(lookup.getProject(), remoteRepos); - List models = this.fetchFromDb(lookup); - - models.addAll(externalModels); - - if (!this.conventionService.isNullOrEmpty(lookup.getLike())) { models = models.stream().filter(x -> x.getLabel().toLowerCase().contains(lookup.getLike().toLowerCase())).collect(Collectors.toList()); } - models.sort(Comparator.comparing(Reference::getLabel)); - - if (lookup.getPage() != null && !lookup.getPage().isEmpty()){ - models = models.stream().skip(initialOffset).limit(lookup.getPage().getSize()).toList(); - } - - return models; - } +// @Override +// public List searchReference(ReferenceSearchLookup lookup) throws HugeResultSetException, MyNotFoundException, InvalidApplicationException { +// int initialOffset = 0; +// if (lookup.getPage() != null && !lookup.getPage().isEmpty()){ +// initialOffset = lookup.getPage().getOffset(); +// lookup.getPage().setOffset(0); +// } +// +// ExternalReferenceCriteria externalReferenceCriteria = new ExternalReferenceCriteria(lookup.getLike()); +// +// List> remoteRepos = remoteFetcherService.getReferences(lookup.getType(), externalReferenceCriteria, lookup.getKey()); +// +// List externalModels = this.builderFactory.builder(ReferenceSearchBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(lookup.getProject(), remoteRepos); +// List models = this.fetchFromDb(lookup); +// +// models.addAll(externalModels); +// +// if (!this.conventionService.isNullOrEmpty(lookup.getLike())) { models = models.stream().filter(x -> x.getLabel().toLowerCase().contains(lookup.getLike().toLowerCase())).collect(Collectors.toList()); } +// models.sort(Comparator.comparing(Reference::getLabel)); +// +// if (lookup.getPage() != null && !lookup.getPage().isEmpty()){ +// models = models.stream().skip(initialOffset).limit(lookup.getPage().getSize()).toList(); +// } +// +// return models; +// } private List fetchFromDb(ReferenceSearchLookup lookup){ ReferenceQuery query = lookup.enrich(this.queryFactory).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).sourceTypes(ReferenceSourceType.Internal); diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherService.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherService.java index aa04303cf..4e9164c82 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherService.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherService.java @@ -1,22 +1,21 @@ -package eu.eudat.service.remotefetcher; - -import eu.eudat.commons.enums.ReferenceType; -import eu.eudat.commons.exceptions.HugeResultSetException; -import eu.eudat.service.remotefetcher.config.entities.GenericUrls; -import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; -import gr.cite.tools.exception.MyNotFoundException; - -import java.util.List; -import java.util.Map; - -public interface RemoteFetcherService { - List> getReferences(ReferenceType referenceType, ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException; - - GenericUrls getExternalUrls(ReferenceType referenceType); - - Integer countEntries(ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException; - - List> getExternalGeneric(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls); - - List> getExternalGenericWithData(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls); -} +//package eu.eudat.service.remotefetcher; +// +//import eu.eudat.commons.exceptions.HugeResultSetException; +//import eu.eudat.service.remotefetcher.config.entities.GenericUrls; +//import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; +//import gr.cite.tools.exception.MyNotFoundException; +// +//import java.util.List; +//import java.util.Map; +// +//public interface RemoteFetcherService { +// List> getReferences(ReferenceType referenceType, ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException; +// +// GenericUrls getExternalUrls(ReferenceType referenceType); +// +// Integer countEntries(ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException; +// +// List> getExternalGeneric(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls); +// +// List> getExternalGenericWithData(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls); +//} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherServiceImpl.java index 12d0fd175..bd270a2af 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherServiceImpl.java @@ -1,533 +1,533 @@ -package eu.eudat.service.remotefetcher; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.jayway.jsonpath.DocumentContext; -import com.jayway.jsonpath.JsonPath; -import eu.eudat.commons.enums.ReferenceType; -import eu.eudat.commons.exceptions.HugeResultSetException; -import eu.eudat.service.remotefetcher.config.AuthenticationConfiguration; -import eu.eudat.service.remotefetcher.config.DataUrlConfiguration; -import eu.eudat.service.remotefetcher.config.QueryConfig; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; -import eu.eudat.service.remotefetcher.config.entities.GenericUrls; -import eu.eudat.service.remotefetcher.models.ExternalRefernceResult; -import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import gr.cite.tools.exception.MyNotFoundException; -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.Unmarshaller; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.*; -import org.springframework.http.client.reactive.ReactorClientHttpConnector; -import org.springframework.http.codec.json.Jackson2JsonDecoder; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.reactive.function.client.WebClient; -import reactor.netty.http.client.HttpClient; - -import java.io.File; -import java.io.StringReader; -import java.lang.reflect.Method; -import java.nio.file.Paths; -import java.util.*; -import java.util.stream.Collectors; - -@Service -public class RemoteFetcherServiceImpl implements RemoteFetcherService { - private static final Logger logger = LoggerFactory.getLogger(RemoteFetcherServiceImpl.class); - - private WebClient webClient; - private final ExternalUrlConfigProvider externalUrlConfigProvider; - @Autowired - public RemoteFetcherServiceImpl(ExternalUrlConfigProvider externalUrlConfigProvider) { - this.externalUrlConfigProvider = externalUrlConfigProvider; - } - - private WebClient getWebClient(){ - if (this.webClient == null) { - this.webClient = WebClient.builder().codecs(clientCodecConfigurer -> { - clientCodecConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(new ObjectMapper(), MediaType.APPLICATION_JSON)); - clientCodecConfigurer.defaultCodecs().maxInMemorySize(2 * ((int) Math.pow(1024, 3))); //GK: Why here??? - } - ).clientConnector(new ReactorClientHttpConnector(HttpClient.create().followRedirect(true))).build(); - } - return webClient; - } - - @Override - public List> getReferences(ReferenceType referenceType, ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException { - FetchStrategy fetchStrategy = null; - GenericUrls exGenericUrls = this.getExternalUrls(referenceType); - List urlConfigs = key != null && !key.isEmpty() ? exGenericUrls.getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) - : exGenericUrls.getUrls(); - - List> results = getAll(urlConfigs, fetchStrategy, externalReferenceCriteria); - for (Map result: results) { - result.put("referenceType", referenceType.name()); - } - return results; - } - - @Override - public GenericUrls getExternalUrls(ReferenceType referenceType) { - return switch (referenceType) { - case Taxonomies -> this.externalUrlConfigProvider.getExternalUrls().getTaxonomies(); - case Licenses -> this.externalUrlConfigProvider.getExternalUrls().getLicenses(); - case Publications -> this.externalUrlConfigProvider.getExternalUrls().getPublications(); - case Journals -> this.externalUrlConfigProvider.getExternalUrls().getJournals(); - case PubRepositories -> this.externalUrlConfigProvider.getExternalUrls().getPubRepositories(); - case DataRepositories -> this.externalUrlConfigProvider.getExternalUrls().getRepositories(); - case Registries -> this.externalUrlConfigProvider.getExternalUrls().getRegistries(); - case Services -> this.externalUrlConfigProvider.getExternalUrls().getServices(); - case Grants -> this.externalUrlConfigProvider.getExternalUrls().getGrants(); - case Organizations -> this.externalUrlConfigProvider.getExternalUrls().getOrganisations(); - case Datasets -> this.externalUrlConfigProvider.getExternalUrls().getDatasets(); - case Funder -> this.externalUrlConfigProvider.getExternalUrls().getFunders(); - case Project -> this.externalUrlConfigProvider.getExternalUrls().getProjects(); - case Researcher -> this.externalUrlConfigProvider.getExternalUrls().getResearchers(); - default -> throw new IllegalArgumentException("Type not found" + referenceType); - }; - } - - @Override - public Integer countEntries(ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException { - List urlConfigs = - key != null && !key.isEmpty() ? this.externalUrlConfigProvider.getExternalUrls().getValidations().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) - : this.externalUrlConfigProvider.getExternalUrls().getValidations().getUrls(); - FetchStrategy fetchStrategy = this.externalUrlConfigProvider.getExternalUrls().getValidations().getFetchMode(); - List> data = this.getAll(urlConfigs, fetchStrategy, externalReferenceCriteria); - return data.size(); - } - - @Override - public List> getExternalGeneric(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls) { - List urlConfigurations = genericUrls.getUrls(); - FetchStrategy fetchStrategy = genericUrls.getFetchMode(); - return getAll(urlConfigurations, fetchStrategy, externalReferenceCriteria); - } - - @Override - public List> getExternalGenericWithData(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls) { - List urlConfigurations = genericUrls.getUrls(); - return getAllWithData(urlConfigurations, externalReferenceCriteria); - } - - private List> getAll(List urlConfigs, FetchStrategy fetchStrategy, ExternalReferenceCriteria externalReferenceCriteria) { - - List> results = new LinkedList<>(); - - if (urlConfigs == null || urlConfigs.isEmpty()) { - return results; - } -// throw new MyNotFoundException("No Repository urls found in configuration"); - - urlConfigs.sort(Comparator.comparing(UrlConfiguration::getOrdinal)); - for (UrlConfiguration urlConfiguration : urlConfigs) { - applyFunderQuery(urlConfiguration, externalReferenceCriteria); - if (urlConfiguration.getType() == null || urlConfiguration.getType().equals("External")) { - try { - String auth = null; - if (urlConfiguration.getAuth() != null) { - auth = this.getAuthentication(urlConfiguration.getAuth()); - } - results.addAll(getAllResultsFromUrl(urlConfiguration.getUrl(), fetchStrategy, urlConfiguration.getData(), urlConfiguration.getPaginationPath(), externalReferenceCriteria, urlConfiguration.getLabel(), urlConfiguration.getKey(), urlConfiguration.getContentType(), urlConfiguration.getFirstpage(), urlConfiguration.getRequestBody(), urlConfiguration.getRequestType(), urlConfiguration.getFilterType(), urlConfiguration.getQueries(), auth)); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - } - } else if (urlConfiguration.getType() != null && urlConfiguration.getType().equals("Internal")) { - results.addAll(getAllResultsFromMockUpJson(urlConfiguration.getUrl(), externalReferenceCriteria.getLike())); - } - } - /* for (UrlConfiguration urlConfig : urlConfigs) { - ifFunderQueryExist(urlConfig, externalUrlCriteria); - if (urlConfig.getType() == null || urlConfig.getType().equals("External")) { - results.addAll(getAllResultsFromUrl(urlConfig.getUrl(), fetchStrategy, urlConfig.getData(), urlConfig.getPaginationPath(), externalUrlCriteria, urlConfig.getLabel(), urlConfig.getKey(), urlConfig.getContentType(), urlConfig.getFirstpage(), urlConfig.getRequestBody(), urlConfig.getRequestType())); - } else if (urlConfig.getType() != null && urlConfig.getType().equals("Internal")) { - results.addAll(getAllResultsFromMockUpJson(urlConfig.getUrl(), externalUrlCriteria.getLike())); - } - }*/ - return results; - } - - private String getAuthentication(AuthenticationConfiguration authenticationConfiguration) { - HttpMethod method = HttpMethod.valueOf(authenticationConfiguration.getAuthMethod()); - Map response = this.getWebClient().method(method).uri(authenticationConfiguration.getAuthUrl()) - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(this.parseBodyString(authenticationConfiguration.getAuthRequestBody())) - .exchangeToMono(mono -> mono.bodyToMono(new ParameterizedTypeReference>() { - })).block(); - - - - return authenticationConfiguration.getType() + " " + response.get(authenticationConfiguration.getAuthTokenPath()); - } - - private List> getAllWithData(List urlConfigs, ExternalReferenceCriteria externalReferenceCriteria) { - - List> results = new LinkedList<>(); - - if (urlConfigs == null || urlConfigs.isEmpty()) { - return results; - } - - urlConfigs.sort(Comparator.comparing(UrlConfiguration::getOrdinal)); - urlConfigs.forEach(urlConfiguration -> { - applyFunderQuery(urlConfiguration, externalReferenceCriteria); - if (urlConfiguration.getType() == null || urlConfiguration.getType().equals("External")) { - try { - results.addAll(getAllResultsFromUrlWithData(urlConfiguration.getUrl(), urlConfiguration.getData(), externalReferenceCriteria, urlConfiguration.getContentType(), urlConfiguration.getFirstpage(), urlConfiguration.getRequestBody(), urlConfiguration.getRequestType(), urlConfiguration.getQueries())); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - } - } - }); - return results; - - } - - private void applyFunderQuery(UrlConfiguration urlConfiguration, ExternalReferenceCriteria externalReferenceCriteria) { - if (urlConfiguration.getFunderQuery() != null) { - if (externalReferenceCriteria.getFunderId() != null && !urlConfiguration.getFunderQuery().startsWith("dmp:")) { - urlConfiguration.setUrl(urlConfiguration.getUrl().replace("{funderQuery}", urlConfiguration.getFunderQuery())); - } - else { - urlConfiguration.setUrl(urlConfiguration.getUrl().replace("{funderQuery}", "")); - } - } - } - - private String calculateQuery(ExternalReferenceCriteria externalReferenceCriteria, List queryConfigs) { - String finalQuery = ""; - QueryConfig queryConfig = queryConfigs.stream().filter(queryConfigl -> externalReferenceCriteria.getLike().matches(queryConfigl.getCondition())) - .min((Comparator.comparing(QueryConfig::getOrdinal))).orElse(null); - if (queryConfig != null) { - if (queryConfig.getSeparator() != null) { - String[] likes = externalReferenceCriteria.getLike().split(queryConfig.getSeparator()); - finalQuery = queryConfig.getValue(); - for (int i = 0; i < likes.length; i++) { - finalQuery = finalQuery.replaceAll("\\{like" + (i+1) + "}", likes[i]); - } - } else { - finalQuery = queryConfig.getValue().replaceAll("\\{like}", externalReferenceCriteria.getLike()); - } - - } - return finalQuery; - } - - protected String replaceCriteriaOnUrl(String path, ExternalReferenceCriteria externalReferenceCriteria, String firstPage, List queries) { - String completedPath = path; - if (externalReferenceCriteria.getLike() != null) { - if ((path.contains("openaire") || path.contains("orcid") || path.contains("ror") || path.contains("fairsharing")) && externalReferenceCriteria.getLike().equals("")) { - completedPath = completedPath.replaceAll("\\{like}", "*"); - completedPath = completedPath.replaceAll("\\{query}", "*"); - } else { - if (completedPath.contains("{query}")) { - completedPath = completedPath.replaceAll("\\{query}", this.calculateQuery(externalReferenceCriteria, queries)); - } else { - completedPath = completedPath.replaceAll("\\{like}", externalReferenceCriteria.getLike()); - } - } - } else { - completedPath = completedPath.replace("{like}", ""); - } - if (externalReferenceCriteria.getFunderId() != null) { - String funderPrefix = externalReferenceCriteria.getFunderId().split(":")[0]; - String funderId = externalReferenceCriteria.getFunderId().replace(funderPrefix + ":", ""); - if (funderId.toCharArray()[0] == ':') { - funderId = externalReferenceCriteria.getFunderId(); - } - /* - try { funderId = URLEncoder.encode(funderId, "UTF-8"); } catch - (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } - */ - completedPath = completedPath.replace("{funderId}", funderId); - } - else if(completedPath.contains("{funderId}")){ - logger.warn("FunderId is null."); - completedPath = completedPath.replace("{funderId}", " "); - } - if (externalReferenceCriteria.getPage() != null) { - completedPath = completedPath.replace("{page}", externalReferenceCriteria.getPage()); - } else { - if (firstPage != null) { - completedPath = completedPath.replace("{page}", firstPage); - } else { - completedPath = completedPath.replace("{page}", "1"); - } - } - if (externalReferenceCriteria.getPageSize() != null) { - completedPath = completedPath.replace("{pageSize}", externalReferenceCriteria.getPageSize()); - } else { - completedPath = completedPath.replace("{pageSize}", "60"); - } - if (externalReferenceCriteria.getHost() != null) { - completedPath = completedPath.replace("{host}", externalReferenceCriteria.getHost()); - } else { - completedPath = completedPath.replace("{host}", ""); - } - if (externalReferenceCriteria.getPath() != null) { - completedPath = completedPath.replace("{path}", externalReferenceCriteria.getPath()); - } else { - completedPath = completedPath.replace("{path}", ""); - } - return completedPath; - } - - private List> getAllResultsFromUrl(String path, FetchStrategy fetchStrategy, final DataUrlConfiguration jsonDataPath, final String jsonPaginationPath, ExternalReferenceCriteria externalReferenceCriteria, String tag, String key, String contentType, String firstPage, String requestBody, String requestType, String filterType, List queries, String auth) throws Exception { - Set pages = new HashSet<>(); - - String replacedPath = replaceCriteriaOnUrl(path, externalReferenceCriteria, firstPage, queries); - String replacedBody = replaceCriteriaOnUrl(requestBody, externalReferenceCriteria, firstPage, queries); - - ExternalRefernceResult externalRefernceResult = getResultsFromUrl(replacedPath, jsonDataPath, jsonPaginationPath, contentType, replacedBody, requestType, auth); - if(externalRefernceResult != null) { - if (filterType != null && filterType.equals("local") && (externalReferenceCriteria.getLike() != null && !externalReferenceCriteria.getLike().isEmpty())) { - externalRefernceResult.setResults(externalRefernceResult.getResults().stream() - .filter(r -> r.get("name").toLowerCase().contains(externalReferenceCriteria.getLike().toLowerCase())) - .collect(Collectors.toList())); - } - if (fetchStrategy == FetchStrategy.FIRST) - return externalRefernceResult.getResults().stream().peek(x -> x.put("tag", tag)).peek(x -> x.put("key", key)).collect(Collectors.toList()); - - if (externalRefernceResult.getPagination() != null && externalRefernceResult.getPagination().get("pages") != null) //if has more pages, add them to the pages set - for (int i = 2; i <= externalRefernceResult.getPagination().get("pages"); i++) - pages.add(i); - - Long maxResults = this.externalUrlConfigProvider.getExternalUrls().getMaxresults(); - if ((maxResults > 0) && (externalRefernceResult.getPagination().get("count") > maxResults)) - throw new HugeResultSetException("The submitted search query " + externalReferenceCriteria.getLike() + " is about to return " + externalRefernceResult.getPagination().get("count") + " results... Please submit a more detailed search query"); - - Optional optionalResults = pages.parallelStream() - .map(page -> getResultsFromUrl(path + "&page=" + page, jsonDataPath, jsonPaginationPath, contentType, replacedBody, requestType, auth)) - .filter(Objects::nonNull) - .reduce((result1, result2) -> { - result1.getResults().addAll(result2.getResults()); - return result1; - }); - ExternalRefernceResult remainingExternalRefernceResult = optionalResults.orElseGet(ExternalRefernceResult::new); - remainingExternalRefernceResult.getResults().addAll(externalRefernceResult.getResults()); - - return remainingExternalRefernceResult.getResults().stream().peek(x -> x.put("tag", tag)).peek(x -> x.put("key", key)).collect(Collectors.toList()); - } - else { - return new LinkedList<>(); - } - } - - private List> getAllResultsFromUrlWithData(String path, final DataUrlConfiguration jsonDataPath, ExternalReferenceCriteria externalReferenceCriteria, String contentType, String firstPage, String requestBody, String requestType, List queries) { - - String replacedPath = replaceCriteriaOnUrl(path, externalReferenceCriteria, firstPage, queries); - String replacedBody = replaceCriteriaOnUrl(requestBody, externalReferenceCriteria, firstPage, queries); - - try { - RestTemplate restTemplate = new RestTemplate(); - HttpHeaders headers = new HttpHeaders(); - HttpEntity entity; - ResponseEntity response; - if (contentType != null && !contentType.isEmpty()) { - headers.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); - headers.setContentType(MediaType.valueOf(contentType)); - } - JsonNode jsonBody = new ObjectMapper().readTree(replacedBody); - entity = new HttpEntity<>(jsonBody, headers); - - response = restTemplate.exchange(replacedPath, HttpMethod.valueOf(requestType), entity, String.class); - if (response.getStatusCode() == HttpStatus.OK) { - if (response.getHeaders().get("Content-Type").get(0).contains("json")) { - DocumentContext jsonContext = JsonPath.parse(response.getBody()); - return jsonContext.read(jsonDataPath.getPath()); - } - } - } - catch (Exception exception) { - logger.error(exception.getMessage(), exception); - } - - return new LinkedList<>(); - } - - - protected ExternalRefernceResult getResultsFromUrl(String urlString, DataUrlConfiguration jsonDataPath, String jsonPaginationPath, String contentType, String requestBody, String requestType, String auth) { - - try { - //RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory()); - //HttpHeaders headers = new HttpHeaders(); - //HttpEntity entity; - ResponseEntity response; - /* - * URL url = new URL(urlString.replaceAll(" ", "%20")); - * - * HttpURLConnection con = (HttpURLConnection) url.openConnection(); - * con.setRequestMethod("GET"); - */ - /* if (contentType != null && !contentType.isEmpty()) { - headers.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); - headers.setContentType(MediaType.valueOf(contentType)); - } - if (auth != null) { - headers.set("Authorization", auth); - }*/ - JsonNode jsonBody = new ObjectMapper().readTree(requestBody); +//package eu.eudat.service.remotefetcher; +// +//import com.fasterxml.jackson.core.type.TypeReference; +//import com.fasterxml.jackson.databind.JsonNode; +//import com.fasterxml.jackson.databind.ObjectMapper; +//import com.jayway.jsonpath.DocumentContext; +//import com.jayway.jsonpath.JsonPath; +//import eu.eudat.commons.exceptions.HugeResultSetException; +//import eu.eudat.service.remotefetcher.config.AuthenticationConfiguration; +//import eu.eudat.service.remotefetcher.config.DataUrlConfiguration; +//import eu.eudat.service.remotefetcher.config.QueryConfig; +//import eu.eudat.service.remotefetcher.config.UrlConfiguration; +//import eu.eudat.service.remotefetcher.config.entities.GenericUrls; +//import eu.eudat.service.remotefetcher.models.ExternalRefernceResult; +//import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; +//import eu.eudat.service.remotefetcher.criteria.FetchStrategy; +//import gr.cite.tools.exception.MyNotFoundException; +//import jakarta.xml.bind.JAXBContext; +//import jakarta.xml.bind.Unmarshaller; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.core.ParameterizedTypeReference; +//import org.springframework.http.*; +//import org.springframework.http.client.reactive.ReactorClientHttpConnector; +//import org.springframework.http.codec.json.Jackson2JsonDecoder; +//import org.springframework.stereotype.Service; +//import org.springframework.web.client.RestTemplate; +//import org.springframework.web.reactive.function.client.WebClient; +//import reactor.netty.http.client.HttpClient; +// +//import java.io.File; +//import java.io.StringReader; +//import java.lang.reflect.Method; +//import java.nio.file.Paths; +//import java.util.*; +//import java.util.stream.Collectors; +// +//@Service +//public class RemoteFetcherServiceImpl implements RemoteFetcherService { +// private static final Logger logger = LoggerFactory.getLogger(RemoteFetcherServiceImpl.class); +// +// private WebClient webClient; +// private final ExternalUrlConfigProvider externalUrlConfigProvider; +// @Autowired +// public RemoteFetcherServiceImpl(ExternalUrlConfigProvider externalUrlConfigProvider) { +// this.externalUrlConfigProvider = externalUrlConfigProvider; +// } +// +// private WebClient getWebClient(){ +// if (this.webClient == null) { +// this.webClient = WebClient.builder().codecs(clientCodecConfigurer -> { +// clientCodecConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(new ObjectMapper(), MediaType.APPLICATION_JSON)); +// clientCodecConfigurer.defaultCodecs().maxInMemorySize(2 * ((int) Math.pow(1024, 3))); //GK: Why here??? +// } +// ).clientConnector(new ReactorClientHttpConnector(HttpClient.create().followRedirect(true))).build(); +// } +// return webClient; +// } +// +// @Override +// public List> getReferences(ReferenceType referenceType, ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException { +// FetchStrategy fetchStrategy = null; +// +//// GenericUrls exGenericUrls = this.getExternalUrls(referenceType); +// List urlConfigs = key != null && !key.isEmpty() ? exGenericUrls.getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) +// : exGenericUrls.getUrls(); +// +// List> results = getAll(urlConfigs, fetchStrategy, externalReferenceCriteria); +// for (Map result: results) { +// result.put("referenceType", referenceType.name()); +// } +// return results; +// } +// +// @Override +// public GenericUrls getExternalUrls(ReferenceType referenceType) { +// return switch (referenceType) { +// case Taxonomies -> this.externalUrlConfigProvider.getExternalUrls().getTaxonomies(); +// case Licenses -> this.externalUrlConfigProvider.getExternalUrls().getLicenses(); +// case Publications -> this.externalUrlConfigProvider.getExternalUrls().getPublications(); +// case Journals -> this.externalUrlConfigProvider.getExternalUrls().getJournals(); +// case PubRepositories -> this.externalUrlConfigProvider.getExternalUrls().getPubRepositories(); +// case DataRepositories -> this.externalUrlConfigProvider.getExternalUrls().getRepositories(); +// case Registries -> this.externalUrlConfigProvider.getExternalUrls().getRegistries(); +// case Services -> this.externalUrlConfigProvider.getExternalUrls().getServices(); +// case Grants -> this.externalUrlConfigProvider.getExternalUrls().getGrants(); +// case Organizations -> this.externalUrlConfigProvider.getExternalUrls().getOrganisations(); +// case Datasets -> this.externalUrlConfigProvider.getExternalUrls().getDatasets(); +// case Funder -> this.externalUrlConfigProvider.getExternalUrls().getFunders(); +// case Project -> this.externalUrlConfigProvider.getExternalUrls().getProjects(); +// case Researcher -> this.externalUrlConfigProvider.getExternalUrls().getResearchers(); +// default -> throw new IllegalArgumentException("Type not found" + referenceType); +// }; +// } +// +// @Override +// public Integer countEntries(ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException { +// List urlConfigs = +// key != null && !key.isEmpty() ? this.externalUrlConfigProvider.getExternalUrls().getValidations().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) +// : this.externalUrlConfigProvider.getExternalUrls().getValidations().getUrls(); +// FetchStrategy fetchStrategy = this.externalUrlConfigProvider.getExternalUrls().getValidations().getFetchMode(); +// List> data = this.getAll(urlConfigs, fetchStrategy, externalReferenceCriteria); +// return data.size(); +// } +// +// @Override +// public List> getExternalGeneric(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls) { +// List urlConfigurations = genericUrls.getUrls(); +// FetchStrategy fetchStrategy = genericUrls.getFetchMode(); +// return getAll(urlConfigurations, fetchStrategy, externalReferenceCriteria); +// } +// +// @Override +// public List> getExternalGenericWithData(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls) { +// List urlConfigurations = genericUrls.getUrls(); +// return getAllWithData(urlConfigurations, externalReferenceCriteria); +// } +// +// private List> getAll(List urlConfigs, FetchStrategy fetchStrategy, ExternalReferenceCriteria externalReferenceCriteria) { +// +// List> results = new LinkedList<>(); +// +// if (urlConfigs == null || urlConfigs.isEmpty()) { +// return results; +// } +//// throw new MyNotFoundException("No Repository urls found in configuration"); +// +// urlConfigs.sort(Comparator.comparing(UrlConfiguration::getOrdinal)); +// for (UrlConfiguration urlConfiguration : urlConfigs) { +// applyFunderQuery(urlConfiguration, externalReferenceCriteria); +// if (urlConfiguration.getType() == null || urlConfiguration.getType().equals("External")) { +// try { +// String auth = null; +// if (urlConfiguration.getAuth() != null) { +// auth = this.getAuthentication(urlConfiguration.getAuth()); +// } +// results.addAll(getAllResultsFromUrl(urlConfiguration.getUrl(), fetchStrategy, urlConfiguration.getData(), urlConfiguration.getPaginationPath(), externalReferenceCriteria, urlConfiguration.getLabel(), urlConfiguration.getKey(), urlConfiguration.getContentType(), urlConfiguration.getFirstpage(), urlConfiguration.getRequestBody(), urlConfiguration.getRequestType(), urlConfiguration.getFilterType(), urlConfiguration.getQueries(), auth)); +// } catch (Exception e) { +// logger.error(e.getLocalizedMessage(), e); +// } +// } else if (urlConfiguration.getType() != null && urlConfiguration.getType().equals("Internal")) { +// results.addAll(getAllResultsFromMockUpJson(urlConfiguration.getUrl(), externalReferenceCriteria.getLike())); +// } +// } +// /* for (UrlConfiguration urlConfig : urlConfigs) { +// ifFunderQueryExist(urlConfig, externalUrlCriteria); +// if (urlConfig.getType() == null || urlConfig.getType().equals("External")) { +// results.addAll(getAllResultsFromUrl(urlConfig.getUrl(), fetchStrategy, urlConfig.getData(), urlConfig.getPaginationPath(), externalUrlCriteria, urlConfig.getLabel(), urlConfig.getKey(), urlConfig.getContentType(), urlConfig.getFirstpage(), urlConfig.getRequestBody(), urlConfig.getRequestType())); +// } else if (urlConfig.getType() != null && urlConfig.getType().equals("Internal")) { +// results.addAll(getAllResultsFromMockUpJson(urlConfig.getUrl(), externalUrlCriteria.getLike())); +// } +// }*/ +// return results; +// } +// +// private String getAuthentication(AuthenticationConfiguration authenticationConfiguration) { +// HttpMethod method = HttpMethod.valueOf(authenticationConfiguration.getAuthMethod()); +// Map response = this.getWebClient().method(method).uri(authenticationConfiguration.getAuthUrl()) +// .contentType(MediaType.APPLICATION_JSON) +// .bodyValue(this.parseBodyString(authenticationConfiguration.getAuthRequestBody())) +// .exchangeToMono(mono -> mono.bodyToMono(new ParameterizedTypeReference>() { +// })).block(); +// +// +// +// return authenticationConfiguration.getType() + " " + response.get(authenticationConfiguration.getAuthTokenPath()); +// } +// +// private List> getAllWithData(List urlConfigs, ExternalReferenceCriteria externalReferenceCriteria) { +// +// List> results = new LinkedList<>(); +// +// if (urlConfigs == null || urlConfigs.isEmpty()) { +// return results; +// } +// +// urlConfigs.sort(Comparator.comparing(UrlConfiguration::getOrdinal)); +// urlConfigs.forEach(urlConfiguration -> { +// applyFunderQuery(urlConfiguration, externalReferenceCriteria); +// if (urlConfiguration.getType() == null || urlConfiguration.getType().equals("External")) { +// try { +// results.addAll(getAllResultsFromUrlWithData(urlConfiguration.getUrl(), urlConfiguration.getData(), externalReferenceCriteria, urlConfiguration.getContentType(), urlConfiguration.getFirstpage(), urlConfiguration.getRequestBody(), urlConfiguration.getRequestType(), urlConfiguration.getQueries())); +// } catch (Exception e) { +// logger.error(e.getLocalizedMessage(), e); +// } +// } +// }); +// return results; +// +// } +// +// private void applyFunderQuery(UrlConfiguration urlConfiguration, ExternalReferenceCriteria externalReferenceCriteria) { +// if (urlConfiguration.getFunderQuery() != null) { +// if (externalReferenceCriteria.getFunderId() != null && !urlConfiguration.getFunderQuery().startsWith("dmp:")) { +// urlConfiguration.setUrl(urlConfiguration.getUrl().replace("{funderQuery}", urlConfiguration.getFunderQuery())); +// } +// else { +// urlConfiguration.setUrl(urlConfiguration.getUrl().replace("{funderQuery}", "")); +// } +// } +// } +// +// private String calculateQuery(ExternalReferenceCriteria externalReferenceCriteria, List queryConfigs) { +// String finalQuery = ""; +// QueryConfig queryConfig = queryConfigs.stream().filter(queryConfigl -> externalReferenceCriteria.getLike().matches(queryConfigl.getCondition())) +// .min((Comparator.comparing(QueryConfig::getOrdinal))).orElse(null); +// if (queryConfig != null) { +// if (queryConfig.getSeparator() != null) { +// String[] likes = externalReferenceCriteria.getLike().split(queryConfig.getSeparator()); +// finalQuery = queryConfig.getValue(); +// for (int i = 0; i < likes.length; i++) { +// finalQuery = finalQuery.replaceAll("\\{like" + (i+1) + "}", likes[i]); +// } +// } else { +// finalQuery = queryConfig.getValue().replaceAll("\\{like}", externalReferenceCriteria.getLike()); +// } +// +// } +// return finalQuery; +// } +// +// protected String replaceCriteriaOnUrl(String path, ExternalReferenceCriteria externalReferenceCriteria, String firstPage, List queries) { +// String completedPath = path; +// if (externalReferenceCriteria.getLike() != null) { +// if ((path.contains("openaire") || path.contains("orcid") || path.contains("ror") || path.contains("fairsharing")) && externalReferenceCriteria.getLike().equals("")) { +// completedPath = completedPath.replaceAll("\\{like}", "*"); +// completedPath = completedPath.replaceAll("\\{query}", "*"); +// } else { +// if (completedPath.contains("{query}")) { +// completedPath = completedPath.replaceAll("\\{query}", this.calculateQuery(externalReferenceCriteria, queries)); +// } else { +// completedPath = completedPath.replaceAll("\\{like}", externalReferenceCriteria.getLike()); +// } +// } +// } else { +// completedPath = completedPath.replace("{like}", ""); +// } +// if (externalReferenceCriteria.getFunderId() != null) { +// String funderPrefix = externalReferenceCriteria.getFunderId().split(":")[0]; +// String funderId = externalReferenceCriteria.getFunderId().replace(funderPrefix + ":", ""); +// if (funderId.toCharArray()[0] == ':') { +// funderId = externalReferenceCriteria.getFunderId(); +// } +// /* +// try { funderId = URLEncoder.encode(funderId, "UTF-8"); } catch +// (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } +// */ +// completedPath = completedPath.replace("{funderId}", funderId); +// } +// else if(completedPath.contains("{funderId}")){ +// logger.warn("FunderId is null."); +// completedPath = completedPath.replace("{funderId}", " "); +// } +// if (externalReferenceCriteria.getPage() != null) { +// completedPath = completedPath.replace("{page}", externalReferenceCriteria.getPage()); +// } else { +// if (firstPage != null) { +// completedPath = completedPath.replace("{page}", firstPage); +// } else { +// completedPath = completedPath.replace("{page}", "1"); +// } +// } +// if (externalReferenceCriteria.getPageSize() != null) { +// completedPath = completedPath.replace("{pageSize}", externalReferenceCriteria.getPageSize()); +// } else { +// completedPath = completedPath.replace("{pageSize}", "60"); +// } +// if (externalReferenceCriteria.getHost() != null) { +// completedPath = completedPath.replace("{host}", externalReferenceCriteria.getHost()); +// } else { +// completedPath = completedPath.replace("{host}", ""); +// } +// if (externalReferenceCriteria.getPath() != null) { +// completedPath = completedPath.replace("{path}", externalReferenceCriteria.getPath()); +// } else { +// completedPath = completedPath.replace("{path}", ""); +// } +// return completedPath; +// } +// +// private List> getAllResultsFromUrl(String path, FetchStrategy fetchStrategy, final DataUrlConfiguration jsonDataPath, final String jsonPaginationPath, ExternalReferenceCriteria externalReferenceCriteria, String tag, String key, String contentType, String firstPage, String requestBody, String requestType, String filterType, List queries, String auth) throws Exception { +// Set pages = new HashSet<>(); +// +// String replacedPath = replaceCriteriaOnUrl(path, externalReferenceCriteria, firstPage, queries); +// String replacedBody = replaceCriteriaOnUrl(requestBody, externalReferenceCriteria, firstPage, queries); +// +// ExternalRefernceResult externalRefernceResult = getResultsFromUrl(replacedPath, jsonDataPath, jsonPaginationPath, contentType, replacedBody, requestType, auth); +// if(externalRefernceResult != null) { +// if (filterType != null && filterType.equals("local") && (externalReferenceCriteria.getLike() != null && !externalReferenceCriteria.getLike().isEmpty())) { +// externalRefernceResult.setResults(externalRefernceResult.getResults().stream() +// .filter(r -> r.get("name").toLowerCase().contains(externalReferenceCriteria.getLike().toLowerCase())) +// .collect(Collectors.toList())); +// } +// if (fetchStrategy == FetchStrategy.FIRST) +// return externalRefernceResult.getResults().stream().peek(x -> x.put("tag", tag)).peek(x -> x.put("key", key)).collect(Collectors.toList()); +// +// if (externalRefernceResult.getPagination() != null && externalRefernceResult.getPagination().get("pages") != null) //if has more pages, add them to the pages set +// for (int i = 2; i <= externalRefernceResult.getPagination().get("pages"); i++) +// pages.add(i); +// +// Long maxResults = this.externalUrlConfigProvider.getExternalUrls().getMaxresults(); +// if ((maxResults > 0) && (externalRefernceResult.getPagination().get("count") > maxResults)) +// throw new HugeResultSetException("The submitted search query " + externalReferenceCriteria.getLike() + " is about to return " + externalRefernceResult.getPagination().get("count") + " results... Please submit a more detailed search query"); +// +// Optional optionalResults = pages.parallelStream() +// .map(page -> getResultsFromUrl(path + "&page=" + page, jsonDataPath, jsonPaginationPath, contentType, replacedBody, requestType, auth)) +// .filter(Objects::nonNull) +// .reduce((result1, result2) -> { +// result1.getResults().addAll(result2.getResults()); +// return result1; +// }); +// ExternalRefernceResult remainingExternalRefernceResult = optionalResults.orElseGet(ExternalRefernceResult::new); +// remainingExternalRefernceResult.getResults().addAll(externalRefernceResult.getResults()); +// +// return remainingExternalRefernceResult.getResults().stream().peek(x -> x.put("tag", tag)).peek(x -> x.put("key", key)).collect(Collectors.toList()); +// } +// else { +// return new LinkedList<>(); +// } +// } +// +// private List> getAllResultsFromUrlWithData(String path, final DataUrlConfiguration jsonDataPath, ExternalReferenceCriteria externalReferenceCriteria, String contentType, String firstPage, String requestBody, String requestType, List queries) { +// +// String replacedPath = replaceCriteriaOnUrl(path, externalReferenceCriteria, firstPage, queries); +// String replacedBody = replaceCriteriaOnUrl(requestBody, externalReferenceCriteria, firstPage, queries); +// +// try { +// RestTemplate restTemplate = new RestTemplate(); +// HttpHeaders headers = new HttpHeaders(); +// HttpEntity entity; +// ResponseEntity response; +// if (contentType != null && !contentType.isEmpty()) { +// headers.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); +// headers.setContentType(MediaType.valueOf(contentType)); +// } +// JsonNode jsonBody = new ObjectMapper().readTree(replacedBody); // entity = new HttpEntity<>(jsonBody, headers); - - - response = this.getWebClient().method(HttpMethod.valueOf(requestType)).uri(urlString).headers(httpHeaders -> { - if (contentType != null && !contentType.isEmpty()) { - httpHeaders.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); - httpHeaders.setContentType(MediaType.valueOf(contentType)); - } - if (auth != null) { - httpHeaders.set("Authorization", auth); - } - }).bodyValue(jsonBody).retrieve().toEntity(String.class).block(); - //response = restTemplate.exchange(urlString, HttpMethod.resolve(requestType), entity, String.class); - if (response.getStatusCode() == HttpStatus.OK) { // success - //do here all the parsing - ExternalRefernceResult externalRefernceResult = new ExternalRefernceResult(); - if (response.getHeaders().get("Content-Type").get(0).contains("json")) { - DocumentContext jsonContext = JsonPath.parse(response.getBody()); - - if (jsonDataPath.getFieldsUrlConfiguration().getPath() != null) { - externalRefernceResult = RemoteFetcherUtils.getFromJsonWithRecursiveFetching(jsonContext, jsonDataPath, this, requestBody, requestType, auth); - } else if (jsonDataPath.getFieldsUrlConfiguration().getFirstName() != null) { - externalRefernceResult = RemoteFetcherUtils.getFromJsonWithFirstAndLastName(jsonContext, jsonDataPath); - } else { - externalRefernceResult = RemoteFetcherUtils.getFromJson(jsonContext, jsonDataPath); - } - externalRefernceResult.setResults(externalRefernceResult.getResults().stream().map(e -> e.entrySet().stream().collect(Collectors.toMap(x -> this.transformKey(jsonDataPath,x.getKey()), Map.Entry::getValue))) - .collect(Collectors.toList())); - } - else if (response.getHeaders().get("Content-Type").get(0).contains("xml")) { - Class aClass = Class.forName(jsonDataPath.getParseClass()); - JAXBContext jaxbContext = JAXBContext.newInstance(aClass); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - StringReader stringReader = new StringReader(response.getBody()); - Object data = unmarshaller.unmarshal(stringReader); - Method reader = null; - if (jsonDataPath.getParseField() != null && !jsonDataPath.getParseField().isEmpty()) { - String camelCaseGetter = jsonDataPath.getParseField() != null && !jsonDataPath.getParseField().isEmpty() ? "get" + jsonDataPath.getParseField().substring(0, 1).toUpperCase() + jsonDataPath.getParseField().substring(1) : ""; - reader = aClass.getMethod(camelCaseGetter); - } - ObjectMapper objectMapper = new ObjectMapper(); - List> values = new ArrayList<>(); - int max = 1; - if (reader != null) { - Object invokedField = reader.invoke(data); - if (invokedField instanceof Collection) { - max = ((Collection) invokedField).size(); - } - } - for (int i = 0; i< max; i++) { - Object value; - if (reader != null) { - Object invokedField = reader.invoke(data); - if (invokedField instanceof Collection) { - value = ((Collection) invokedField).toArray()[i]; - } else { - value = invokedField; - } - } else { - value = data; - } - Map map = objectMapper.convertValue(value, Map.class); - if (jsonDataPath.getMergedFields() != null && !jsonDataPath.getMergedFields().isEmpty() && jsonDataPath.getMergedFieldName() != null && !jsonDataPath.getMergedFieldName().isEmpty()) { - Map finalMap = new HashMap<>(); - for (Map.Entry entry : map.entrySet()) { - if (jsonDataPath.getMergedFields().contains(entry.getKey())) { - if (!finalMap.containsKey(jsonDataPath.getMergedFieldName())) { - finalMap.put(jsonDataPath.getMergedFieldName(), entry.getValue()); - } else { - finalMap.put(jsonDataPath.getMergedFieldName(), finalMap.get(jsonDataPath.getMergedFieldName()) + " " + entry.getValue()); - } - } else { - finalMap.put(entry.getKey(), entry.getValue()); - } - } - values.add(finalMap); - } else { - values.add(map); - } - } - externalRefernceResult = new ExternalRefernceResult(values, new HashMap<>(1, 1)); - } - - if (externalRefernceResult.getPagination().isEmpty()) { - externalRefernceResult.getPagination().put("pages", 1); - externalRefernceResult.getPagination().put("count", externalRefernceResult.getResults().size()); - } - return externalRefernceResult; - } - } catch (Exception exception) { - logger.error(exception.getMessage(), exception); - } //maybe print smth... - - return null; - } - - private List> getAllResultsFromMockUpJson(String path, String query) { - List> internalResults; - try { - String filePath = Paths.get(path).toUri().toURL().toString(); - ObjectMapper mapper = new ObjectMapper(); - internalResults = mapper.readValue(new File(filePath), new TypeReference>>(){}); - return searchListMap(internalResults, query); - } catch (Exception e) { - logger.error(e.getMessage(), e); - return new LinkedList<>(); - } - } - - private List> searchListMap(List> internalResults, String query) { - List> list = new LinkedList<>(); - for (Map map : internalResults) - { - if (map.get("name") != null && map.get("name").toUpperCase().contains(query.toUpperCase())) { - list.add(map); - } - if (map.get("label") != null && map.get("label").toUpperCase().contains(query.toUpperCase())) { - list.add(map); - } - } - return list; - } - - private String transformKey(DataUrlConfiguration dataUrlConfiguration, String key) { - if (dataUrlConfiguration.getFieldsUrlConfiguration().getId() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getId().replace("'",""))) { - if(dataUrlConfiguration.getFieldsUrlConfiguration().getPid() == null) - return "pid"; - else - return "originalId"; - } - if (dataUrlConfiguration.getFieldsUrlConfiguration().getPid() != null && key.equals("pid")) return "pid"; - if (dataUrlConfiguration.getFieldsUrlConfiguration().getPidTypeField() != null && key.equals("pidTypeField")) return "pidTypeField"; - if (dataUrlConfiguration.getFieldsUrlConfiguration().getDescription() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getDescription().replace("'",""))) return "description"; - if (dataUrlConfiguration.getFieldsUrlConfiguration().getUri() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getUri().replace("'",""))) return "uri"; - if (dataUrlConfiguration.getFieldsUrlConfiguration().getName() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getName().replace("'",""))) return "name"; - if (dataUrlConfiguration.getFieldsUrlConfiguration().getSource() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getSource().replace("'",""))) return "source"; - if (dataUrlConfiguration.getFieldsUrlConfiguration().getCount() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getCount().replace("'",""))) return "count"; - if (dataUrlConfiguration.getFieldsUrlConfiguration().getPath() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getPath().replace("'",""))) return "path"; - if (dataUrlConfiguration.getFieldsUrlConfiguration().getHost() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getHost().replace("'",""))) return "host"; - return null; - } - - private String parseBodyString(String bodyString) { - String finalBodyString = bodyString; - if (bodyString.contains("{env:")) { - int index = bodyString.indexOf("{env: "); - while (index >= 0) { - int endIndex = bodyString.indexOf("}", index + 6); - String envName = bodyString.substring(index + 6, endIndex); - finalBodyString = finalBodyString.replace("{env: " + envName + "}", System.getenv(envName)); - index = bodyString.indexOf("{env: ", index + 6); - } - } - return finalBodyString; - } - -} +// +// response = restTemplate.exchange(replacedPath, HttpMethod.valueOf(requestType), entity, String.class); +// if (response.getStatusCode() == HttpStatus.OK) { +// if (response.getHeaders().get("Content-Type").get(0).contains("json")) { +// DocumentContext jsonContext = JsonPath.parse(response.getBody()); +// return jsonContext.read(jsonDataPath.getPath()); +// } +// } +// } +// catch (Exception exception) { +// logger.error(exception.getMessage(), exception); +// } +// +// return new LinkedList<>(); +// } +// +// +// protected ExternalRefernceResult getResultsFromUrl(String urlString, DataUrlConfiguration jsonDataPath, String jsonPaginationPath, String contentType, String requestBody, String requestType, String auth) { +// +// try { +// //RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory()); +// //HttpHeaders headers = new HttpHeaders(); +// //HttpEntity entity; +// ResponseEntity response; +// /* +// * URL url = new URL(urlString.replaceAll(" ", "%20")); +// * +// * HttpURLConnection con = (HttpURLConnection) url.openConnection(); +// * con.setRequestMethod("GET"); +// */ +// /* if (contentType != null && !contentType.isEmpty()) { +// headers.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); +// headers.setContentType(MediaType.valueOf(contentType)); +// } +// if (auth != null) { +// headers.set("Authorization", auth); +// }*/ +// JsonNode jsonBody = new ObjectMapper().readTree(requestBody); +//// entity = new HttpEntity<>(jsonBody, headers); +// +// +// response = this.getWebClient().method(HttpMethod.valueOf(requestType)).uri(urlString).headers(httpHeaders -> { +// if (contentType != null && !contentType.isEmpty()) { +// httpHeaders.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); +// httpHeaders.setContentType(MediaType.valueOf(contentType)); +// } +// if (auth != null) { +// httpHeaders.set("Authorization", auth); +// } +// }).bodyValue(jsonBody).retrieve().toEntity(String.class).block(); +// //response = restTemplate.exchange(urlString, HttpMethod.resolve(requestType), entity, String.class); +// if (response.getStatusCode() == HttpStatus.OK) { // success +// //do here all the parsing +// ExternalRefernceResult externalRefernceResult = new ExternalRefernceResult(); +// if (response.getHeaders().get("Content-Type").get(0).contains("json")) { +// DocumentContext jsonContext = JsonPath.parse(response.getBody()); +// +// if (jsonDataPath.getFieldsUrlConfiguration().getPath() != null) { +// externalRefernceResult = RemoteFetcherUtils.getFromJsonWithRecursiveFetching(jsonContext, jsonDataPath, this, requestBody, requestType, auth); +// } else if (jsonDataPath.getFieldsUrlConfiguration().getFirstName() != null) { +// externalRefernceResult = RemoteFetcherUtils.getFromJsonWithFirstAndLastName(jsonContext, jsonDataPath); +// } else { +// externalRefernceResult = RemoteFetcherUtils.getFromJson(jsonContext, jsonDataPath); +// } +// externalRefernceResult.setResults(externalRefernceResult.getResults().stream().map(e -> e.entrySet().stream().collect(Collectors.toMap(x -> this.transformKey(jsonDataPath,x.getKey()), Map.Entry::getValue))) +// .collect(Collectors.toList())); +// } +// else if (response.getHeaders().get("Content-Type").get(0).contains("xml")) { +// Class aClass = Class.forName(jsonDataPath.getParseClass()); +// JAXBContext jaxbContext = JAXBContext.newInstance(aClass); +// Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); +// StringReader stringReader = new StringReader(response.getBody()); +// Object data = unmarshaller.unmarshal(stringReader); +// Method reader = null; +// if (jsonDataPath.getParseField() != null && !jsonDataPath.getParseField().isEmpty()) { +// String camelCaseGetter = jsonDataPath.getParseField() != null && !jsonDataPath.getParseField().isEmpty() ? "get" + jsonDataPath.getParseField().substring(0, 1).toUpperCase() + jsonDataPath.getParseField().substring(1) : ""; +// reader = aClass.getMethod(camelCaseGetter); +// } +// ObjectMapper objectMapper = new ObjectMapper(); +// List> values = new ArrayList<>(); +// int max = 1; +// if (reader != null) { +// Object invokedField = reader.invoke(data); +// if (invokedField instanceof Collection) { +// max = ((Collection) invokedField).size(); +// } +// } +// for (int i = 0; i< max; i++) { +// Object value; +// if (reader != null) { +// Object invokedField = reader.invoke(data); +// if (invokedField instanceof Collection) { +// value = ((Collection) invokedField).toArray()[i]; +// } else { +// value = invokedField; +// } +// } else { +// value = data; +// } +// Map map = objectMapper.convertValue(value, Map.class); +// if (jsonDataPath.getMergedFields() != null && !jsonDataPath.getMergedFields().isEmpty() && jsonDataPath.getMergedFieldName() != null && !jsonDataPath.getMergedFieldName().isEmpty()) { +// Map finalMap = new HashMap<>(); +// for (Map.Entry entry : map.entrySet()) { +// if (jsonDataPath.getMergedFields().contains(entry.getKey())) { +// if (!finalMap.containsKey(jsonDataPath.getMergedFieldName())) { +// finalMap.put(jsonDataPath.getMergedFieldName(), entry.getValue()); +// } else { +// finalMap.put(jsonDataPath.getMergedFieldName(), finalMap.get(jsonDataPath.getMergedFieldName()) + " " + entry.getValue()); +// } +// } else { +// finalMap.put(entry.getKey(), entry.getValue()); +// } +// } +// values.add(finalMap); +// } else { +// values.add(map); +// } +// } +// externalRefernceResult = new ExternalRefernceResult(values, new HashMap<>(1, 1)); +// } +// +// if (externalRefernceResult.getPagination().isEmpty()) { +// externalRefernceResult.getPagination().put("pages", 1); +// externalRefernceResult.getPagination().put("count", externalRefernceResult.getResults().size()); +// } +// return externalRefernceResult; +// } +// } catch (Exception exception) { +// logger.error(exception.getMessage(), exception); +// } //maybe print smth... +// +// return null; +// } +// +// private List> getAllResultsFromMockUpJson(String path, String query) { +// List> internalResults; +// try { +// String filePath = Paths.get(path).toUri().toURL().toString(); +// ObjectMapper mapper = new ObjectMapper(); +// internalResults = mapper.readValue(new File(filePath), new TypeReference>>(){}); +// return searchListMap(internalResults, query); +// } catch (Exception e) { +// logger.error(e.getMessage(), e); +// return new LinkedList<>(); +// } +// } +// +// private List> searchListMap(List> internalResults, String query) { +// List> list = new LinkedList<>(); +// for (Map map : internalResults) +// { +// if (map.get("name") != null && map.get("name").toUpperCase().contains(query.toUpperCase())) { +// list.add(map); +// } +// if (map.get("label") != null && map.get("label").toUpperCase().contains(query.toUpperCase())) { +// list.add(map); +// } +// } +// return list; +// } +// +// private String transformKey(DataUrlConfiguration dataUrlConfiguration, String key) { +// if (dataUrlConfiguration.getFieldsUrlConfiguration().getId() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getId().replace("'",""))) { +// if(dataUrlConfiguration.getFieldsUrlConfiguration().getPid() == null) +// return "pid"; +// else +// return "originalId"; +// } +// if (dataUrlConfiguration.getFieldsUrlConfiguration().getPid() != null && key.equals("pid")) return "pid"; +// if (dataUrlConfiguration.getFieldsUrlConfiguration().getPidTypeField() != null && key.equals("pidTypeField")) return "pidTypeField"; +// if (dataUrlConfiguration.getFieldsUrlConfiguration().getDescription() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getDescription().replace("'",""))) return "description"; +// if (dataUrlConfiguration.getFieldsUrlConfiguration().getUri() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getUri().replace("'",""))) return "uri"; +// if (dataUrlConfiguration.getFieldsUrlConfiguration().getName() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getName().replace("'",""))) return "name"; +// if (dataUrlConfiguration.getFieldsUrlConfiguration().getSource() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getSource().replace("'",""))) return "source"; +// if (dataUrlConfiguration.getFieldsUrlConfiguration().getCount() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getCount().replace("'",""))) return "count"; +// if (dataUrlConfiguration.getFieldsUrlConfiguration().getPath() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getPath().replace("'",""))) return "path"; +// if (dataUrlConfiguration.getFieldsUrlConfiguration().getHost() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getHost().replace("'",""))) return "host"; +// return null; +// } +// +// private String parseBodyString(String bodyString) { +// String finalBodyString = bodyString; +// if (bodyString.contains("{env:")) { +// int index = bodyString.indexOf("{env: "); +// while (index >= 0) { +// int endIndex = bodyString.indexOf("}", index + 6); +// String envName = bodyString.substring(index + 6, endIndex); +// finalBodyString = finalBodyString.replace("{env: " + envName + "}", System.getenv(envName)); +// index = bodyString.indexOf("{env: ", index + 6); +// } +// } +// return finalBodyString; +// } +// +//} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherUtils.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherUtils.java index af2f35d8a..081a1c1f1 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherUtils.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherUtils.java @@ -1,152 +1,152 @@ -package eu.eudat.service.remotefetcher; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.jayway.jsonpath.DocumentContext; -import eu.eudat.service.remotefetcher.config.DataUrlConfiguration; -import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; -import eu.eudat.service.remotefetcher.models.ExternalRefernceResult; -import net.minidev.json.JSONArray; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.*; -import java.util.stream.Collectors; - -public class RemoteFetcherUtils { - private final static Logger logger = LoggerFactory.getLogger(RemoteFetcherUtils.class); - private static final ObjectMapper mapper = new ObjectMapper(); - - public static ExternalRefernceResult getFromJson(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { - return new ExternalRefernceResult(parseData(jsonContext, jsonDataPath), - new HashMap<>(1, 1)); - } - - public static ExternalRefernceResult getFromJsonWithRecursiveFetching(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath, RemoteFetcherServiceImpl remoteFetcherService, String requestBody, String requestType, String auth) { - ExternalRefernceResult externalRefernceResult = new ExternalRefernceResult(parseData(jsonContext, jsonDataPath), - new HashMap<>(1, 1)); - - List> multiResults = externalRefernceResult.getResults().stream().map(result -> { - ExternalReferenceCriteria externalReferenceCriteria = new ExternalReferenceCriteria(); - externalReferenceCriteria.setPath(result.get("path")); - externalReferenceCriteria.setHost(result.get("host")); - String replacedPath = remoteFetcherService.replaceCriteriaOnUrl(jsonDataPath.getUrlConfiguration().getUrl(), externalReferenceCriteria, jsonDataPath.getUrlConfiguration().getFirstpage(), jsonDataPath.getUrlConfiguration().getQueries()); - return remoteFetcherService.getResultsFromUrl(replacedPath, jsonDataPath.getUrlConfiguration().getData(), jsonDataPath.getUrlConfiguration().getData().getPath(), jsonDataPath.getUrlConfiguration().getContentType(), requestBody, requestType, auth); - }).filter(Objects::nonNull).map(externalRefernceResult1 -> externalRefernceResult1.getResults().get(0)).collect(Collectors.toList()); - return new ExternalRefernceResult(multiResults, new HashMap<>(1, 1)); - } - - public static ExternalRefernceResult getFromJsonWithFirstAndLastName(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { - ExternalRefernceResult externalRefernceResult = new ExternalRefernceResult(parseData(jsonContext, jsonDataPath), - new HashMap<>(1, 1)); - externalRefernceResult.getResults().stream().forEach(entry -> { - String name = entry.get(jsonDataPath.getFieldsUrlConfiguration().getFirstName().replace("'", "")) + " " + entry.get(jsonDataPath.getFieldsUrlConfiguration().getLastName().replace("'", "")); - entry.put("name", name); - entry.remove(jsonDataPath.getFieldsUrlConfiguration().getFirstName().replace("'", "")); - entry.remove(jsonDataPath.getFieldsUrlConfiguration().getLastName().replace("'", "")); - }); - return externalRefernceResult; - } - - private static List> parseData (DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { - List > rawData = jsonContext.read(jsonDataPath.getPath()); - List> parsedData = new ArrayList<>(); - rawData.forEach(stringObjectMap -> { - parsedData.add(new LinkedHashMap<>()); - Arrays.stream(jsonDataPath.getFieldsUrlConfiguration().getClass().getDeclaredFields()).forEach(field -> { - String getterMethodName = "get" + field.getName().substring(0, 1).toUpperCase(Locale.ROOT) + field.getName().substring(1); - Method getterMethod = Arrays.stream(jsonDataPath.getFieldsUrlConfiguration().getClass().getDeclaredMethods()).filter(method -> method.getName().equals(getterMethodName)).collect(Collectors.toList()).get(0); - try { - String value = ((String) getterMethod.invoke(jsonDataPath.getFieldsUrlConfiguration())); - if (value != null) { - if (field.getName().equals("pid") || field.getName().equals("pidTypeField")) { - String pid = null; - Object pidObj = stringObjectMap.get(value.split("\\.")[0]); - if(pidObj != null){ - if(pidObj instanceof Map){ - Object o = ((Map) pidObj).get(value.split("\\.")[1]); - if(o instanceof String){ - pid = (String)o; - } - else if(o instanceof Integer){ - pid = String.valueOf(o); - } - } - else if(pidObj instanceof List){ - Object o = ((List>) pidObj).get(0).get(value.split("\\.")[1]); - if(o instanceof String){ - pid = (String)o; - } - else if(o instanceof Integer){ - pid = String.valueOf(o); - } - } - } - if(pid != null) { - if ((field.getName().equals("pid"))){ - parsedData.get(parsedData.size() - 1).put("pid", pid); - } - else{ - parsedData.get(parsedData.size() - 1).put("pidTypeField", pid); - } - } - } else { - value = value.replace("'", ""); - if (value.contains(".")) { - String[] parts = value.split("\\."); - Map tempMap = stringObjectMap; - for (int i = 0; i < parts.length; i++) { - if (tempMap.containsKey(parts[i])) { - if (i + 1 < parts.length) { - tempMap = (Map) tempMap.get(parts[i]); - } else { - parsedData.get(parsedData.size() - 1).put(field.getName().equals("types") ? "tags" : value, normalizeValue(tempMap.get(parts[i]), (field.getName().equals("types") || field.getName().equals("uri")))); - } - } - } - } else { - if (stringObjectMap.containsKey(value)) { - parsedData.get(parsedData.size() - 1).put(field.getName().equals("types") ? "tags" : value, normalizeValue(stringObjectMap.get(value), (field.getName().equals("types") || field.getName().equals("uri")))); - } - } - } - } - } catch (IllegalAccessException | InvocationTargetException e) { - logger.error(e.getLocalizedMessage(), e); - } - }); - }); - return parsedData; - } - - private static String normalizeValue(Object value, boolean jsonString) { - if (value instanceof JSONArray) { - if (jsonString) { - return ((JSONArray)value).toJSONString(); - } - JSONArray jarr = (JSONArray) value; - if (jarr.get(0) instanceof String) { - return jarr.get(0).toString(); - } else { - for (Object o : jarr) { - if ((o instanceof Map) && ((Map) o).containsKey("content")) { - try { - return ((Map) o).get("content"); - } - catch (ClassCastException e){ - if(((Map) o).get("content") instanceof Integer) { - return String.valueOf(((Map) o).get("content")); - } - return null; - } - } - } - } - } else if (value instanceof Map) { - String key = ((Map)value).containsKey("$") ? "$" : "content"; - return ((Map)value).get(key); - } - return value != null ? value.toString() : null; - } -} +//package eu.eudat.service.remotefetcher; +// +//import com.fasterxml.jackson.databind.ObjectMapper; +//import com.jayway.jsonpath.DocumentContext; +//import eu.eudat.service.remotefetcher.config.DataUrlConfiguration; +//import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; +//import eu.eudat.service.remotefetcher.models.ExternalRefernceResult; +//import net.minidev.json.JSONArray; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//import java.lang.reflect.InvocationTargetException; +//import java.lang.reflect.Method; +//import java.util.*; +//import java.util.stream.Collectors; +// +//public class RemoteFetcherUtils { +// private final static Logger logger = LoggerFactory.getLogger(RemoteFetcherUtils.class); +// private static final ObjectMapper mapper = new ObjectMapper(); +// +// public static ExternalRefernceResult getFromJson(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { +// return new ExternalRefernceResult(parseData(jsonContext, jsonDataPath), +// new HashMap<>(1, 1)); +// } +// +// public static ExternalRefernceResult getFromJsonWithRecursiveFetching(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath, RemoteFetcherServiceImpl remoteFetcherService, String requestBody, String requestType, String auth) { +// ExternalRefernceResult externalRefernceResult = new ExternalRefernceResult(parseData(jsonContext, jsonDataPath), +// new HashMap<>(1, 1)); +// +// List> multiResults = externalRefernceResult.getResults().stream().map(result -> { +// ExternalReferenceCriteria externalReferenceCriteria = new ExternalReferenceCriteria(); +// externalReferenceCriteria.setPath(result.get("path")); +// externalReferenceCriteria.setHost(result.get("host")); +// String replacedPath = remoteFetcherService.replaceCriteriaOnUrl(jsonDataPath.getUrlConfiguration().getUrl(), externalReferenceCriteria, jsonDataPath.getUrlConfiguration().getFirstpage(), jsonDataPath.getUrlConfiguration().getQueries()); +// return remoteFetcherService.getResultsFromUrl(replacedPath, jsonDataPath.getUrlConfiguration().getData(), jsonDataPath.getUrlConfiguration().getData().getPath(), jsonDataPath.getUrlConfiguration().getContentType(), requestBody, requestType, auth); +// }).filter(Objects::nonNull).map(externalRefernceResult1 -> externalRefernceResult1.getResults().get(0)).collect(Collectors.toList()); +// return new ExternalRefernceResult(multiResults, new HashMap<>(1, 1)); +// } +// +// public static ExternalRefernceResult getFromJsonWithFirstAndLastName(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { +// ExternalRefernceResult externalRefernceResult = new ExternalRefernceResult(parseData(jsonContext, jsonDataPath), +// new HashMap<>(1, 1)); +// externalRefernceResult.getResults().stream().forEach(entry -> { +// String name = entry.get(jsonDataPath.getFieldsUrlConfiguration().getFirstName().replace("'", "")) + " " + entry.get(jsonDataPath.getFieldsUrlConfiguration().getLastName().replace("'", "")); +// entry.put("name", name); +// entry.remove(jsonDataPath.getFieldsUrlConfiguration().getFirstName().replace("'", "")); +// entry.remove(jsonDataPath.getFieldsUrlConfiguration().getLastName().replace("'", "")); +// }); +// return externalRefernceResult; +// } +// +// private static List> parseData (DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { +// List > rawData = jsonContext.read(jsonDataPath.getPath()); +// List> parsedData = new ArrayList<>(); +// rawData.forEach(stringObjectMap -> { +// parsedData.add(new LinkedHashMap<>()); +// Arrays.stream(jsonDataPath.getFieldsUrlConfiguration().getClass().getDeclaredFields()).forEach(field -> { +// String getterMethodName = "get" + field.getName().substring(0, 1).toUpperCase(Locale.ROOT) + field.getName().substring(1); +// Method getterMethod = Arrays.stream(jsonDataPath.getFieldsUrlConfiguration().getClass().getDeclaredMethods()).filter(method -> method.getName().equals(getterMethodName)).collect(Collectors.toList()).get(0); +// try { +// String value = ((String) getterMethod.invoke(jsonDataPath.getFieldsUrlConfiguration())); +// if (value != null) { +// if (field.getName().equals("pid") || field.getName().equals("pidTypeField")) { +// String pid = null; +// Object pidObj = stringObjectMap.get(value.split("\\.")[0]); +// if(pidObj != null){ +// if(pidObj instanceof Map){ +// Object o = ((Map) pidObj).get(value.split("\\.")[1]); +// if(o instanceof String){ +// pid = (String)o; +// } +// else if(o instanceof Integer){ +// pid = String.valueOf(o); +// } +// } +// else if(pidObj instanceof List){ +// Object o = ((List>) pidObj).get(0).get(value.split("\\.")[1]); +// if(o instanceof String){ +// pid = (String)o; +// } +// else if(o instanceof Integer){ +// pid = String.valueOf(o); +// } +// } +// } +// if(pid != null) { +// if ((field.getName().equals("pid"))){ +// parsedData.get(parsedData.size() - 1).put("pid", pid); +// } +// else{ +// parsedData.get(parsedData.size() - 1).put("pidTypeField", pid); +// } +// } +// } else { +// value = value.replace("'", ""); +// if (value.contains(".")) { +// String[] parts = value.split("\\."); +// Map tempMap = stringObjectMap; +// for (int i = 0; i < parts.length; i++) { +// if (tempMap.containsKey(parts[i])) { +// if (i + 1 < parts.length) { +// tempMap = (Map) tempMap.get(parts[i]); +// } else { +// parsedData.get(parsedData.size() - 1).put(field.getName().equals("types") ? "tags" : value, normalizeValue(tempMap.get(parts[i]), (field.getName().equals("types") || field.getName().equals("uri")))); +// } +// } +// } +// } else { +// if (stringObjectMap.containsKey(value)) { +// parsedData.get(parsedData.size() - 1).put(field.getName().equals("types") ? "tags" : value, normalizeValue(stringObjectMap.get(value), (field.getName().equals("types") || field.getName().equals("uri")))); +// } +// } +// } +// } +// } catch (IllegalAccessException | InvocationTargetException e) { +// logger.error(e.getLocalizedMessage(), e); +// } +// }); +// }); +// return parsedData; +// } +// +// private static String normalizeValue(Object value, boolean jsonString) { +// if (value instanceof JSONArray) { +// if (jsonString) { +// return ((JSONArray)value).toJSONString(); +// } +// JSONArray jarr = (JSONArray) value; +// if (jarr.get(0) instanceof String) { +// return jarr.get(0).toString(); +// } else { +// for (Object o : jarr) { +// if ((o instanceof Map) && ((Map) o).containsKey("content")) { +// try { +// return ((Map) o).get("content"); +// } +// catch (ClassCastException e){ +// if(((Map) o).get("content") instanceof Integer) { +// return String.valueOf(((Map) o).get("content")); +// } +// return null; +// } +// } +// } +// } +// } else if (value instanceof Map) { +// String key = ((Map)value).containsKey("$") ? "$" : "content"; +// return ((Map)value).get(key); +// } +// return value != null ? value.toString() : null; +// } +//} diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/PublicDatasetsDescriptionDocumentation.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/PublicDatasetsDescriptionDocumentation.java index 9c246d1f9..44c572765 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/PublicDatasetsDescriptionDocumentation.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/PublicDatasetsDescriptionDocumentation.java @@ -20,6 +20,7 @@ import eu.eudat.query.DescriptionQuery; import eu.eudat.query.DmpQuery; import eu.eudat.query.lookup.DescriptionLookup; import eu.eudat.query.lookup.DmpLookup; +import eu.eudat.service.publicapi.PublicApiProperties; import eu.eudat.types.ApiMessageCode; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; @@ -67,21 +68,24 @@ public class PublicDatasetsDescriptionDocumentation { private final DescriptionToPublicApiDatasetListingMapper descriptionToPublicApiDatasetListingMapper; + private final PublicApiProperties config; + private final DmpToPublicApiDmpListingMapper dmpToPublicApiDmpListingMapper; @Autowired public PublicDatasetsDescriptionDocumentation( - QueryFactory queryFactory, - BuilderFactory builderFactory, - MessageSource messageSource, - DescriptionToPublicApiDatasetMapper descriptionToPublicApiDatasetMapper, - DescriptionToPublicApiDatasetListingMapper descriptionToPublicApiDatasetListingMapper, DmpToPublicApiDmpListingMapper dmpToPublicApiDmpListingMapper) { + QueryFactory queryFactory, + BuilderFactory builderFactory, + MessageSource messageSource, + DescriptionToPublicApiDatasetMapper descriptionToPublicApiDatasetMapper, + DescriptionToPublicApiDatasetListingMapper descriptionToPublicApiDatasetListingMapper, PublicApiProperties config, DmpToPublicApiDmpListingMapper dmpToPublicApiDmpListingMapper) { this.queryFactory = queryFactory; this.builderFactory = builderFactory; this.messageSource = messageSource; this.descriptionToPublicApiDatasetMapper = descriptionToPublicApiDatasetMapper; this.descriptionToPublicApiDatasetListingMapper = descriptionToPublicApiDatasetListingMapper; - this.dmpToPublicApiDmpListingMapper = dmpToPublicApiDmpListingMapper; + this.config = config; + this.dmpToPublicApiDmpListingMapper = dmpToPublicApiDmpListingMapper; } @Operation(summary = "This method is used to get a listing of public datasets.", description = PublicApiStaticHelpers.Description.getPagedNotes) @@ -103,7 +107,7 @@ public class PublicDatasetsDescriptionDocumentation { List data = query.collectAs(lookup.getProject()); List models = this.builderFactory.builder(DescriptionBuilder.class).build(lookup.getProject(), data); DataTableData dataTableData = new DataTableData<>(); - dataTableData.setData(models.stream().map(this.descriptionToPublicApiDatasetListingMapper::toPublicListingModel).toList()); + dataTableData.setData(models.stream().map(x-> this.descriptionToPublicApiDatasetListingMapper.toPublicListingModel(x, this.config.getReferenceTypeMap())).toList()); dataTableData.setTotalCount(count); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTableData)); } @@ -130,7 +134,7 @@ public class PublicDatasetsDescriptionDocumentation { DmpLookup dmpLookup = getDmpLookup(); Dmp dmp = this.builderFactory.builder(DmpBuilder.class).build(dmpLookup.getProject(), dmpQuery.firstAs(dmpLookup.getProject())); - DatasetPublicModel dataset = this.descriptionToPublicApiDatasetMapper.toPublicModel(model, this.dmpToPublicApiDmpListingMapper.toPublicListingModel(dmp)); + DatasetPublicModel dataset = this.descriptionToPublicApiDatasetMapper.toPublicModel(model, this.dmpToPublicApiDmpListingMapper.toPublicListingModel(dmp, this.config.getReferenceTypeMap()), this.config.getReferenceTypeMap()); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataset)); } @@ -148,6 +152,7 @@ public class PublicDatasetsDescriptionDocumentation { String.join(".", Description._createdBy, User._name), String.join(".", Description._descriptionReferences, DescriptionReference._reference, Reference._id), String.join(".", Description._descriptionReferences, DescriptionReference._reference, Reference._type), + String.join(".", Description._descriptionReferences, DescriptionReference._reference, Reference._type, Reference._id), String.join(".", Description._descriptionReferences, DescriptionReference._reference, Reference._reference), String.join(".", Description._descriptionReferences, DescriptionReference._reference, Reference._label), String.join(".", Description._descriptionReferences, DescriptionReference._reference, Reference._abbreviation), diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/PublicDmpsDocumentation.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/PublicDmpsDocumentation.java index 872e8bebb..2435bd091 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/PublicDmpsDocumentation.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/PublicDmpsDocumentation.java @@ -20,6 +20,7 @@ import eu.eudat.query.DmpDescriptionTemplateQuery; import eu.eudat.query.DmpQuery; import eu.eudat.query.EntityDoiQuery; import eu.eudat.query.lookup.DmpLookup; +import eu.eudat.service.publicapi.PublicApiProperties; import eu.eudat.types.ApiMessageCode; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; @@ -65,20 +66,22 @@ public class PublicDmpsDocumentation { private final DmpToPublicApiDmpMapper dmpToPublicApiDmpMapper; + private final PublicApiProperties config; private final DmpToPublicApiDmpListingMapper dmpToPublicApiDmpListingMapper; @Autowired public PublicDmpsDocumentation( - QueryFactory queryFactory, - BuilderFactory builderFactory, - MessageSource messageSource, - DmpToPublicApiDmpMapper dmpToPublicApiDmpMapper, - DmpToPublicApiDmpListingMapper dmpToPublicApiDmpListingMapper) { + QueryFactory queryFactory, + BuilderFactory builderFactory, + MessageSource messageSource, + DmpToPublicApiDmpMapper dmpToPublicApiDmpMapper, PublicApiProperties config, + DmpToPublicApiDmpListingMapper dmpToPublicApiDmpListingMapper) { this.queryFactory = queryFactory; this.builderFactory = builderFactory; this.messageSource = messageSource; this.dmpToPublicApiDmpMapper = dmpToPublicApiDmpMapper; - this.dmpToPublicApiDmpListingMapper = dmpToPublicApiDmpListingMapper; + this.config = config; + this.dmpToPublicApiDmpListingMapper = dmpToPublicApiDmpListingMapper; } @Operation(summary = "This method is used to get a listing of public dmps.", description = PublicApiStaticHelpers.Dmp.getPagedNotes) @@ -104,7 +107,7 @@ public class PublicDmpsDocumentation { List data = query.collectAs(lookup.getProject()); List models = this.builderFactory.builder(DmpBuilder.class).build(lookup.getProject(), data); DataTableData dataTableData = new DataTableData<>(); - dataTableData.setData(models.stream().map(this.dmpToPublicApiDmpListingMapper::toPublicListingModel).toList()); + dataTableData.setData(models.stream().map(x-> this.dmpToPublicApiDmpListingMapper.toPublicListingModel(x, this.config.getReferenceTypeMap())).toList()); dataTableData.setTotalCount(count); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTableData)); } @@ -125,7 +128,8 @@ public class PublicDmpsDocumentation { String.join(".", Dmp._dmpUsers, DmpUser._role), String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._id), String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._type), - String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._reference), + String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._type), + String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._type, ReferenceType._id), String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._label), String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._definition, Definition._fields, Field._code), String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._definition, Definition._fields, Field._dataType), @@ -173,6 +177,7 @@ public class PublicDmpsDocumentation { String.join(".", Dmp._dmpUsers, DmpUser._role), String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._id), String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._type), + String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._type, ReferenceType._id), String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._reference), String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._label), String.join(".", Dmp._dmpReferences, DmpReference._reference, Reference._abbreviation), @@ -193,7 +198,7 @@ public class PublicDmpsDocumentation { BaseFieldSet templateFieldSet = new BaseFieldSet(); DmpDescriptionTemplateQuery dmpDescriptionTemplateQuery = this.queryFactory.query(DmpDescriptionTemplateQuery.class).dmpIds(UUID.fromString(id)).isActive(IsActive.Active); List descriptionTemplates = this.builderFactory.builder(DmpDescriptionTemplateBuilder.class).build(templateFieldSet, dmpDescriptionTemplateQuery.collectAs(templateFieldSet)); - DataManagementPlanPublicModel dataManagementPlan = this.dmpToPublicApiDmpMapper.toPublicModel(model, entityDoiQuery.collect(), descriptionTemplates); + DataManagementPlanPublicModel dataManagementPlan = this.dmpToPublicApiDmpMapper.toPublicModel(model, entityDoiQuery.collect(), descriptionTemplates, this.config.getReferenceTypeMap()); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); } diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ReferenceController.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ReferenceController.java index 23e1bc185..f9bde0744 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ReferenceController.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ReferenceController.java @@ -93,19 +93,8 @@ public class ReferenceController { return new QueryResult<>(models, count); } + @PostMapping("search") - public List searchReference(@RequestBody ReferenceSearchLookup lookup) throws HugeResultSetException, MyNotFoundException, InvalidApplicationException { - logger.debug("search {}", Reference.class.getSimpleName()); - - this.censorFactory.censor(ReferenceCensor.class).censor(lookup.getProject(), null); - List references = this.referenceService.searchReference(lookup); - - this.auditService.track(AuditableAction.Reference_Search, "lookup", lookup); - - return references; - } - - @PostMapping("search-with-db-definition") public List searchReferenceWithDefinition(@RequestBody ReferenceDefinitionSearchLookup lookup) throws HugeResultSetException, MyNotFoundException, InvalidApplicationException { logger.debug("search with db definition {}", Reference.class.getSimpleName()); diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetProfileManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetProfileManager.java index ffdc9e914..060be60f9 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetProfileManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DatasetProfileManager.java @@ -1,7 +1,6 @@ package eu.eudat.logic.managers; import eu.eudat.logic.proxy.config.configloaders.ConfigLoader; -import eu.eudat.service.remotefetcher.RemoteFetcherService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -20,12 +19,11 @@ public class DatasetProfileManager { private static final List cache = new ArrayList<>(); private final ConfigLoader configLoader; - private final RemoteFetcherService remoteFetcherService; +// private final RemoteFetcherService remoteFetcherService; @Autowired - public DatasetProfileManager(ConfigLoader configLoader, RemoteFetcherService remoteFetcherService) { + public DatasetProfileManager(ConfigLoader configLoader) { this.configLoader = configLoader; - this.remoteFetcherService = remoteFetcherService; } private static String parseItem(Object item) { if (item instanceof String) { diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ValidationManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ValidationManager.java index e96958ef7..8800ad717 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ValidationManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ValidationManager.java @@ -7,24 +7,25 @@ import org.springframework.stereotype.Component; import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; import eu.eudat.commons.exceptions.HugeResultSetException; -import eu.eudat.service.remotefetcher.RemoteFetcherService; +//import eu.eudat.service.remotefetcher.RemoteFetcherService; @Component public class ValidationManager { - private RemoteFetcherService remoteFetcherService; +// private RemoteFetcherService remoteFetcherService; private final UserScope userScope; @Autowired - public ValidationManager(RemoteFetcherService remoteFetcherService, UserScope userScope) { + public ValidationManager(UserScope userScope) { super(); - this.remoteFetcherService = remoteFetcherService; +// this.remoteFetcherService = remoteFetcherService; this.userScope = userScope; } public Boolean validateIdentifier(String identifier, String type) throws MyNotFoundException, HugeResultSetException { ExternalReferenceCriteria externalReferenceCriteria = new ExternalReferenceCriteria(identifier); - Integer count = this.remoteFetcherService.countEntries(externalReferenceCriteria, type); +// Integer count = this.remoteFetcherService.countEntries(externalReferenceCriteria, type); + Integer count = 1; return this.userScope.isSet() && count > 0; } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/ExternalValidationService.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/ExternalValidationService.java index e91ae4bfb..eed16a8d7 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/ExternalValidationService.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/ExternalValidationService.java @@ -3,7 +3,7 @@ package eu.eudat.logic.services; import eu.eudat.commons.scope.user.UserScope; import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; import eu.eudat.commons.exceptions.HugeResultSetException; -import eu.eudat.service.remotefetcher.RemoteFetcherService; +//import eu.eudat.service.remotefetcher.RemoteFetcherService; import gr.cite.tools.exception.MyNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -11,19 +11,20 @@ import org.springframework.stereotype.Service; @Service public class ExternalValidationService { - private RemoteFetcherService remoteFetcherService; +// private RemoteFetcherService remoteFetcherService; private final UserScope userScope; @Autowired - public ExternalValidationService(RemoteFetcherService remoteFetcherService, UserScope userScope) { + public ExternalValidationService(UserScope userScope) { super(); - this.remoteFetcherService = remoteFetcherService; +// this.remoteFetcherService = remoteFetcherService; this.userScope = userScope; } public Boolean validateIdentifier(String identifier, String type) throws MyNotFoundException, HugeResultSetException { ExternalReferenceCriteria externalReferenceCriteria = new ExternalReferenceCriteria(identifier); - Integer count = this.remoteFetcherService.countEntries(externalReferenceCriteria, type); +// Integer count = this.remoteFetcherService.countEntries(externalReferenceCriteria, type); + Integer count = 1; return userScope.isSet() && count > 0; } diff --git a/dmp-backend/web/src/main/resources/config/application.yml b/dmp-backend/web/src/main/resources/config/application.yml index dc7b597ee..a60b25ebf 100644 --- a/dmp-backend/web/src/main/resources/config/application.yml +++ b/dmp-backend/web/src/main/resources/config/application.yml @@ -29,5 +29,7 @@ spring: optional:classpath:config/queue.yml[.yml], optional:classpath:config/queue-${spring.profiles.active}.yml[.yml], optional:file:../config/queue-${spring.profiles.active}.yml[.yml], optional:classpath:config/notification.yml[.yml], optional:classpath:config/notification-${spring.profiles.active}.yml[.yml], optional:file:../config/notification-${spring.profiles.active}.yml[.yml], optional:classpath:config/locale.yml[.yml], optional:classpath:config/locale-${spring.profiles.active}.yml[.yml], optional:file:../config/locale-${spring.profiles.active}.yml[.yml], + optional:classpath:config/public-api.yml[.yml], optional:classpath:config/public-api-${spring.profiles.active}.yml[.yml], optional:file:../config/public-api-${spring.profiles.active}.yml[.yml], + optional:classpath:config/dashboard.yml[.yml], optional:classpath:config/dashboard-${spring.profiles.active}.yml[.yml], optional:file:../config/dashboard-${spring.profiles.active}.yml[.yml], optional:classpath:config/transformer.yml[.yml], optional:classpath:config/transformer-${spring.profiles.active}.yml[.yml], optional:file:../config/transformer-${spring.profiles.active}.yml[.yml] diff --git a/dmp-backend/web/src/main/resources/config/dashboard.yml b/dmp-backend/web/src/main/resources/config/dashboard.yml new file mode 100644 index 000000000..ed280bb46 --- /dev/null +++ b/dmp-backend/web/src/main/resources/config/dashboard.yml @@ -0,0 +1,4 @@ +dashboard: + reference-type-counters: + - "7eeffb98-58fb-4921-82ec-e27f32f8e738" + - "5b9c284f-f041-4995-96cc-fad7ad13289c" \ No newline at end of file diff --git a/dmp-backend/web/src/main/resources/config/permissions.yml b/dmp-backend/web/src/main/resources/config/permissions.yml index e4f2ac7dc..d4ebb62a7 100644 --- a/dmp-backend/web/src/main/resources/config/permissions.yml +++ b/dmp-backend/web/src/main/resources/config/permissions.yml @@ -90,6 +90,11 @@ permissions: clients: [ ] allowAnonymous: true allowAuthenticated: true + PublicBrowseReferenceType: + roles: [ ] + clients: [ ] + allowAnonymous: true + allowAuthenticated: true # Elastic ManageElastic: roles: diff --git a/dmp-backend/web/src/main/resources/config/public-api.yml b/dmp-backend/web/src/main/resources/config/public-api.yml new file mode 100644 index 000000000..de7b59e8f --- /dev/null +++ b/dmp-backend/web/src/main/resources/config/public-api.yml @@ -0,0 +1,10 @@ +public-api: + reference-type-map: + funderTypeId: "538928bb-c7c6-452e-b66d-08e539f5f082" + grantTypeId: "5b9c284f-f041-4995-96cc-fad7ad13289c" + registryTypeId: "2beacaad-3223-43ad-ad99-1e5f21328e7b" + serviceTypeId: "9ec2000d-95c7-452e-b356-755fc8e2574c" + dataRepositoryTypeId: "d26b64ba-fda0-4b14-b3ef-9856a492d55a" + datasetTypeId: "a3ce0fb2-d72c-48bb-b322-7401940cb802" + researcherTypeId: "5a2112e7-ea99-4cfe-98a1-68665e26726e" + organizationTypeId: "7eeffb98-58fb-4921-82ec-e27f32f8e738" \ No newline at end of file From 87dd56ff2c442e3b6c11078af39ac0cd0bf44a1a Mon Sep 17 00:00:00 2001 From: sgiannopoulos Date: Thu, 8 Feb 2024 18:27:54 +0200 Subject: [PATCH 2/5] reference type refactor --- .../enums/DmpBlueprintFieldCategory.java | 4 +-- ...ity.java => ReferenceTypeFieldEntity.java} | 2 +- .../types/dmpblueprint/SectionEntity.java | 2 +- ...va => ReferenceTypeFieldImportExport.java} | 2 +- .../importexport/SectionImportExport.java | 6 ++-- .../ReferenceFieldBuilder.java | 31 ++++++++++++++----- .../SectionBuilder.java | 3 +- .../DmpBlueprintFileTransformerBuilder.java | 7 +---- .../ReferenceField.java | 17 ---------- .../ReferenceTypeField.java | 19 ++++++++++++ ...st.java => ReferenceTypeFieldPersist.java} | 12 +++---- .../SectionPersist.java | 6 ++-- ...ava => DashboardServiceConfiguration.java} | 2 +- .../eu/eudat/service/dmp/DmpServiceImpl.java | 6 ++-- .../dmpblueprint/DmpBlueprintServiceImpl.java | 24 +++++++------- 15 files changed, 76 insertions(+), 67 deletions(-) rename dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/{ReferenceFieldEntity.java => ReferenceTypeFieldEntity.java} (89%) rename dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/{ReferenceFieldImportExport.java => ReferenceTypeFieldImportExport.java} (97%) delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceField.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceTypeField.java rename dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/{ReferenceFieldPersist.java => ReferenceTypeFieldPersist.java} (75%) rename dmp-backend/core/src/main/java/eu/eudat/service/dashborad/{PublicApiConfiguration.java => DashboardServiceConfiguration.java} (85%) diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintFieldCategory.java b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintFieldCategory.java index 611b92281..16c93f5f6 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintFieldCategory.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/DmpBlueprintFieldCategory.java @@ -8,12 +8,12 @@ import java.util.Map; public enum DmpBlueprintFieldCategory implements DatabaseEnum { System((short) 0), Extra((short) 1), - Reference((short) 1); + ReferenceType((short) 1); public static class Names { public static final String System = "system"; public static final String Extra = "extra"; - public static final String Reference = "reference"; + public static final String ReferenceType = "referenceType"; } private final Short value; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/ReferenceFieldEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/ReferenceTypeFieldEntity.java similarity index 89% rename from dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/ReferenceFieldEntity.java rename to dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/ReferenceTypeFieldEntity.java index aff2ac1d2..f4b1658cd 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/ReferenceFieldEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/ReferenceTypeFieldEntity.java @@ -7,7 +7,7 @@ import jakarta.xml.bind.annotation.XmlAttribute; import java.util.UUID; @XmlAccessorType(XmlAccessType.FIELD) -public class ReferenceFieldEntity extends FieldEntity { +public class ReferenceTypeFieldEntity extends FieldEntity { @XmlAttribute(name="referenceTypeId") private UUID referenceTypeId; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SectionEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SectionEntity.java index 100266770..39767a2cb 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SectionEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/SectionEntity.java @@ -26,7 +26,7 @@ public class SectionEntity { @XmlElements({ @XmlElement(name = DmpBlueprintFieldCategory.Names.Extra, type = ExtraFieldEntity.class), @XmlElement(name = DmpBlueprintFieldCategory.Names.System, type = SystemFieldEntity.class), - @XmlElement(name = DmpBlueprintFieldCategory.Names.Reference, type = ReferenceFieldEntity.class), + @XmlElement(name = DmpBlueprintFieldCategory.Names.ReferenceType, type = ReferenceTypeFieldEntity.class), }) private List fields; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/ReferenceFieldImportExport.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/ReferenceTypeFieldImportExport.java similarity index 97% rename from dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/ReferenceFieldImportExport.java rename to dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/ReferenceTypeFieldImportExport.java index 05ae2e63b..969819957 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/ReferenceFieldImportExport.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/ReferenceTypeFieldImportExport.java @@ -7,7 +7,7 @@ import jakarta.xml.bind.annotation.XmlAttribute; import java.util.UUID; @XmlAccessorType(XmlAccessType.FIELD) -public class ReferenceFieldImportExport { +public class ReferenceTypeFieldImportExport { @XmlAttribute(name = "id") private UUID id; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/SectionImportExport.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/SectionImportExport.java index 641405acf..7f5688a17 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/SectionImportExport.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/dmpblueprint/importexport/SectionImportExport.java @@ -24,7 +24,7 @@ public class SectionImportExport { private List extraFields; @XmlElementWrapper(name = "referenceFields") @XmlElement(name = "referenceField") - private List referenceFields; + private List referenceFields; @XmlAttribute(name = "hasTemplates") private boolean hasTemplates; @XmlElementWrapper(name = "descriptionTemplates") @@ -79,11 +79,11 @@ public class SectionImportExport { this.extraFields = extraFields; } - public List getReferenceFields() { + public List getReferenceFields() { return referenceFields; } - public void setReferenceFields(List referenceFields) { + public void setReferenceFields(List referenceFields) { this.referenceFields = referenceFields; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/ReferenceFieldBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/ReferenceFieldBuilder.java index bc7714d42..396ae4d33 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/ReferenceFieldBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/ReferenceFieldBuilder.java @@ -1,8 +1,16 @@ package eu.eudat.model.builder.dmpblueprintdefinition; -import eu.eudat.commons.types.dmpblueprint.ReferenceFieldEntity; +import eu.eudat.commons.types.dmpblueprint.ReferenceTypeFieldEntity; import eu.eudat.convention.ConventionService; -import eu.eudat.model.dmpblueprintdefinition.ReferenceField; +import eu.eudat.model.Dmp; +import eu.eudat.model.PublicReferenceType; +import eu.eudat.model.builder.PublicReferenceTypeBuilder; +import eu.eudat.model.builder.ReferenceTypeBuilder; +import eu.eudat.model.dmpblueprintdefinition.ReferenceTypeField; +import eu.eudat.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; @@ -13,20 +21,27 @@ import org.springframework.stereotype.Component; @Component @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class ReferenceFieldBuilder extends FieldBuilder { +public class ReferenceFieldBuilder extends FieldBuilder { + private final QueryFactory queryFactory; + + private final BuilderFactory builderFactory; @Autowired public ReferenceFieldBuilder( - ConventionService conventionService) { + ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory) { super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceFieldBuilder.class))); + this.queryFactory = queryFactory; + this.builderFactory = builderFactory; } - protected ReferenceField getInstance() { - return new ReferenceField(); + protected ReferenceTypeField getInstance() { + return new ReferenceTypeField(); } - protected ReferenceField buildChild(FieldSet fields, ReferenceFieldEntity data, ReferenceField model) { - if (fields.hasField(this.asIndexer(ReferenceField._referenceTypeId))) model.setReferenceTypeId(data.getReferenceTypeId()); + 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 return model; } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/SectionBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/SectionBuilder.java index 3af4ee3b7..0c3e20314 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/SectionBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/dmpblueprintdefinition/SectionBuilder.java @@ -18,7 +18,6 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.*; -import java.util.stream.Collectors; @Component("dmpblueprintdefinitionsectionbuilder") @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) @@ -65,7 +64,7 @@ public class SectionBuilder extends BaseBuilder { 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.Reference.equals(x.getCategory())).map(x-> (ReferenceFieldEntity)x).toList(); + 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)); } models.add(m); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DmpBlueprintFileTransformerBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DmpBlueprintFileTransformerBuilder.java index f7099d02e..9e07b29f9 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DmpBlueprintFileTransformerBuilder.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/builder/filetransformer/DmpBlueprintFileTransformerBuilder.java @@ -6,16 +6,11 @@ import eu.eudat.commons.JsonHandlingService; import eu.eudat.commons.XmlHandlingService; import eu.eudat.commons.types.dmpblueprint.*; import eu.eudat.convention.ConventionService; -import eu.eudat.data.DescriptionTemplateEntity; import eu.eudat.data.DmpBlueprintEntity; import eu.eudat.file.transformer.enums.DmpBlueprintExtraFieldDataType; -import eu.eudat.file.transformer.enums.DmpBlueprintFieldCategory; import eu.eudat.file.transformer.enums.DmpBlueprintSystemFieldType; -import eu.eudat.file.transformer.models.descriptiontemplate.DescriptionTemplateFileTransformerModel; import eu.eudat.file.transformer.models.dmpblueprint.DmpBlueprintFileTransformerModel; import eu.eudat.file.transformer.models.dmpblueprint.definition.*; -import eu.eudat.model.dmpblueprintdefinition.*; -import eu.eudat.query.DescriptionTemplateQuery; import eu.eudat.query.DmpBlueprintQuery; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.query.QueryFactory; @@ -111,7 +106,7 @@ public class DmpBlueprintFileTransformerBuilder extends BaseFileTransformerBuild FieldFileTransformerModel m = switch (fieldEntity.getCategory()) { case System -> new SystemFieldFileTransformerModel(); case Extra -> new ExtraFieldFileTransformerModelFileTransformerModel(); - case Reference -> throw new NotImplementedException("ReferenceFieldFileTransformerModel"); + case ReferenceType -> throw new NotImplementedException("ReferenceFieldFileTransformerModel"); default -> throw new MyApplicationException("unrecognized type " + fieldEntity.getCategory()); }; m.setId(fieldEntity.getId()); diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceField.java b/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceField.java deleted file mode 100644 index 51ba03a06..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceField.java +++ /dev/null @@ -1,17 +0,0 @@ -package eu.eudat.model.dmpblueprintdefinition; - -import java.util.UUID; - -public class ReferenceField extends Field { - - public final static String _referenceTypeId = "referenceTypeId"; - private UUID referenceTypeId; - - public UUID getReferenceTypeId() { - return referenceTypeId; - } - - public void setReferenceTypeId(UUID referenceTypeId) { - this.referenceTypeId = referenceTypeId; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceTypeField.java b/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceTypeField.java new file mode 100644 index 000000000..bb0fd723e --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/dmpblueprintdefinition/ReferenceTypeField.java @@ -0,0 +1,19 @@ +package eu.eudat.model.dmpblueprintdefinition; + +import eu.eudat.model.ReferenceType; + +import java.util.UUID; + +public class ReferenceTypeField extends Field { + + public final static String _referenceType = "referenceTypeId"; + private ReferenceType referenceType; + + public ReferenceType getReferenceType() { + return referenceType; + } + + public void setReferenceType(ReferenceType referenceType) { + this.referenceType = referenceType; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/ReferenceFieldPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/ReferenceTypeFieldPersist.java similarity index 75% rename from dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/ReferenceFieldPersist.java rename to dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/ReferenceTypeFieldPersist.java index 0c3bb02d9..c5c6b4c15 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/ReferenceFieldPersist.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/ReferenceTypeFieldPersist.java @@ -12,7 +12,7 @@ import org.springframework.stereotype.Component; import java.util.List; import java.util.UUID; -public class ReferenceFieldPersist extends FieldPersist { +public class ReferenceTypeFieldPersist extends FieldPersist { private UUID referenceTypeId; @@ -28,7 +28,7 @@ public class ReferenceFieldPersist extends FieldPersist { @Component(ReferenceFieldPersistPersistValidator.ValidatorName) @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class ReferenceFieldPersistPersistValidator extends BaseFieldPersistValidator { + public static class ReferenceFieldPersistPersistValidator extends BaseFieldPersistValidator { public static final String ValidatorName = "DmpBlueprint.ReferenceFieldPersistPersistValidator"; @@ -37,17 +37,17 @@ public class ReferenceFieldPersist extends FieldPersist { } @Override - protected Class modelClass() { - return ReferenceFieldPersist.class; + protected Class modelClass() { + return ReferenceTypeFieldPersist.class; } @Override - protected List specifications(ReferenceFieldPersist item) { + protected List specifications(ReferenceTypeFieldPersist item) { List specifications = getBaseSpecifications(item); specifications.add( this.spec() .must(() -> !this.isNull(item.getReferenceTypeId())) - .failOn(ReferenceFieldPersist._referenceTypeId).failWith(messageSource.getMessage("Validation_Required", new Object[]{ReferenceFieldPersist._referenceTypeId}, LocaleContextHolder.getLocale())) + .failOn(ReferenceTypeFieldPersist._referenceTypeId).failWith(messageSource.getMessage("Validation_Required", new Object[]{ReferenceTypeFieldPersist._referenceTypeId}, LocaleContextHolder.getLocale())) ); return specifications; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SectionPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SectionPersist.java index 84fa1c41b..4a6eee0bc 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SectionPersist.java +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/dmpblueprintdefinition/SectionPersist.java @@ -1,6 +1,5 @@ package eu.eudat.model.persist.dmpblueprintdefinition; -import eu.eudat.commons.enums.DmpBlueprintFieldCategory; import eu.eudat.commons.validation.BaseValidator; import gr.cite.tools.exception.MyApplicationException; import gr.cite.tools.validation.ValidatorFactory; @@ -14,7 +13,6 @@ import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Component; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; @@ -154,8 +152,8 @@ public class SectionPersist { case System -> { return this.validatorFactory.validator(SystemFieldPersist.SystemFieldPersistValidator.class); } - case Reference -> { - return this.validatorFactory.validator(ReferenceFieldPersist.ReferenceFieldPersistPersistValidator.class); + case ReferenceType -> { + return this.validatorFactory.validator(ReferenceTypeFieldPersist.ReferenceFieldPersistPersistValidator.class); } default -> throw new MyApplicationException("unrecognized type " + ((FieldPersist) itm).getCategory()); } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/PublicApiConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/DashboardServiceConfiguration.java similarity index 85% rename from dmp-backend/core/src/main/java/eu/eudat/service/dashborad/PublicApiConfiguration.java rename to dmp-backend/core/src/main/java/eu/eudat/service/dashborad/DashboardServiceConfiguration.java index 19984991e..ae2afa317 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/PublicApiConfiguration.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/dashborad/DashboardServiceConfiguration.java @@ -5,6 +5,6 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties(DashboardServiceProperties.class) -public class PublicApiConfiguration { +public class DashboardServiceConfiguration { } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java index 90ddefd11..8e44298e1 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/dmp/DmpServiceImpl.java @@ -12,7 +12,7 @@ import eu.eudat.commons.types.actionconfirmation.DmpInvitationEntity; import eu.eudat.commons.types.dmp.DmpBlueprintValueEntity; import eu.eudat.commons.types.dmp.DmpContactEntity; import eu.eudat.commons.types.dmp.DmpPropertiesEntity; -import eu.eudat.commons.types.dmpblueprint.ReferenceFieldEntity; +import eu.eudat.commons.types.dmpblueprint.ReferenceTypeFieldEntity; import eu.eudat.commons.types.dmpreference.DmpReferenceDataEntity; import eu.eudat.commons.types.notification.*; import eu.eudat.commons.types.reference.DefinitionEntity; @@ -650,8 +650,8 @@ public class DmpServiceImpl implements DmpService { referenceEntity = this.entityManager.find(ReferenceEntity.class, referencePersist.getId()); if (referenceEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{referencePersist.getId(), Reference.class.getSimpleName()}, LocaleContextHolder.getLocale())); } else { - ReferenceFieldEntity fieldEntity = blueprintDefinition.getFieldById(model.getData().getBlueprintFieldId()).stream().filter(x-> x.getCategory().equals(DmpBlueprintFieldCategory.Reference)).map(x-> (ReferenceFieldEntity)x).findFirst().orElse(null); - if (fieldEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getData().getBlueprintFieldId(), ReferenceFieldEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); + ReferenceTypeFieldEntity fieldEntity = blueprintDefinition.getFieldById(model.getData().getBlueprintFieldId()).stream().filter(x-> x.getCategory().equals(DmpBlueprintFieldCategory.ReferenceType)).map(x-> (ReferenceTypeFieldEntity)x).findFirst().orElse(null); + if (fieldEntity == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getData().getBlueprintFieldId(), ReferenceTypeFieldEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); referenceEntity = this.queryFactory.query(ReferenceQuery.class).sourceTypes(referencePersist.getSourceType()).typeIds(fieldEntity.getReferenceTypeId()).sources(referencePersist.getSource()).isActive(IsActive.Active).references(referencePersist.getReference()).first(); if (referenceEntity == null){ diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/dmpblueprint/DmpBlueprintServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/dmpblueprint/DmpBlueprintServiceImpl.java index 19d07b834..3f04c8499 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/dmpblueprint/DmpBlueprintServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/dmpblueprint/DmpBlueprintServiceImpl.java @@ -262,9 +262,9 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService { dataTyped.setType(((SystemFieldPersist) persist).getSystemFieldType()); data = dataTyped; } - case Reference -> { - ReferenceFieldEntity dataTyped = new ReferenceFieldEntity(); - dataTyped.setReferenceTypeId(((ReferenceFieldPersist) persist).getReferenceTypeId()); + case ReferenceType -> { + ReferenceTypeFieldEntity dataTyped = new ReferenceTypeFieldEntity(); + dataTyped.setReferenceTypeId(((ReferenceTypeFieldPersist) persist).getReferenceTypeId()); data = dataTyped; } default -> throw new InternalError("unknown type: " + persist.getCategory()); @@ -490,10 +490,10 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService { } xml.setExtraFields(dmpBlueprintExtraFieldModels); - List dmpBlueprintReferenceFieldModels = new LinkedList<>(); + List dmpBlueprintReferenceFieldModels = new LinkedList<>(); if (!this.conventionService.isListNullOrEmpty(entity.getFields())) { - for (ReferenceFieldEntity referenceFieldEntity : entity.getFields().stream().filter(x -> x.getCategory() == DmpBlueprintFieldCategory.Reference).map(x -> (ReferenceFieldEntity) x).toList()) { - dmpBlueprintReferenceFieldModels.add(this.referenceFieldXmlToExport(referenceFieldEntity)); + for (ReferenceTypeFieldEntity referenceTypeFieldEntity : entity.getFields().stream().filter(x -> x.getCategory() == DmpBlueprintFieldCategory.ReferenceType).map(x -> (ReferenceTypeFieldEntity) x).toList()) { + dmpBlueprintReferenceFieldModels.add(this.referenceFieldXmlToExport(referenceTypeFieldEntity)); } } xml.setReferenceFields(dmpBlueprintReferenceFieldModels); @@ -529,8 +529,8 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService { return xml; } - private ReferenceFieldImportExport referenceFieldXmlToExport(ReferenceFieldEntity entity) { - ReferenceFieldImportExport xml = new ReferenceFieldImportExport(); + private ReferenceTypeFieldImportExport referenceFieldXmlToExport(ReferenceTypeFieldEntity entity) { + ReferenceTypeFieldImportExport xml = new ReferenceTypeFieldImportExport(); xml.setId(entity.getId()); xml.setReferenceTypeId(entity.getReferenceTypeId()); xml.setLabel(entity.getLabel()); @@ -603,7 +603,7 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService { } } if (!this.conventionService.isListNullOrEmpty(importXml.getReferenceFields())) { - for (ReferenceFieldImportExport referenceField : importXml.getReferenceFields()) { + for (ReferenceTypeFieldImportExport referenceField : importXml.getReferenceFields()) { dmpBlueprintFieldModels.add(this.xmlReferenceFieldToPersist(referenceField)); } } @@ -658,10 +658,10 @@ public class DmpBlueprintServiceImpl implements DmpBlueprintService { return persist; } - private FieldPersist xmlReferenceFieldToPersist(ReferenceFieldImportExport importXml) { - ReferenceFieldPersist persist = new ReferenceFieldPersist(); + private FieldPersist xmlReferenceFieldToPersist(ReferenceTypeFieldImportExport importXml) { + ReferenceTypeFieldPersist persist = new ReferenceTypeFieldPersist(); persist.setId(importXml.getId()); - persist.setCategory(DmpBlueprintFieldCategory.Reference); + persist.setCategory(DmpBlueprintFieldCategory.ReferenceType); persist.setReferenceTypeId(importXml.getReferenceTypeId()); persist.setLabel(importXml.getLabel()); persist.setPlaceholder(importXml.getPlaceholder()); From 80096e9164974d531fe038b713cfadeb90609298 Mon Sep 17 00:00:00 2001 From: Thomas Georgios Giannos Date: Fri, 9 Feb 2024 13:24:23 +0200 Subject: [PATCH 3/5] Refactoring public api dependencies from 'to be deleted' data and queryable modules --- .../dao/criteria/DatasetPublicCriteria.java | 69 ------------------- .../dataset/DatasetPublicTableRequest.java | 58 ---------------- .../eu/eudat/types/grant/GrantStateType.java | 29 -------- .../controllers/publicapi}/QueryableList.java | 7 +- .../publicapi}/collector/Collector.java | 5 +- .../publicapi}/collector/ProjectionField.java | 3 +- .../publicapi}/criteria/Criteria.java | 2 +- .../dataset/DatasetPublicCriteria.java | 2 +- .../dmp/DataManagementPlanPublicCriteria.java | 2 +- .../exceptions/NotSingleResultException.java | 2 +- .../QueryableHibernateList.java | 14 ++-- .../jpa/predicates/EntitySelectPredicate.java | 3 +- .../jpa/predicates/GroupByPredicate.java | 2 +- .../NestedQuerySinglePredicate.java | 2 +- .../jpa/predicates/OrderByPredicate.java | 2 +- .../jpa/predicates/QueryablePredicate.java | 2 +- .../jpa/predicates/SelectPredicate.java | 2 +- .../jpa/predicates/SinglePredicate.java | 2 +- .../publicapi}/query/PaginationService.java | 10 +-- .../query/definition/Collector.java | 4 +- .../query/definition/CriteriaQuery.java | 6 +- .../publicapi}/query/definition/Query.java | 6 +- .../query/definition/TableCriteriaQuery.java | 6 +- .../query/definition/TableQuery.java | 10 +-- .../definition/helpers/ColumnOrderings.java | 2 +- .../query/definition/helpers/Ordering.java | 2 +- .../definition/helpers/SelectionFields.java | 2 +- .../dataset/DatasetPublicTableRequest.java | 8 +-- .../DataManagmentPlanPublicTableRequest.java | 10 +-- .../publicapi}/types/FieldSelectionType.java | 2 +- .../publicapi}/types/SelectionField.java | 2 +- 31 files changed, 60 insertions(+), 218 deletions(-) delete mode 100644 dmp-backend/data/src/main/java/eu/eudat/data/dao/criteria/DatasetPublicCriteria.java delete mode 100644 dmp-backend/data/src/main/java/eu/eudat/data/query/items/table/dataset/DatasetPublicTableRequest.java delete mode 100644 dmp-backend/data/src/main/java/eu/eudat/types/grant/GrantStateType.java rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/QueryableList.java (94%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/collector/Collector.java (93%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/collector/ProjectionField.java (98%) rename dmp-backend/{data/src/main/java/eu/eudat/data/dao => web/src/main/java/eu/eudat/controllers/publicapi}/criteria/Criteria.java (88%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/exceptions/NotSingleResultException.java (88%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/jpa/hibernatequeryablelist/QueryableHibernateList.java (98%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/jpa/predicates/EntitySelectPredicate.java (73%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/jpa/predicates/GroupByPredicate.java (82%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/jpa/predicates/NestedQuerySinglePredicate.java (85%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/jpa/predicates/OrderByPredicate.java (81%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/jpa/predicates/QueryablePredicate.java (61%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/jpa/predicates/SelectPredicate.java (57%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/jpa/predicates/SinglePredicate.java (86%) rename dmp-backend/{data/src/main/java/eu/eudat/data => web/src/main/java/eu/eudat/controllers/publicapi}/query/PaginationService.java (89%) rename dmp-backend/{data/src/main/java/eu/eudat/data => web/src/main/java/eu/eudat/controllers/publicapi}/query/definition/Collector.java (64%) rename dmp-backend/{data/src/main/java/eu/eudat/data => web/src/main/java/eu/eudat/controllers/publicapi}/query/definition/CriteriaQuery.java (50%) rename dmp-backend/{data/src/main/java/eu/eudat/data => web/src/main/java/eu/eudat/controllers/publicapi}/query/definition/Query.java (91%) rename dmp-backend/{data/src/main/java/eu/eudat/data => web/src/main/java/eu/eudat/controllers/publicapi}/query/definition/TableCriteriaQuery.java (54%) rename dmp-backend/{data/src/main/java/eu/eudat/data => web/src/main/java/eu/eudat/controllers/publicapi}/query/definition/TableQuery.java (81%) rename dmp-backend/{data/src/main/java/eu/eudat/data => web/src/main/java/eu/eudat/controllers/publicapi}/query/definition/helpers/ColumnOrderings.java (96%) rename dmp-backend/{data/src/main/java/eu/eudat/data => web/src/main/java/eu/eudat/controllers/publicapi}/query/definition/helpers/Ordering.java (94%) rename dmp-backend/{data/src/main/java/eu/eudat/data => web/src/main/java/eu/eudat/controllers/publicapi}/query/definition/helpers/SelectionFields.java (84%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/types/FieldSelectionType.java (72%) rename dmp-backend/{queryable/src/main/java/eu/eudat/queryable => web/src/main/java/eu/eudat/controllers/publicapi}/types/SelectionField.java (93%) diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/dao/criteria/DatasetPublicCriteria.java b/dmp-backend/data/src/main/java/eu/eudat/data/dao/criteria/DatasetPublicCriteria.java deleted file mode 100644 index 10b5bd3c9..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/data/dao/criteria/DatasetPublicCriteria.java +++ /dev/null @@ -1,69 +0,0 @@ -package eu.eudat.data.dao.criteria; - -import eu.eudat.data.DescriptionEntity; -import eu.eudat.types.grant.GrantStateType; - -import java.util.List; -import java.util.UUID; - -/** - * Created by ikalyvas on 10/2/2018. - */ -public class DatasetPublicCriteria extends Criteria{ - private GrantStateType grantStatus; - private List grants; - private List datasetProfile; - private List dmpOrganisations; -// private List tags; TODO: - private List dmpIds; - private Integer role; - - public GrantStateType getGrantStatus() { - return grantStatus; - } - public void setGrantStatus(GrantStateType grantStatus) { - this.grantStatus = grantStatus; - } - - public List getGrants() { - return grants; - } - public void setGrants(List grants) { - this.grants = grants; - } - - public List getDatasetProfile() { - return datasetProfile; - } - public void setDatasetProfile(List datasetProfile) { - this.datasetProfile = datasetProfile; - } - - public List getDmpOrganisations() { - return dmpOrganisations; - } - public void setDmpOrganisations(List dmpOrganisations) { - this.dmpOrganisations = dmpOrganisations; - } - -// public List getTags() { -// return tags; -// } -// public void setTags(List tags) { -// this.tags = tags; -// } - - public List getDmpIds() { - return dmpIds; - } - public void setDmpIds(List dmpIds) { - this.dmpIds = dmpIds; - } - - public Integer getRole() { - return role; - } - public void setRole(Integer role) { - this.role = role; - } -} diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/items/table/dataset/DatasetPublicTableRequest.java b/dmp-backend/data/src/main/java/eu/eudat/data/query/items/table/dataset/DatasetPublicTableRequest.java deleted file mode 100644 index 879abf9a7..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/items/table/dataset/DatasetPublicTableRequest.java +++ /dev/null @@ -1,58 +0,0 @@ -package eu.eudat.data.query.items.table.dataset; - -import eu.eudat.commons.enums.DescriptionStatus; -import eu.eudat.commons.enums.IsActive; -import eu.eudat.data.dao.criteria.DatasetPublicCriteria; -import eu.eudat.data.DescriptionEntity; -import eu.eudat.data.query.definition.TableQuery; -import eu.eudat.queryable.QueryableList; -import eu.eudat.queryable.types.FieldSelectionType; -import eu.eudat.queryable.types.SelectionField; -import eu.eudat.types.grant.GrantStateType; - -import java.util.Arrays; -import java.util.Date; -import java.util.UUID; - -/** - * Created by ikalyvas on 10/2/2018. - */ -public class DatasetPublicTableRequest extends TableQuery { - @Override - public QueryableList applyCriteria() { - QueryableList query = this.getQuery(); - query.where((builder, root) -> builder.equal(root.get("dmp").get("isPublic"), true)); - query.where((builder, root) -> builder.equal(root.get("status"), DescriptionStatus.Finalized.getValue())); - query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), - query.subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("dmp").get("groupId"), nestedRoot.get("dmp").get("groupId")), - Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:version")), String.class))); - if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty()) - query.where((builder, root) -> builder.or( - builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"), - builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%"))); - if (this.getCriteria().getGrants() != null && !this.getCriteria().getGrants().isEmpty()) - query.where(((builder, root) -> root.get("dmp").get("grant").get("id").in(this.getCriteria().getGrants()))); - if (this.getCriteria().getGrantStatus() != null) { - if (this.getCriteria().getGrantStatus().getValue().equals(GrantStateType.FINISHED.getValue())) - query.where((builder, root) -> builder.lessThan(root.get("dmp").get("grant").get("enddate"), new Date())); - if (this.getCriteria().getGrantStatus().getValue().equals(GrantStateType.ONGOING.getValue())) - query.where((builder, root) -> - builder.or(builder.greaterThan(root.get("dmp").get("grant").get("enddate"), new Date()) - , builder.isNull(root.get("dmp").get("grant").get("enddate")))); - } - if (this.getCriteria().getDmpIds() != null && !this.getCriteria().getDmpIds().isEmpty()) { - query.where(((builder, root) -> root.get("dmp").get("id").in(this.getCriteria().getDmpIds()))); - } - if (this.getCriteria().getDatasetProfile() != null && !this.getCriteria().getDatasetProfile().isEmpty()) query - .where(((builder, root) -> root.get("profile").get("id").in(this.getCriteria().getDatasetProfile()))); - if (this.getCriteria().getDmpOrganisations() != null && !this.getCriteria().getDmpOrganisations().isEmpty()) query - .where(((builder, root) -> root.join("dmp").join("organisations").get("reference").in(this.getCriteria().getDmpOrganisations()))); - query.where((builder, root) -> builder.notEqual(root.get(DescriptionEntity._isActive), IsActive.Inactive)); - return query; - } - - @Override - public QueryableList applyPaging(QueryableList items) { - return null; - } -} diff --git a/dmp-backend/data/src/main/java/eu/eudat/types/grant/GrantStateType.java b/dmp-backend/data/src/main/java/eu/eudat/types/grant/GrantStateType.java deleted file mode 100644 index 3522d1a90..000000000 --- a/dmp-backend/data/src/main/java/eu/eudat/types/grant/GrantStateType.java +++ /dev/null @@ -1,29 +0,0 @@ -package eu.eudat.types.grant; - -/** - * Created by ikalyvas on 8/24/2018. - */ -public enum GrantStateType { - ONGOING(0), FINISHED(1); - - private Integer value; - - private GrantStateType(Integer value) { - this.value = value; - } - - public Integer getValue() { - return value; - } - - public static GrantStateType fromInteger(Integer value) { - switch (value) { - case 0: - return ONGOING; - case 1: - return FINISHED; - default: - throw new RuntimeException("Unsupported Grant State Type"); - } - } -} diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/QueryableList.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/QueryableList.java similarity index 94% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/QueryableList.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/QueryableList.java index 628c574b2..39af79f64 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/QueryableList.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/QueryableList.java @@ -1,8 +1,7 @@ -package eu.eudat.queryable; - -import eu.eudat.queryable.jpa.predicates.*; -import eu.eudat.queryable.types.SelectionField; +package eu.eudat.controllers.publicapi; +import eu.eudat.controllers.publicapi.jpa.predicates.*; +import eu.eudat.controllers.publicapi.types.SelectionField; import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.Subquery; diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/collector/Collector.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/collector/Collector.java similarity index 93% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/collector/Collector.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/collector/Collector.java index e3b654418..9a30d9731 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/collector/Collector.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/collector/Collector.java @@ -1,8 +1,7 @@ -package eu.eudat.queryable.collector; - -import com.fasterxml.jackson.databind.ObjectMapper; +package eu.eudat.controllers.publicapi.collector; import jakarta.persistence.Tuple; + import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/collector/ProjectionField.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/collector/ProjectionField.java similarity index 98% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/collector/ProjectionField.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/collector/ProjectionField.java index 31e5bd1fd..4baaa22b8 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/collector/ProjectionField.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/collector/ProjectionField.java @@ -1,6 +1,7 @@ -package eu.eudat.queryable.collector; +package eu.eudat.controllers.publicapi.collector; import jakarta.persistence.Tuple; + import java.util.*; import java.util.stream.Collectors; diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/dao/criteria/Criteria.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/criteria/Criteria.java similarity index 88% rename from dmp-backend/data/src/main/java/eu/eudat/data/dao/criteria/Criteria.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/criteria/Criteria.java index 42b693035..7debd0720 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/dao/criteria/Criteria.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/criteria/Criteria.java @@ -1,4 +1,4 @@ -package eu.eudat.data.dao.criteria; +package eu.eudat.controllers.publicapi.criteria; import io.swagger.annotations.ApiModelProperty; diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/criteria/dataset/DatasetPublicCriteria.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/criteria/dataset/DatasetPublicCriteria.java index 76e58a9ec..e98c333b0 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/criteria/dataset/DatasetPublicCriteria.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/criteria/dataset/DatasetPublicCriteria.java @@ -1,6 +1,6 @@ package eu.eudat.controllers.publicapi.criteria.dataset; -import eu.eudat.data.dao.criteria.Criteria; +import eu.eudat.controllers.publicapi.criteria.Criteria; import eu.eudat.data.DescriptionEntity; import io.swagger.annotations.ApiModelProperty; diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/criteria/dmp/DataManagementPlanPublicCriteria.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/criteria/dmp/DataManagementPlanPublicCriteria.java index 0f9c27c7a..b64eeac31 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/criteria/dmp/DataManagementPlanPublicCriteria.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/criteria/dmp/DataManagementPlanPublicCriteria.java @@ -1,7 +1,7 @@ package eu.eudat.controllers.publicapi.criteria.dmp; +import eu.eudat.controllers.publicapi.criteria.Criteria; import eu.eudat.data.DmpEntity; -import eu.eudat.data.dao.criteria.Criteria; import io.swagger.annotations.ApiModelProperty; import java.util.Date; diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/exceptions/NotSingleResultException.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/exceptions/NotSingleResultException.java similarity index 88% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/exceptions/NotSingleResultException.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/exceptions/NotSingleResultException.java index 2ed8bbbcf..0f84cbd9c 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/exceptions/NotSingleResultException.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/exceptions/NotSingleResultException.java @@ -1,4 +1,4 @@ -package eu.eudat.queryable.exceptions; +package eu.eudat.controllers.publicapi.exceptions; public class NotSingleResultException extends RuntimeException { diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/hibernatequeryablelist/QueryableHibernateList.java similarity index 98% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/hibernatequeryablelist/QueryableHibernateList.java index 176ffafed..720dd3570 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/hibernatequeryablelist/QueryableHibernateList.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/hibernatequeryablelist/QueryableHibernateList.java @@ -1,12 +1,12 @@ -package eu.eudat.queryable.jpa.hibernatequeryablelist; +package eu.eudat.controllers.publicapi.jpa.hibernatequeryablelist; import com.fasterxml.jackson.databind.ObjectMapper; -import eu.eudat.queryable.QueryableList; -import eu.eudat.queryable.collector.Collector; -import eu.eudat.queryable.exceptions.NotSingleResultException; -import eu.eudat.queryable.jpa.predicates.*; -import eu.eudat.queryable.types.FieldSelectionType; -import eu.eudat.queryable.types.SelectionField; +import eu.eudat.controllers.publicapi.QueryableList; +import eu.eudat.controllers.publicapi.collector.Collector; +import eu.eudat.controllers.publicapi.exceptions.NotSingleResultException; +import eu.eudat.controllers.publicapi.jpa.predicates.*; +import eu.eudat.controllers.publicapi.types.FieldSelectionType; +import eu.eudat.controllers.publicapi.types.SelectionField; import jakarta.persistence.EntityManager; import jakarta.persistence.Tuple; import jakarta.persistence.TypedQuery; diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/EntitySelectPredicate.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/EntitySelectPredicate.java similarity index 73% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/EntitySelectPredicate.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/EntitySelectPredicate.java index 88ea75067..abd061352 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/EntitySelectPredicate.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/EntitySelectPredicate.java @@ -1,8 +1,7 @@ -package eu.eudat.queryable.jpa.predicates; +package eu.eudat.controllers.publicapi.jpa.predicates; import jakarta.persistence.criteria.Path; import jakarta.persistence.criteria.Root; -import java.util.function.Predicate; /** * Created by ikalyvas on 10/10/2018. diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/GroupByPredicate.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/GroupByPredicate.java similarity index 82% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/GroupByPredicate.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/GroupByPredicate.java index 870a17a40..a56ed50ba 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/GroupByPredicate.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/GroupByPredicate.java @@ -1,4 +1,4 @@ -package eu.eudat.queryable.jpa.predicates; +package eu.eudat.controllers.publicapi.jpa.predicates; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.Expression; diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/NestedQuerySinglePredicate.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/NestedQuerySinglePredicate.java similarity index 85% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/NestedQuerySinglePredicate.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/NestedQuerySinglePredicate.java index e2b8813c1..ef482da1b 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/NestedQuerySinglePredicate.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/NestedQuerySinglePredicate.java @@ -1,4 +1,4 @@ -package eu.eudat.queryable.jpa.predicates; +package eu.eudat.controllers.publicapi.jpa.predicates; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.Predicate; diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/OrderByPredicate.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/OrderByPredicate.java similarity index 81% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/OrderByPredicate.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/OrderByPredicate.java index 8b236fdcf..a76cefc08 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/OrderByPredicate.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/OrderByPredicate.java @@ -1,4 +1,4 @@ -package eu.eudat.queryable.jpa.predicates; +package eu.eudat.controllers.publicapi.jpa.predicates; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.Order; diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/QueryablePredicate.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/QueryablePredicate.java similarity index 61% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/QueryablePredicate.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/QueryablePredicate.java index 288f4d5d5..118b81c46 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/QueryablePredicate.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/QueryablePredicate.java @@ -1,4 +1,4 @@ -package eu.eudat.queryable.jpa.predicates; +package eu.eudat.controllers.publicapi.jpa.predicates; /** * Created by ikalyvas on 2/7/2018. diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/SelectPredicate.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/SelectPredicate.java similarity index 57% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/SelectPredicate.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/SelectPredicate.java index 4b7b60980..238972d3d 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/SelectPredicate.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/SelectPredicate.java @@ -1,4 +1,4 @@ -package eu.eudat.queryable.jpa.predicates; +package eu.eudat.controllers.publicapi.jpa.predicates; public interface SelectPredicate { R applySelection(T item); diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/SinglePredicate.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/SinglePredicate.java similarity index 86% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/SinglePredicate.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/SinglePredicate.java index fbbcb8dbc..fa666b00c 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/jpa/predicates/SinglePredicate.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/jpa/predicates/SinglePredicate.java @@ -1,4 +1,4 @@ -package eu.eudat.queryable.jpa.predicates; +package eu.eudat.controllers.publicapi.jpa.predicates; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.Predicate; diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/PaginationService.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/PaginationService.java similarity index 89% rename from dmp-backend/data/src/main/java/eu/eudat/data/query/PaginationService.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/PaginationService.java index 044a77dfa..3767aa3a7 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/PaginationService.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/PaginationService.java @@ -1,9 +1,9 @@ -package eu.eudat.data.query; +package eu.eudat.controllers.publicapi.query; -import eu.eudat.data.query.definition.TableQuery; -import eu.eudat.data.query.definition.helpers.ColumnOrderings; -import eu.eudat.data.query.definition.helpers.Ordering; -import eu.eudat.queryable.QueryableList; +import eu.eudat.controllers.publicapi.QueryableList; +import eu.eudat.controllers.publicapi.query.definition.TableQuery; +import eu.eudat.controllers.publicapi.query.definition.helpers.ColumnOrderings; +import eu.eudat.controllers.publicapi.query.definition.helpers.Ordering; import java.util.Arrays; import java.util.Collection; diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Collector.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/Collector.java similarity index 64% rename from dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Collector.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/Collector.java index bedd0c8c2..c47bea7e9 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Collector.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/Collector.java @@ -1,6 +1,6 @@ -package eu.eudat.data.query.definition; +package eu.eudat.controllers.publicapi.query.definition; -import eu.eudat.queryable.QueryableList; +import eu.eudat.controllers.publicapi.QueryableList; /** * Created by ikalyvas on 3/21/2018. diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/CriteriaQuery.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/CriteriaQuery.java similarity index 50% rename from dmp-backend/data/src/main/java/eu/eudat/data/query/definition/CriteriaQuery.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/CriteriaQuery.java index 7fbcda3a9..193b7f3cc 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/CriteriaQuery.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/CriteriaQuery.java @@ -1,7 +1,7 @@ -package eu.eudat.data.query.definition; +package eu.eudat.controllers.publicapi.query.definition; -import eu.eudat.data.dao.criteria.Criteria; -import eu.eudat.queryable.QueryableList; +import eu.eudat.controllers.publicapi.QueryableList; +import eu.eudat.controllers.publicapi.criteria.Criteria; /** * Created by ikalyvas on 3/21/2018. diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Query.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/Query.java similarity index 91% rename from dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Query.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/Query.java index 3b9d8c423..52b9e68d9 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/Query.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/Query.java @@ -1,7 +1,7 @@ -package eu.eudat.data.query.definition; +package eu.eudat.controllers.publicapi.query.definition; -import eu.eudat.data.dao.criteria.Criteria; -import eu.eudat.queryable.QueryableList; +import eu.eudat.controllers.publicapi.QueryableList; +import eu.eudat.controllers.publicapi.criteria.Criteria; import io.swagger.annotations.ApiModelProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableCriteriaQuery.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/TableCriteriaQuery.java similarity index 54% rename from dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableCriteriaQuery.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/TableCriteriaQuery.java index 6ae6400c6..9a61ee975 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableCriteriaQuery.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/TableCriteriaQuery.java @@ -1,7 +1,7 @@ -package eu.eudat.data.query.definition; +package eu.eudat.controllers.publicapi.query.definition; -import eu.eudat.data.dao.criteria.Criteria; -import eu.eudat.queryable.QueryableList; +import eu.eudat.controllers.publicapi.QueryableList; +import eu.eudat.controllers.publicapi.criteria.Criteria; /** * Created by ikalyvas on 3/21/2018. diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableQuery.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/TableQuery.java similarity index 81% rename from dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableQuery.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/TableQuery.java index 9eb755d8a..888b3ba3f 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/TableQuery.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/TableQuery.java @@ -1,9 +1,9 @@ -package eu.eudat.data.query.definition; +package eu.eudat.controllers.publicapi.query.definition; -import eu.eudat.data.dao.criteria.Criteria; -import eu.eudat.data.query.definition.helpers.ColumnOrderings; -import eu.eudat.data.query.definition.helpers.SelectionFields; -import eu.eudat.queryable.QueryableList; +import eu.eudat.controllers.publicapi.QueryableList; +import eu.eudat.controllers.publicapi.criteria.Criteria; +import eu.eudat.controllers.publicapi.query.definition.helpers.ColumnOrderings; +import eu.eudat.controllers.publicapi.query.definition.helpers.SelectionFields; import io.swagger.annotations.ApiModelProperty; diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/helpers/ColumnOrderings.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/helpers/ColumnOrderings.java similarity index 96% rename from dmp-backend/data/src/main/java/eu/eudat/data/query/definition/helpers/ColumnOrderings.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/helpers/ColumnOrderings.java index c5587a126..b94aabf47 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/helpers/ColumnOrderings.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/helpers/ColumnOrderings.java @@ -1,4 +1,4 @@ -package eu.eudat.data.query.definition.helpers; +package eu.eudat.controllers.publicapi.query.definition.helpers; import io.swagger.annotations.ApiModelProperty; diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/helpers/Ordering.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/helpers/Ordering.java similarity index 94% rename from dmp-backend/data/src/main/java/eu/eudat/data/query/definition/helpers/Ordering.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/helpers/Ordering.java index 2054f2eb1..2d9a64579 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/helpers/Ordering.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/helpers/Ordering.java @@ -1,4 +1,4 @@ -package eu.eudat.data.query.definition.helpers; +package eu.eudat.controllers.publicapi.query.definition.helpers; public class Ordering { diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/helpers/SelectionFields.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/helpers/SelectionFields.java similarity index 84% rename from dmp-backend/data/src/main/java/eu/eudat/data/query/definition/helpers/SelectionFields.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/helpers/SelectionFields.java index ec41027ec..4445f4c4d 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/query/definition/helpers/SelectionFields.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/query/definition/helpers/SelectionFields.java @@ -1,4 +1,4 @@ -package eu.eudat.data.query.definition.helpers; +package eu.eudat.controllers.publicapi.query.definition.helpers; import io.swagger.annotations.ApiModelProperty; diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/request/dataset/DatasetPublicTableRequest.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/request/dataset/DatasetPublicTableRequest.java index c11b12cf0..979b24fa3 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/request/dataset/DatasetPublicTableRequest.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/request/dataset/DatasetPublicTableRequest.java @@ -2,12 +2,12 @@ package eu.eudat.controllers.publicapi.request.dataset; import eu.eudat.commons.enums.DescriptionStatus; import eu.eudat.commons.enums.IsActive; +import eu.eudat.controllers.publicapi.QueryableList; import eu.eudat.controllers.publicapi.criteria.dataset.DatasetPublicCriteria; +import eu.eudat.controllers.publicapi.query.definition.TableQuery; +import eu.eudat.controllers.publicapi.types.FieldSelectionType; +import eu.eudat.controllers.publicapi.types.SelectionField; import eu.eudat.data.DescriptionEntity; -import eu.eudat.data.query.definition.TableQuery; -import eu.eudat.queryable.QueryableList; -import eu.eudat.queryable.types.FieldSelectionType; -import eu.eudat.queryable.types.SelectionField; import java.util.Arrays; import java.util.Date; diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/request/dmp/DataManagmentPlanPublicTableRequest.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/request/dmp/DataManagmentPlanPublicTableRequest.java index c37848f2d..cd9c4e9f5 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/request/dmp/DataManagmentPlanPublicTableRequest.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/request/dmp/DataManagmentPlanPublicTableRequest.java @@ -1,13 +1,13 @@ package eu.eudat.controllers.publicapi.request.dmp; import eu.eudat.commons.enums.IsActive; +import eu.eudat.controllers.publicapi.QueryableList; import eu.eudat.controllers.publicapi.criteria.dmp.DataManagementPlanPublicCriteria; +import eu.eudat.controllers.publicapi.query.PaginationService; +import eu.eudat.controllers.publicapi.query.definition.TableQuery; +import eu.eudat.controllers.publicapi.types.FieldSelectionType; +import eu.eudat.controllers.publicapi.types.SelectionField; import eu.eudat.data.DmpEntity; -import eu.eudat.data.query.PaginationService; -import eu.eudat.data.query.definition.TableQuery; -import eu.eudat.queryable.QueryableList; -import eu.eudat.queryable.types.FieldSelectionType; -import eu.eudat.queryable.types.SelectionField; import jakarta.persistence.criteria.Predicate; import java.util.*; diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/types/FieldSelectionType.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/types/FieldSelectionType.java similarity index 72% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/types/FieldSelectionType.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/types/FieldSelectionType.java index cf4039d75..6b0d5b5cb 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/types/FieldSelectionType.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/types/FieldSelectionType.java @@ -1,4 +1,4 @@ -package eu.eudat.queryable.types; +package eu.eudat.controllers.publicapi.types; /** * Created by ikalyvas on 2/7/2018. diff --git a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/types/SelectionField.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/types/SelectionField.java similarity index 93% rename from dmp-backend/queryable/src/main/java/eu/eudat/queryable/types/SelectionField.java rename to dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/types/SelectionField.java index 7cef18e0d..3be5f8f06 100644 --- a/dmp-backend/queryable/src/main/java/eu/eudat/queryable/types/SelectionField.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/publicapi/types/SelectionField.java @@ -1,4 +1,4 @@ -package eu.eudat.queryable.types; +package eu.eudat.controllers.publicapi.types; /** * Created by ikalyvas on 2/7/2018. From 9f5002802bc2b2713901ff300d523c9fc3d4feb6 Mon Sep 17 00:00:00 2001 From: Diamantis Tziotzios Date: Fri, 9 Feb 2024 22:46:05 +0200 Subject: [PATCH 4/5] some frontend changes for reference type refactor --- .../controllers/v2/ReferenceController.java | 2 +- .../enum/description-template-field-type.ts | 28 +- .../enum/dmp-blueprint-field-category.ts | 5 + .../dmp-blueprint-section-field-category.ts | 4 - .../enum/dmp-blueprint-system-field-type.ts | 22 +- .../app/core/common/enum/reference-type.ts | 16 - .../description-template-persist.ts | 31 +- .../description-template.ts | 26 +- .../core/model/dmp-blueprint/dmp-blueprint.ts | 35 +- .../src/app/core/model/reference/reference.ts | 5 +- .../src/app/core/pipes/field-value.pipe.ts | 15 +- .../recent-activity-item-lookup.lookup.ts | 1 - .../app/core/query/reference-search.lookup.ts | 7 +- .../src/app/core/query/reference.lookup.ts | 5 +- .../reference-type/reference-type.service.ts | 8 + .../services/reference/reference.service.ts | 67 ++-- .../services/utilities/enum-utils.service.ts | 61 +--- .../description-template.module.ts | 4 +- ...late-editor-composite-field.component.html | 49 +-- ...mplate-editor-composite-field.component.ts | 30 +- ...-editor-external-select-field.component.ts | 1 - ...editor-reference-type-field.component.html | 23 ++ ...editor-reference-type-field.component.scss | 3 + ...e-editor-reference-type-field.component.ts | 20 ++ ...ption-template-editor-field.component.html | 74 +--- ...ription-template-editor-field.component.ts | 26 +- .../description-template-editor.component.ts | 16 +- .../description-template-editor.model.ts | 339 ++---------------- .../description-template-editor.resolver.ts | 17 +- .../dmp-blueprint-editor.component.html | 68 ++-- .../editor/dmp-blueprint-editor.component.ts | 143 +++----- .../editor/dmp-blueprint-editor.model.ts | 60 ++-- .../editor/dmp-blueprint-editor.resolver.ts | 10 +- .../editor/reference-editor.component.html | 37 +- .../editor/reference-editor.component.ts | 17 +- .../editor/reference-editor.model.ts | 18 +- .../editor/reference-editor.resolver.ts | 3 +- .../reference-listing-filters.component.html | 7 +- .../reference-listing-filters.component.ts | 17 +- .../listing/reference-listing.component.html | 2 +- .../listing/reference-listing.component.ts | 4 +- .../editor/description-editor.component.ts | 8 +- .../editor/description-editor.model.ts | 8 +- .../form-field/form-field.component.html | 205 +---------- .../form-field/form-field.component.ts | 279 +------------- .../description-listing-item.component.html | 2 +- .../description-listing-item.component.ts | 4 +- .../description-overview.component.html | 4 +- .../description-overview.component.ts | 10 +- .../dmp-editor.component.html | 39 +- .../dmp-editor.component.ts | 41 +-- .../dmp-editor-blueprint/dmp-editor.model.ts | 5 +- .../dmp-editor.resolver.ts | 12 +- .../dmp-listing-item.component.html | 2 +- .../dmp-listing-item.component.ts | 12 +- .../dmp/overview/dmp-overview.component.html | 4 +- .../ui/dmp/overview/dmp-overview.component.ts | 16 +- .../reference-field.component.html | 4 +- .../reference-field.component.ts | 7 +- dmp-frontend/src/assets/i18n/en.json | 28 +- .../formatting/common-formatting.module.ts | 12 +- .../formatting/pipes/reference-type.pipe.ts | 11 - 62 files changed, 542 insertions(+), 1497 deletions(-) create mode 100644 dmp-frontend/src/app/core/common/enum/dmp-blueprint-field-category.ts delete mode 100644 dmp-frontend/src/app/core/common/enum/dmp-blueprint-section-field-category.ts delete mode 100644 dmp-frontend/src/app/core/common/enum/reference-type.ts create mode 100644 dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.html create mode 100644 dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.scss create mode 100644 dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.ts delete mode 100644 dmp-frontend/src/common/formatting/pipes/reference-type.pipe.ts diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ReferenceController.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ReferenceController.java index f9bde0744..0b3e45fd7 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ReferenceController.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/ReferenceController.java @@ -95,7 +95,7 @@ public class ReferenceController { @PostMapping("search") - public List searchReferenceWithDefinition(@RequestBody ReferenceDefinitionSearchLookup lookup) throws HugeResultSetException, MyNotFoundException, InvalidApplicationException { + public List search(@RequestBody ReferenceDefinitionSearchLookup lookup) throws HugeResultSetException, MyNotFoundException, InvalidApplicationException { logger.debug("search with db definition {}", Reference.class.getSimpleName()); this.censorFactory.censor(ReferenceCensor.class).censor(lookup.getProject(), null); diff --git a/dmp-frontend/src/app/core/common/enum/description-template-field-type.ts b/dmp-frontend/src/app/core/common/enum/description-template-field-type.ts index 6bc550ca7..dca669bb4 100644 --- a/dmp-frontend/src/app/core/common/enum/description-template-field-type.ts +++ b/dmp-frontend/src/app/core/common/enum/description-template-field-type.ts @@ -1,10 +1,7 @@ export enum DescriptionTemplateFieldType { - EXTERNAL_SELECT = "externalSelect", SELECT = "select", BOOLEAN_DECISION = "booleanDecision", RADIO_BOX = "radiobox", - INTERNAL_DMP_ENTRIES = "internalDmpEntities", //Delete - INTERNAL_DMP_ENTRIES_RESEARCHERS = "internalDmpResearchers", INTERNAL_DMP_ENTRIES_DMPS = "internalDmpDmps", INTERNAL_ENTRIES_DESCRIPTIONS = "internalDmpDescriptions", CHECK_BOX = "checkBox", @@ -14,18 +11,23 @@ export enum DescriptionTemplateFieldType { UPLOAD = "upload", DATE_PICKER = "datePicker", EXTERNAL_DATASETS = "externalDatasets", - DATA_REPOSITORIES = "dataRepositories", - JOURNAL_REPOSITORIES = "journalRepositories", - PUB_REPOSITORIES = "pubRepositories", - LICENSES = "licenses", - TAXONOMIES = "taxonomies", - PUBLICATIONS = "publications", - REGISTRIES = "registries", - SERVICES = "services", + REFERENCE_TYPES = "referenceTypes", TAGS = "tags", - RESEARCHERS = "researchers", - ORGANIZATIONS = "organizations", DATASET_IDENTIFIER = "datasetIdentifier", CURRENCY = "currency", VALIDATION = "validation" + + //EXTERNAL_SELECT = "externalSelect", + // INTERNAL_DMP_ENTRIES_RESEARCHERS = "internalDmpResearchers", + // DATA_REPOSITORIES = "dataRepositories", + // JOURNAL_REPOSITORIES = "journalRepositories", + // PUB_REPOSITORIES = "pubRepositories", + // LICENSES = "licenses", + // TAXONOMIES = "taxonomies", + // PUBLICATIONS = "publications", + // REGISTRIES = "registries", + // SERVICES = "services", + + // RESEARCHERS = "researchers", + // ORGANIZATIONS = "organizations", } \ No newline at end of file diff --git a/dmp-frontend/src/app/core/common/enum/dmp-blueprint-field-category.ts b/dmp-frontend/src/app/core/common/enum/dmp-blueprint-field-category.ts new file mode 100644 index 000000000..de6927973 --- /dev/null +++ b/dmp-frontend/src/app/core/common/enum/dmp-blueprint-field-category.ts @@ -0,0 +1,5 @@ +export enum DmpBlueprintFieldCategory { + System = 0, + Extra = 1, + ReferenceType = 2 +} \ No newline at end of file diff --git a/dmp-frontend/src/app/core/common/enum/dmp-blueprint-section-field-category.ts b/dmp-frontend/src/app/core/common/enum/dmp-blueprint-section-field-category.ts deleted file mode 100644 index 3907fd2d6..000000000 --- a/dmp-frontend/src/app/core/common/enum/dmp-blueprint-section-field-category.ts +++ /dev/null @@ -1,4 +0,0 @@ -export enum DmpBlueprintSectionFieldCategory { - SYSTEM = 0, - EXTRA = 1 -} \ No newline at end of file diff --git a/dmp-frontend/src/app/core/common/enum/dmp-blueprint-system-field-type.ts b/dmp-frontend/src/app/core/common/enum/dmp-blueprint-system-field-type.ts index 654df49d9..52d993bca 100644 --- a/dmp-frontend/src/app/core/common/enum/dmp-blueprint-system-field-type.ts +++ b/dmp-frontend/src/app/core/common/enum/dmp-blueprint-system-field-type.ts @@ -1,13 +1,13 @@ export enum DmpBlueprintSystemFieldType { - TEXT = 0, - HTML_TEXT = 1, - RESEARCHERS = 2, - ORGANIZATIONS = 3, - LANGUAGE = 4, - CONTACT = 5, - FUNDER = 6, - GRANT = 7, - PROJECT = 8, - LICENSE = 9, - ACCESS_RIGHTS = 10 + Title = 0, + Description = 1, + // RESEARCHERS = 2, + // ORGANIZATIONS = 3, + Language = 2, + Contact = 3, + // FUNDER = 6, + // GRANT = 7, + // PROJECT = 8, + // LICENSE = 9, + AccessRights = 4 } diff --git a/dmp-frontend/src/app/core/common/enum/reference-type.ts b/dmp-frontend/src/app/core/common/enum/reference-type.ts deleted file mode 100644 index 0c5c48d9b..000000000 --- a/dmp-frontend/src/app/core/common/enum/reference-type.ts +++ /dev/null @@ -1,16 +0,0 @@ -export enum ReferenceType { - Taxonomies = 0, - Licenses = 1, - Publications = 2, - Journals = 3, - PubRepositories = 4, - DataRepositories = 5, - Registries = 6, - Services = 7, - Project = 8, - Funder = 9, - Datasets = 10, - Organizations = 11, - Grants = 12, - Researcher = 13 -} \ No newline at end of file diff --git a/dmp-frontend/src/app/core/model/description-template/description-template-persist.ts b/dmp-frontend/src/app/core/model/description-template/description-template-persist.ts index 22b780f64..7f4950ea2 100644 --- a/dmp-frontend/src/app/core/model/description-template/description-template-persist.ts +++ b/dmp-frontend/src/app/core/model/description-template/description-template-persist.ts @@ -101,12 +101,12 @@ export interface DescriptionTemplateBaseFieldDataPersist { // Field Types // -export interface DescriptionTemplateExternalDatasetDataPersist extends DescriptionTemplateLabelAndMultiplicityDataPersist { - type: DescriptionTemplateFieldDataExternalDatasetType; +export interface DescriptionTemplateReferenceTypeFieldPersist extends DescriptionTemplateLabelAndMultiplicityDataPersist { + referenceTypeId: Guid; } -export interface DescriptionTemplateExternalSelectDataPersist extends DescriptionTemplateLabelAndMultiplicityDataPersist { - sources: DescriptionTemplateExternalSelectSourcePersist[]; +export interface DescriptionTemplateExternalDatasetDataPersist extends DescriptionTemplateLabelAndMultiplicityDataPersist { + type: DescriptionTemplateFieldDataExternalDatasetType; } export interface DescriptionTemplateLabelAndMultiplicityDataPersist extends DescriptionTemplateBaseFieldDataPersist { @@ -132,34 +132,11 @@ export interface DescriptionTemplateUploadDataPersist extends DescriptionTemplat // // Others // -export interface DescriptionTemplateExternalSelectSourcePersist { - url: string; - method: string; - optionsRoot: string; - sourceBinding: DescriptionTemplateExternalSelectSourceBindingPersist; - hasAuth: boolean; - auth: DescriptionTemplateExternalSelectAuthDataPersist -} - -export interface DescriptionTemplateExternalSelectAuthDataPersist { - url: string; - method: string; - body: string; - path: string; - type: string; -} - export interface DescriptionTemplateSelectOptionPersist { label: string; value: string; } -export interface DescriptionTemplateExternalSelectSourceBindingPersist { - label: string; - value: string; - source: string; -} - export interface DescriptionTemplateRadioBoxOptionPersist { label: string; value: string; diff --git a/dmp-frontend/src/app/core/model/description-template/description-template.ts b/dmp-frontend/src/app/core/model/description-template/description-template.ts index fc81139eb..dae11eead 100644 --- a/dmp-frontend/src/app/core/model/description-template/description-template.ts +++ b/dmp-frontend/src/app/core/model/description-template/description-template.ts @@ -107,8 +107,8 @@ export interface DescriptionTemplateExternalDatasetData extends DescriptionTempl type?: DescriptionTemplateFieldDataExternalDatasetType; } -export interface DescriptionTemplateExternalSelectData extends DescriptionTemplateLabelAndMultiplicityData { - sources: DescriptionTemplateExternalSelectSource[]; +export interface DescriptionTemplateReferenceTypeData extends DescriptionTemplateLabelAndMultiplicityData { + referenceTypeId?: Guid; } export interface DescriptionTemplateRadioBoxData extends DescriptionTemplateBaseFieldData { @@ -128,28 +128,6 @@ export interface DescriptionTemplateUploadData extends DescriptionTemplateBaseFi // // Others // -export interface DescriptionTemplateExternalSelectSource { - url: string; - method: string; - optionsRoot: string; - sourceBinding: DescriptionTemplateExternalSelectSourceBinding; - hasAuth: boolean; - auth: DescriptionTemplateExternalSelectAuthData -} - -export interface DescriptionTemplateExternalSelectAuthData { - url: string; - method: string; - body: string; - path: string; - type: string; -} - -export interface DescriptionTemplateExternalSelectSourceBinding { - label: string; - value: string; - source: string; -} export interface DescriptionTemplateSelectOption { label: string; diff --git a/dmp-frontend/src/app/core/model/dmp-blueprint/dmp-blueprint.ts b/dmp-frontend/src/app/core/model/dmp-blueprint/dmp-blueprint.ts index 2fd5249f2..30ace1679 100644 --- a/dmp-frontend/src/app/core/model/dmp-blueprint/dmp-blueprint.ts +++ b/dmp-frontend/src/app/core/model/dmp-blueprint/dmp-blueprint.ts @@ -1,9 +1,10 @@ +import { DmpBlueprintFieldCategory } from "@app/core/common/enum/dmp-blueprint-field-category"; import { DmpBlueprintExtraFieldDataType } from "@app/core/common/enum/dmp-blueprint-field-type"; -import { DmpBlueprintSectionFieldCategory } from "@app/core/common/enum/dmp-blueprint-section-field-category"; import { DmpBlueprintStatus } from "@app/core/common/enum/dmp-blueprint-status"; import { DmpBlueprintSystemFieldType } from "@app/core/common/enum/dmp-blueprint-system-field-type"; import { BaseEntity, BaseEntityPersist } from "@common/base/base-entity.model"; import { Guid } from "@common/types/guid"; +import { ReferenceType } from "../reference-type/reference-type"; export interface DmpBlueprint extends BaseEntity { @@ -38,9 +39,7 @@ export interface DescriptionTemplatesInSection { export interface FieldInSection { id: Guid; - category: DmpBlueprintSectionFieldCategory; - dataType: DmpBlueprintExtraFieldDataType; - systemFieldType: DmpBlueprintSystemFieldType; + category: DmpBlueprintFieldCategory; label: string; placeholder: string; description: string; @@ -48,6 +47,18 @@ export interface FieldInSection { ordinal: number; } +export interface SystemFieldInSection extends FieldInSection { + systemFieldType: DmpBlueprintSystemFieldType; +} + +export interface ExtraFieldInSection extends FieldInSection { + dataType: DmpBlueprintExtraFieldDataType; +} + +export interface ReferenceTypeFieldInSection extends FieldInSection { + referenceType: ReferenceType; +} + // // Persist // @@ -86,12 +97,22 @@ export interface DescriptionTemplatesInSectionPersist { export interface FieldInSectionPersist { id: Guid; - category: DmpBlueprintSectionFieldCategory; - dataType: DmpBlueprintExtraFieldDataType; - systemFieldType: DmpBlueprintSystemFieldType; + category: DmpBlueprintFieldCategory; label: string; placeholder: string; description: string; required: boolean; ordinal: number; +} + +export interface SystemFieldInSectionPersist extends FieldInSectionPersist { + systemFieldType: DmpBlueprintSystemFieldType; +} + +export interface ExtraFieldInSectionPersist extends FieldInSectionPersist { + dataType: DmpBlueprintExtraFieldDataType; +} + +export interface ReferenceTypeFieldInSectionPersist extends FieldInSectionPersist { + referenceTypeId: Guid; } \ No newline at end of file diff --git a/dmp-frontend/src/app/core/model/reference/reference.ts b/dmp-frontend/src/app/core/model/reference/reference.ts index e5a19a695..5b53cf413 100644 --- a/dmp-frontend/src/app/core/model/reference/reference.ts +++ b/dmp-frontend/src/app/core/model/reference/reference.ts @@ -1,7 +1,8 @@ import { ReferenceFieldDataType } from "@app/core/common/enum/reference-field-data-type"; import { ReferenceSourceType } from "@app/core/common/enum/reference-source-type"; -import { ReferenceType } from "@app/core/common/enum/reference-type"; import { BaseEntity, BaseEntityPersist } from "@common/base/base-entity.model"; +import { ReferenceType } from "../reference-type/reference-type"; +import { Guid } from "@common/types/guid"; export interface Reference extends BaseEntity { label: string; @@ -47,7 +48,7 @@ export interface FetcherReference { export interface ReferencePersist extends BaseEntityPersist { label: string; - type: ReferenceType; + typeId: Guid; description: string; definition: DefinitionPersist; reference: string; diff --git a/dmp-frontend/src/app/core/pipes/field-value.pipe.ts b/dmp-frontend/src/app/core/pipes/field-value.pipe.ts index d8a5f41e6..68e25404e 100644 --- a/dmp-frontend/src/app/core/pipes/field-value.pipe.ts +++ b/dmp-frontend/src/app/core/pipes/field-value.pipe.ts @@ -1,6 +1,7 @@ import { DatePipe } from "@angular/common"; import { Pipe, PipeTransform } from "@angular/core"; import { DescriptionTemplateFieldType } from "../common/enum/description-template-field-type"; +import { Reference } from "../model/reference/reference"; @Pipe({ name: 'fieldValue' @@ -33,7 +34,6 @@ export class FieldValuePipe implements PipeTransform { return this.date.transform(controlValue.value, 'dd/MM/yyyy'); case DescriptionTemplateFieldType.FREE_TEXT: return value; - case DescriptionTemplateFieldType.EXTERNAL_SELECT: case DescriptionTemplateFieldType.SELECT: if (value && controlValue.data.options && !controlValue.data.multipleSelect) { return controlValue.data.options.find(option => value == option.value).label; @@ -48,20 +48,11 @@ export class FieldValuePipe implements PipeTransform { break; case DescriptionTemplateFieldType.TEXT_AREA: return value; - case DescriptionTemplateFieldType.REGISTRIES: - case DescriptionTemplateFieldType.SERVICES: - case DescriptionTemplateFieldType.RESEARCHERS: - case DescriptionTemplateFieldType.ORGANIZATIONS: + case DescriptionTemplateFieldType.REFERENCE_TYPES: + return (value as Reference)?.label; case DescriptionTemplateFieldType.EXTERNAL_DATASETS: - case DescriptionTemplateFieldType.DATA_REPOSITORIES: - case DescriptionTemplateFieldType.PUB_REPOSITORIES: - case DescriptionTemplateFieldType.JOURNAL_REPOSITORIES: - case DescriptionTemplateFieldType.TAXONOMIES: - case DescriptionTemplateFieldType.LICENSES: - case DescriptionTemplateFieldType.PUBLICATIONS: case DescriptionTemplateFieldType.TAGS: return this.parseJson(value); - case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_RESEARCHERS: case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_DMPS: case DescriptionTemplateFieldType.INTERNAL_ENTRIES_DESCRIPTIONS: return this.parseJson(value, 'label'); diff --git a/dmp-frontend/src/app/core/query/recent-activity-item-lookup.lookup.ts b/dmp-frontend/src/app/core/query/recent-activity-item-lookup.lookup.ts index b22f8fdde..fa6e7331f 100644 --- a/dmp-frontend/src/app/core/query/recent-activity-item-lookup.lookup.ts +++ b/dmp-frontend/src/app/core/query/recent-activity-item-lookup.lookup.ts @@ -1,6 +1,5 @@ import { Lookup } from "@common/model/lookup"; import { RecentActivityOrder } from "../common/enum/recent-activity-order"; -import { ReferenceType } from "../common/enum/reference-type"; export class RecentActivityItemLookup implements RecentActivityItemFilter { like: string; diff --git a/dmp-frontend/src/app/core/query/reference-search.lookup.ts b/dmp-frontend/src/app/core/query/reference-search.lookup.ts index 16e8e7bbd..f536eb3a6 100644 --- a/dmp-frontend/src/app/core/query/reference-search.lookup.ts +++ b/dmp-frontend/src/app/core/query/reference-search.lookup.ts @@ -1,10 +1,9 @@ import { Lookup } from "@common/model/lookup"; -import { ReferenceType } from "../common/enum/reference-type"; import { Guid } from "@common/types/guid"; -export class ReferenceSearchLookup extends Lookup{ +export class ReferenceSearchLookup extends Lookup { like: string; - type: ReferenceType; + referenceTypeId: Guid; key: string; constructor() { @@ -13,7 +12,7 @@ export class ReferenceSearchLookup extends Lookup{ } -export class ReferenceSearchDefinitionLookup extends Lookup{ +export class ReferenceSearchDefinitionLookup extends Lookup { like: string; referenceTypeId: Guid; key: string; diff --git a/dmp-frontend/src/app/core/query/reference.lookup.ts b/dmp-frontend/src/app/core/query/reference.lookup.ts index 36d30aef8..f78da6047 100644 --- a/dmp-frontend/src/app/core/query/reference.lookup.ts +++ b/dmp-frontend/src/app/core/query/reference.lookup.ts @@ -2,7 +2,6 @@ import { Lookup } from '@common/model/lookup'; import { Guid } from '@common/types/guid'; import { IsActive } from '../common/enum/is-active.enum'; import { ReferenceSourceType } from '../common/enum/reference-source-type'; -import { ReferenceType } from '../common/enum/reference-type'; export class ReferenceLookup extends Lookup implements ReferenceFilter { ids: Guid[]; @@ -10,7 +9,7 @@ export class ReferenceLookup extends Lookup implements ReferenceFilter { like: string; isActive: IsActive[]; sourceTypes: ReferenceSourceType[]; - types: ReferenceType[]; + typeIds: Guid[]; constructor() { super(); @@ -23,5 +22,5 @@ export interface ReferenceFilter { like: string; isActive: IsActive[]; sourceTypes: ReferenceSourceType[]; - types: ReferenceType[]; + typeIds: Guid[]; } diff --git a/dmp-frontend/src/app/core/services/reference-type/reference-type.service.ts b/dmp-frontend/src/app/core/services/reference-type/reference-type.service.ts index 185ed3652..25cc90232 100644 --- a/dmp-frontend/src/app/core/services/reference-type/reference-type.service.ts +++ b/dmp-frontend/src/app/core/services/reference-type/reference-type.service.ts @@ -129,4 +129,12 @@ export class ReferenceTypeService { return fields; } + + public getResearcherReferenceType(): Guid { + return null; + } + + public getGrantReferenceType(): Guid { + return null; + } } \ No newline at end of file diff --git a/dmp-frontend/src/app/core/services/reference/reference.service.ts b/dmp-frontend/src/app/core/services/reference/reference.service.ts index 8f1012b9a..fb273bc21 100644 --- a/dmp-frontend/src/app/core/services/reference/reference.service.ts +++ b/dmp-frontend/src/app/core/services/reference/reference.service.ts @@ -1,7 +1,6 @@ import { Injectable } from '@angular/core'; import { IsActive } from '@app/core/common/enum/is-active.enum'; import { ReferenceSourceType } from '@app/core/common/enum/reference-source-type'; -import { ReferenceType } from '@app/core/common/enum/reference-type'; import { DmpReference } from '@app/core/model/dmp/dmp-reference'; import { Definition, Field, Reference, ReferencePersist } from '@app/core/model/reference/reference'; import { ReferenceSearchDefinitionLookup, ReferenceSearchLookup } from '@app/core/query/reference-search.lookup'; @@ -36,13 +35,13 @@ export class ReferenceService { return this.http.post>(url, q).pipe(catchError((error: any) => throwError(error))); } - search(q: ReferenceSearchLookup): Observable { - const url = `${this.apiBase}/search`; - return this.http.post(url, q).pipe(catchError((error: any) => throwError(error))); - } + // search(q: ReferenceSearchLookup): Observable { + // const url = `${this.apiBase}/search`; + // return this.http.post(url, q).pipe(catchError((error: any) => throwError(error))); + // } searchWithDefinition(q: ReferenceSearchDefinitionLookup): Observable { - const url = `${this.apiBase}/search-with-db-definition`; + const url = `${this.apiBase}/search`; return this.http.post(url, q).pipe(catchError((error: any) => throwError(error))); } @@ -74,29 +73,29 @@ export class ReferenceService { // // Autocomplete Commons - Query // - public getSingleAutocompleteQueryConfiguration(types?: ReferenceType[], sourceTypes?: ReferenceSourceType[]): SingleAutoCompleteConfiguration { + public getSingleAutocompleteQueryConfiguration(referenceTypeIds?: Guid[], sourceTypes?: ReferenceSourceType[]): SingleAutoCompleteConfiguration { return { - initialItems: (data?: any) => this.query(this.buildAutocompleteQueryLookup(types, sourceTypes)).pipe(map(x => x.items)), - filterFn: (searchQuery: string, data?: any) => this.query(this.buildAutocompleteQueryLookup(types, sourceTypes, searchQuery)).pipe(map(x => x.items)), - getSelectedItem: (selectedItem: any) => this.query(this.buildAutocompleteQueryLookup(types, sourceTypes, null, null, [selectedItem])).pipe(map(x => x.items[0])), + initialItems: (data?: any) => this.query(this.buildAutocompleteQueryLookup(referenceTypeIds, sourceTypes)).pipe(map(x => x.items)), + filterFn: (searchQuery: string, data?: any) => this.query(this.buildAutocompleteQueryLookup(referenceTypeIds, sourceTypes, searchQuery)).pipe(map(x => x.items)), + getSelectedItem: (selectedItem: any) => this.query(this.buildAutocompleteQueryLookup(referenceTypeIds, sourceTypes, null, null, [selectedItem])).pipe(map(x => x.items[0])), displayFn: (item: Reference) => item.label, titleFn: (item: Reference) => item.label, valueAssign: (item: Reference) => item.id, }; }; - public getMultipleAutoCompleteQueryConfiguration(types?: ReferenceType[], sourceTypes?: ReferenceSourceType[]): MultipleAutoCompleteConfiguration { + public getMultipleAutoCompleteQueryConfiguration(referenceTypeIds?: Guid[], sourceTypes?: ReferenceSourceType[]): MultipleAutoCompleteConfiguration { return { - initialItems: (excludedItems: any[], data?: any) => this.query(this.buildAutocompleteQueryLookup(types, sourceTypes, null, excludedItems ? excludedItems : null)).pipe(map(x => x.items)), - filterFn: (searchQuery: string, excludedItems: any[]) => this.query(this.buildAutocompleteQueryLookup(types, sourceTypes, searchQuery, excludedItems)).pipe(map(x => x.items)), - getSelectedItems: (selectedItems: any[]) => this.query(this.buildAutocompleteQueryLookup(types, sourceTypes, null, null, selectedItems)).pipe(map(x => x.items)), + initialItems: (excludedItems: any[], data?: any) => this.query(this.buildAutocompleteQueryLookup(referenceTypeIds, sourceTypes, null, excludedItems ? excludedItems : null)).pipe(map(x => x.items)), + filterFn: (searchQuery: string, excludedItems: any[]) => this.query(this.buildAutocompleteQueryLookup(referenceTypeIds, sourceTypes, searchQuery, excludedItems)).pipe(map(x => x.items)), + getSelectedItems: (selectedItems: any[]) => this.query(this.buildAutocompleteQueryLookup(referenceTypeIds, sourceTypes, null, null, selectedItems)).pipe(map(x => x.items)), displayFn: (item: Reference) => item.label, titleFn: (item: Reference) => item.label, valueAssign: (item: Reference) => item.id, }; } - private buildAutocompleteQueryLookup(types?: ReferenceType[], sourceTypes?: ReferenceSourceType[], like?: string, excludedIds?: Guid[], ids?: Guid[]): ReferenceLookup { + private buildAutocompleteQueryLookup(referenceTypeIds?: Guid[], sourceTypes?: ReferenceSourceType[], like?: string, excludedIds?: Guid[], ids?: Guid[]): ReferenceLookup { const lookup: ReferenceLookup = new ReferenceLookup(); lookup.page = { size: 100, offset: 0 }; if (excludedIds && excludedIds.length > 0) { lookup.excludedIds = excludedIds; } @@ -108,7 +107,7 @@ export class ReferenceService { nameof(x => x.label), ] }; - if (types && types.length > 0) { lookup.types = types; } + if (referenceTypeIds && referenceTypeIds.length > 0) { lookup.typeIds = referenceTypeIds; } if (sourceTypes && sourceTypes.length > 0) { lookup.sourceTypes = sourceTypes; } lookup.order = { items: [nameof(x => x.label)] }; if (like) { lookup.like = this.filterService.transformLike(like); } @@ -118,22 +117,22 @@ export class ReferenceService { // // Autocomplete Commons - Search // - public getSingleAutocompleteSearchConfiguration(type: ReferenceType): SingleAutoCompleteConfiguration { + public getSingleAutocompleteSearchConfiguration(typeId: Guid): SingleAutoCompleteConfiguration { return { - initialItems: (data?: any) => this.search(this.buildAutocompleteSearchLookup(type)).pipe(map(x => x)), - filterFn: (searchQuery: string, data?: any) => this.search(this.buildAutocompleteSearchLookup(type, searchQuery)).pipe(map(x => x)), - getSelectedItem: (selectedItem: any) => this.query(this.buildAutocompleteSearchSelectedItemsLookup([type], null, null, null, [selectedItem])).pipe(map(x => x.items[0])), + initialItems: (data?: any) => this.searchWithDefinition(this.buildAutocompleteSearchLookup(typeId)).pipe(map(x => x)), + filterFn: (searchQuery: string, data?: any) => this.searchWithDefinition(this.buildAutocompleteSearchLookup(typeId, searchQuery)).pipe(map(x => x)), + getSelectedItem: (selectedItem: any) => this.query(this.buildAutocompleteSearchSelectedItemsLookup([typeId], null, null, null, [selectedItem])).pipe(map(x => x.items[0])), displayFn: (item: Reference) => item.label, titleFn: (item: Reference) => item.label, valueAssign: (item: Reference) => item.id, }; }; - public getMultipleAutoCompleteSearchConfiguration(type: ReferenceType): MultipleAutoCompleteConfiguration { + public getMultipleAutoCompleteSearchConfiguration(typeId: Guid): MultipleAutoCompleteConfiguration { return { - initialItems: (excludedItems: any[], data?: any) => this.search(this.buildAutocompleteSearchLookup(type, null)).pipe(map(x => x)), - filterFn: (searchQuery: string, excludedItems: any[]) => this.search(this.buildAutocompleteSearchLookup(type, searchQuery)).pipe(map(x => x)), - getSelectedItems: (selectedItems: any[]) => this.query(this.buildAutocompleteSearchSelectedItemsLookup([type], null, null, null, selectedItems?.map(x => x.id))).pipe(map(x => x.items)), + initialItems: (excludedItems: any[], data?: any) => this.searchWithDefinition(this.buildAutocompleteSearchLookup(typeId, null)).pipe(map(x => x)), + filterFn: (searchQuery: string, excludedItems: any[]) => this.searchWithDefinition(this.buildAutocompleteSearchLookup(typeId, searchQuery)).pipe(map(x => x)), + getSelectedItems: (selectedItems: any[]) => this.query(this.buildAutocompleteSearchSelectedItemsLookup([typeId], null, null, null, selectedItems?.map(x => x.id))).pipe(map(x => x.items)), displayFn: (item: Reference) => item.label, titleFn: (item: Reference) => item.label, subtitleFn: (item: Reference) => item?.sourceType === ReferenceSourceType.External ? this.language.instant('REFERENCE-FIELD-COMPONENT.EXTERNAL-SOURCE') + ': ' + item.source : this.language.instant('REFERENCE-FIELD-COMPONENT.INTERNAL-SOURCE'), @@ -142,7 +141,7 @@ export class ReferenceService { }; } - private buildAutocompleteSearchLookup(type: ReferenceType, like?: string): ReferenceSearchLookup { + private buildAutocompleteSearchLookup(typeId: Guid, like?: string): ReferenceSearchLookup { const lookup: ReferenceSearchLookup = new ReferenceSearchLookup(); lookup.page = { size: 100, offset: 0 }; lookup.project = { @@ -161,13 +160,13 @@ export class ReferenceService { nameof(x => x.sourceType), ] }; - lookup.type = type; + lookup.referenceTypeId = typeId; lookup.order = { items: [nameof(x => x.label)] }; if (like) { lookup.like = this.filterService.transformLike(like); } return lookup; } - private buildAutocompleteSearchSelectedItemsLookup(types?: ReferenceType[], sourceTypes?: ReferenceSourceType[], like?: string, excludedIds?: Guid[], ids?: Guid[]): ReferenceLookup { + private buildAutocompleteSearchSelectedItemsLookup(referenceTypeIds?: Guid[], sourceTypes?: ReferenceSourceType[], like?: string, excludedIds?: Guid[], ids?: Guid[]): ReferenceLookup { const lookup: ReferenceLookup = new ReferenceLookup(); lookup.page = { size: 100, offset: 0 }; if (excludedIds && excludedIds.length > 0) { lookup.excludedIds = excludedIds; } @@ -188,7 +187,7 @@ export class ReferenceService { nameof(x => x.sourceType), ] }; - if (types && types.length > 0) { lookup.types = types; } + if (referenceTypeIds && referenceTypeIds.length > 0) { lookup.typeIds = referenceTypeIds; } if (sourceTypes && sourceTypes.length > 0) { lookup.sourceTypes = sourceTypes; } lookup.order = { items: [nameof(x => x.label)] }; if (like) { lookup.like = this.filterService.transformLike(like); } @@ -202,16 +201,16 @@ export class ReferenceService { // // - hasRerefenceOfTypes(dmpReferences: DmpReference[], referenceTypes: ReferenceType[]): boolean { - return this.getReferencesForTypes(dmpReferences, referenceTypes)?.length > 0; + hasRerefenceOfTypes(dmpReferences: DmpReference[], referenceTypeIds?: Guid[]): boolean { + return this.getReferencesForTypes(dmpReferences, referenceTypeIds)?.length > 0; } - getReferencesForTypes(dmpReferences: DmpReference[], referenceTypes: ReferenceType[]): DmpReference[] { - return dmpReferences?.filter(x => referenceTypes?.includes(x?.reference?.type)); + getReferencesForTypes(dmpReferences: DmpReference[], referenceTypeIds?: Guid[]): DmpReference[] { + return dmpReferences?.filter(x => referenceTypeIds?.includes(x?.reference?.type?.id)); } - getReferencesForTypesFirstSafe(dmpReferences: DmpReference[], referenceTypes: ReferenceType[]): DmpReference { - return this.getReferencesForTypes(dmpReferences, referenceTypes)?.find(Boolean); + getReferencesForTypesFirstSafe(dmpReferences: DmpReference[], referenceTypeIds?: Guid[]): DmpReference { + return this.getReferencesForTypes(dmpReferences, referenceTypeIds)?.find(Boolean); } } diff --git a/dmp-frontend/src/app/core/services/utilities/enum-utils.service.ts b/dmp-frontend/src/app/core/services/utilities/enum-utils.service.ts index a66409751..59078df05 100644 --- a/dmp-frontend/src/app/core/services/utilities/enum-utils.service.ts +++ b/dmp-frontend/src/app/core/services/utilities/enum-utils.service.ts @@ -24,7 +24,6 @@ import { NotificationType } from '@app/core/common/enum/notification-type'; import { RecentActivityOrder } from '@app/core/common/enum/recent-activity-order'; import { ReferenceFieldDataType } from '@app/core/common/enum/reference-field-data-type'; import { ReferenceSourceType } from '@app/core/common/enum/reference-source-type'; -import { ReferenceType } from '@app/core/common/enum/reference-type'; import { ReferenceTypeExternalApiHTTPMethodType } from '@app/core/common/enum/reference-type-external-api-http-method-type'; import { ReferenceTypeSourceType } from '@app/core/common/enum/reference-type-source-type'; import { RoleOrganizationType } from '@app/core/common/enum/role-organization-type'; @@ -37,6 +36,7 @@ import { DmpBlueprintType } from '../../common/enum/dmp-blueprint-type'; import { DmpStatus } from '../../common/enum/dmp-status'; import { ValidationType } from '../../common/enum/validation-type'; import { DescriptionTemplateExternalSelectAuthType } from '@app/core/common/enum/description-template-external-select-auth-type'; +import { DmpBlueprintFieldCategory } from '@app/core/common/enum/dmp-blueprint-field-category'; @Injectable() export class EnumUtils { @@ -133,17 +133,11 @@ export class EnumUtils { toDmpBlueprintSystemFieldTypeString(status: DmpBlueprintSystemFieldType): string { switch (status) { - case DmpBlueprintSystemFieldType.TEXT: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.TEXT'); - case DmpBlueprintSystemFieldType.HTML_TEXT: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.HTML_TEXT'); - case DmpBlueprintSystemFieldType.RESEARCHERS: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.RESEARCHERS'); - case DmpBlueprintSystemFieldType.ORGANIZATIONS: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.ORGANIZATIONS'); - case DmpBlueprintSystemFieldType.LANGUAGE: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.LANGUAGE'); - case DmpBlueprintSystemFieldType.CONTACT: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.CONTACT'); - case DmpBlueprintSystemFieldType.FUNDER: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.FUNDER'); - case DmpBlueprintSystemFieldType.GRANT: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.GRANT'); - case DmpBlueprintSystemFieldType.PROJECT: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.PROJECT'); - case DmpBlueprintSystemFieldType.LICENSE: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.LICENSE'); - case DmpBlueprintSystemFieldType.ACCESS_RIGHTS: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.ACCESS_RIGHTS'); + case DmpBlueprintSystemFieldType.Title: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.TITLE'); + case DmpBlueprintSystemFieldType.Description: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.DESCRIPTION'); + case DmpBlueprintSystemFieldType.Language: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.LANGUAGE'); + case DmpBlueprintSystemFieldType.Contact: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.CONTACT'); + case DmpBlueprintSystemFieldType.AccessRights: return this.language.instant('TYPES.DMP-BLUEPRINT-SYSTEM-FIELD-TYPE.ACCESS_RIGHTS'); } } @@ -158,11 +152,9 @@ export class EnumUtils { toDescriptionTemplateFieldTypeString(status: DescriptionTemplateFieldType): string { switch (status) { - case DescriptionTemplateFieldType.EXTERNAL_SELECT: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.EXTERNAL-SELECT'); case DescriptionTemplateFieldType.SELECT: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.SELECT'); case DescriptionTemplateFieldType.BOOLEAN_DECISION: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.BOOLEAN-DECISION'); case DescriptionTemplateFieldType.RADIO_BOX: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.RADIO-BOX'); - case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_RESEARCHERS: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.INTERNAL-DMP-ENTITIES-RESEARCHERS'); case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_DMPS: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.INTERNAL-DMP-ENTITIES-DMPS'); case DescriptionTemplateFieldType.INTERNAL_ENTRIES_DESCRIPTIONS: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.INTERNAL-DMP-ENTITIES-DATASETS'); case DescriptionTemplateFieldType.CHECK_BOX: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.CHECKBOX'); @@ -172,17 +164,8 @@ export class EnumUtils { case DescriptionTemplateFieldType.UPLOAD: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.UPLOAD'); case DescriptionTemplateFieldType.DATE_PICKER: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.DATE-PICKER'); case DescriptionTemplateFieldType.EXTERNAL_DATASETS: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.EXTERNAL-DATASETS'); - case DescriptionTemplateFieldType.DATA_REPOSITORIES: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.DATA-REPOSITORIES'); - case DescriptionTemplateFieldType.JOURNAL_REPOSITORIES: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.JOURNALS-REPOSITORIES'); - case DescriptionTemplateFieldType.PUB_REPOSITORIES: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.PUB-REPOSITORIES'); - case DescriptionTemplateFieldType.LICENSES: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.LICENSES'); - case DescriptionTemplateFieldType.TAXONOMIES: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.TAXONOMIES'); - case DescriptionTemplateFieldType.PUBLICATIONS: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.PUBLICATIONS'); - case DescriptionTemplateFieldType.REGISTRIES: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.REGISTRIES'); - case DescriptionTemplateFieldType.SERVICES: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.SERVICES'); case DescriptionTemplateFieldType.TAGS: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.TAGS'); - case DescriptionTemplateFieldType.RESEARCHERS: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.RESEARCHERS'); - case DescriptionTemplateFieldType.ORGANIZATIONS: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.ORGANIZATIONS'); + case DescriptionTemplateFieldType.REFERENCE_TYPES: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.REFERENCE-TYPES'); case DescriptionTemplateFieldType.DATASET_IDENTIFIER: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.DATASET-IDENTIFIER'); case DescriptionTemplateFieldType.CURRENCY: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.CURRENCY'); case DescriptionTemplateFieldType.VALIDATION: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-FIELD-TYPE.VALIDATION'); @@ -218,26 +201,6 @@ export class EnumUtils { } } - toReferenceTypeString(status: ReferenceType): string { - switch (status) { - case ReferenceType.Taxonomies: return this.language.instant('TYPES.REFERENCE-TYPE.TAXONOMY'); - case ReferenceType.Licenses: return this.language.instant('TYPES.REFERENCE-TYPE.LICENCE'); - case ReferenceType.Publications: return this.language.instant('TYPES.REFERENCE-TYPE.PUBLICATION'); - case ReferenceType.Journals: return this.language.instant('TYPES.REFERENCE-TYPE.JOURNAL'); - case ReferenceType.PubRepositories: return this.language.instant('TYPES.REFERENCE-TYPE.PUB-REPOSITORY'); - case ReferenceType.DataRepositories: return this.language.instant('TYPES.REFERENCE-TYPE.DATA-REPOSITORY'); - case ReferenceType.Registries: return this.language.instant('TYPES.REFERENCE-TYPE.REGISTRY'); - case ReferenceType.Services: return this.language.instant('TYPES.REFERENCE-TYPE.SERVICE'); - case ReferenceType.Project: return this.language.instant('TYPES.REFERENCE-TYPE.PROJECT'); - case ReferenceType.Funder: return this.language.instant('TYPES.REFERENCE-TYPE.FUNDER'); - case ReferenceType.Datasets: return this.language.instant('TYPES.REFERENCE-TYPE.DATASET'); - case ReferenceType.Organizations: return this.language.instant('TYPES.REFERENCE-TYPE.ORGANISATION'); - case ReferenceType.Grants: return this.language.instant('TYPES.REFERENCE-TYPE.GRANT'); - case ReferenceType.Researcher: return this.language.instant('TYPES.REFERENCE-TYPE.RESEARCHER'); - - } - } - toReferenceSourceTypeString(status: ReferenceSourceType): string { switch (status) { case ReferenceSourceType.Internal: return this.language.instant('TYPES.REFERENCE-SOURCE-TYPE.INTERNAL'); @@ -415,4 +378,14 @@ export class EnumUtils { case DescriptionTemplateExternalSelectAuthType.BEARER: return this.language.instant('TYPES.DESCRIPTION-TEMPLATE-EXTERNAL-SELECT-AUTH-TYPE.BEARER'); } } + + public toDmpBlueprintFieldCategoryString(value: DmpBlueprintFieldCategory): string { + switch (value) { + case DmpBlueprintFieldCategory.System: return this.language.instant('TYPES.DMP-BLUEPRINT-FIELD-CATEGORY.SYSTEM'); + case DmpBlueprintFieldCategory.Extra: return this.language.instant('TYPES.DMP-BLUEPRINT-FIELD-CATEGORY.EXTRA'); + case DmpBlueprintFieldCategory.ReferenceType: return this.language.instant('TYPES.DMP-BLUEPRINT-FIELD-CATEGORY.REFERENCE-TYPE'); + } + } + + } diff --git a/dmp-frontend/src/app/ui/admin/description-template/description-template.module.ts b/dmp-frontend/src/app/ui/admin/description-template/description-template.module.ts index 40a4ee124..2cce04d94 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/description-template.module.ts +++ b/dmp-frontend/src/app/ui/admin/description-template/description-template.module.ts @@ -14,7 +14,6 @@ import { DescriptionTemplateRoutingModule } from './description-template.routing import { DescriptionTemplateEditorCompositeFieldComponent } from './editor/components/composite-field/description-template-editor-composite-field.component'; import { DescriptionTemplateEditorDefaultValueComponent } from './editor/components/default-value/description-template-editor-default-value.component'; import { DescriptionTemplateEditorExternalDatasetsFieldComponent } from './editor/components/field-type/external-datasets/description-template-editor-external-datasets-field.component'; -import { DescriptionTemplateEditorExternalSelectFieldComponent } from './editor/components/field-type/external-select/description-template-editor-external-select-field.component'; import { DescriptionTemplateEditorLabelAndMultiplicityFieldComponent } from './editor/components/field-type/label-and-multiplicity-field/description-template-editor-label-and-multiplicity-field.component'; import { DescriptionTemplateEditorLabelFieldComponent } from './editor/components/field-type/label-field/description-template-editor-label-field.component'; import { DescriptionTemplateEditorRadioBoxFieldComponent } from './editor/components/field-type/radio-box/description-template-editor-radio-box-field.component'; @@ -30,6 +29,7 @@ import { DescriptionTemplateTableOfContentsInternalSection } from './editor/tabl import { DescriptionTemplateListingComponent } from './listing/description-template-listing.component'; import { DescriptionTemplateListingFiltersComponent } from "./listing/filters/description-template-listing-filters.component"; import { ImportDescriptionTemplateDialogComponent } from './listing/import-description-template/import-description-template.dialog.component'; +import { DescriptionTemplateEditorReferenceTypeFieldComponent } from './editor/components/field-type/reference-type/description-template-editor-reference-type-field.component'; @NgModule({ imports: [ @@ -68,7 +68,7 @@ import { ImportDescriptionTemplateDialogComponent } from './listing/import-descr DescriptionTemplateEditorDefaultValueComponent, DescriptionTemplateEditorRuleComponent, - DescriptionTemplateEditorExternalSelectFieldComponent, + DescriptionTemplateEditorReferenceTypeFieldComponent, DescriptionTemplateEditorSelectFieldComponent, DescriptionTemplateEditorLabelFieldComponent, DescriptionTemplateEditorLabelAndMultiplicityFieldComponent, diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.html b/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.html index a9c4c74e5..9a3a9bde9 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.html +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.html @@ -65,8 +65,7 @@
- +
  • @@ -190,54 +189,14 @@ APIs - - - - - - - - - - - diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.ts b/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.ts index 782407c90..c0727b36f 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.ts +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/components/composite-field/description-template-editor-composite-field.component.ts @@ -5,7 +5,6 @@ import { MatDialog } from '@angular/material/dialog'; import { DescriptionTemplateFieldType } from '@app/core/common/enum/description-template-field-type'; import { ValidationType } from '@app/core/common/enum/validation-type'; import { - DescriptionTemplateExternalSelectData, DescriptionTemplateSelectOption, DescriptionTemplateExternalDatasetData, DescriptionTemplateField, @@ -13,7 +12,8 @@ import { DescriptionTemplateUploadData, DescriptionTemplateSelectData, DescriptionTemplateLabelData, - DescriptionTemplateLabelAndMultiplicityData + DescriptionTemplateLabelAndMultiplicityData, + DescriptionTemplateReferenceTypeData } from '@app/core/model/description-template/description-template'; import { ConfigurationService } from "@app/core/services/configuration/configuration.service"; import { DescriptionTemplateService } from '@app/core/services/description-template/description-template.service'; @@ -483,11 +483,10 @@ export class DescriptionTemplateEditorCompositeFieldComponent extends BaseCompon } as DescriptionTemplateField; switch (type) { - case DescriptionTemplateFieldType.EXTERNAL_SELECT: { - const data: DescriptionTemplateExternalSelectData = { - sources: [], - multipleSelect: false, + case DescriptionTemplateFieldType.REFERENCE_TYPES: { + const data: DescriptionTemplateReferenceTypeData = { label: '', + multipleSelect: false, fieldType: type } field.data = data; @@ -531,19 +530,12 @@ export class DescriptionTemplateEditorCompositeFieldComponent extends BaseCompon break; } - case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_RESEARCHERS: + case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_DMPS: { + //TODO: refactor + break; + } case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_DMPS: - case DescriptionTemplateFieldType.INTERNAL_ENTRIES_DESCRIPTIONS: - case DescriptionTemplateFieldType.DATA_REPOSITORIES: - case DescriptionTemplateFieldType.JOURNAL_REPOSITORIES: - case DescriptionTemplateFieldType.PUB_REPOSITORIES: - case DescriptionTemplateFieldType.LICENSES: - case DescriptionTemplateFieldType.TAXONOMIES: - case DescriptionTemplateFieldType.PUBLICATIONS: - case DescriptionTemplateFieldType.REGISTRIES: - case DescriptionTemplateFieldType.SERVICES: - case DescriptionTemplateFieldType.RESEARCHERS: - case DescriptionTemplateFieldType.ORGANIZATIONS: { + case DescriptionTemplateFieldType.INTERNAL_ENTRIES_DESCRIPTIONS: { const data: DescriptionTemplateLabelAndMultiplicityData = { label: '', multipleSelect: false, @@ -573,7 +565,7 @@ export class DescriptionTemplateEditorCompositeFieldComponent extends BaseCompon } } - (this.form.get('fields')).push(new DescriptionTemplateFieldEditorModel(this.validationErrorModel).fromModel(field).buildForm({rootPath: this.validationRootPath + '.fields[' + this.fieldsArray.length + ']'})); + (this.form.get('fields')).push(new DescriptionTemplateFieldEditorModel(this.validationErrorModel).fromModel(field).buildForm({ rootPath: this.validationRootPath + '.fields[' + this.fieldsArray.length + ']' })); this.inputs.init(); // fieldForm.get('viewStyle').get('renderStyle').updateValueAndValidity(); // fieldForm.get('data').updateValueAndValidity(); diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/external-select/description-template-editor-external-select-field.component.ts b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/external-select/description-template-editor-external-select-field.component.ts index c1d412f01..04f201e1c 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/external-select/description-template-editor-external-select-field.component.ts +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/external-select/description-template-editor-external-select-field.component.ts @@ -1,6 +1,5 @@ import { Component, Input, OnInit } from '@angular/core'; import { UntypedFormArray, UntypedFormGroup } from '@angular/forms'; -import { DescriptionTemplateExternalSelectDataEditorModel, DescriptionTemplateExternalSelectSourceEditorModel } from '../../../description-template-editor.model'; import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; import { DescriptionTemplateExternalSelectHttpMethodType } from '@app/core/common/enum/description-template-external-select-http-method-type'; import { DescriptionTemplateExternalSelectAuthType } from '@app/core/common/enum/description-template-external-select-auth-type'; diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.html b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.html new file mode 100644 index 000000000..03d349164 --- /dev/null +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.html @@ -0,0 +1,23 @@ +
    +
    {{'DESCRIPTION-TEMPLATE-EDITOR.FIELDS.REFERENCE-TYPE-TITLE' + | translate}}
    + + {{'DESCRIPTION-TEMPLATE-EDITOR.FIELDS.MULTIPLE-SELECT' | translate}} + + +
    + + {{'DESCRIPTION-TEMPLATE-EDITOR.FIELDS.LABEL' | translate}} + + {{form.get('data').get('label').getError('backendError').message}} + +
    +
    + + {{'DESCRIPTION-TEMPLATE-EDITOR.FIELDS.REFERENCE-TYPE' | translate}} + + {{form.get('data').get('referenceTypeId').getError('backendError').message}} + {{'GENERAL.VALIDATION.REQUIRED' | translate}} + +
    +
    \ No newline at end of file diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.scss b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.scss new file mode 100644 index 000000000..3db0dee74 --- /dev/null +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.scss @@ -0,0 +1,3 @@ +.full-width { + width: 100%; +} diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.ts b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.ts new file mode 100644 index 000000000..c321e7698 --- /dev/null +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field-type/reference-type/description-template-editor-reference-type-field.component.ts @@ -0,0 +1,20 @@ +import { Component, Input, OnInit } from '@angular/core'; +import { UntypedFormGroup } from '@angular/forms'; +import { ReferenceTypeService } from '@app/core/services/reference-type/reference-type.service'; + +@Component({ + selector: 'app-description-template-editor-reference-type-field-component', + styleUrls: ['./description-template-editor-reference-type-field.component.scss'], + templateUrl: './description-template-editor-reference-type-field.component.html' +}) +export class DescriptionTemplateEditorReferenceTypeFieldComponent implements OnInit { + + @Input() form: UntypedFormGroup; + constructor( + public referenceTypeService: ReferenceTypeService + ) { } + + ngOnInit() { + + } +} diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.html b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.html index 00e7960ab..2d41acbfc 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.html +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.html @@ -88,54 +88,14 @@ - + Registries icon - {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.REGISTRIES)}} - - - Services icon - {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.SERVICES)}} - - - Researchers icon - {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.RESEARCHERS)}} - - - Organizations icon - {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.ORGANIZATIONS)}} + {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.REFERENCE_TYPES)}} ExternalDatasets icon {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.EXTERNAL_DATASETS)}} - - DataRepositories icon - {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.DATA_REPOSITORIES)}} - - - PubRepositories icon - {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.PUB_REPOSITORIES)}} - - - Journal Repositories icon - {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.JOURNAL_REPOSITORIES)}} - - - Taxonomies icon - {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.TAXONOMIES)}} - - - licenses icon - {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.LICENSES)}} - - - Publications icon - {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.PUBLICATIONS)}} - - - Other icon - {{enumUtils.toDescriptionTemplateFieldTypeString(descriptionTemplateFieldTypeEnum.EXTERNAL_SELECT)}} - @@ -168,7 +128,7 @@ {{'GENERAL.VALIDATION.REQUIRED' | translate}} - {{form.get('data').get('fieldType').getError('backendError').message}} + {{form.get('data').get('fieldType').getError('backendError').message}} @@ -178,16 +138,15 @@ {{'DESCRIPTION-TEMPLATE-EDITOR.STEPS.FORM.COMPOSITE-FIELD.FIELDS.SEMANTICS' | translate}} - {{form.get('schematics').getError('backendError').message}} + {{form.get('schematics').getError('backendError').message}} {{'DESCRIPTION-TEMPLATE-EDITOR.STEPS.FORM.COMPOSITE-FIELD.FIELDS.EXPORT' | translate}} - {{form.get('includeInExport').getError('backendError').message}} + {{form.get('includeInExport').getError('backendError').message}} - +
    @@ -208,12 +167,12 @@
    -->
-
+
- - - - + + + + @@ -228,19 +187,8 @@ - - - - - - - - - - -
\ No newline at end of file diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.ts b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.ts index efa628322..67877419a 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.ts +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/components/field/description-template-editor-field.component.ts @@ -8,10 +8,10 @@ import { DescriptionTemplateFieldType } from '@app/core/common/enum/description- import { ValidationType } from '@app/core/common/enum/validation-type'; import { DescriptionTemplateExternalDatasetData, - DescriptionTemplateExternalSelectData, DescriptionTemplateLabelAndMultiplicityData, DescriptionTemplateLabelData, DescriptionTemplateRadioBoxData, + DescriptionTemplateReferenceTypeData, DescriptionTemplateSelectData, DescriptionTemplateSelectOption, DescriptionTemplateUploadData @@ -107,7 +107,6 @@ export class DescriptionTemplateEditorFieldComponent extends BaseComponent imple case DescriptionTemplateFieldType.BOOLEAN_DECISION: case DescriptionTemplateFieldType.RADIO_BOX: case DescriptionTemplateFieldType.SELECT: - case DescriptionTemplateFieldType.EXTERNAL_SELECT: case DescriptionTemplateFieldType.CHECK_BOX: case DescriptionTemplateFieldType.DATE_PICKER: return true; @@ -126,10 +125,8 @@ export class DescriptionTemplateEditorFieldComponent extends BaseComponent imple } switch (type) { - case DescriptionTemplateFieldType.EXTERNAL_SELECT: { - const data: DescriptionTemplateExternalSelectData = { - sources: [], - multipleSelect: false, + case DescriptionTemplateFieldType.REFERENCE_TYPES: { + const data: DescriptionTemplateLabelData = { label: '', fieldType: type } @@ -174,19 +171,12 @@ export class DescriptionTemplateEditorFieldComponent extends BaseComponent imple break; } - case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_RESEARCHERS: + case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_DMPS: { + //TODO: refactor + break; + } case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_DMPS: - case DescriptionTemplateFieldType.INTERNAL_ENTRIES_DESCRIPTIONS: - case DescriptionTemplateFieldType.DATA_REPOSITORIES: - case DescriptionTemplateFieldType.JOURNAL_REPOSITORIES: - case DescriptionTemplateFieldType.PUB_REPOSITORIES: - case DescriptionTemplateFieldType.LICENSES: - case DescriptionTemplateFieldType.TAXONOMIES: - case DescriptionTemplateFieldType.PUBLICATIONS: - case DescriptionTemplateFieldType.REGISTRIES: - case DescriptionTemplateFieldType.SERVICES: - case DescriptionTemplateFieldType.RESEARCHERS: - case DescriptionTemplateFieldType.ORGANIZATIONS: { + case DescriptionTemplateFieldType.INTERNAL_ENTRIES_DESCRIPTIONS:{ const data: DescriptionTemplateLabelAndMultiplicityData = { label: '', multipleSelect: false, diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.component.ts b/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.component.ts index 2ccb3b3e6..2452d61a4 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.component.ts +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.component.ts @@ -1254,7 +1254,7 @@ export class DescriptionTemplateEditorComponent extends BaseEditor { - // if ((field.get('category').value == FieldCategory.SYSTEM || field.get('category').value == DescriptionTemplateSectionFieldCategory.SYSTEM)) { + // if ((field.get('category').value == FieldCategory.System || field.get('category').value == DescriptionTemplateSectionFieldCategory.System)) { // systemFieldsInSection.push(this.fieldList.find(f => f.type == field.get('type').value).type); // } // }) @@ -1471,7 +1471,7 @@ export class DescriptionTemplateEditorComponent extends BaseEditor section.fields.some(field => (field.category === DescriptionTemplateSectionFieldCategory.SYSTEM || field.category as unknown === DescriptionTemplateSectionFieldCategory.SYSTEM) && field.systemFieldType === DescriptionTemplateSystemFieldType.TEXT)); + // return descriptionTemplate.definition.sections.some(section => section.fields.some(field => (field.category === DescriptionTemplateSectionFieldCategory.System || field.category as unknown === DescriptionTemplateSectionFieldCategory.System) && field.systemFieldType === DescriptionTemplateSystemFieldType.TEXT)); // } // hasDescription(): boolean { // const descriptionTemplate: DescriptionTemplatePersist = this.formGroup.value; - // return descriptionTemplate.definition.sections.some(section => section.fields.some(field => (field.category === DescriptionTemplateSectionFieldCategory.SYSTEM || field.category as unknown === DescriptionTemplateSectionFieldCategory.SYSTEM) && field.systemFieldType === DescriptionTemplateSystemFieldType.HTML_TEXT)); + // return descriptionTemplate.definition.sections.some(section => section.fields.some(field => (field.category === DescriptionTemplateSectionFieldCategory.System || field.category as unknown === DescriptionTemplateSectionFieldCategory.System) && field.systemFieldType === DescriptionTemplateSystemFieldType.Description)); // } // hasDescriptionTemplates(): boolean { diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.model.ts b/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.model.ts index cd7bfc8f8..b7c80e5f0 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.model.ts +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.model.ts @@ -4,8 +4,8 @@ import { DescriptionTemplateFieldType } from "@app/core/common/enum/description- import { DescriptionTemplateFieldValidationType } from "@app/core/common/enum/description-template-field-validation-type"; import { DescriptionTemplateStatus } from "@app/core/common/enum/description-template-status"; import { UserDescriptionTemplateRole } from "@app/core/common/enum/user-description-template-role"; -import { DescriptionTemplate, DescriptionTemplateDefinition, DescriptionTemplateExternalSelectSourceBinding, DescriptionTemplateField, DescriptionTemplateFieldSet, DescriptionTemplateLabelData, DescriptionTemplateMultiplicity, DescriptionTemplatePage, DescriptionTemplateRule, DescriptionTemplateSection } from "@app/core/model/description-template/description-template"; -import { DescriptionTemplateDefinitionPersist, DescriptionTemplateExternalDatasetDataPersist, DescriptionTemplateExternalSelectAuthDataPersist, DescriptionTemplateExternalSelectDataPersist, DescriptionTemplateExternalSelectSourceBindingPersist, DescriptionTemplateExternalSelectSourcePersist, DescriptionTemplateFieldPersist, DescriptionTemplateFieldSetPersist, DescriptionTemplateLabelAndMultiplicityDataPersist, DescriptionTemplateLabelDataPersist, DescriptionTemplateMultiplicityPersist, DescriptionTemplatePagePersist, DescriptionTemplatePersist, DescriptionTemplateRadioBoxDataPersist, DescriptionTemplateRadioBoxOptionPersist, DescriptionTemplateRulePersist, DescriptionTemplateSectionPersist, DescriptionTemplateSelectDataPersist, DescriptionTemplateSelectOptionPersist, DescriptionTemplateUploadDataPersist, DescriptionTemplateUploadOptionPersist, UserDescriptionTemplatePersist } from "@app/core/model/description-template/description-template-persist"; +import { DescriptionTemplate, DescriptionTemplateDefinition, DescriptionTemplateField, DescriptionTemplateFieldSet, DescriptionTemplateLabelData, DescriptionTemplateMultiplicity, DescriptionTemplatePage, DescriptionTemplateReferenceTypeData, DescriptionTemplateRule, DescriptionTemplateSection } from "@app/core/model/description-template/description-template"; +import { DescriptionTemplateDefinitionPersist, DescriptionTemplateExternalDatasetDataPersist, DescriptionTemplateFieldPersist, DescriptionTemplateFieldSetPersist, DescriptionTemplateLabelAndMultiplicityDataPersist, DescriptionTemplateLabelDataPersist, DescriptionTemplateMultiplicityPersist, DescriptionTemplatePagePersist, DescriptionTemplatePersist, DescriptionTemplateRadioBoxDataPersist, DescriptionTemplateRadioBoxOptionPersist, DescriptionTemplateReferenceTypeFieldPersist, DescriptionTemplateRulePersist, DescriptionTemplateSectionPersist, DescriptionTemplateSelectDataPersist, DescriptionTemplateSelectOptionPersist, DescriptionTemplateUploadDataPersist, DescriptionTemplateUploadOptionPersist, UserDescriptionTemplatePersist } from "@app/core/model/description-template/description-template-persist"; import { BaseEditorModel } from "@common/base/base-form-editor-model"; import { BackendErrorValidator } from "@common/forms/validation/custom-validator"; import { ValidationErrorModel } from "@common/forms/validation/error-model/validation-error-model"; @@ -229,7 +229,7 @@ export class DescriptionTemplateDefinitionEditorModel implements DescriptionTemp this.validationErrorModel ).fromModel(item).buildForm({ rootPath: `${rootPath}pages[${index}].` - }) + }) ), context.getValidation('pages').validators ), }); @@ -802,8 +802,8 @@ export class DescriptionTemplateFieldEditorModel implements DescriptionTemplateF private getFieldEditorModel(fieldType: DescriptionTemplateFieldType): DescriptionTemplateLabelDataEditorModel { switch (fieldType) { - case DescriptionTemplateFieldType.EXTERNAL_SELECT: - return new DescriptionTemplateExternalSelectDataEditorModel(this.validationErrorModel); + case DescriptionTemplateFieldType.REFERENCE_TYPES: + return new DescriptionTemplateReferenceTypeDataEditorModel(this.validationErrorModel); case DescriptionTemplateFieldType.RADIO_BOX: return new DescriptionTemplateRadioBoxDataEditorModel(this.validationErrorModel); case DescriptionTemplateFieldType.SELECT: @@ -819,19 +819,8 @@ export class DescriptionTemplateFieldEditorModel implements DescriptionTemplateF case DescriptionTemplateFieldType.CURRENCY: case DescriptionTemplateFieldType.VALIDATION: return new DescriptionTemplateLabelDataEditorModel(this.validationErrorModel); - case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_RESEARCHERS: case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_DMPS: case DescriptionTemplateFieldType.INTERNAL_ENTRIES_DESCRIPTIONS: - case DescriptionTemplateFieldType.DATA_REPOSITORIES: - case DescriptionTemplateFieldType.JOURNAL_REPOSITORIES: - case DescriptionTemplateFieldType.PUB_REPOSITORIES: - case DescriptionTemplateFieldType.LICENSES: - case DescriptionTemplateFieldType.TAXONOMIES: - case DescriptionTemplateFieldType.PUBLICATIONS: - case DescriptionTemplateFieldType.REGISTRIES: - case DescriptionTemplateFieldType.SERVICES: - case DescriptionTemplateFieldType.RESEARCHERS: - case DescriptionTemplateFieldType.ORGANIZATIONS: return new DescriptionTemplateLabelAndMultiplicityDataEditorModel(this.validationErrorModel); case DescriptionTemplateFieldType.EXTERNAL_DATASETS: return new DescriptionTemplateExternalDatasetDataEditorModel(this.validationErrorModel); @@ -864,7 +853,7 @@ export class DescriptionTemplateFieldEditorModel implements DescriptionTemplateF validationErrorModel: validationErrorModel }); - if(formGroup?.get('data').get('fieldType').value != undefined){ + if (formGroup?.get('data').get('fieldType').value != undefined) { switch (formGroup?.get('data').get('fieldType').value) { case DescriptionTemplateFieldType.UPLOAD: DescriptionTemplateUploadDataEditorModel.reapplyUploadDataValidators({ @@ -887,8 +876,8 @@ export class DescriptionTemplateFieldEditorModel implements DescriptionTemplateF validationErrorModel: validationErrorModel }); break; - case DescriptionTemplateFieldType.EXTERNAL_SELECT: - DescriptionTemplateExternalSelectDataEditorModel.reapplyValidators({ + case DescriptionTemplateFieldType.REFERENCE_TYPES: + DescriptionTemplateReferenceTypeDataEditorModel.reapplyValidators({ formGroup: formGroup?.get('data') as UntypedFormGroup, rootPath: `${rootPath}data.`, validationErrorModel: validationErrorModel @@ -900,7 +889,7 @@ export class DescriptionTemplateFieldEditorModel implements DescriptionTemplateF validationErrorModel: validationErrorModel }); break; - + } } @@ -1190,26 +1179,23 @@ export class DescriptionTemplateExternalDatasetDataEditorModel extends Descripti } } - // // -// External Select Field +// Reference Types // // -export class DescriptionTemplateExternalSelectDataEditorModel extends DescriptionTemplateLabelDataEditorModel implements DescriptionTemplateExternalSelectDataPersist { - multipleSelect: boolean = false; - sources: DescriptionTemplateExternalSelectSourceEditorModel[] = []; +export class DescriptionTemplateReferenceTypeDataEditorModel extends DescriptionTemplateLabelAndMultiplicityDataEditorModel implements DescriptionTemplateReferenceTypeFieldPersist { + referenceTypeId: Guid; protected formBuilder: UntypedFormBuilder = new UntypedFormBuilder(); constructor( public validationErrorModel: ValidationErrorModel = new ValidationErrorModel() ) { super(validationErrorModel); } - fromModel(item: DescriptionTemplateExternalSelectDataPersist): DescriptionTemplateExternalSelectDataEditorModel { + fromModel(item: DescriptionTemplateReferenceTypeData): DescriptionTemplateReferenceTypeDataEditorModel { if (item) { super.fromModel(item); - this.multipleSelect = item.multipleSelect ?? false; - if (item.sources) { item.sources.map(x => this.sources.push(new DescriptionTemplateExternalSelectSourceEditorModel(this.validationErrorModel).fromModel(x))); } + this.referenceTypeId = item.referenceTypeId; } return this; } @@ -1221,21 +1207,14 @@ export class DescriptionTemplateExternalSelectDataEditorModel extends Descriptio }): UntypedFormGroup { let { context = null, disabled = false, rootPath } = params ?? {} if (context == null) { - context = DescriptionTemplateExternalSelectDataEditorModel.createValidationContext({ + context = DescriptionTemplateReferenceTypeDataEditorModel.createValidationContext({ validationErrorModel: this.validationErrorModel, rootPath }); } const formGroup = super.buildForm({ context, disabled, rootPath }); - formGroup.setControl('multipleSelect', new FormControl({ value: this.multipleSelect, disabled: disabled }, context.getValidation('multipleSelect').validators)); - formGroup.setControl('sources', this.formBuilder.array( - (this.sources ?? []).map( - (item, index) => item.buildForm({ - rootPath: `${rootPath}sources[${index}].` - }) - ), context.getValidation('sources').validators - )); + formGroup.setControl('referenceTypeId', new FormControl({ value: this.referenceTypeId, disabled: disabled }, context.getValidation('referenceTypeId').validators)); return formGroup; } @@ -1245,8 +1224,7 @@ export class DescriptionTemplateExternalSelectDataEditorModel extends Descriptio }): ValidationContext { const { rootPath = '', validationErrorModel } = params; const baseContext: ValidationContext = super.createValidationContext({ rootPath, validationErrorModel }); - baseContext.validation.push({ key: 'multipleSelect', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}multipleSelect`)] }); - baseContext.validation.push({ key: 'sources', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}sources`)] }); + baseContext.validation.push({ key: 'referenceTypeId', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}referenceTypeId`)] }); return baseContext; } @@ -1257,285 +1235,12 @@ export class DescriptionTemplateExternalSelectDataEditorModel extends Descriptio }): void { const { formGroup, rootPath, validationErrorModel } = params; - const context = DescriptionTemplateExternalSelectDataEditorModel.createValidationContext({ + const context = DescriptionTemplateReferenceTypeDataEditorModel.createValidationContext({ rootPath, validationErrorModel }); - ['multipleSelect'].forEach(keyField => { - const control = formGroup?.get(keyField); - control?.clearValidators(); - control?.addValidators(context.getValidation(keyField).validators); - }); - - (formGroup.get('sources') as FormArray).controls?.forEach( - (control, index) => DescriptionTemplateExternalSelectSourceEditorModel.reapplyValidators({ - formGroup: control as UntypedFormGroup, - rootPath: `${rootPath}sources[${index}].`, - validationErrorModel: validationErrorModel - } - ) - ); - } -} - -export class DescriptionTemplateExternalSelectSourceEditorModel implements DescriptionTemplateExternalSelectSourcePersist { - url: string; - method: string; - optionsRoot: string; - sourceBinding: DescriptionTemplateExternalSelectSourceBindingEditorModel = new DescriptionTemplateExternalSelectSourceBindingEditorModel(this.validationErrorModel); - hasAuth: boolean; - auth: DescriptionTemplateExternalSelectAuthDataEditorModel = new DescriptionTemplateExternalSelectAuthDataEditorModel(this.validationErrorModel); - protected formBuilder: UntypedFormBuilder = new UntypedFormBuilder(); - - constructor( - public validationErrorModel: ValidationErrorModel = new ValidationErrorModel() - ) { } - - fromModel(item: DescriptionTemplateExternalSelectSourcePersist): DescriptionTemplateExternalSelectSourceEditorModel { - if (item) { - this.url = item.url; - this.sourceBinding = new DescriptionTemplateExternalSelectSourceBindingEditorModel(this.validationErrorModel).fromModel(item.sourceBinding); - this.optionsRoot = item.optionsRoot; - this.hasAuth = item.hasAuth; - this.auth = new DescriptionTemplateExternalSelectAuthDataEditorModel(this.validationErrorModel).fromModel(item.auth); - this.method = item.method; - } - return this; - } - - buildForm(params?: { - context?: ValidationContext, - disabled?: boolean, - rootPath?: string - }): UntypedFormGroup { - let { context = null, disabled = false, rootPath } = params ?? {} - if (context == null) { - context = DescriptionTemplateExternalSelectSourceEditorModel.createValidationContext({ - validationErrorModel: this.validationErrorModel, - rootPath - }); - } - - return this.formBuilder.group({ - url: [{ value: this.url, disabled: disabled }, context.getValidation('url').validators], - optionsRoot: [{ value: this.optionsRoot, disabled: disabled }, context.getValidation('optionsRoot').validators], - hasAuth: [{ value: this.hasAuth, disabled: disabled }, context.getValidation('hasAuth').validators], - method: [{ value: this.method, disabled: disabled }, context.getValidation('method').validators], - sourceBinding: this.sourceBinding.buildForm({ - rootPath: `${rootPath}sourceBinding.` - }), - auth: this.auth.buildForm({ - rootPath: `${rootPath}auth.` - }), - }); - } - - static createValidationContext(params: { - rootPath?: string, - validationErrorModel: ValidationErrorModel - }): ValidationContext { - const { rootPath = '', validationErrorModel } = params; - - const baseContext: ValidationContext = new ValidationContext(); - const baseValidationArray: Validation[] = new Array(); - baseValidationArray.push({ key: 'url', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}url`)] }); - baseValidationArray.push({ key: 'optionsRoot', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}optionsRoot`)] }); - baseValidationArray.push({ key: 'hasAuth', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}hasAuth`)] }); - baseValidationArray.push({ key: 'method', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}method`)] }); - baseValidationArray.push({ key: 'extendedDescription', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}extendedDescription`)] }); - baseValidationArray.push({ key: 'additionalInformation', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}additionalInformation`)] }); - baseValidationArray.push({ key: 'hasCommentField', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}hasCommentField`)] }); - baseValidationArray.push({ key: 'fields', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}fields`)] }); - - baseContext.validation = baseValidationArray; - return baseContext; - } - - static reapplyValidators(params: { - formGroup: UntypedFormGroup, - validationErrorModel: ValidationErrorModel, - rootPath: string - }): void { - - const { formGroup, rootPath, validationErrorModel } = params; - const context = DescriptionTemplateExternalSelectSourceEditorModel.createValidationContext({ - rootPath, - validationErrorModel - }); - - ['url', 'optionsRoot', 'hasAuth', 'method'].forEach(keyField => { - const control = formGroup?.get(keyField); - control?.clearValidators(); - control?.addValidators(context.getValidation(keyField).validators); - }); - - DescriptionTemplateExternalSelectSourceBindingEditorModel.reapplyValidators({ - formGroup: formGroup?.get('sourceBinding') as UntypedFormGroup, - rootPath: `${rootPath}sourceBinding.`, - validationErrorModel: validationErrorModel - }); - - DescriptionTemplateExternalSelectAuthDataEditorModel.reapplyValidators({ - formGroup: formGroup?.get('auth') as UntypedFormGroup, - rootPath: `${rootPath}auth.`, - validationErrorModel: validationErrorModel - }); - - } -} - -export class DescriptionTemplateExternalSelectSourceBindingEditorModel implements DescriptionTemplateExternalSelectSourceBindingPersist { - label: string; - value: string; - source: string; - protected formBuilder: UntypedFormBuilder = new UntypedFormBuilder(); - - constructor( - public validationErrorModel: ValidationErrorModel = new ValidationErrorModel() - ) { } - - fromModel(item: DescriptionTemplateExternalSelectSourceBinding): DescriptionTemplateExternalSelectSourceBindingEditorModel { - if (item) { - this.label = item.label; - this.value = item.value; - this.source = item.source; - } - return this; - } - - buildForm(params?: { - context?: ValidationContext, - disabled?: boolean, - rootPath?: string - }): UntypedFormGroup { - let { context = null, disabled = false, rootPath } = params ?? {} - if (context == null) { - context = DescriptionTemplateExternalSelectSourceBindingEditorModel.createValidationContext({ - validationErrorModel: this.validationErrorModel, - rootPath - }); - } - - return this.formBuilder.group({ - label: [{ value: this.label, disabled: disabled }, context.getValidation('label').validators], - value: [{ value: this.value, disabled: disabled }, context.getValidation('value').validators], - source: [{ value: this.source, disabled: disabled }, context.getValidation('source').validators], - }); - } - - static createValidationContext(params: { - rootPath?: string, - validationErrorModel: ValidationErrorModel - }): ValidationContext { - const { rootPath = '', validationErrorModel } = params; - - const baseContext: ValidationContext = new ValidationContext(); - const baseValidationArray: Validation[] = new Array(); - baseValidationArray.push({ key: 'label', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}label`)] }); - baseValidationArray.push({ key: 'value', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}value`)] }); - baseValidationArray.push({ key: 'source', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}source`)] }); - - baseContext.validation = baseValidationArray; - return baseContext; - } - - static reapplyValidators(params: { - formGroup: UntypedFormGroup, - validationErrorModel: ValidationErrorModel, - rootPath: string - }): void { - - const { formGroup, rootPath, validationErrorModel } = params; - const context = DescriptionTemplateExternalSelectSourceBindingEditorModel.createValidationContext({ - rootPath, - validationErrorModel - }); - - ['label', 'value', 'source'].forEach(keyField => { - const control = formGroup?.get(keyField); - control?.clearValidators(); - control?.addValidators(context.getValidation(keyField).validators); - }) - } -} - -export class DescriptionTemplateExternalSelectAuthDataEditorModel implements DescriptionTemplateExternalSelectAuthDataPersist { - url: string; - method: string; - body: string; - path: string; - type: string; - protected formBuilder: UntypedFormBuilder = new UntypedFormBuilder(); - - constructor( - public validationErrorModel: ValidationErrorModel = new ValidationErrorModel() - ) { } - - fromModel(item: DescriptionTemplateExternalSelectAuthDataPersist): DescriptionTemplateExternalSelectAuthDataEditorModel { - if (item) { - this.url = item.url; - this.method = item.method; - this.body = item.body; - this.path = item.path; - this.type = item.type; - } - return this; - } - - buildForm(params?: { - context?: ValidationContext, - disabled?: boolean, - rootPath?: string - }): UntypedFormGroup { - let { context = null, disabled = false, rootPath } = params ?? {} - if (context == null) { - context = DescriptionTemplateExternalSelectAuthDataEditorModel.createValidationContext({ - validationErrorModel: this.validationErrorModel, - rootPath - }); - } - - return this.formBuilder.group({ - url: [{ value: this.url, disabled: disabled }, context.getValidation('url').validators], - method: [{ value: this.method, disabled: disabled }, context.getValidation('method').validators], - body: [{ value: this.body, disabled: disabled }, context.getValidation('body').validators], - path: [{ value: this.path, disabled: disabled }, context.getValidation('path').validators], - type: [{ value: this.type, disabled: disabled }, context.getValidation('type').validators], - }); - } - - static createValidationContext(params: { - rootPath?: string, - validationErrorModel: ValidationErrorModel - }): ValidationContext { - const { rootPath = '', validationErrorModel } = params; - - const baseContext: ValidationContext = new ValidationContext(); - const baseValidationArray: Validation[] = new Array(); - baseValidationArray.push({ key: 'url', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}url`)] }); - baseValidationArray.push({ key: 'method', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}method`)] }); - baseValidationArray.push({ key: 'body', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}body`)] }); - baseValidationArray.push({ key: 'path', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}path`)] }); - baseValidationArray.push({ key: 'type', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}type`)] }); - - baseContext.validation = baseValidationArray; - return baseContext; - } - - static reapplyValidators(params: { - formGroup: UntypedFormGroup, - validationErrorModel: ValidationErrorModel, - rootPath: string - }): void { - - const { formGroup, rootPath, validationErrorModel } = params; - const context = DescriptionTemplateExternalSelectAuthDataEditorModel.createValidationContext({ - rootPath, - validationErrorModel - }); - - ['url', 'method', 'body', 'path', 'type'].forEach(keyField => { + ['referenceTypeId'].forEach(keyField => { const control = formGroup?.get(keyField); control?.clearValidators(); control?.addValidators(context.getValidation(keyField).validators); @@ -1586,7 +1291,7 @@ export class DescriptionTemplateRadioBoxDataEditorModel extends DescriptionTempl rootPath: `${rootPath}options[${index}].` }) ), context.getValidation('options').validators - )); + )); return formGroup; } @@ -1733,7 +1438,7 @@ export class DescriptionTemplateSelectDataEditorModel extends DescriptionTemplat rootPath: `${rootPath}options[${index}].` }) ), context.getValidation('options').validators - )); + )); return formGroup; } @@ -1894,7 +1599,7 @@ export class DescriptionTemplateUploadDataEditorModel extends DescriptionTemplat rootPath: `${rootPath}types[${index}].` }) ), context.getValidation('types').validators - )); + )); return formGroup; } diff --git a/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.resolver.ts b/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.resolver.ts index b89976b71..11b59922d 100644 --- a/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.resolver.ts +++ b/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor.resolver.ts @@ -1,7 +1,7 @@ import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { DescriptionTemplateType } from '@app/core/model/description-template-type/description-template-type'; -import { DescriptionTemplate, DescriptionTemplateExternalSelectData, DescriptionTemplateBaseFieldData, DescriptionTemplateSelectOption, DescriptionTemplateDefinition, DescriptionTemplateField, DescriptionTemplateFieldSet, DescriptionTemplateMultiplicity, DescriptionTemplatePage, DescriptionTemplateRule, DescriptionTemplateSection, DescriptionTemplateSelectData, DescriptionTemplateExternalDatasetData, DescriptionTemplateExternalSelectSource, DescriptionTemplateExternalSelectAuthData, DescriptionTemplateExternalSelectSourceBinding, DescriptionTemplateUploadData, DescriptionTemplateUploadOption } from '@app/core/model/description-template/description-template'; +import { DescriptionTemplate, DescriptionTemplateBaseFieldData, DescriptionTemplateDefinition, DescriptionTemplateExternalDatasetData, DescriptionTemplateField, DescriptionTemplateFieldSet, DescriptionTemplateLabelAndMultiplicityData, DescriptionTemplateMultiplicity, DescriptionTemplatePage, DescriptionTemplateReferenceTypeData, DescriptionTemplateRule, DescriptionTemplateSection, DescriptionTemplateSelectData, DescriptionTemplateSelectOption, DescriptionTemplateUploadData, DescriptionTemplateUploadOption } from '@app/core/model/description-template/description-template'; import { DescriptionTemplateService } from '@app/core/services/description-template/description-template.service'; import { BreadcrumbService } from '@app/ui/misc/breadcrumb/breadcrumb.service'; import { BaseEditorResolver } from '@common/base/base-editor.resolver'; @@ -70,20 +70,9 @@ export class DescriptionTemplateEditorResolver extends BaseEditorResolver { [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.multipleSelect)].join('.'), [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.options), nameof(x => x.label)].join('.'), [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.options), nameof(x => x.value)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.multipleSelect)].join('.'), + [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.multipleSelect)].join('.'), [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.type)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.url)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.method)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.optionsRoot)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.sourceBinding), nameof(x => x.label)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.sourceBinding), nameof(x => x.value)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.sourceBinding), nameof(x => x.source)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.hasAuth)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.auth), nameof(x => x.url)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.auth), nameof(x => x.method)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.auth), nameof(x => x.body)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.auth), nameof(x => x.path)].join('.'), - [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.sources), nameof(x => x.auth), nameof(x => x.type)].join('.'), + [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.referenceTypeId)].join('.'), [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.maxFileSizeInMB)].join('.'), [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.types), nameof(x => x.label)].join('.'), [nameof(x => x.definition), nameof(x => x.pages), nameof(x => x.sections), nameof(x => x.fieldSets), nameof(x => x.fields), nameof(x => x.data), nameof(x => x.types), nameof(x => x.value)].join('.'), diff --git a/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.component.html b/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.component.html index 7fd040978..1358c0f37 100644 --- a/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.component.html +++ b/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.component.html @@ -85,19 +85,10 @@ {{'GENERAL.VALIDATION.REQUIRED' | translate}}
-
- - {{'DMP-BLUEPRINT-EDITOR.FIELDS.SYSTEM-FIELDS' | translate}} - - {{enumUtils.toDmpBlueprintSystemFieldTypeString(systemFieldType)}} - - -
- +
-
@@ -105,17 +96,27 @@ {{fieldIndex + 1}}
drag_indicator
-
+
- {{'DMP-BLUEPRINT-EDITOR.FIELDS.SYSTEM-FIELD' | translate}} - - {{field.get('dataType').getError('backendError').message}} - {{'GENERAL.VALIDATION.REQUIRED' | translate}} + {{'DMP-BLUEPRINT-EDITOR.FIELDS.CATEGORY' | translate}} + + {{enumUtils.toDmpBlueprintFieldCategoryString(fieldCategory)}} +
-
+
- {{'DMP-BLUEPRINT-EDITOR.FIELDS.FIELD-DATA-TYPE' | translate}} + {{'DMP-BLUEPRINT-EDITOR.FIELDS.SYSTEM-FIELD-TYPE' | translate}} + + {{enumUtils.toDmpBlueprintSystemFieldTypeString(systemFieldType)}} + + {{field.get('systemFieldType').getError('backendError').message}} + {{'GENERAL.VALIDATION.REQUIRED' | translate}} + +
+
+ + {{'DMP-BLUEPRINT-EDITOR.FIELDS.DATA-TYPE' | translate}} {{enumUtils.toDmpBlueprintExtraFieldDataTypeString(extraFieldDataType)}} @@ -125,7 +126,15 @@ {{'GENERAL.VALIDATION.REQUIRED' | translate}}
-
+
+ + {{'DMP-BLUEPRINT-EDITOR.FIELDS.REFERENCE-TYPE' | translate}} + + {{field.get('referenceTypeId').getError('backendError').message}} + {{'GENERAL.VALIDATION.REQUIRED' | translate}} + +
+
{{'DMP-BLUEPRINT-EDITOR.FIELDS.FIELD-LABEL' | translate}} @@ -133,7 +142,7 @@ {{'GENERAL.VALIDATION.REQUIRED' | translate}}
-
+
{{'DMP-BLUEPRINT-EDITOR.FIELDS.FIELD-PLACEHOLDER' | translate}} @@ -141,7 +150,7 @@ {{'GENERAL.VALIDATION.REQUIRED' | translate}}
-
+
{{'DMP-BLUEPRINT-EDITOR.FIELDS.FIELD-DESCRIPTION' | translate}} @@ -149,18 +158,13 @@ {{'GENERAL.VALIDATION.REQUIRED' | translate}}
-
- {{'DMP-BLUEPRINT-EDITOR.FIELDS.FIELD-REQUIRED' | translate}} +
+ {{'DMP-BLUEPRINT-EDITOR.FIELDS.FIELD-REQUIRED' | translate}} {{field.get('systemFieldType').getError('backendError').message}} {{'GENERAL.VALIDATION.REQUIRED' | translate}}
-
- -
-
-
@@ -174,7 +178,7 @@
- + {{'DMP-BLUEPRINT-EDITOR.FIELDS.DESCRIPTION-TEMPLATES' | translate}} {{section.get('hasTemplates').getError('backendError').message}} {{'GENERAL.VALIDATION.REQUIRED' | translate}} @@ -185,7 +189,7 @@
- +
@@ -229,7 +233,7 @@ delete
-
+
{{section.get('descriptionTemplates').getError('backendError').message}}
diff --git a/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.component.ts b/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.component.ts index 18de7bda0..d7571f922 100644 --- a/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.component.ts +++ b/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.component.ts @@ -9,18 +9,23 @@ import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; // import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item'; import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; import { DatePipe } from '@angular/common'; +import { MatCheckboxChange } from '@angular/material/checkbox'; +import { MatSelectChange } from '@angular/material/select'; +import { DmpBlueprintFieldCategory } from '@app/core/common/enum/dmp-blueprint-field-category'; import { DmpBlueprintExtraFieldDataType } from '@app/core/common/enum/dmp-blueprint-field-type'; -import { DmpBlueprintSectionFieldCategory } from '@app/core/common/enum/dmp-blueprint-section-field-category'; import { DmpBlueprintStatus } from '@app/core/common/enum/dmp-blueprint-status'; import { DmpBlueprintSystemFieldType } from '@app/core/common/enum/dmp-blueprint-system-field-type'; import { IsActive } from '@app/core/common/enum/is-active.enum'; import { AppPermission } from '@app/core/common/enum/permission.enum'; -import { DmpBlueprint, DmpBlueprintPersist, NewVersionDmpBlueprintPersist } from '@app/core/model/dmp-blueprint/dmp-blueprint'; +import { DescriptionTemplate } from '@app/core/model/description-template/description-template'; +import { DmpBlueprint, DmpBlueprintPersist, NewVersionDmpBlueprintPersist, SystemFieldInSection } from '@app/core/model/dmp-blueprint/dmp-blueprint'; import { AuthService } from '@app/core/services/auth/auth.service'; +import { DescriptionTemplateService } from '@app/core/services/description-template/description-template.service'; import { LoggingService } from '@app/core/services/logging/logging-service'; import { MatomoService } from '@app/core/services/matomo/matomo-service'; import { FileUtils } from '@app/core/services/utilities/file-utils.service'; import { QueryParamsService } from '@app/core/services/utilities/query-params.service'; +import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration'; import { BaseEditor } from '@common/base/base-editor'; import { FormService } from '@common/forms/form-service'; import { FormValidationErrorsDialogComponent } from '@common/forms/form-validation-errors-dialog/form-validation-errors-dialog.component'; @@ -31,15 +36,11 @@ import { Guid } from '@common/types/guid'; import { TranslateService } from '@ngx-translate/core'; import * as FileSaver from 'file-saver'; import { map, takeUntil } from 'rxjs/operators'; -import { DescriptionTemplatesInSectionEditorModel, DmpBlueprintDefinitionSectionEditorModel, DmpBlueprintEditorModel, FieldInSectionEditorModel } from './dmp-blueprint-editor.model'; +import { DescriptionTemplatePreviewDialogComponent } from '../../description-template/description-template-preview/description-template-preview-dialog.component'; +import { DmpBlueprintEditorModel } from './dmp-blueprint-editor.model'; import { DmpBlueprintEditorResolver } from './dmp-blueprint-editor.resolver'; import { DmpBlueprintEditorService } from './dmp-blueprint-editor.service'; -import { DescriptionTemplateService } from '@app/core/services/description-template/description-template.service'; -import { DescriptionTemplate } from '@app/core/model/description-template/description-template'; -import { MatSelectChange } from '@angular/material/select'; -import { DescriptionTemplatePreviewDialogComponent } from '../../description-template/description-template-preview/description-template-preview-dialog.component'; -import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration'; -import { MatCheckboxChange } from '@angular/material/checkbox'; +import { ReferenceTypeService } from '@app/core/services/reference-type/reference-type.service'; @Component({ @@ -56,15 +57,16 @@ export class DmpBlueprintEditorComponent extends BaseEditor = []; - dmpBlueprintSectionFieldCategory = DmpBlueprintSectionFieldCategory; + + dmpBlueprintSectionFieldCategory = DmpBlueprintFieldCategory; dmpBlueprintSystemFieldType = DmpBlueprintSystemFieldType; public dmpBlueprintSystemFieldTypeEnum = this.enumUtils.getEnumValues(DmpBlueprintSystemFieldType); dmpBlueprintExtraFieldDataType = DmpBlueprintExtraFieldDataType; public dmpBlueprintExtraFieldDataTypeEnum = this.enumUtils.getEnumValues(DmpBlueprintExtraFieldDataType); + public dmpBlueprintFieldCategoryEnum = this.enumUtils.getEnumValues(DmpBlueprintFieldCategory); descriptionTempalteGroupSingleAutocompleteConfiguration: SingleAutoCompleteConfiguration = { initialItems: (data?: any) => this.descriptionTemplateService.query(this.descriptionTemplateService.buildDescriptionTempalteGroupAutocompleteLookup(null, null, null, this.getUsedDescriptionTemplateGroupIds())).pipe(map(x => x.items)), - filterFn: (searchQuery: string, data?: any) => this.descriptionTemplateService.query(this.descriptionTemplateService.buildDescriptionTempalteGroupAutocompleteLookup(searchQuery, null, null, this.getUsedDescriptionTemplateGroupIds() ? this.getUsedDescriptionTemplateGroupIds(): null)).pipe(map(x => x.items)), + filterFn: (searchQuery: string, data?: any) => this.descriptionTemplateService.query(this.descriptionTemplateService.buildDescriptionTempalteGroupAutocompleteLookup(searchQuery, null, null, this.getUsedDescriptionTemplateGroupIds() ? this.getUsedDescriptionTemplateGroupIds() : null)).pipe(map(x => x.items)), getSelectedItem: (selectedItem: any) => this.descriptionTemplateService.query(this.descriptionTemplateService.buildDescriptionTempalteGroupAutocompleteLookup(null, null, [selectedItem])).pipe(map(x => x.items[0])), displayFn: (item: DescriptionTemplate) => item.label, titleFn: (item: DescriptionTemplate) => item.label, @@ -119,7 +121,8 @@ export class DmpBlueprintEditorComponent extends BaseEditor void): void { - if (this.isNew && !this.isClone && !this.isNewVersion){ + if (this.isNew && !this.isClone && !this.isNewVersion) { const formData = this.formService.getValue(this.formGroup.value) as DmpBlueprintPersist; this.dmpBlueprintService.persist(formData) @@ -303,81 +305,13 @@ export class DmpBlueprintEditorComponent extends BaseEditor (x.get('fields') as FormArray).controls.some(y => (y as UntypedFormGroup).get('systemFieldType')?.value === systemField)); - // for (let section in (this.formGroup.get('definition').get('sections')as FormArray)?.controls) { - // if (i != sectionIndex) { - // for (let f of this.fieldsArray(i).controls) { - // if ((f.get('category').value == FieldCategory.SYSTEM || f.get('category').value == DmpBlueprintSectionFieldCategory.SYSTEM) && f.get('type').value == systemField) { - // return true; - // } - // } - // } - // i++; - // } - // return false; - } - selectedSystemFieldDisabled(): Array { - return (this.formGroup.get('definition').get('sections') as FormArray)?.controls.flatMap(x => (x.get('fields') as FormArray).controls.map(y => (y as UntypedFormGroup).get('systemFieldType')?.value as DmpBlueprintSystemFieldType)); - } - - addSystemField(sectionIndex: number, matSelect: MatSelectChange): void { - let systemFieldTypes = matSelect.value as number[]; - let sectionsFormArray: FormArray = this.formGroup.get('definition').get('sections') as FormArray; - let sectionFieldsFormArray: FormArray = sectionsFormArray.at(sectionIndex).get('fields') as FormArray; - const fieldSize = sectionFieldsFormArray.length; - systemFieldTypes = systemFieldTypes.filter(field => !sectionsFormArray.controls.some(x => (x.get('fields') as FormArray).controls.some(y => (y as UntypedFormGroup).get('systemFieldType')?.value === field))); - for (let systemFieldType of systemFieldTypes) { - sectionFieldsFormArray.push(this.editorModel.createChildSystemField(sectionIndex, fieldSize, systemFieldType)); - // const fieldSize = sectionFieldsFormArray.length; - // if (fieldSize == 0) { - // sectionFieldsFormArray.push(this.editorModel.createChildSystemField(sectionIndex, fieldSize, systemFieldType)); - // return; - // } else { - // if (!sectionFieldsFormArray.controls.some(y => (y as UntypedFormGroup).get('systemFieldType')?.value === systemFieldType)) { - // sectionFieldsFormArray.push(this.editorModel.createChildSystemField(sectionIndex, fieldSize, systemFieldType)); - // return; - // } - // } - } - } - - removeSystemField(sectionIndex: number, fieldIndex: number): void { - const fieldsArray = (this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray; - const systemFieldType = fieldsArray.at(fieldIndex).get('systemFieldType').value - if(systemFieldType > -1) { - if (this.selectedSystemFields.length == 1){ - this.selectedSystemFields = []; - }else{ - const index = this.selectedSystemFields.indexOf(systemFieldType); - if (index > -1) { - this.selectedSystemFields.splice(index, 1); - this.selectedSystemFields = [...this.selectedSystemFields]; - } - } - } - fieldsArray.removeAt(fieldIndex); - fieldsArray.controls.forEach((section, index) => { - section.get('ordinal').setValue(index + 1); - }); - - DmpBlueprintEditorModel.reApplySectionValidators( - { - formGroup: this.formGroup, - validationErrorModel: this.editorModel.validationErrorModel - } - ); - fieldsArray.markAsDirty(); - } - - addExtraField(sectionIndex: number): void { + addField(sectionIndex: number) { ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray) - .push(this.editorModel.createChildExtraField(sectionIndex, ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray).length)); - + .push(this.editorModel.createChildField(sectionIndex, ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray).length)); } - removeExtraField(sectionIndex: number, fieldIndex: number): void { + removeField(sectionIndex: number, fieldIndex: number): void { const formArray = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray); formArray.removeAt(fieldIndex); formArray.controls.forEach((section, index) => { @@ -394,6 +328,21 @@ export class DmpBlueprintEditorComponent extends BaseEditor (x.get('fields') as FormArray).controls.some(y => (y as UntypedFormGroup).get('systemFieldType')?.value === systemField)); + } + + fieldCategoryChanged(sectionIndex: number, fieldIndex: number) { + //Reapply validators + DmpBlueprintEditorModel.reApplySectionValidators( + { + formGroup: this.formGroup, + validationErrorModel: this.editorModel.validationErrorModel + } + ); + (this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields').markAsDirty(); + } + dropFields(event: CdkDragDrop, sectionIndex: number) { const fieldsFormArray = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray); @@ -414,34 +363,34 @@ export class DmpBlueprintEditorComponent extends BaseEditor { const descriptionTempaltesArray = (this.formGroup.get('definition').get('sections') as FormArray).at(index).get('descriptionTemplates') as FormArray; - if (descriptionTempaltesArray.length > 1){ + if (descriptionTempaltesArray.length > 1) { descriptionTempaltesArray.controls.forEach((template, index) => { - if(template.get('descriptionTemplateGroupId').value != undefined) excludedGroupIds.push(template.get('descriptionTemplateGroupId').value as Guid); + if (template.get('descriptionTemplateGroupId').value != undefined) excludedGroupIds.push(template.get('descriptionTemplateGroupId').value as Guid); }) } }); - + return excludedGroupIds; } removeDescriptionTemplate(sectionIndex: number, descriptionTemplateIndex: number): void { - const descriptionTempaltesArray = (this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('descriptionTemplates') as FormArray; + const descriptionTempaltesArray = (this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('descriptionTemplates') as FormArray; descriptionTempaltesArray.removeAt(descriptionTemplateIndex); DmpBlueprintEditorModel.reApplySectionValidators( @@ -523,12 +472,12 @@ export class DmpBlueprintEditorComponent extends BaseEditor section.fields.some(field => (field.category === DmpBlueprintSectionFieldCategory.SYSTEM || field.category as unknown === DmpBlueprintSectionFieldCategory.SYSTEM) && field.systemFieldType === DmpBlueprintSystemFieldType.TEXT)); + return dmpBlueprint.definition.sections.some(section => section.fields.some(field => (field.category == DmpBlueprintFieldCategory.System) && (field as SystemFieldInSection).systemFieldType === DmpBlueprintSystemFieldType.Title)); } hasDescription(): boolean { const dmpBlueprint: DmpBlueprintPersist = this.formGroup.value; - return dmpBlueprint.definition.sections.some(section => section.fields.some(field => (field.category === DmpBlueprintSectionFieldCategory.SYSTEM || field.category as unknown === DmpBlueprintSectionFieldCategory.SYSTEM) && field.systemFieldType === DmpBlueprintSystemFieldType.HTML_TEXT)); + return dmpBlueprint.definition.sections.some(section => section.fields.some(field => (field.category == DmpBlueprintFieldCategory.System) && (field as SystemFieldInSection).systemFieldType === DmpBlueprintSystemFieldType.Description)); } hasDescriptionTemplates(): boolean { diff --git a/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.model.ts b/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.model.ts index 5cfe3ccd9..8a15d2641 100644 --- a/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.model.ts +++ b/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.model.ts @@ -1,9 +1,9 @@ import { FormArray, UntypedFormArray, UntypedFormBuilder, UntypedFormGroup, Validators } from "@angular/forms"; +import { DmpBlueprintFieldCategory } from "@app/core/common/enum/dmp-blueprint-field-category"; import { DmpBlueprintExtraFieldDataType } from "@app/core/common/enum/dmp-blueprint-field-type"; -import { DmpBlueprintSectionFieldCategory } from "@app/core/common/enum/dmp-blueprint-section-field-category"; import { DmpBlueprintStatus } from "@app/core/common/enum/dmp-blueprint-status"; import { DmpBlueprintSystemFieldType } from "@app/core/common/enum/dmp-blueprint-system-field-type"; -import { DescriptionTemplatesInSection, DescriptionTemplatesInSectionPersist, DmpBlueprint, DmpBlueprintDefinition, DmpBlueprintDefinitionPersist, DmpBlueprintDefinitionSection, DmpBlueprintDefinitionSectionPersist, DmpBlueprintPersist, FieldInSection, FieldInSectionPersist } from "@app/core/model/dmp-blueprint/dmp-blueprint"; +import { DescriptionTemplatesInSection, DescriptionTemplatesInSectionPersist, DmpBlueprint, DmpBlueprintDefinition, DmpBlueprintDefinitionPersist, DmpBlueprintDefinitionSection, DmpBlueprintDefinitionSectionPersist, DmpBlueprintPersist, ExtraFieldInSection, FieldInSection, FieldInSectionPersist, ReferenceTypeFieldInSection, SystemFieldInSection } from "@app/core/model/dmp-blueprint/dmp-blueprint"; import { BaseEditorModel } from "@common/base/base-form-editor-model"; import { BackendErrorValidator } from "@common/forms/validation/custom-validator"; import { ValidationErrorModel } from "@common/forms/validation/error-model/validation-error-model"; @@ -67,22 +67,10 @@ export class DmpBlueprintEditorModel extends BaseEditorModel implements DmpBluep return section.buildForm({ rootPath: 'definition.sections[' + index + '].' }); } - createChildSystemField(sectionIndex: number, index: number, systemFieldType: DmpBlueprintSystemFieldType): UntypedFormGroup { - console.log(sectionIndex, index, systemFieldType.toString()); + createChildField(sectionIndex: number, index: number): UntypedFormGroup { const field: FieldInSectionEditorModel = new FieldInSectionEditorModel(this.validationErrorModel); field.id = Guid.create(); field.ordinal = index + 1; - field.category = DmpBlueprintSectionFieldCategory.SYSTEM; - field.systemFieldType = systemFieldType; - field.required = (systemFieldType == DmpBlueprintSystemFieldType.TEXT || systemFieldType == DmpBlueprintSystemFieldType.HTML_TEXT) ? true : false; - return field.buildForm({ rootPath: 'definition.sections[' + sectionIndex + '].fields[' + index + '].' }); - } - - createChildExtraField(sectionIndex: number, index: number): UntypedFormGroup { - const field: FieldInSectionEditorModel = new FieldInSectionEditorModel(this.validationErrorModel); - field.id = Guid.create(); - field.ordinal = index + 1; - field.category = DmpBlueprintSectionFieldCategory.EXTRA; return field.buildForm({ rootPath: 'definition.sections[' + sectionIndex + '].fields[' + index + '].' }); } @@ -311,14 +299,15 @@ export class DmpBlueprintDefinitionSectionEditorModel implements DmpBlueprintDef export class FieldInSectionEditorModel implements FieldInSectionPersist { public id: Guid; - public category: DmpBlueprintSectionFieldCategory; - public dataType: DmpBlueprintExtraFieldDataType; - public systemFieldType: DmpBlueprintSystemFieldType; + public category: DmpBlueprintFieldCategory; public label: string; public placeholder: string; public description: string; public required: boolean = false; public ordinal: number; + public dataType: DmpBlueprintExtraFieldDataType; + public systemFieldType: DmpBlueprintSystemFieldType; + public referenceTypeId: Guid; protected formBuilder: UntypedFormBuilder = new UntypedFormBuilder(); @@ -329,13 +318,20 @@ export class FieldInSectionEditorModel implements FieldInSectionPersist { fromModel(item: FieldInSection): FieldInSectionEditorModel { this.id = item.id; this.category = item.category; - this.dataType = item.dataType; - this.systemFieldType = item.systemFieldType; this.label = item.label; this.placeholder = item.placeholder; this.description = item.description; this.required = item.required; this.ordinal = item.ordinal; + + if (this.category == DmpBlueprintFieldCategory.System) { + this.systemFieldType = (item as SystemFieldInSection).systemFieldType; + } else if (this.category == DmpBlueprintFieldCategory.Extra) { + this.dataType = (item as ExtraFieldInSection).dataType; + } else if (this.category == DmpBlueprintFieldCategory.ReferenceType) { + this.referenceTypeId = (item as ReferenceTypeFieldInSection).referenceType?.id; + } + return this; } @@ -356,14 +352,14 @@ export class FieldInSectionEditorModel implements FieldInSectionPersist { id: [{ value: this.id, disabled: disabled }, context.getValidation('id').validators], category: [{ value: this.category, disabled: disabled }, context.getValidation('category').validators], - dataType: [{ value: this.dataType, disabled: disabled }, context.getValidation('dataType').validators], - systemFieldType: [{ value: this.systemFieldType, disabled: disabled }, context.getValidation('systemFieldType').validators], - label: [{ value: this.label, disabled: disabled }, this.category === DmpBlueprintSectionFieldCategory.SYSTEM ? context.getValidation('label-system').validators : context.getValidation('label-extra').validators], + label: [{ value: this.label, disabled: disabled }, this.category === DmpBlueprintFieldCategory.System ? context.getValidation('label-system').validators : context.getValidation('label-extra').validators], placeholder: [{ value: this.placeholder, disabled: disabled }, context.getValidation('placeholder').validators], description: [{ value: this.description, disabled: disabled }, context.getValidation('description').validators], required: [{ value: this.required, disabled: disabled }, context.getValidation('required').validators], ordinal: [{ value: this.ordinal, disabled: disabled }, context.getValidation('ordinal').validators], - + dataType: [{ value: this.dataType, disabled: disabled }, context.getValidation('dataType').validators], + systemFieldType: [{ value: this.systemFieldType, disabled: disabled }, context.getValidation('systemFieldType').validators], + referenceTypeId: [{ value: this.referenceTypeId, disabled: disabled }, context.getValidation('referenceTypeId').validators], }); } @@ -378,14 +374,15 @@ export class FieldInSectionEditorModel implements FieldInSectionPersist { baseValidationArray.push({ key: 'id', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}id`)] }); baseValidationArray.push({ key: 'category', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}category`)] }); - baseValidationArray.push({ key: 'dataType', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}dataType`)] }); - baseValidationArray.push({ key: 'systemFieldType', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}systemFieldType`)] }); baseValidationArray.push({ key: 'label-system', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}label`)] }); baseValidationArray.push({ key: 'label-extra', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}label`)] }); baseValidationArray.push({ key: 'placeholder', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}placeholder`)] }); baseValidationArray.push({ key: 'description', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}description`)] }); baseValidationArray.push({ key: 'required', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}required`)] }); baseValidationArray.push({ key: 'ordinal', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}ordinal`)] }); + baseValidationArray.push({ key: 'dataType', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}dataType`)] }); + baseValidationArray.push({ key: 'systemFieldType', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}systemFieldType`)] }); + baseValidationArray.push({ key: 'referenceTypeId', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}referenceTypeId`)] }); baseContext.validation = baseValidationArray; return baseContext; @@ -403,11 +400,20 @@ export class FieldInSectionEditorModel implements FieldInSectionPersist { validationErrorModel }); - ['id', 'category', 'dataType', 'systemFieldType', , 'label', 'placeholder', 'description', 'required', 'ordinal'].forEach(keyField => { + ['id', 'category', 'dataType', 'systemFieldType', 'referenceTypeId', 'label', 'placeholder', 'description', 'required', 'ordinal'].forEach(keyField => { const control = formGroup?.get(keyField); control?.clearValidators(); if (keyField == 'label') { control?.addValidators(context.has('label-system') ? context.getValidation('label-system').validators : context.getValidation('label-extra').validators); + } else if (keyField == 'referenceTypeId') { + if (formGroup.get('category').value == DmpBlueprintFieldCategory.ReferenceType) control?.addValidators([Validators.required, ...context.getValidation('referenceTypeId').validators]); + else control?.addValidators([...context.getValidation('referenceTypeId').validators]); + } else if (keyField == 'systemFieldType') { + if (formGroup.get('category').value == DmpBlueprintFieldCategory.System) control?.addValidators([Validators.required, ...context.getValidation('systemFieldType').validators]); + else control?.addValidators([...context.getValidation('systemFieldType').validators]); + } else if (keyField == 'dataType') { + if (formGroup.get('category').value == DmpBlueprintFieldCategory.Extra) control?.addValidators([Validators.required, ...context.getValidation('dataType').validators]); + else control?.addValidators([...context.getValidation('dataType').validators]); } else { control?.addValidators(context.getValidation(keyField).validators); } diff --git a/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.resolver.ts b/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.resolver.ts index da0131a13..c9d62e2ce 100644 --- a/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.resolver.ts +++ b/dmp-frontend/src/app/ui/admin/dmp-blueprint/editor/dmp-blueprint-editor.resolver.ts @@ -1,6 +1,7 @@ import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; -import { DescriptionTemplatesInSection, DmpBlueprint, DmpBlueprintDefinition, DmpBlueprintDefinitionSection, FieldInSection } from '@app/core/model/dmp-blueprint/dmp-blueprint'; +import { DescriptionTemplatesInSection, DmpBlueprint, DmpBlueprintDefinition, DmpBlueprintDefinitionSection, ExtraFieldInSection, FieldInSection, ReferenceTypeFieldInSection, SystemFieldInSection } from '@app/core/model/dmp-blueprint/dmp-blueprint'; +import { ReferenceType } from '@app/core/model/reference-type/reference-type'; import { DmpBlueprintService } from '@app/core/services/dmp/dmp-blueprint.service'; import { BreadcrumbService } from '@app/ui/misc/breadcrumb/breadcrumb.service'; import { BaseEditorResolver } from '@common/base/base-editor.resolver'; @@ -29,13 +30,16 @@ export class DmpBlueprintEditorResolver extends BaseEditorResolver { [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.id)].join('.'), [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.category)].join('.'), - [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.dataType)].join('.'), - [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.systemFieldType)].join('.'), [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.label)].join('.'), [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.placeholder)].join('.'), [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.description)].join('.'), [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.required)].join('.'), [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.ordinal)].join('.'), + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.systemFieldType)].join('.'), + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.dataType)].join('.'), + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.referenceType), nameof(x => x.id)].join('.'), + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.referenceType), nameof(x => x.name)].join('.'), + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.referenceType), nameof(x => x.code)].join('.'), [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.descriptionTemplates), nameof(x => x.descriptionTemplateGroupId)].join('.'), [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.descriptionTemplates), nameof(x => x.label)].join('.'), diff --git a/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.component.html b/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.component.html index 73b029153..6023a9d09 100644 --- a/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.component.html +++ b/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.component.html @@ -40,13 +40,10 @@
{{'REFERENCE-EDITOR.FIELDS.TYPE' | translate}} - - - {{enumUtils.toReferenceTypeString(type)}} - - - {{formGroup.get('type').getError('backendError').message}} - {{'GENERAL.VALIDATION.REQUIRED' | translate}} + + + {{formGroup.get('type').getError('backendError').message}} + {{'GENERAL.VALIDATION.REQUIRED' | translate}}
@@ -55,7 +52,7 @@
- {{formGroup.get('description').getError('backendError').message}} + {{formGroup.get('description').getError('backendError').message}} {{'GENERAL.VALIDATION.REQUIRED'| translate}}
@@ -64,7 +61,7 @@ {{'REFERENCE-EDITOR.FIELDS.SOURCE' | translate}} - {{formGroup.get('source').getError('backendError').message}} + {{formGroup.get('source').getError('backendError').message}} {{'GENERAL.VALIDATION.REQUIRED' | translate}}
@@ -75,8 +72,8 @@ {{enumUtils.toReferenceSourceTypeString(sourceType)}} - - {{formGroup.get('sourceType').getError('backendError').message}} + + {{formGroup.get('sourceType').getError('backendError').message}} {{'GENERAL.VALIDATION.REQUIRED' | translate}}
@@ -84,7 +81,7 @@ {{'REFERENCE-EDITOR.FIELDS.REFERENCE' | translate}} - {{formGroup.get('reference').getError('backendError').message}} + {{formGroup.get('reference').getError('backendError').message}} {{'GENERAL.VALIDATION.REQUIRED' | translate}}
@@ -92,16 +89,16 @@ {{'REFERENCE-EDITOR.FIELDS.ABBREVIATION' | translate}} - {{formGroup.get('abbreviation').getError('backendError').message}} + {{formGroup.get('abbreviation').getError('backendError').message}} {{'GENERAL.VALIDATION.REQUIRED' | translate}}
- +

{{'REFERENCE-EDITOR.FIELDS.FIELDS' | translate}} - +

@@ -115,12 +112,12 @@
-
+
{{'REFERENCE-EDITOR.FIELDS.CODE' | translate}} - {{field.get('code').getError('backendError').message}} + {{field.get('code').getError('backendError').message}} {{'GENERAL.VALIDATION.REQUIRED' | translate}}
@@ -131,8 +128,8 @@ {{enumUtils.toReferenceFieldDataTypeString(dataType)}} - - {{field.get('dataType').getError('backendError').message}} + + {{field.get('dataType').getError('backendError').message}} {{'GENERAL.VALIDATION.REQUIRED' | translate}}
@@ -140,7 +137,7 @@ {{'REFERENCE-EDITOR.FIELDS.VALUE' | translate}} - {{field.get('value').getError('backendError').message}} + {{field.get('value').getError('backendError').message}} {{'GENERAL.VALIDATION.REQUIRED' | translate}}
diff --git a/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.component.ts b/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.component.ts index a5741084e..7917784f0 100644 --- a/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.component.ts +++ b/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.component.ts @@ -3,20 +3,22 @@ import { Component, OnInit } from '@angular/core'; import { FormArray, UntypedFormGroup } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { ActivatedRoute, Router } from '@angular/router'; -import { ReferenceService } from '@app/core/services/reference/reference.service'; import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service'; +import { ReferenceService } from '@app/core/services/reference/reference.service'; import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; // import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item'; import { DatePipe } from '@angular/common'; import { IsActive } from '@app/core/common/enum/is-active.enum'; import { AppPermission } from '@app/core/common/enum/permission.enum'; +import { ReferenceFieldDataType } from '@app/core/common/enum/reference-field-data-type'; +import { ReferenceSourceType } from '@app/core/common/enum/reference-source-type'; import { Reference, ReferencePersist } from '@app/core/model/reference/reference'; import { AuthService } from '@app/core/services/auth/auth.service'; import { LoggingService } from '@app/core/services/logging/logging-service'; import { MatomoService } from '@app/core/services/matomo/matomo-service'; +import { ReferenceTypeService } from '@app/core/services/reference-type/reference-type.service'; import { FileUtils } from '@app/core/services/utilities/file-utils.service'; import { QueryParamsService } from '@app/core/services/utilities/query-params.service'; -import { MultipleAutoCompleteConfiguration } from '@app/library/auto-complete/multiple/multiple-auto-complete-configuration'; import { BaseEditor } from '@common/base/base-editor'; import { FormService } from '@common/forms/form-service'; import { ConfirmationDialogComponent } from '@common/modules/confirmation-dialog/confirmation-dialog.component'; @@ -25,12 +27,9 @@ import { FilterService } from '@common/modules/text-filter/filter-service'; import { Guid } from '@common/types/guid'; import { TranslateService } from '@ngx-translate/core'; import { map, takeUntil } from 'rxjs/operators'; +import { ReferenceEditorModel } from './reference-editor.model'; import { ReferenceEditorResolver } from './reference-editor.resolver'; import { ReferenceEditorService } from './reference-editor.service'; -import { FieldEditorModel, ReferenceEditorModel } from './reference-editor.model'; -import { ReferenceType } from '@app/core/common/enum/reference-type'; -import { ReferenceSourceType } from '@app/core/common/enum/reference-source-type'; -import { ReferenceFieldDataType } from '@app/core/common/enum/reference-field-data-type'; @Component({ @@ -45,7 +44,6 @@ export class ReferenceEditorComponent extends BaseEditor(); baseValidationArray.push({ key: 'id', validators: [BackendErrorValidator(this.validationErrorModel, 'id')] }); baseValidationArray.push({ key: 'label', validators: [Validators.required, BackendErrorValidator(this.validationErrorModel, 'label')] }); - baseValidationArray.push({ key: 'type', validators: [Validators.required, BackendErrorValidator(this.validationErrorModel, 'type')] }); + baseValidationArray.push({ key: 'typeId', validators: [Validators.required, BackendErrorValidator(this.validationErrorModel, 'typeId')] }); baseValidationArray.push({ key: 'description', validators: [BackendErrorValidator(this.validationErrorModel, 'description')] }); baseValidationArray.push({ key: 'reference', validators: [Validators.required, BackendErrorValidator(this.validationErrorModel, 'reference')] }); baseValidationArray.push({ key: 'abbreviation', validators: [BackendErrorValidator(this.validationErrorModel, 'abbreviation')] }); @@ -98,7 +98,7 @@ export class ReferenceEditorModel extends BaseEditorModel implements ReferencePe } export class DefinitionEditorModel implements DefinitionPersist { - fields: FieldEditorModel[]= []; + fields: FieldEditorModel[] = []; protected formBuilder: UntypedFormBuilder = new UntypedFormBuilder(); diff --git a/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.resolver.ts b/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.resolver.ts index 87b7ba78e..0c8f4560f 100644 --- a/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.resolver.ts +++ b/dmp-frontend/src/app/ui/admin/reference/editor/reference-editor.resolver.ts @@ -1,5 +1,6 @@ import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; +import { ReferenceType } from '@app/core/model/reference-type/reference-type'; import { Definition, Field, Reference } from '@app/core/model/reference/reference'; import { ReferenceService } from '@app/core/services/reference/reference.service'; import { BreadcrumbService } from '@app/ui/misc/breadcrumb/breadcrumb.service'; @@ -20,7 +21,7 @@ export class ReferenceEditorResolver extends BaseEditorResolver { ...BaseEditorResolver.lookupFields(), nameof(x => x.id), nameof(x => x.label), - nameof(x => x.type), + [nameof(x => x.type), nameof(x => x.id)].join('.'), nameof(x => x.description), nameof(x => x.reference), nameof(x => x.abbreviation), diff --git a/dmp-frontend/src/app/ui/admin/reference/listing/filters/reference-listing-filters.component.html b/dmp-frontend/src/app/ui/admin/reference/listing/filters/reference-listing-filters.component.html index 1c4b04b95..12a0dd0da 100644 --- a/dmp-frontend/src/app/ui/admin/reference/listing/filters/reference-listing-filters.component.html +++ b/dmp-frontend/src/app/ui/admin/reference/listing/filters/reference-listing-filters.component.html @@ -22,9 +22,8 @@
{{'REFERENCE-LISTING.FILTER.TYPE' | translate}} - - {{enumUtils.toReferenceTypeString(referenceType)}} - + +
@@ -49,4 +48,4 @@ -
+
\ No newline at end of file diff --git a/dmp-frontend/src/app/ui/admin/reference/listing/filters/reference-listing-filters.component.ts b/dmp-frontend/src/app/ui/admin/reference/listing/filters/reference-listing-filters.component.ts index 425ffbedc..4d1e7d2f0 100644 --- a/dmp-frontend/src/app/ui/admin/reference/listing/filters/reference-listing-filters.component.ts +++ b/dmp-frontend/src/app/ui/admin/reference/listing/filters/reference-listing-filters.component.ts @@ -1,10 +1,11 @@ import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core'; import { IsActive } from '@app/core/common/enum/is-active.enum'; import { ReferenceSourceType } from '@app/core/common/enum/reference-source-type'; -import { ReferenceType } from '@app/core/common/enum/reference-type'; import { ReferenceFilter } from '@app/core/query/reference.lookup'; +import { ReferenceTypeService } from '@app/core/services/reference-type/reference-type.service'; import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; import { BaseComponent } from '@common/base/base.component'; +import { Guid } from '@common/types/guid'; import { nameof } from 'ts-simple-nameof'; @Component({ @@ -18,7 +19,6 @@ export class ReferenceListingFiltersComponent extends BaseComponent implements O @Output() filterChange = new EventEmitter(); referenceSourceTypeEnumValues = this.enumUtils.getEnumValues(ReferenceSourceType) - referenceTypeEnumValues = this.enumUtils.getEnumValues(ReferenceType); // * State internalFilters: ReferenceListingFilters = this._getEmptyFilters(); @@ -26,6 +26,7 @@ export class ReferenceListingFiltersComponent extends BaseComponent implements O protected appliedFilterCount: number = 0; constructor( public enumUtils: EnumUtils, + public referenceTypeService: ReferenceTypeService ) { super(); } ngOnInit() { @@ -50,12 +51,12 @@ export class ReferenceListingFiltersComponent extends BaseComponent implements O } protected applyFilters(): void { - const { isActive, like, types, sourceTypes } = this.internalFilters ?? {} + const { isActive, like, typeIds, sourceTypes } = this.internalFilters ?? {} this.filterChange.emit({ ...this.filter, like, isActive: isActive ? [IsActive.Active] : [IsActive.Inactive], - types, + typeIds, sourceTypes }) } @@ -66,12 +67,12 @@ export class ReferenceListingFiltersComponent extends BaseComponent implements O return this._getEmptyFilters(); } - let { excludedIds, ids, isActive, like, types, sourceTypes } = inputFilter; + let { excludedIds, ids, isActive, like, typeIds, sourceTypes } = inputFilter; return { isActive: (isActive ?? [])?.includes(IsActive.Active) || !isActive?.length, like: like, - types: types, + typeIds: typeIds, sourceTypes: sourceTypes } @@ -81,7 +82,7 @@ export class ReferenceListingFiltersComponent extends BaseComponent implements O return { isActive: true, like: null, - types: null, + typeIds: null, sourceTypes: null } } @@ -102,6 +103,6 @@ export class ReferenceListingFiltersComponent extends BaseComponent implements O interface ReferenceListingFilters { isActive: boolean; like: string; - types: ReferenceType[]; + typeIds: Guid[]; sourceTypes: ReferenceSourceType[]; } diff --git a/dmp-frontend/src/app/ui/admin/reference/listing/reference-listing.component.html b/dmp-frontend/src/app/ui/admin/reference/listing/reference-listing.component.html index 6f349fd72..5cfb20b66 100644 --- a/dmp-frontend/src/app/ui/admin/reference/listing/reference-listing.component.html +++ b/dmp-frontend/src/app/ui/admin/reference/listing/reference-listing.component.html @@ -69,7 +69,7 @@ {{'REFERENCE-LISTING.FIELDS.TYPE' | translate}}: - {{enumUtils.toReferenceTypeString(item.type) | nullifyValue}} + {{item?.type?.name | nullifyValue}}
diff --git a/dmp-frontend/src/app/ui/admin/reference/listing/reference-listing.component.ts b/dmp-frontend/src/app/ui/admin/reference/listing/reference-listing.component.ts index dc6ed1de6..90b09195c 100644 --- a/dmp-frontend/src/app/ui/admin/reference/listing/reference-listing.component.ts +++ b/dmp-frontend/src/app/ui/admin/reference/listing/reference-listing.component.ts @@ -22,8 +22,8 @@ import { Observable } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { nameof } from 'ts-simple-nameof'; import { IsActiveTypePipe } from '@common/formatting/pipes/is-active-type.pipe'; -import { ReferenceTypePipe } from '@common/formatting/pipes/reference-type.pipe'; import { ReferenceSourceTypePipe } from '@common/formatting/pipes/reference-source-type.pipe'; +import { ReferenceType } from '@app/core/model/reference-type/reference-type'; @Component({ templateUrl: './REFERENCE-LISTING.component.html', @@ -110,7 +110,7 @@ export class ReferenceListingComponent extends BaseListingComponent(x => x.type), sortable: true, languageName: 'REFERENCE-LISTING.FIELDS.TYPE', - pipe: this.pipeService.getPipe(ReferenceTypePipe) + valueFunction: (item: Reference) => (item?.type?.name) }, { prop: nameof(x => x.createdAt), diff --git a/dmp-frontend/src/app/ui/description/editor/description-editor.component.ts b/dmp-frontend/src/app/ui/description/editor/description-editor.component.ts index 12fe1f764..0366aafbb 100644 --- a/dmp-frontend/src/app/ui/description/editor/description-editor.component.ts +++ b/dmp-frontend/src/app/ui/description/editor/description-editor.component.ts @@ -845,7 +845,7 @@ export class DescriptionEditorComponent extends BaseEditor x.data?.fieldId == descriptionTemplateField?.id && x.isActive == IsActive.Active).map(x => x.reference); - this.reference = descriptionReferences?.find(x => x.data?.fieldId == descriptionTemplateField?.id && x.isActive == IsActive.Active)?.reference; + //TODO: refactor reference type + //this.references = descriptionReferences?.filter(x => x.data?.fieldId == descriptionTemplateField?.id && x.isActive == IsActive.Active).map(x => x.reference); + //this.reference = descriptionReferences?.find(x => x.data?.fieldId == descriptionTemplateField?.id && x.isActive == IsActive.Active)?.reference; this.externalIdentifier = new DescriptionExternalIdentifierEditorModel(this.validationErrorModel).fromModel(item.externalIdentifier); } return this; @@ -559,7 +560,8 @@ export class DescriptionReferenceEditorModel implements DescriptionReferencePers fromModel(item: DescriptionReference): DescriptionReferenceEditorModel { this.id = item.id; - this.reference = item.reference; + //TODO: refactor reference type + //this.reference = item.reference; this.hash = item.hash; return this; diff --git a/dmp-frontend/src/app/ui/description/editor/description-form/components/form-field/form-field.component.html b/dmp-frontend/src/app/ui/description/editor/description-form/components/form-field/form-field.component.html index 8c1d20051..c4c459ecc 100644 --- a/dmp-frontend/src/app/ui/description/editor/description-form/components/form-field/form-field.component.html +++ b/dmp-frontend/src/app/ui/description/editor/description-form/components/form-field/form-field.component.html @@ -15,8 +15,8 @@ {{'GENERAL.VALIDATION.URL.MESSAGE' | translate}} -
-
+
+
@@ -56,25 +56,6 @@
-
-
- - - - - {{propertiesFormGroup?.get(field.id).get('textListValue').getError('backendError').message}} - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - - {{propertiesFormGroup?.get(field.id).get('textValue').getError('backendError').message}} - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - {{ "TYPES.DATASET-PROFILE-COMBO-BOX-TYPE.EXTERNAL-SOURCE-HINT" | translate }} - -
-
@@ -204,148 +185,6 @@
-
-
- - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - {{ "TYPES.DATASET-PROFILE-COMBO-BOX-TYPE.EXTERNAL-SOURCE-HINT" | translate }} - -
-
-
-
- - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - {{ "TYPES.DATASET-PROFILE-COMBO-BOX-TYPE.EXTERNAL-SOURCE-HINT" | translate }} - -
-
-
-
- - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - \ - {{ "TYPES.DATASET-PROFILE-COMBO-BOX-TYPE.EXTERNAL-SOURCE-HINT" | translate }} - -
-
- -
-
- - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - {{ "TYPES.DATASET-PROFILE-COMBO-BOX-TYPE.EXTERNAL-SOURCE-HINT" | translate }} - -
-
- -
-
- - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - {{ "TYPES.DATASET-PROFILE-COMBO-BOX-TYPE.EXTERNAL-SOURCE-HINT" | translate }} - -
-
- -
-
- - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - {{ "TYPES.DATASET-PROFILE-COMBO-BOX-TYPE.EXTERNAL-SOURCE-HINT" | translate }} - -
-
- -
-
- - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - {{ "TYPES.DATASET-PROFILE-COMBO-BOX-TYPE.EXTERNAL-SOURCE-HINT" | translate }} - -
-
- -
-
- - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - {{ "TYPES.DATASET-PROFILE-COMBO-BOX-TYPE.EXTERNAL-SOURCE-HINT" | translate }} - -
-
-
@@ -355,44 +194,6 @@
-
-
- - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - {{ "TYPES.DATASET-PROFILE-COMBO-BOX-TYPE.EXTERNAL-SOURCE-HINT" | translate }} - -
-
- -
-
- - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - - {{'GENERAL.VALIDATION.REQUIRED' | translate}} - - - - {{ "TYPES.DATASET-PROFILE-COMBO-BOX-TYPE.EXTERNAL-SOURCE-HINT" | translate }} - -
-
-
diff --git a/dmp-frontend/src/app/ui/description/editor/description-form/components/form-field/form-field.component.ts b/dmp-frontend/src/app/ui/description/editor/description-form/components/form-field/form-field.component.ts index 8c97dbdb9..032f2df9e 100644 --- a/dmp-frontend/src/app/ui/description/editor/description-form/components/form-field/form-field.component.ts +++ b/dmp-frontend/src/app/ui/description/editor/description-form/components/form-field/form-field.component.ts @@ -5,10 +5,8 @@ import { UntypedFormControl, UntypedFormGroup } from '@angular/forms'; import { MatDialog } from "@angular/material/dialog"; import { DescriptionTemplateFieldType } from '@app/core/common/enum/description-template-field-type'; import { DescriptionTemplateFieldValidationType } from '@app/core/common/enum/description-template-field-validation-type'; -import { ReferenceType } from '@app/core/common/enum/reference-type'; -import { DescriptionTemplateExternalSelectData, DescriptionTemplateExternalSelectSource, DescriptionTemplateField, DescriptionTemplateFieldSet, DescriptionTemplateUploadData } from '@app/core/model/description-template/description-template'; -import { FetcherReference, Reference } from '@app/core/model/reference/reference'; -import { ReferenceSearchLookup } from '@app/core/query/reference-search.lookup'; +import { DescriptionTemplateField, DescriptionTemplateFieldSet, DescriptionTemplateLabelAndMultiplicityData, DescriptionTemplateUploadData } from '@app/core/model/description-template/description-template'; +import { FetcherReference } from '@app/core/model/reference/reference'; import { DmpService } from '@app/core/services/dmp/dmp.service'; import { SnackBarNotificationLevel, UiNotificationService } from "@app/core/services/notification/ui-notification-service"; import { ReferenceService } from '@app/core/services/reference/reference.service'; @@ -16,7 +14,6 @@ import { FileUtils } from '@app/core/services/utilities/file-utils.service'; import { MultipleAutoCompleteConfiguration } from '@app/library/auto-complete/multiple/multiple-auto-complete-configuration'; import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration'; import { VisibilityRulesService } from '@app/ui/description/editor/description-form/visibility-rules/visibility-rules.service'; -import { isNullOrUndefined } from '@app/utilities/enhancers/utils'; import { BaseComponent } from '@common/base/base.component'; import { TranslateService } from '@ngx-translate/core'; import { Observable } from 'rxjs'; @@ -41,7 +38,6 @@ export class DescriptionFormFieldComponent extends BaseComponent implements OnIn // @Input() form: UntypedFormGroup; @Input() datasetProfileId: any; @Input() isChild: Boolean = false; - autocompleteOptions: DescriptionTemplateExternalSelectSource[]; visible: boolean = true; @@ -54,20 +50,10 @@ export class DescriptionFormFieldComponent extends BaseComponent implements OnIn public singleAutoCompleteConfiguration: SingleAutoCompleteConfiguration; public multipleAutoCompleteConfiguration: MultipleAutoCompleteConfiguration; - - externalDatasetAutoCompleteConfiguration: SingleAutoCompleteConfiguration; - dataRepositoriesAutoCompleteConfiguration: SingleAutoCompleteConfiguration; - pubRepositoriesAutoCompleteConfiguration: SingleAutoCompleteConfiguration; - journalRepositoriesAutoCompleteConfiguration: SingleAutoCompleteConfiguration; - taxonomiesAutoCompleteConfiguration: SingleAutoCompleteConfiguration; - licensesAutoCompleteConfiguration: SingleAutoCompleteConfiguration; - publicationsAutoCompleteConfiguration: SingleAutoCompleteConfiguration; - registriesAutoCompleteConfiguration: SingleAutoCompleteConfiguration; - servicesAutoCompleteConfiguration: SingleAutoCompleteConfiguration; tagsAutoCompleteConfiguration: SingleAutoCompleteConfiguration; - researchersAutoCompleteConfiguration: MultipleAutoCompleteConfiguration; - organisationsAutoCompleteConfiguration: MultipleAutoCompleteConfiguration; currencyAutoCompleteConfiguration: SingleAutoCompleteConfiguration; + multipleReferenceAutoCompleteConfiguration: MultipleAutoCompleteConfiguration; + readonly separatorKeysCodes: number[] = [ENTER, COMMA]; @@ -154,123 +140,17 @@ export class DescriptionFormFieldComponent extends BaseComponent implements OnIn // } // } - // Setup autocomplete configuration if needed - if (this.field?.data?.fieldType === DescriptionTemplateFieldType.EXTERNAL_SELECT) { - if (!((this.field.data as DescriptionTemplateExternalSelectData).multipleSelect)) { - this.singleAutoCompleteConfiguration = { - filterFn: this.searchFromAutocomplete.bind(this), - initialItems: () => this.searchFromAutocomplete(''), - displayFn: (item) => { try { return (item != null && item.length > 1) ? JSON.parse(item).label : item['label'] } catch { return '' } }, - titleFn: (item) => { try { return item['label'] } catch { return '' } }, - valueAssign: (item) => { try { return JSON.stringify(item) } catch { return '' } }, - subtitleFn: (item) => { try { return item['source'] ? this.language.instant('DATASET-WIZARD.EDITOR.FIELDS.EXTERNAL-AUTOCOMPLETE-SUBTITLE') + item['source'] : this.language.instant('DATASET-WIZARD.EDITOR.FIELDS.EXTERNAL-AUTOCOMPLETE-NO-SOURCE') } catch { return '' } } - }; - } - else { - this.multipleAutoCompleteConfiguration = { - filterFn: this.searchFromAutocomplete.bind(this), - initialItems: () => this.searchFromAutocomplete(''), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['label'] : item['label'] } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['label'] : item['label'] } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } }, - subtitleFn: (item) => { try { return item['source'] ? this.language.instant('DATASET-WIZARD.EDITOR.FIELDS.EXTERNAL-AUTOCOMPLETE-SUBTITLE') + item['source'] : this.language.instant('DATASET-WIZARD.EDITOR.FIELDS.EXTERNAL-AUTOCOMPLETE-NO-SOURCE') } catch { return '' } } - } - } - if (isNullOrUndefined(this.datasetProfileId)) { - this.autocompleteOptions = (this.field.data as DescriptionTemplateExternalSelectData).sources; - } - } - switch (this.field?.data?.fieldType) { case DescriptionTemplateFieldType.EXTERNAL_DATASETS: - this.externalDatasetAutoCompleteConfiguration = { - filterFn: this.searchDatasetExternalDatasets.bind(this), - initialItems: () => this.searchDatasetExternalDatasets(''),//.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - subtitleFn: (item) => { try { return item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE') } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } - }; - break; - case DescriptionTemplateFieldType.DATA_REPOSITORIES: - this.dataRepositoriesAutoCompleteConfiguration = { - filterFn: this.searchDatasetExternalDataRepositories.bind(this), - initialItems: () => this.searchDatasetExternalDataRepositories(''), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - subtitleFn: (item) => { try { return item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE') } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } - }; - break; - case DescriptionTemplateFieldType.PUB_REPOSITORIES: - this.pubRepositoriesAutoCompleteConfiguration = { - filterFn: this.searchDatasetExternalPubRepositories.bind(this), - initialItems: () => this.searchDatasetExternalPubRepositories(''), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - subtitleFn: (item) => { try { return item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE') } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } - }; - break; - case DescriptionTemplateFieldType.JOURNAL_REPOSITORIES: - this.journalRepositoriesAutoCompleteConfiguration = { - filterFn: this.searchDatasetExternalJournalRepositories.bind(this), - initialItems: () => this.searchDatasetExternalJournalRepositories(''), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - subtitleFn: (item) => { try { return item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE') } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } - }; - break; - case DescriptionTemplateFieldType.TAXONOMIES: - this.taxonomiesAutoCompleteConfiguration = { - filterFn: this.searchDatasetExternalTaxonomies.bind(this), - initialItems: () => this.searchDatasetExternalTaxonomies(''), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - subtitleFn: (item) => { try { return item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE') } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } - }; - break; - case DescriptionTemplateFieldType.LICENSES: - this.licensesAutoCompleteConfiguration = { - filterFn: this.searchDatasetExternalLicences.bind(this), - initialItems: () => this.searchDatasetExternalLicences(''), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - subtitleFn: (item) => { try { return item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE') } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } - }; - break; - case DescriptionTemplateFieldType.PUBLICATIONS: - this.publicationsAutoCompleteConfiguration = { - filterFn: this.searchDatasetExternalPublications.bind(this), - initialItems: () => this.searchDatasetExternalPublications(''), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - subtitleFn: (item) => { try { return item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE') } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } - }; - break; - case DescriptionTemplateFieldType.REGISTRIES: - this.registriesAutoCompleteConfiguration = { - filterFn: this.searchDatasetExternalRegistries.bind(this), - initialItems: () => this.searchDatasetExternalRegistries(''), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - subtitleFn: (item) => { try { return item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE') } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } - }; - break; - case DescriptionTemplateFieldType.SERVICES: - this.servicesAutoCompleteConfiguration = { - filterFn: this.searchDatasetExternalServices.bind(this), - initialItems: () => this.searchDatasetExternalServices(''), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - subtitleFn: (item) => { try { return item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE') } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } - }; + //TODO: refactor + // this.multipleReferenceAutoCompleteConfiguration = { + // filterFn: this.filterOrganisations.bind(this), + // initialItems: (excludedItems: any[]) => this.filterOrganisations('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))), + // displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, + // titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, + // subtitleFn: (item) => { try { return item['tag'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['tag'] : (item['key'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['key'] : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE')) } catch { return '' } }, + // valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } + // }; break; case DescriptionTemplateFieldType.TAGS: this.tagsAutoCompleteConfiguration = { @@ -282,26 +162,7 @@ export class DescriptionFormFieldComponent extends BaseComponent implements OnIn }; this.parseTags(); break; - case DescriptionTemplateFieldType.RESEARCHERS: - this.researchersAutoCompleteConfiguration = { - filterFn: this.filterResearchers.bind(this), - initialItems: (excludedItems: any[]) => this.filterResearchers('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - subtitleFn: (item) => { try { return item['tag'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['tag'] : (item['key'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['key'] : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE')) } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } - }; - break; - case DescriptionTemplateFieldType.ORGANIZATIONS: - this.organisationsAutoCompleteConfiguration = { - filterFn: this.filterOrganisations.bind(this), - initialItems: (excludedItems: any[]) => this.filterOrganisations('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))), - displayFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - titleFn: (item) => { try { return typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name } catch { return '' } }, - subtitleFn: (item) => { try { return item['tag'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['tag'] : (item['key'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['key'] : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE')) } catch { return '' } }, - valueAssign: (item) => { try { return typeof (item) == 'string' ? item : JSON.stringify(item) } catch { return '' } } - }; - break; + case DescriptionTemplateFieldType.DATASET_IDENTIFIER: // const value = this.propertiesFormGroup.get(this.field.id).get('value').value; // const disabled = this.propertiesFormGroup.get(this.field.id).disabled; @@ -332,9 +193,6 @@ export class DescriptionFormFieldComponent extends BaseComponent implements OnIn // this.form.disable(); // } break; - case DescriptionTemplateFieldType.INTERNAL_DMP_ENTRIES_RESEARCHERS: - this.makeAutocompleteConfiguration(this.searchResearchers.bind(this), "name", "tag"); - break; case DescriptionTemplateFieldType.INTERNAL_ENTRIES_DESCRIPTIONS: this.makeAutocompleteConfiguration(this.searchDatasets.bind(this), "label"); break; @@ -344,7 +202,7 @@ export class DescriptionFormFieldComponent extends BaseComponent implements OnIn } // this.form = this.visibilityRulesService.getFormGroup(this.field.id); - + //TODO: refactor // this.propertiesFormGroup.get(this.field.id).get('value').valueChanges // .pipe( @@ -441,7 +299,7 @@ export class DescriptionFormFieldComponent extends BaseComponent implements OnIn } makeAutocompleteConfiguration(myfunc: Function, title: string, subtitle?: string): void { - if (!((this.field.data as DescriptionTemplateExternalSelectData).multipleSelect)) { + if (!((this.field.data as DescriptionTemplateLabelAndMultiplicityData).multipleSelect)) { this.singleAutoCompleteConfiguration = { filterFn: myfunc.bind(this), initialItems: (extraData) => myfunc(''), @@ -463,91 +321,6 @@ export class DescriptionFormFieldComponent extends BaseComponent implements OnIn } } - searchDatasetExternalDatasets(query: string): Observable { - // const requestItem: RequestItem = new RequestItem(); - // requestItem.criteria = new ExternalDatasetCriteria(); - // requestItem.criteria.like = query; - // requestItem.criteria.type = ''; - // //return this.externalSourcesService.searchDatasetSExternalDatasetservice(requestItem); - // return this.externalSourcesService.listExternal(ReferenceType.Datasets, requestItem.criteria.like, requestItem.criteria.type); - const lookup = new ReferenceSearchLookup(); - lookup.like = query; - lookup.key = ''; - lookup.type = ReferenceType.Datasets; - return this.referenceService.search(lookup); - } - - searchDatasetExternalDataRepositories(query: string): Observable { - // const requestItem: RequestItem = new RequestItem(); - // requestItem.criteria = new DataRepositoryCriteria(); - // requestItem.criteria.like = query; - // requestItem.criteria.type = ''; - // return this.externalSourcesService.listExternal(ReferenceType.DataRepositories, requestItem.criteria.like, requestItem.criteria.type); - const lookup = new ReferenceSearchLookup(); - lookup.like = query; - lookup.key = ''; - lookup.type = ReferenceType.DataRepositories; - return this.referenceService.search(lookup); - } - searchDatasetExternalPubRepositories(query: string): Observable { - // const requestItem: RequestItem = new RequestItem(); - // requestItem.criteria = new DataRepositoryCriteria(); - // requestItem.criteria.like = query; - // requestItem.criteria.type = ''; - // return this.externalSourcesService.listExternal(ReferenceType.PubRepositories, requestItem.criteria.like, requestItem.criteria.type); - const lookup = new ReferenceSearchLookup(); - lookup.like = query; - lookup.key = ''; - lookup.type = ReferenceType.PubRepositories; - return this.referenceService.search(lookup); - } - searchDatasetExternalJournalRepositories(query: string): Observable { - // const requestItem: RequestItem = new RequestItem(); - // requestItem.criteria = new DataRepositoryCriteria(); - // requestItem.criteria.like = query; - // requestItem.criteria.type = ''; - // return this.externalSourcesService.listExternal(ReferenceType.Journals, requestItem.criteria.like, requestItem.criteria.type); - const lookup = new ReferenceSearchLookup(); - lookup.like = query; - lookup.key = ''; - lookup.type = ReferenceType.Journals; - return this.referenceService.search(lookup); - } - searchDatasetExternalTaxonomies(query: string): Observable { - //TODO refactor - return null; - // const requestItem: RequestItem = new RequestItem(); - // requestItem.criteria = new TaxonomyCriteria(); - // requestItem.criteria.like = query; - // requestItem.criteria.type = ''; - // return this.externalSourcesService.listExternal(ReferenceType.Taxonomies, requestItem.criteria.like, requestItem.criteria.type); - } - searchDatasetExternalLicences(query: string): Observable { - // const requestItem: RequestItem = new RequestItem(); - // requestItem.criteria = new LicenseCriteria(); - // requestItem.criteria.like = query; - // requestItem.criteria.type = ''; - // return this.externalSourcesService.listExternal(ReferenceType.Licenses, requestItem.criteria.like, requestItem.criteria.type); - const lookup = new ReferenceSearchLookup(); - lookup.like = query; - lookup.key = ''; - lookup.type = ReferenceType.Licenses; - return this.referenceService.search(lookup); - } - searchDatasetExternalPublications(query: string): Observable { - // const requestItem: RequestItem = new RequestItem(); - // requestItem.criteria = new PublicationCriteria(); - // requestItem.criteria.like = query; - // requestItem.criteria.type = ''; - //return this.externalSourcesService.listExternal(ReferenceType.Publications, requestItem.criteria.like, requestItem.criteria.type); - - const lookup = new ReferenceSearchLookup(); - lookup.like = query; - lookup.key = ''; - lookup.type = ReferenceType.Publications; - return this.referenceService.search(lookup); - } - searchDatasetExternalRegistries(query: string): Observable { //TODO refactor return null; @@ -631,26 +404,6 @@ export class DescriptionFormFieldComponent extends BaseComponent implements OnIn // } } - filterOrganisations(value: string): Observable { - //return this.externalSourcesService.searchDMPOrganizations(value); - //return this.externalSourcesService.listExternal(ReferenceType.Organizations, value, ''); - const lookup = new ReferenceSearchLookup(); - lookup.like = value; - lookup.key = ''; - lookup.type = ReferenceType.Organizations; - return this.referenceService.search(lookup); - } - - filterResearchers(value: string): Observable { - //return this.externalSourcesService.searchDMPResearchers({ criteria: { name: value, like: null } }); - //return this.externalSourcesService.listExternal(ReferenceType.Researcher, value, ''); - const lookup = new ReferenceSearchLookup(); - lookup.like = value; - lookup.key = ''; - lookup.type = ReferenceType.Researcher; - return this.referenceService.search(lookup); - } - getDatasetIdControl(name: string): UntypedFormControl { return this.propertiesFormGroup.get(this.field.id).get(name) as UntypedFormControl; } diff --git a/dmp-frontend/src/app/ui/description/listing/listing-item/description-listing-item.component.html b/dmp-frontend/src/app/ui/description/listing/listing-item/description-listing-item.component.html index cd0b57a03..2bc4c1997 100644 --- a/dmp-frontend/src/app/ui/description/listing/listing-item/description-listing-item.component.html +++ b/dmp-frontend/src/app/ui/description/listing/listing-item/description-listing-item.component.html @@ -14,7 +14,7 @@ done{{ enumUtils.toDescriptionStatusString(description.status) }} create{{ enumUtils.toDescriptionStatusString(description.status) }} . - {{'DESCRIPTION-LISTING.GRANT' | translate}}: {{referenceService.getReferencesForTypesFirstSafe(description?.dmp?.dmpReferences, [referenceTypeEnum.Grants])?.reference?.label}} + {{'DESCRIPTION-LISTING.GRANT' | translate}}: {{referenceService.getReferencesForTypesFirstSafe(description?.dmp?.dmpReferences, [this.referenceTypeService.getGrantReferenceType()])?.reference?.label}}
{{'DESCRIPTION-LISTING.PART-OF' | translate}} diff --git a/dmp-frontend/src/app/ui/description/listing/listing-item/description-listing-item.component.ts b/dmp-frontend/src/app/ui/description/listing/listing-item/description-listing-item.component.ts index f4c5e3bc9..241ed11db 100644 --- a/dmp-frontend/src/app/ui/description/listing/listing-item/description-listing-item.component.ts +++ b/dmp-frontend/src/app/ui/description/listing/listing-item/description-listing-item.component.ts @@ -5,7 +5,6 @@ import { MatDialog } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { DmpAccessType } from '@app/core/common/enum/dmp-access-type'; import { IsActive } from '@app/core/common/enum/is-active.enum'; -import { ReferenceType } from '@app/core/common/enum/reference-type'; import { Description } from '@app/core/model/description/description'; import { AuthService } from '@app/core/services/auth/auth.service'; import { DescriptionService } from '@app/core/services/description/description.service'; @@ -14,6 +13,7 @@ import { FileTransformerService } from '@app/core/services/file-transformer/file import { LockService } from '@app/core/services/lock/lock.service'; import { MatomoService } from '@app/core/services/matomo/matomo-service'; import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service'; +import { ReferenceTypeService } from '@app/core/services/reference-type/reference-type.service'; import { ReferenceService } from '@app/core/services/reference/reference.service'; import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; import { FileUtils } from '@app/core/services/utilities/file-utils.service'; @@ -44,7 +44,6 @@ export class DescriptionListingItemComponent extends BaseComponent implements On isUserOwner: boolean; descriptionStatusEnum = DescriptionStatus; dmpAccessTypeEnum = DmpAccessType; - referenceTypeEnum = ReferenceType; constructor( @@ -61,6 +60,7 @@ export class DescriptionListingItemComponent extends BaseComponent implements On private fileUtils: FileUtils, public dmpService: DmpService, public referenceService: ReferenceService, + public referenceTypeService: ReferenceTypeService, public fileTransformerService: FileTransformerService ) { super(); diff --git a/dmp-frontend/src/app/ui/description/overview/description-overview.component.html b/dmp-frontend/src/app/ui/description/overview/description-overview.component.html index c2d51c832..a72ea117e 100644 --- a/dmp-frontend/src/app/ui/description/overview/description-overview.component.html +++ b/dmp-frontend/src/app/ui/description/overview/description-overview.component.html @@ -59,9 +59,9 @@
-
+
{{'DESCRIPTION-OVERVIEW.GRANT' | translate}}
-
{{referenceService.getReferencesForTypesFirstSafe(description?.dmp?.dmpReferences, [referenceTypeEnum.Grants])?.reference?.label}}
+
{{referenceService.getReferencesForTypesFirstSafe(description?.dmp?.dmpReferences, [this.referenceTypeService.getGrantReferenceType()])?.reference?.label}}
{{'DESCRIPTION-OVERVIEW.RESEARCHERS' | translate}}
diff --git a/dmp-frontend/src/app/ui/description/overview/description-overview.component.ts b/dmp-frontend/src/app/ui/description/overview/description-overview.component.ts index 6e23e99fb..5fc270e5a 100644 --- a/dmp-frontend/src/app/ui/description/overview/description-overview.component.ts +++ b/dmp-frontend/src/app/ui/description/overview/description-overview.component.ts @@ -9,7 +9,6 @@ import { DescriptionStatus } from '@app/core/common/enum/description-status'; import { DmpAccessType } from '@app/core/common/enum/dmp-access-type'; import { DmpStatus } from '@app/core/common/enum/dmp-status'; import { DmpUserRole } from '@app/core/common/enum/dmp-user-role'; -import { ReferenceType } from '@app/core/common/enum/reference-type'; import { DescriptionTemplate } from '@app/core/model/description-template/description-template'; import { Description, DescriptionStatusPersist } from '@app/core/model/description/description'; import { Dmp, DmpUser, DmpUserRemovePersist } from '@app/core/model/dmp/dmp'; @@ -22,6 +21,7 @@ import { DmpService } from '@app/core/services/dmp/dmp.service'; import { FileTransformerService } from '@app/core/services/file-transformer/file-transformer.service'; import { MatomoService } from '@app/core/services/matomo/matomo-service'; import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service'; +import { ReferenceTypeService } from '@app/core/services/reference-type/reference-type.service'; import { ReferenceService } from '@app/core/services/reference/reference.service'; import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; import { FileUtils } from '@app/core/services/utilities/file-utils.service'; @@ -53,7 +53,6 @@ export class DescriptionOverviewComponent extends BaseComponent implements OnIni lockStatus: Boolean; descriptionStatusEnum = DescriptionStatus; dmpAccessTypeEnum = DmpAccessType; - referenceTypeEnum = ReferenceType; dmpStatusEnum = DmpStatus; dmpUserRoleEnum = DmpUserRole; @@ -72,7 +71,8 @@ export class DescriptionOverviewComponent extends BaseComponent implements OnIni public enumUtils: EnumUtils, private matomoService: MatomoService, private fileUtils: FileUtils, - public fileTransformerService: FileTransformerService + public fileTransformerService: FileTransformerService, + private referenceTypeService: ReferenceTypeService ) { super(); } @@ -92,7 +92,7 @@ export class DescriptionOverviewComponent extends BaseComponent implements OnIni .pipe(takeUntil(this._destroyed)) .subscribe(data => { this.description = data; - this.researchers = this.referenceService.getReferencesForTypes(this.description?.dmp?.dmpReferences, [ReferenceType.Researcher]); + this.researchers = this.referenceService.getReferencesForTypes(this.description?.dmp?.dmpReferences, [this.referenceTypeService.getResearcherReferenceType()]); // this.users = this.description.dmp.users; this.checkLockStatus(this.description.id); this.setIsUserOwner(); @@ -117,7 +117,7 @@ export class DescriptionOverviewComponent extends BaseComponent implements OnIni .pipe(takeUntil(this._destroyed)) .subscribe(data => { this.description = data; - this.researchers = this.referenceService.getReferencesForTypes(this.description?.dmp?.dmpReferences, [ReferenceType.Researcher]); + this.researchers = this.referenceService.getReferencesForTypes(this.description?.dmp?.dmpReferences, [this.referenceTypeService.getResearcherReferenceType()]); // this.users = this.description.dmp.users; // const breadCrumbs = []; // breadCrumbs.push({ parentComponentName: null, label: this.language.instant('NAV-BAR.PUBLIC DESCRIPTIONS'), url: "/explore" }); diff --git a/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.component.html b/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.component.html index ed45c212a..508c48e5b 100644 --- a/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.component.html +++ b/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.component.html @@ -132,12 +132,12 @@
-
{{i + 1}}.{{j + 1}} {{enumUtils.toDmpBlueprintSystemFieldTypeString(field.systemFieldType)}}*
+
{{i + 1}}.{{j + 1}} {{enumUtils.toDmpBlueprintSystemFieldTypeString(field.systemFieldType)}}*
{{i + 1}}.{{j + 1}} {{field.label}}*
{{field.description}}
-
-
+
+
@@ -146,29 +146,11 @@ {{'GENERAL.VALIDATION.REQUIRED' | translate}}
-
+
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
+
@@ -179,7 +161,7 @@ {{'GENERAL.VALIDATION.REQUIRED' | translate}}
-
+
@@ -248,7 +230,7 @@
-
+
@@ -260,7 +242,12 @@
-
+
+
+ +
+
+
{{field.label}} diff --git a/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.component.ts b/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.component.ts index 80c327600..cef5087c4 100644 --- a/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.component.ts +++ b/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.component.ts @@ -1,25 +1,36 @@ +import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; import { DatePipe } from '@angular/common'; import { Component, OnInit } from '@angular/core'; +import { FormArray, UntypedFormArray, UntypedFormGroup } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { DescriptionStatus } from '@app/core/common/enum/description-status'; +import { DmpAccessType } from '@app/core/common/enum/dmp-access-type'; +import { DmpBlueprintFieldCategory } from '@app/core/common/enum/dmp-blueprint-field-category'; import { DmpBlueprintExtraFieldDataType } from '@app/core/common/enum/dmp-blueprint-field-type'; -import { DmpBlueprintSectionFieldCategory } from '@app/core/common/enum/dmp-blueprint-section-field-category'; +import { DmpBlueprintStatus } from '@app/core/common/enum/dmp-blueprint-status'; import { DmpBlueprintSystemFieldType } from '@app/core/common/enum/dmp-blueprint-system-field-type'; +import { DmpContactType } from '@app/core/common/enum/dmp-contact-type'; import { DmpStatus } from '@app/core/common/enum/dmp-status'; import { IsActive } from '@app/core/common/enum/is-active.enum'; import { AppPermission } from '@app/core/common/enum/permission.enum'; import { DmpBlueprint } from '@app/core/model/dmp-blueprint/dmp-blueprint'; import { Dmp, DmpPersist } from '@app/core/model/dmp/dmp'; +import { LanguageInfo } from '@app/core/model/language-info'; import { AuthService } from '@app/core/services/auth/auth.service'; import { ConfigurationService } from '@app/core/services/configuration/configuration.service'; +import { LanguageInfoService } from '@app/core/services/culture/language-info-service'; +import { DescriptionTemplateService } from '@app/core/services/description-template/description-template.service'; import { DmpBlueprintService } from '@app/core/services/dmp/dmp-blueprint.service'; import { DmpService } from '@app/core/services/dmp/dmp.service'; import { LockService } from '@app/core/services/lock/lock.service'; import { LoggingService } from '@app/core/services/logging/logging-service'; import { MatomoService } from '@app/core/services/matomo/matomo-service'; import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service'; +import { UserService } from '@app/core/services/user/user.service'; +import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; import { QueryParamsService } from '@app/core/services/utilities/query-params.service'; +import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration'; import { PopupNotificationDialogComponent } from '@app/library/notification/popup/popup-notification.component'; import { isNullOrUndefined } from '@app/utilities/enhancers/utils'; import { BaseEditor } from '@common/base/base-editor'; @@ -33,21 +44,6 @@ import { map, takeUntil } from 'rxjs/operators'; import { DmpEditorModel } from './dmp-editor.model'; import { DmpEditorResolver } from './dmp-editor.resolver'; import { DmpEditorService } from './dmp-editor.service'; -import { ReferenceType } from '@app/core/common/enum/reference-type'; -import { LanguageInfo } from '@app/core/model/language-info'; -import { LanguageInfoService } from '@app/core/services/culture/language-info-service'; -import { DmpAccessType } from '@app/core/common/enum/dmp-access-type'; -import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; -import { FormArray, UntypedFormArray, UntypedFormGroup } from '@angular/forms'; -import { DescriptionTemplateService } from '@app/core/services/description-template/description-template.service'; -import { LockPersist } from '@app/core/model/lock/lock.model'; -import { LockTargetType } from '@app/core/common/enum/lock-target-type'; -import { UserService } from '@app/core/services/user/user.service'; -import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; -import { DmpContactType } from '@app/core/common/enum/dmp-contact-type'; -import { MatButtonToggleChange } from '@angular/material/button-toggle'; -import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration'; -import { DmpBlueprintStatus } from '@app/core/common/enum/dmp-blueprint-status'; @Component({ selector: 'app-dmp-editor', @@ -64,10 +60,9 @@ export class DmpEditorComponent extends BaseEditor implemen lockStatus: Boolean = false; step: number = 0; descriptionStatusEnum = DescriptionStatus; - dmpBlueprintSectionFieldCategoryEnum = DmpBlueprintSectionFieldCategory; + dmpBlueprintSectionFieldCategoryEnum = DmpBlueprintFieldCategory; dmpBlueprintSystemFieldTypeEnum = DmpBlueprintSystemFieldType; dmpBlueprintExtraFieldDataTypeEnum = DmpBlueprintExtraFieldDataType; - referenceTypeEnum = ReferenceType; dmpAccessTypeEnum = DmpAccessType; dmpAccessTypeEnumValues = this.enumUtils.getEnumValues(DmpAccessType); dmpContactTypeEnum = DmpContactType; @@ -580,7 +575,7 @@ export class DmpEditorComponent extends BaseEditor implemen - // dmpBlueprintSectionFieldCategory = DmpBlueprintSectionFieldCategory; + // dmpBlueprintSectionFieldCategory = DmpBlueprintFieldCategory; // dmpBlueprintSystemFieldType = DmpBlueprintSystemFieldType; // //public dmpBlueprintSystemFieldTypeEnum = this.enumUtils.getEnumValues(DmpBlueprintSystemFieldType); // dmpBlueprintExtraFieldDataType = DmpBlueprintExtraFieldDataType; @@ -1353,7 +1348,7 @@ export class DmpEditorComponent extends BaseEditor implemen // private buildExtraFields(): void { // const extraFields = new Array(); // this.selectedDmpBlueprintDefinition.sections.forEach(section => section.fields.forEach(field => { - // if (field.category as unknown == DmpBlueprintSectionFieldCategory.EXTRA) { + // if (field.category as unknown == DmpBlueprintFieldCategory.Extra) { // let extraField = new DmpExtraFieldEditorModel(); // extraField.id = field.id.toString(); // if (!isNullOrUndefined(this.dmp.extraFields)) { @@ -1382,7 +1377,7 @@ export class DmpEditorComponent extends BaseEditor implemen // let hasGrant = false; // this.selectedDmpBlueprintDefinition.sections.forEach(section => section.fields.forEach( // field => { - // if (field.category as unknown === DmpBlueprintSectionFieldCategory.SYSTEM && field.systemFieldType === DmpBlueprintSystemFieldType.GRANT) { + // if (field.category as unknown === DmpBlueprintFieldCategory.System && field.systemFieldType === DmpBlueprintSystemFieldType.GRANT) { // hasGrant = true; // } // } @@ -1396,7 +1391,7 @@ export class DmpEditorComponent extends BaseEditor implemen // let hasFunder = false; // this.selectedDmpBlueprintDefinition.sections.forEach(section => section.fields.forEach( // field => { - // if (field.category as unknown === DmpBlueprintSectionFieldCategory.SYSTEM && field.systemFieldType === DmpBlueprintSystemFieldType.FUNDER) { + // if (field.category as unknown === DmpBlueprintFieldCategory.System && field.systemFieldType === DmpBlueprintSystemFieldType.FUNDER) { // hasFunder = true; // } // } @@ -1410,7 +1405,7 @@ export class DmpEditorComponent extends BaseEditor implemen // let hasProject = false; // this.selectedDmpBlueprintDefinition.sections.forEach(section => section.fields.forEach( // field => { - // if (field.category as unknown === DmpBlueprintSectionFieldCategory.SYSTEM && field.systemFieldType === DmpBlueprintSystemFieldType.PROJECT) { + // if (field.category as unknown === DmpBlueprintFieldCategory.System && field.systemFieldType === DmpBlueprintSystemFieldType.PROJECT) { // hasProject = true; // } // } diff --git a/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.model.ts b/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.model.ts index e50816b13..d6d4d1a00 100644 --- a/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.model.ts +++ b/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.model.ts @@ -269,7 +269,8 @@ export class DmpBlueprintValueEditorModel implements DmpBlueprintValuePersist { fromModel(item: DmpBlueprintValue, dmpReferences: DmpReference[]): DmpBlueprintValueEditorModel { this.fieldId = item.fieldId; this.fieldValue = item.fieldValue; - this.references = dmpReferences?.filter(x => x.data?.blueprintFieldId === this.fieldId) || []; + //TODO: refactor reference type + // this.references = dmpReferences?.filter(x => x.data?.blueprintFieldId === this.fieldId) || []; return this; } @@ -428,7 +429,7 @@ export class DmpReferenceEditorModel implements DmpReferencePersist { fromModel(item: DmpReference): DmpReferenceEditorModel { this.id = item.id; - this.reference = item.reference; + // this.reference = item.reference; //TODO: refactor reference type this.data = item.data; this.hash = item.hash; diff --git a/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.resolver.ts b/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.resolver.ts index 32b7caedc..baac027e3 100644 --- a/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.resolver.ts +++ b/dmp-frontend/src/app/ui/dmp/dmp-editor-blueprint/dmp-editor.resolver.ts @@ -1,9 +1,10 @@ import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { Description } from '@app/core/model/description/description'; -import { DescriptionTemplatesInSection, DmpBlueprint, DmpBlueprintDefinition, DmpBlueprintDefinitionSection, FieldInSection } from '@app/core/model/dmp-blueprint/dmp-blueprint'; +import { DescriptionTemplatesInSection, DmpBlueprint, DmpBlueprintDefinition, DmpBlueprintDefinitionSection, ExtraFieldInSection, FieldInSection, ReferenceTypeFieldInSection, SystemFieldInSection } from '@app/core/model/dmp-blueprint/dmp-blueprint'; import { Dmp, DmpBlueprintValue, DmpContact, DmpDescriptionTemplate, DmpProperties } from '@app/core/model/dmp/dmp'; import { DmpReference, DmpReferenceData } from '@app/core/model/dmp/dmp-reference'; +import { ReferenceType } from '@app/core/model/reference-type/reference-type'; import { Reference } from '@app/core/model/reference/reference'; import { DmpAssociatedUser, User } from '@app/core/model/user/user'; import { DmpService } from '@app/core/services/dmp/dmp.service'; @@ -93,13 +94,16 @@ export class DmpEditorResolver extends BaseEditorResolver { (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.descriptionTemplates), nameof(x => x.descriptionTemplateGroupId)].join('.'), (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.id)].join('.'), (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.category)].join('.'), - (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.dataType)].join('.'), - (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.systemFieldType)].join('.'), (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.label)].join('.'), (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.placeholder)].join('.'), (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.description)].join('.'), (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.required)].join('.'), - (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.ordinal)].join('.') + (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.ordinal)].join('.'), + (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.dataType)].join('.'), + (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.systemFieldType)].join('.'), + (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.referenceType), nameof(x => x.id)].join('.'), + (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.referenceType), nameof(x => x.name)].join('.'), + (prefix ? prefix + '.' : '') + [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.referenceType), nameof(x => x.code)].join('.'), ] } diff --git a/dmp-frontend/src/app/ui/dmp/listing/listing-item/dmp-listing-item.component.html b/dmp-frontend/src/app/ui/dmp/listing/listing-item/dmp-listing-item.component.html index 44d3a0bfb..c5fd6000a 100644 --- a/dmp-frontend/src/app/ui/dmp/listing/listing-item/dmp-listing-item.component.html +++ b/dmp-frontend/src/app/ui/dmp/listing/listing-item/dmp-listing-item.component.html @@ -15,7 +15,7 @@ . {{'DMP-LISTING.VERSION' | translate}} {{dmp.version}} . - {{ 'DMP-LISTING.GRANT' | translate }}: {{referenceService.getReferencesForTypesFirstSafe(dmp?.dmpReferences, [referenceTypeEnum.Grants])?.reference?.label}} + {{ 'DMP-LISTING.GRANT' | translate }}: {{referenceService.getReferencesForTypesFirstSafe(dmp?.dmpReferences, [this.referenceTypeService.getGrantReferenceType()])?.reference?.label}}
{{'DMP-LISTING.CONTAINED-DESCRIPTIONS' | translate}}: ({{ dmp.descriptions?.length }})
diff --git a/dmp-frontend/src/app/ui/dmp/listing/listing-item/dmp-listing-item.component.ts b/dmp-frontend/src/app/ui/dmp/listing/listing-item/dmp-listing-item.component.ts index 9cc02a874..4f07834e2 100644 --- a/dmp-frontend/src/app/ui/dmp/listing/listing-item/dmp-listing-item.component.ts +++ b/dmp-frontend/src/app/ui/dmp/listing/listing-item/dmp-listing-item.component.ts @@ -5,13 +5,14 @@ import { MatDialog } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { DmpAccessType } from '@app/core/common/enum/dmp-access-type'; import { DmpUserRole } from '@app/core/common/enum/dmp-user-role'; -import { ReferenceType } from '@app/core/common/enum/reference-type'; -import { CloneDmpPersist, Dmp } from '@app/core/model/dmp/dmp'; +import { Dmp } from '@app/core/model/dmp/dmp'; import { DmpBlueprintService } from '@app/core/services/dmp/dmp-blueprint.service'; import { DmpService } from '@app/core/services/dmp/dmp.service'; +import { FileTransformerService } from '@app/core/services/file-transformer/file-transformer.service'; import { LockService } from '@app/core/services/lock/lock.service'; import { MatomoService } from '@app/core/services/matomo/matomo-service'; import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service'; +import { ReferenceTypeService } from '@app/core/services/reference-type/reference-type.service'; import { ReferenceService } from '@app/core/services/reference/reference.service'; import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; import { FileUtils } from '@app/core/services/utilities/file-utils.service'; @@ -22,12 +23,9 @@ import { TranslateService } from '@ngx-translate/core'; import { takeUntil } from 'rxjs/operators'; import { DmpStatus } from '../../../../core/common/enum/dmp-status'; import { AuthService } from '../../../../core/services/auth/auth.service'; -import * as FileSaver from 'file-saver'; -import { FileFormat } from '@app/core/model/file/file-format.model'; -import { FileTransformerService } from '@app/core/services/file-transformer/file-transformer.service'; import { CloneDmpDialogComponent } from '../../clone-dialog/dmp-clone-dialog.component'; -import { NewVersionDmpDialogComponent } from '../../new-version-dialog/dmp-new-version-dialog.component'; import { DmpInvitationDialogComponent } from '../../invitation/dialog/dmp-invitation-dialog.component'; +import { NewVersionDmpDialogComponent } from '../../new-version-dialog/dmp-new-version-dialog.component'; @Component({ selector: 'app-dmp-listing-item-component', @@ -45,7 +43,6 @@ export class DmpListingItemComponent extends BaseComponent implements OnInit { isFinalized: boolean; isPublished: boolean; dmpStatusEnum = DmpStatus; - referenceTypeEnum = ReferenceType; constructor( private router: Router, @@ -61,6 +58,7 @@ export class DmpListingItemComponent extends BaseComponent implements OnInit { private httpClient: HttpClient, private matomoService: MatomoService, public referenceService: ReferenceService, + public referenceTypeService: ReferenceTypeService, public fileTransformerService: FileTransformerService, private fileUtils: FileUtils) { super(); diff --git a/dmp-frontend/src/app/ui/dmp/overview/dmp-overview.component.html b/dmp-frontend/src/app/ui/dmp/overview/dmp-overview.component.html index ce029b58d..5f4741056 100644 --- a/dmp-frontend/src/app/ui/dmp/overview/dmp-overview.component.html +++ b/dmp-frontend/src/app/ui/dmp/overview/dmp-overview.component.html @@ -54,9 +54,9 @@ delete
-
+
{{'DMP-OVERVIEW.GRANT' | translate}}
-
{{referenceService.getReferencesForTypesFirstSafe(dmp?.dmpReferences, [referenceTypeEnum.Grants])?.reference?.label}}
+
{{referenceService.getReferencesForTypesFirstSafe(dmp?.dmpReferences, [this.referenceTypeService.getGrantReferenceType()])?.reference?.label}}
{{'DESCRIPTION-OVERVIEW.RESEARCHERS' | translate}}
diff --git a/dmp-frontend/src/app/ui/dmp/overview/dmp-overview.component.ts b/dmp-frontend/src/app/ui/dmp/overview/dmp-overview.component.ts index bb0b23b4b..27c4101c7 100644 --- a/dmp-frontend/src/app/ui/dmp/overview/dmp-overview.component.ts +++ b/dmp-frontend/src/app/ui/dmp/overview/dmp-overview.component.ts @@ -14,7 +14,6 @@ import { Location } from '@angular/common'; import { DescriptionStatus } from '@app/core/common/enum/description-status'; import { DmpAccessType } from '@app/core/common/enum/dmp-access-type'; import { DmpUserRole } from '@app/core/common/enum/dmp-user-role'; -import { ReferenceType } from '@app/core/common/enum/reference-type'; import { DepositConfiguration } from '@app/core/model/deposit/deposit-configuration'; import { Description } from '@app/core/model/description/description'; import { Dmp, DmpUser, DmpUserRemovePersist } from '@app/core/model/dmp/dmp'; @@ -38,6 +37,7 @@ import * as FileSaver from 'file-saver'; import { takeUntil } from 'rxjs/operators'; import { nameof } from 'ts-simple-nameof'; import { DmpInvitationDialogComponent } from '../invitation/dialog/dmp-invitation-dialog.component'; +import { ReferenceTypeService } from '@app/core/services/reference-type/reference-type.service'; @Component({ selector: 'app-dmp-overview', @@ -66,7 +66,6 @@ export class DmpOverviewComponent extends BaseComponent implements OnInit { descriptionStatusEnum = DescriptionStatus; dmpAccessTypeEnum = DmpAccessType; - referenceTypeEnum = ReferenceType; dmpStatusEnum = DmpStatus; dmpUserRoleEnum = DmpUserRole; @@ -88,7 +87,8 @@ export class DmpOverviewComponent extends BaseComponent implements OnInit { private fileUtils: FileUtils, public referenceService: ReferenceService, public enumUtils: EnumUtils, - public fileTransformerService: FileTransformerService + public fileTransformerService: FileTransformerService, + private referenceTypeService: ReferenceTypeService ) { super(); } @@ -108,7 +108,7 @@ export class DmpOverviewComponent extends BaseComponent implements OnInit { .pipe(takeUntil(this._destroyed)) .subscribe(data => { this.dmp = data; - this.researchers = this.referenceService.getReferencesForTypes(this.dmp?.dmpReferences, [ReferenceType.Researcher]); + this.researchers = this.referenceService.getReferencesForTypes(this.dmp?.dmpReferences, [this.referenceTypeService.getResearcherReferenceType()]); if (!this.hasDoi()) { this.selectedModel = this.dmp.entityDois[0]; } @@ -136,7 +136,7 @@ export class DmpOverviewComponent extends BaseComponent implements OnInit { .pipe(takeUntil(this._destroyed)) .subscribe(data => { this.dmp = data; - this.researchers = this.referenceService.getReferencesForTypes(this.dmp?.dmpReferences, [ReferenceType.Researcher]); + this.researchers = this.referenceService.getReferencesForTypes(this.dmp?.dmpReferences, [this.referenceTypeService.getResearcherReferenceType()]); if (!this.hasDoi()) { this.selectedModel = this.dmp.entityDois[0]; } @@ -226,7 +226,7 @@ export class DmpOverviewComponent extends BaseComponent implements OnInit { // let hasGrant = false; // blueprint.sections.forEach(section => section.fields.forEach( // field => { - // if (field.category as unknown === DmpBlueprintSectionFieldCategory.SYSTEM && field.systemFieldType === DmpBlueprintSystemFieldType.GRANT) { + // if (field.category as unknown === DmpBlueprintFieldCategory.System && field.systemFieldType === DmpBlueprintSystemFieldType.GRANT) { // hasGrant = true; // } // } @@ -240,7 +240,7 @@ export class DmpOverviewComponent extends BaseComponent implements OnInit { // let hasFunder = false; // blueprint.sections.forEach(section => section.fields.forEach( // field => { - // if (field.category as unknown === DmpBlueprintSectionFieldCategory.SYSTEM && field.systemFieldType === DmpBlueprintSystemFieldType.FUNDER) { + // if (field.category as unknown === DmpBlueprintFieldCategory.System && field.systemFieldType === DmpBlueprintSystemFieldType.FUNDER) { // hasFunder = true; // } // } @@ -254,7 +254,7 @@ export class DmpOverviewComponent extends BaseComponent implements OnInit { // let hasProject = false; // blueprint.sections.forEach(section => section.fields.forEach( // field => { - // if (field.category as unknown === DmpBlueprintSectionFieldCategory.SYSTEM && field.systemFieldType === DmpBlueprintSystemFieldType.PROJECT) { + // if (field.category as unknown === DmpBlueprintFieldCategory.System && field.systemFieldType === DmpBlueprintSystemFieldType.PROJECT) { // hasProject = true; // } // } diff --git a/dmp-frontend/src/app/ui/reference/reference-field/reference-field.component.html b/dmp-frontend/src/app/ui/reference/reference-field/reference-field.component.html index 6f85c7994..2d40b0a0a 100644 --- a/dmp-frontend/src/app/ui/reference/reference-field/reference-field.component.html +++ b/dmp-frontend/src/app/ui/reference/reference-field/reference-field.component.html @@ -1,6 +1,6 @@ - {{label ?? enumUtils.toReferenceTypeString(referenceType)}} - + {{label ?? referenceType?.name}} + {{form.getError('backendError').message}} {{'GENERAL.VALIDATION.REQUIRED' | translate}} diff --git a/dmp-frontend/src/app/ui/reference/reference-field/reference-field.component.ts b/dmp-frontend/src/app/ui/reference/reference-field/reference-field.component.ts index ce35d8dae..fe9bf2eac 100644 --- a/dmp-frontend/src/app/ui/reference/reference-field/reference-field.component.ts +++ b/dmp-frontend/src/app/ui/reference/reference-field/reference-field.component.ts @@ -1,10 +1,11 @@ import { Component, Input, OnInit } from '@angular/core'; import { UntypedFormGroup } from '@angular/forms'; -import { ReferenceType } from '@app/core/common/enum/reference-type'; +import { ReferenceType } from '@app/core/model/reference-type/reference-type'; import { ReferenceService } from '@app/core/services/reference/reference.service'; import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; import { MultipleAutoCompleteConfiguration } from '@app/library/auto-complete/multiple/multiple-auto-complete-configuration'; import { BaseComponent } from '@common/base/base.component'; +import { Guid } from '@common/types/guid'; @Component({ selector: 'app-reference-field-component', @@ -16,7 +17,7 @@ export class ReferenceFieldComponent extends BaseComponent implements OnInit { @Input() referenceType: ReferenceType = null; @Input() form: UntypedFormGroup = null; @Input() label: string = null; - @Input() placeholder: string = "Enter text"; + @Input() placeholder: string; multipleAutoCompleteSearchConfiguration: MultipleAutoCompleteConfiguration; @@ -26,7 +27,7 @@ export class ReferenceFieldComponent extends BaseComponent implements OnInit { ) { super(); } ngOnInit() { - this.multipleAutoCompleteSearchConfiguration = this.referenceService.getMultipleAutoCompleteSearchConfiguration(this.referenceType); + this.multipleAutoCompleteSearchConfiguration = this.referenceService.getMultipleAutoCompleteSearchConfiguration(this.referenceType.id); } addReference() { diff --git a/dmp-frontend/src/assets/i18n/en.json b/dmp-frontend/src/assets/i18n/en.json index 2d4d2d305..2d850c3e9 100644 --- a/dmp-frontend/src/assets/i18n/en.json +++ b/dmp-frontend/src/assets/i18n/en.json @@ -1604,13 +1604,13 @@ "SECTION-PREFIX": "Section", "SECTION-NAME": "Section Name", "SECTION-DESCRIPTION": "Section Description", - "SYSTEM-FIELDS": "System Fields", - "SYSTEM-FIELD": "System Field", - "FIELD-TYPE": "Field Type", + "REFERENCE-TYPE": "Reference Type", + "SYSTEM-FIELD-TYPE": "System Field", "FIELD-LABEL": "Label", "FIELD-PLACEHOLDER": "Placeholder", "FIELD-DESCRIPTION": "Description", - "FIELD-DATA-TYPE": "Data Type", + "DATA-TYPE": "Data Type", + "CATEGORY": "Field Type", "FIELD-REQUIRED": "Required", "DESCRIPTION-TEMPLATES": "Description Templates", "DESCRIPTION-TEMPLATE": "Description Template", @@ -1628,9 +1628,8 @@ } }, "ACTIONS": { - "ADD-EXTRA-FIELD": "Add Extra Field", - "REMOVE-SYSTEM-FIELD": "Delete", - "REMOVE-EXTRA-FIELD": "Delete", + "ADD-FIELD": "Add Field", + "REMOVE-FIELD": "Delete", "REMOVE-SECTION": "Remove Section", "ADD-DESCRIPTION-TEMPLATE": "Add Description Template", "REMOVE-DESCRIPTION-TEMPLATE": "Remove Description Template", @@ -2296,16 +2295,10 @@ "DRAFT": "Draft" }, "DMP-BLUEPRINT-SYSTEM-FIELD-TYPE": { - "TEXT": "Title", - "HTML_TEXT": "Description", - "RESEARCHERS": "Researchers", - "ORGANIZATIONS": "Organizations", + "TITLE": "Title", + "DESCRIPTION": "Description", "LANGUAGE": "Language", "CONTACT": "Contact", - "FUNDER": "Funder", - "GRANT": "Grant", - "PROJECT": "Project", - "LICENSE": "License", "ACCESS_RIGHTS": "Access" }, "DMP-BLUEPRINT-EXTRA-FIELD-DATA-TYPE": { @@ -2433,6 +2426,11 @@ "DMP-CONTACT-TYPE": { "INTERNAL": "Internal", "EXTERNAL": "External" + }, + "DMP-BLUEPRINT-FIELD-CATEGORY": { + "SYSTEM": "System", + "EXTRA": "Custom", + "REFERENCE-TYPE": "External Reference" } }, "ADDRESEARCHERS-EDITOR": { diff --git a/dmp-frontend/src/common/formatting/common-formatting.module.ts b/dmp-frontend/src/common/formatting/common-formatting.module.ts index 788a33ee9..7f85e399c 100644 --- a/dmp-frontend/src/common/formatting/common-formatting.module.ts +++ b/dmp-frontend/src/common/formatting/common-formatting.module.ts @@ -5,15 +5,14 @@ import { DataTableDateOnlyFormatPipe, DateOnlyPipe } from '@common/formatting/pi import { DataTableDateTimeFormatPipe, DateTimeFormatPipe } from '@common/formatting/pipes/date-time-format.pipe'; import { LowercaseFirstLetterPipe } from '@common/formatting/pipes/lowercase-first-letter.pipe'; import { IsActiveTypePipe } from './pipes/is-active-type.pipe'; -import { ReferenceTypePipe } from './pipes/reference-type.pipe'; -import { ReferenceSourceTypePipe } from './pipes/reference-source-type.pipe'; -import { NotificationTemplateChannelPipe } from './pipes/notification-template-channel.pipe'; -import { NotificationTemplateKindPipe } from './pipes/notification-template-kind.pipe'; -import { NotificationTypePipe } from './pipes/notification-type.pipe'; import { NotificationContactTypePipe } from './pipes/notification-contact-type.pipe'; import { NotificationNotifyStatePipe } from './pipes/notification-notify-state.pipe'; +import { NotificationTemplateChannelPipe } from './pipes/notification-template-channel.pipe'; +import { NotificationTemplateKindPipe } from './pipes/notification-template-kind.pipe'; import { NotificationTrackingProcessPipe } from './pipes/notification-tracking-process.pipe'; import { NotificationTrackingStatePipe } from './pipes/notification-tracking-state.pipe'; +import { NotificationTypePipe } from './pipes/notification-type.pipe'; +import { ReferenceSourceTypePipe } from './pipes/reference-source-type.pipe'; // // @@ -31,7 +30,6 @@ import { NotificationTrackingStatePipe } from './pipes/notification-tracking-sta DateOnlyPipe, DataTableDateOnlyFormatPipe, IsActiveTypePipe, - ReferenceTypePipe, ReferenceSourceTypePipe, NotificationTemplateChannelPipe, NotificationTemplateKindPipe, @@ -51,7 +49,6 @@ import { NotificationTrackingStatePipe } from './pipes/notification-tracking-sta DateOnlyPipe, DataTableDateOnlyFormatPipe, IsActiveTypePipe, - ReferenceTypePipe, ReferenceSourceTypePipe, NotificationTemplateChannelPipe, NotificationTemplateKindPipe, @@ -71,7 +68,6 @@ import { NotificationTrackingStatePipe } from './pipes/notification-tracking-sta DateOnlyPipe, DataTableDateOnlyFormatPipe, IsActiveTypePipe, - ReferenceTypePipe, ReferenceSourceTypePipe, NotificationTemplateChannelPipe, NotificationTemplateKindPipe, diff --git a/dmp-frontend/src/common/formatting/pipes/reference-type.pipe.ts b/dmp-frontend/src/common/formatting/pipes/reference-type.pipe.ts deleted file mode 100644 index d5276b3e5..000000000 --- a/dmp-frontend/src/common/formatting/pipes/reference-type.pipe.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Pipe, PipeTransform } from '@angular/core'; -import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; - -@Pipe({ name: 'ReferenceTypeFormat' }) -export class ReferenceTypePipe implements PipeTransform { - constructor(private enumUtils: EnumUtils) { } - - public transform(value): any { - return this.enumUtils.toReferenceTypeString(value); - } -} From 957c1fad58df3155551fe6634c4f812987f4579d Mon Sep 17 00:00:00 2001 From: sgiannopoulos Date: Mon, 12 Feb 2024 17:43:41 +0200 Subject: [PATCH 5/5] reference fetcher changes --- .../AuthenticationConfigurationEntity.java | 3 +- .../referencetype/QueryConfigEntity.java | 3 +- ...enceTypeSourceBaseConfigurationEntity.java | 3 +- ...eSourceExternalApiConfigurationEntity.java | 3 +- ...SourceStaticOptionConfigurationEntity.java | 3 +- .../ReferenceTypeStaticOptionEntity.java | 3 +- ...esultFieldsMappingConfigurationEntity.java | 3 +- .../ResultsConfigurationEntity.java | 3 +- .../DefinitionSearchBuilder.java | 58 -- .../referencesearch/FieldSearchBuilder.java | 88 -- .../ReferenceSearchBuilder.java | 96 -- .../prefilling/PrefillingServiceImpl.java | 10 +- .../service/reference/ReferenceService.java | 6 +- .../reference/ReferenceServiceImpl.java | 735 +++++++------- .../ReferenceTypeServiceImpl.java | 1 - .../remotefetcher/RemoteFetcherService.java | 35 +- .../RemoteFetcherServiceImpl.java | 917 ++++++++---------- .../remotefetcher/RemoteFetcherUtils.java | 152 --- .../config/AuthenticationConfiguration.java | 57 -- .../config/DataFieldsUrlConfiguration.java | 134 --- .../config/DataUrlConfiguration.java | 82 -- .../remotefetcher/config/ExternalUrls.java | 173 ---- .../remotefetcher/config/QueryConfig.java | 48 - .../config/UrlConfiguration.java | 128 +-- .../entities/AuthenticationConfiguration.java | 18 + .../config/entities/DatasetUrls.java | 33 - .../config/entities/FunderUrls.java | 33 - .../config/entities/GeneralUrls.java | 31 - .../config/entities/GenericUrls.java | 5 +- .../config/entities/GrantUrls.java | 35 - .../config/entities/JournalUrls.java | 34 - .../config/entities/LicenseUrls.java | 33 - .../config/entities/OrganisationUrls.java | 34 - .../config/entities/PrefillingSearch.java | 4 +- .../config/entities/ProjectUrls.java | 33 - .../config/entities/PubRepositoryUrls.java | 34 - .../config/entities/PublicationsUrls.java | 34 - .../config/entities/QueryConfig.java | 11 + .../config/entities/RegistryUrls.java | 35 - .../config/entities/RepositoryUrls.java | 34 - .../config/entities/ResearcherUrls.java | 35 - .../ResultFieldsMappingConfiguration.java | 6 + .../config/entities/ResultsConfiguration.java | 9 + .../config/entities/ServiceUrls.java | 35 - .../entities/SourceBaseConfiguration.java | 10 + .../SourceExternalApiConfiguration.java | 29 + .../SourceStaticOptionConfiguration.java | 7 + .../config/entities/StaticOption.java | 6 + .../config/entities/TagUrls.java | 35 - .../config/entities/TaxonomiesUrls.java | 34 - .../config/entities/ValidationUrls.java | 35 - .../models/ExternalDataResult.java | 46 + .../models/ExternalRefernceResult.java | 37 - .../controllers/v2/ReferenceController.java | 5 +- 54 files changed, 923 insertions(+), 2591 deletions(-) delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/DefinitionSearchBuilder.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/FieldSearchBuilder.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/ReferenceSearchBuilder.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherUtils.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/AuthenticationConfiguration.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/DataFieldsUrlConfiguration.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/DataUrlConfiguration.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/QueryConfig.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/AuthenticationConfiguration.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/DatasetUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/FunderUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GeneralUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GrantUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/JournalUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/LicenseUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/OrganisationUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ProjectUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PubRepositoryUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PublicationsUrls.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/QueryConfig.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/RegistryUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/RepositoryUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResearcherUrls.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResultFieldsMappingConfiguration.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResultsConfiguration.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ServiceUrls.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceBaseConfiguration.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceExternalApiConfiguration.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceStaticOptionConfiguration.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/StaticOption.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/TagUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/TaxonomiesUrls.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ValidationUrls.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/models/ExternalDataResult.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/models/ExternalRefernceResult.java diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/AuthenticationConfigurationEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/AuthenticationConfigurationEntity.java index 3990b2c1f..2af7bf7f4 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/AuthenticationConfigurationEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/AuthenticationConfigurationEntity.java @@ -1,9 +1,10 @@ package eu.eudat.commons.types.referencetype; import eu.eudat.commons.enums.ReferenceTypeExternalApiHTTPMethodType; +import eu.eudat.service.remotefetcher.config.entities.AuthenticationConfiguration; import jakarta.xml.bind.annotation.XmlElement; -public class AuthenticationConfigurationEntity { +public class AuthenticationConfigurationEntity implements AuthenticationConfiguration { private Boolean enabled; private String authUrl; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/QueryConfigEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/QueryConfigEntity.java index 52ab71f86..7edefb26d 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/QueryConfigEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/QueryConfigEntity.java @@ -1,8 +1,9 @@ package eu.eudat.commons.types.referencetype; +import eu.eudat.service.remotefetcher.config.entities.QueryConfig; import jakarta.xml.bind.annotation.XmlElement; -public class QueryConfigEntity { +public class QueryConfigEntity implements QueryConfig { private String condition; private String separator; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceBaseConfigurationEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceBaseConfigurationEntity.java index ead9bec7c..fb10b4981 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceBaseConfigurationEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceBaseConfigurationEntity.java @@ -1,12 +1,13 @@ package eu.eudat.commons.types.referencetype; import eu.eudat.commons.enums.ReferenceTypeSourceType; +import eu.eudat.service.remotefetcher.config.entities.SourceBaseConfiguration; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElementWrapper; import java.util.List; -public abstract class ReferenceTypeSourceBaseConfigurationEntity { +public abstract class ReferenceTypeSourceBaseConfigurationEntity implements SourceBaseConfiguration { private String key; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceExternalApiConfigurationEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceExternalApiConfigurationEntity.java index 3fbe81027..2905e2b33 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceExternalApiConfigurationEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceExternalApiConfigurationEntity.java @@ -2,11 +2,12 @@ package eu.eudat.commons.types.referencetype; import eu.eudat.commons.enums.ReferenceTypeExternalApiHTTPMethodType; +import eu.eudat.service.remotefetcher.config.entities.SourceExternalApiConfiguration; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElementWrapper; import java.util.List; -public class ReferenceTypeSourceExternalApiConfigurationEntity extends ReferenceTypeSourceBaseConfigurationEntity { +public class ReferenceTypeSourceExternalApiConfigurationEntity extends ReferenceTypeSourceBaseConfigurationEntity implements SourceExternalApiConfiguration { private String url; private ResultsConfigurationEntity results; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceStaticOptionConfigurationEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceStaticOptionConfigurationEntity.java index 99d6b273d..f8f141068 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceStaticOptionConfigurationEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeSourceStaticOptionConfigurationEntity.java @@ -1,11 +1,12 @@ package eu.eudat.commons.types.referencetype; +import eu.eudat.service.remotefetcher.config.entities.SourceStaticOptionConfiguration; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElementWrapper; import java.util.List; -public class ReferenceTypeSourceStaticOptionConfigurationEntity extends ReferenceTypeSourceBaseConfigurationEntity { +public class ReferenceTypeSourceStaticOptionConfigurationEntity extends ReferenceTypeSourceBaseConfigurationEntity implements SourceStaticOptionConfiguration { List options; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeStaticOptionEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeStaticOptionEntity.java index e8c4c85bb..f5b85c170 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeStaticOptionEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ReferenceTypeStaticOptionEntity.java @@ -1,8 +1,9 @@ package eu.eudat.commons.types.referencetype; +import eu.eudat.service.remotefetcher.config.entities.StaticOption; import jakarta.xml.bind.annotation.XmlElement; -public class ReferenceTypeStaticOptionEntity { +public class ReferenceTypeStaticOptionEntity implements StaticOption { private String code; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ResultFieldsMappingConfigurationEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ResultFieldsMappingConfigurationEntity.java index 28ecf655f..e988a9ee6 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ResultFieldsMappingConfigurationEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ResultFieldsMappingConfigurationEntity.java @@ -1,8 +1,9 @@ package eu.eudat.commons.types.referencetype; +import eu.eudat.service.remotefetcher.config.entities.ResultFieldsMappingConfiguration; import jakarta.xml.bind.annotation.XmlElement; -public class ResultFieldsMappingConfigurationEntity { +public class ResultFieldsMappingConfigurationEntity implements ResultFieldsMappingConfiguration { private String code; private String responsePath; diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ResultsConfigurationEntity.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ResultsConfigurationEntity.java index 84eec895b..7e8071ba6 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ResultsConfigurationEntity.java +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/referencetype/ResultsConfigurationEntity.java @@ -1,11 +1,12 @@ package eu.eudat.commons.types.referencetype; +import eu.eudat.service.remotefetcher.config.entities.ResultsConfiguration; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElementWrapper; import java.util.List; -public class ResultsConfigurationEntity { +public class ResultsConfigurationEntity implements ResultsConfiguration { private String resultsArrayPath; private List fieldsMapping; diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/DefinitionSearchBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/DefinitionSearchBuilder.java deleted file mode 100644 index b66a528d1..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/DefinitionSearchBuilder.java +++ /dev/null @@ -1,58 +0,0 @@ -//package eu.eudat.model.builder.referencesearch; -// -//import eu.eudat.authorization.AuthorizationFlags; -//import eu.eudat.configurations.referencetype.ReferenceTypeProperties; -//import eu.eudat.convention.ConventionService; -//import eu.eudat.model.builder.BaseBuilder; -//import eu.eudat.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 -//@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -//public class DefinitionSearchBuilder extends BaseBuilder> { -// -// private final BuilderFactory builderFactory; -// private final ReferenceTypeProperties properties; -// private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); -// -// @Autowired -// public DefinitionSearchBuilder( -// ConventionService conventionService, BuilderFactory builderFactory, ReferenceTypeProperties properties) { -// super(conventionService, new LoggerService(LoggerFactory.getLogger(DefinitionSearchBuilder.class))); -// this.builderFactory = builderFactory; -// this.properties = properties; -// } -// -// public DefinitionSearchBuilder 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 (data == null) -// return new ArrayList<>(); -// -// List models = new ArrayList<>(); -// //for (Map d : data) { -// Definition m = new Definition(); -// m.setFields(this.builderFactory.builder(FieldSearchBuilder.class).authorize(this.authorize).build(null, data)); -// models.add(m); -// //} -// this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); -// return models; -// } -//} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/FieldSearchBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/FieldSearchBuilder.java deleted file mode 100644 index 5480bcec2..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/FieldSearchBuilder.java +++ /dev/null @@ -1,88 +0,0 @@ -//package eu.eudat.model.builder.referencesearch; -// -//import eu.eudat.authorization.AuthorizationFlags; -//import eu.eudat.commons.enums.ReferenceFieldDataType; -//import eu.eudat.configurations.referencetype.ReferenceTypeField; -//import eu.eudat.configurations.referencetype.ReferenceTypeProperties; -//import eu.eudat.convention.ConventionService; -//import eu.eudat.model.builder.BaseBuilder; -//import eu.eudat.model.referencedefinition.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.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 FieldSearchBuilder extends BaseBuilder> { -// -// private final ReferenceTypeProperties properties; -// private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); -// -// @Autowired -// public FieldSearchBuilder( -// ConventionService conventionService, ReferenceTypeProperties properties) { -// super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldSearchBuilder.class))); -// this.properties = properties; -// } -// -// public FieldSearchBuilder authorize(EnumSet values) { -// this.authorize = values; -// return this; -// } -// -// @Override -// public List build(FieldSet fields, List< Map> 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 (data == null) -// return new ArrayList<>(); -// -// List models = new ArrayList<>(); -// for (Map d : data) { -// -// ReferenceType referenceType = ReferenceType.valueOf(d.getOrDefault("referenceType", null)); -// List typeFields = this.getPropertiesFields(referenceType); -// if (typeFields.isEmpty()){ -// return new ArrayList<>(); -// } -// -// for (ReferenceTypeField typeField: typeFields){ -// Field m = new Field(); -// m.setCode(typeField.getCode()); -// m.setDataType(ReferenceFieldDataType.valueOf(typeField.getDataType())); -// m.setValue(d.getOrDefault(typeField.getCode(), null)); -// models.add(m); -// } -// } -// this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); -// return models; -// } -// -// private List getPropertiesFields(ReferenceType referenceType){ -// switch (referenceType) { -// case Taxonomies: return properties.getTaxonomy().get("fields"); -// case Licenses: return properties.getLicence().get("fields"); -// case Publications: return properties.getPublication().get("fields"); -// case Journals: return properties.getJournal().get("fields"); -// case PubRepositories: return properties.getPubRepository().get("fields"); -// case DataRepositories: return properties.getDataRepository().get("fields"); -// case Registries: return properties.getRegistry().get("fields"); -// case Services: return properties.getService().get("fields"); -// case Organizations: return properties.getOrganisation().get("fields"); -// case Datasets: return properties.getDataset().get("fields"); -// case Funder: return properties.getFunder().get("fields"); -// case Grants: return properties.getGrant().get("fields"); -// case Project: return properties.getProject().get("fields"); -// case Researcher: return properties.getResearcher().get("fields"); -// default: return null; -// } -// } -//} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/ReferenceSearchBuilder.java b/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/ReferenceSearchBuilder.java deleted file mode 100644 index 734feccd7..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/model/builder/referencesearch/ReferenceSearchBuilder.java +++ /dev/null @@ -1,96 +0,0 @@ -//package eu.eudat.model.builder.referencesearch; -// -//import eu.eudat.authorization.AuthorizationFlags; -//import eu.eudat.commons.enums.ReferenceSourceType; -//import eu.eudat.convention.ConventionService; -//import eu.eudat.model.Reference; -//import eu.eudat.model.builder.BaseBuilder; -//import eu.eudat.model.referencedefinition.Definition; -//import eu.eudat.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 -//@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -//public class ReferenceSearchBuilder extends BaseBuilder> { -// -// private final BuilderFactory builderFactory; -// private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); -// -// @Autowired -// public ReferenceSearchBuilder( -// ConventionService conventionService, -// BuilderFactory builderFactory) { -// super(conventionService, new LoggerService(LoggerFactory.getLogger(ReferenceSearchBuilder.class))); -// this.builderFactory = builderFactory; -// } -// -// public ReferenceSearchBuilder 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 (data == null) -// return new ArrayList<>(); -// -// List models = new ArrayList<>(); -// for (Map d : data) { -// Reference m = new Reference(); -// if (d.containsKey("id")) m.setId(UUID.fromString(d.getOrDefault("id", null))); -// m.setLabel(d.getOrDefault("name", null)); -// m.setSourceType(ReferenceSourceType.External); -// String type = d.getOrDefault("referenceType", null); -// if (type != null) m.setType(ReferenceType.valueOf(type)); -// -// Definition definition = this.builderFactory.builder(DefinitionSearchBuilder.class).authorize(this.authorize).build(null, d); -// m.setDefinition(definition); -// -// switch (m.getType()){ -// case Researcher: -// case Organizations: -// case Funder: -// case Grants: -// case DataRepositories: -// case PubRepositories: -// case Journals: -// case Datasets: -// case Registries: -// case Services:{ -// for (Field field : definition.getFields()) { -// if (field.getCode().equals("pid") && field.getValue() != null) { -// if (d.containsKey("key")) { -// m.setReference(d.get("key") + ":" + field.getValue()); -// } -// } -// if (field.getCode().equals("tag") && field.getValue() != null){ -// m.setSource(field.getValue()); -// } -// } -// } -// } -// -// m.setDescription(d.getOrDefault("description", null)); -// m.setAbbreviation(d.getOrDefault("abbreviation", null)); -// -// models.add(m); -// -// } -// this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); -// return models; -// } -// -//} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/prefilling/PrefillingServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/prefilling/PrefillingServiceImpl.java index 9c7d89303..f8e57c96b 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/prefilling/PrefillingServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/prefilling/PrefillingServiceImpl.java @@ -20,6 +20,7 @@ import eu.eudat.model.descriptionproperties.PropertyDefinitionFieldSetItem; import eu.eudat.model.persist.DescriptionProfilingRequest; import eu.eudat.model.persist.DescriptionProfilingWithDataRequest; import eu.eudat.service.remotefetcher.ExternalUrlConfigProvider; +import eu.eudat.service.remotefetcher.RemoteFetcherService; import eu.eudat.service.remotefetcher.config.entities.*; import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; import gr.cite.tools.data.builder.BuilderFactory; @@ -66,6 +67,7 @@ public class PrefillingServiceImpl implements PrefillingService { private final ExternalUrlConfigProvider externalUrlConfigProvider; private final XmlHandlingService xmlHandlingService; private final ValidatorFactory validatorFactory; + private final RemoteFetcherService remoteFetcherService; @Autowired public PrefillingServiceImpl( EntityManager entityManager, @@ -75,8 +77,9 @@ public class PrefillingServiceImpl implements PrefillingService { MessageSource messageSource, JsonHandlingService jsonHandlingService, ExternalUrlConfigProvider externalUrlConfigProvider, - XmlHandlingService xmlHandlingService, - ValidatorFactory validatorFactory) { + XmlHandlingService xmlHandlingService, + ValidatorFactory validatorFactory, + RemoteFetcherService remoteFetcherService) { this.entityManager = entityManager; this.builderFactory = builderFactory; this.queryFactory = queryFactory; @@ -86,6 +89,7 @@ public class PrefillingServiceImpl implements PrefillingService { this.externalUrlConfigProvider = externalUrlConfigProvider; this.xmlHandlingService = xmlHandlingService; this.validatorFactory = validatorFactory; + this.remoteFetcherService = remoteFetcherService; } @Override @@ -98,7 +102,7 @@ public class PrefillingServiceImpl implements PrefillingService { List> map; Map prefillingConfigs = this.externalUrlConfigProvider.getExternalUrls().getPrefillings(); // for (PrefillingConfig prefillingConfig: prefillingConfigs.values()) {//TODO new reference logic -// map = remoteFetcherService.getExternalGeneric(externalReferenceCriteria, prefillingConfig.getPrefillingSearch()); +// map = remoteFetcherService.getExternalData(prefillingConfig.getPrefillingSearch().getUrls(), externalReferenceCriteria, prefillingConfig.getPrefillingSearch().getFetchMode()); // prefillings.addAll(map.stream().map(submap -> PrefillingEntity.build(submap, this.jsonHandlingService)).toList()); // if (prefillingConfig.getPrefillingSearch().getUrlConfig().isDataInListing()) { // List> mapData = remoteFetcherService.getExternalGenericWithData(externalReferenceCriteria, prefillingConfig.getPrefillingSearch()); diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceService.java b/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceService.java index 9ec36e969..610259eec 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceService.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceService.java @@ -2,10 +2,12 @@ package eu.eudat.service.reference; import com.fasterxml.jackson.core.JsonProcessingException; import eu.eudat.commons.exceptions.HugeResultSetException; +import eu.eudat.data.ReferenceTypeEntity; import eu.eudat.model.Reference; import eu.eudat.model.persist.ReferencePersist; -import eu.eudat.query.lookup.ReferenceDefinitionSearchLookup; import eu.eudat.query.lookup.ReferenceSearchLookup; +import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; +import eu.eudat.service.remotefetcher.models.ExternalDataResult; import gr.cite.tools.exception.MyApplicationException; import gr.cite.tools.exception.MyForbiddenException; import gr.cite.tools.exception.MyNotFoundException; @@ -24,5 +26,5 @@ public interface ReferenceService { void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException; - List searchReferenceWithDefinition(ReferenceDefinitionSearchLookup lookup) throws HugeResultSetException, MyNotFoundException, InvalidApplicationException; + List searchReferenceData(ReferenceSearchLookup lookup) throws MyNotFoundException; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceServiceImpl.java index 790412ecf..f78be7775 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/reference/ReferenceServiceImpl.java @@ -1,18 +1,12 @@ package eu.eudat.service.reference; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.jayway.jsonpath.DocumentContext; -import com.jayway.jsonpath.JsonPath; import eu.eudat.authorization.AuthorizationFlags; import eu.eudat.authorization.Permission; import eu.eudat.commons.XmlHandlingService; import eu.eudat.commons.enums.IsActive; +import eu.eudat.commons.enums.ReferenceFieldDataType; import eu.eudat.commons.enums.ReferenceSourceType; -import eu.eudat.commons.enums.ReferenceTypeExternalApiHTTPMethodType; -import eu.eudat.commons.enums.ReferenceTypeSourceType; -import eu.eudat.commons.exceptions.HugeResultSetException; import eu.eudat.commons.types.reference.DefinitionEntity; import eu.eudat.commons.types.reference.FieldEntity; import eu.eudat.commons.types.referencetype.*; @@ -20,17 +14,18 @@ import eu.eudat.convention.ConventionService; import eu.eudat.data.ReferenceEntity; import eu.eudat.data.ReferenceTypeEntity; import eu.eudat.model.Reference; +import eu.eudat.model.ReferenceType; import eu.eudat.model.builder.ReferenceBuilder; import eu.eudat.model.deleter.ReferenceDeleter; import eu.eudat.model.persist.ReferencePersist; import eu.eudat.model.persist.referencedefinition.DefinitionPersist; import eu.eudat.model.persist.referencedefinition.FieldPersist; import eu.eudat.query.ReferenceQuery; -import eu.eudat.query.ReferenceTypeQuery; -import eu.eudat.query.lookup.ReferenceDefinitionSearchLookup; import eu.eudat.query.lookup.ReferenceSearchLookup; -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.models.ExternalRefernceResult; +import eu.eudat.service.remotefetcher.RemoteFetcherService; +import eu.eudat.service.remotefetcher.config.entities.SourceBaseConfiguration; +import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; +import eu.eudat.service.remotefetcher.models.ExternalDataResult; import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.deleter.DeleterFactory; @@ -45,28 +40,17 @@ import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.MapLogEntry; import jakarta.persistence.EntityManager; import jakarta.xml.bind.JAXBException; -import net.minidev.json.JSONArray; import org.jetbrains.annotations.NotNull; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.client.reactive.ReactorClientHttpConnector; -import org.springframework.http.codec.json.Jackson2JsonDecoder; import org.springframework.stereotype.Service; -import org.springframework.web.reactive.function.client.WebClient; -import reactor.netty.http.client.HttpClient; import javax.management.InvalidApplicationException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.time.Instant; import java.util.*; -import java.util.stream.Collectors; @Service public class ReferenceServiceImpl implements ReferenceService { @@ -81,17 +65,16 @@ public class ReferenceServiceImpl implements ReferenceService { private final QueryFactory queryFactory; private final XmlHandlingService xmlHandlingService; - private final WebClient client; - + public final RemoteFetcherService remoteFetcherService; public ReferenceServiceImpl( - EntityManager entityManager, - AuthorizationService authorizationService, - DeleterFactory deleterFactory, - BuilderFactory builderFactory, - ConventionService conventionService, - MessageSource messageSource, - QueryFactory queryFactory, - XmlHandlingService xmlHandlingService) { + EntityManager entityManager, + AuthorizationService authorizationService, + DeleterFactory deleterFactory, + BuilderFactory builderFactory, + ConventionService conventionService, + MessageSource messageSource, + QueryFactory queryFactory, + XmlHandlingService xmlHandlingService, RemoteFetcherService remoteFetcherService) { this.entityManager = entityManager; this.authorizationService = authorizationService; this.deleterFactory = deleterFactory; @@ -100,11 +83,7 @@ public class ReferenceServiceImpl implements ReferenceService { this.messageSource = messageSource; this.queryFactory = queryFactory; this.xmlHandlingService = xmlHandlingService; - this.client = WebClient.builder().codecs(clientCodecConfigurer -> { - clientCodecConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(new ObjectMapper(), MediaType.APPLICATION_JSON)); - clientCodecConfigurer.defaultCodecs().maxInMemorySize(2 * ((int) Math.pow(1024, 3))); //GK: Why here??? - } - ).clientConnector(new ReactorClientHttpConnector(HttpClient.create().followRedirect(true))).build(); + this.remoteFetcherService = remoteFetcherService; } @Override @@ -178,380 +157,340 @@ public class ReferenceServiceImpl implements ReferenceService { this.deleterFactory.deleter(ReferenceDeleter.class).deleteAndSaveByIds(List.of(id)); } -// public List searchReference(ReferenceType externalType, String query, String type) throws HugeResultSet, MyNotFoundException, InvalidApplicationException { -// ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query); -// -// List> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().get(externalType, externalUrlCriteria, type); -// -// List list = this.fetchFromDb(externalType, query, type, remoteRepos); -// -// list.addAll(remoteRepos.stream().map(FetcherReference::fromRemoteModel).toList()); -// list = list.stream().filter(x -> x.getName().toLowerCase().contains(query.toLowerCase())).collect(Collectors.toList()); -// list.sort(Comparator.comparing(FetcherReference::getName)); -// return list; -// } + @Override + public List searchReferenceData(ReferenceSearchLookup lookup) throws MyNotFoundException { + int initialOffset = 0; + if (lookup.getPage() != null && !lookup.getPage().isEmpty()){ + initialOffset = lookup.getPage().getOffset(); + lookup.getPage().setOffset(0); + } -// @Override -// public List searchReference(ReferenceSearchLookup lookup) throws HugeResultSetException, MyNotFoundException, InvalidApplicationException { -// int initialOffset = 0; -// if (lookup.getPage() != null && !lookup.getPage().isEmpty()){ -// initialOffset = lookup.getPage().getOffset(); -// lookup.getPage().setOffset(0); -// } -// -// ExternalReferenceCriteria externalReferenceCriteria = new ExternalReferenceCriteria(lookup.getLike()); -// -// List> remoteRepos = remoteFetcherService.getReferences(lookup.getType(), externalReferenceCriteria, lookup.getKey()); -// -// List externalModels = this.builderFactory.builder(ReferenceSearchBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(lookup.getProject(), remoteRepos); -// List models = this.fetchFromDb(lookup); -// -// models.addAll(externalModels); -// -// if (!this.conventionService.isNullOrEmpty(lookup.getLike())) { models = models.stream().filter(x -> x.getLabel().toLowerCase().contains(lookup.getLike().toLowerCase())).collect(Collectors.toList()); } -// models.sort(Comparator.comparing(Reference::getLabel)); -// -// if (lookup.getPage() != null && !lookup.getPage().isEmpty()){ -// models = models.stream().skip(initialOffset).limit(lookup.getPage().getSize()).toList(); -// } -// -// return models; -// } + ReferenceTypeEntity data = this.entityManager.find(ReferenceTypeEntity.class, lookup.getTypeId()); + if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{lookup.getTypeId(), ReferenceType.class.getSimpleName()}, LocaleContextHolder.getLocale())); + + ExternalReferenceCriteria externalReferenceCriteria = new ExternalReferenceCriteria(lookup.getLike()); - private List fetchFromDb(ReferenceSearchLookup lookup){ - ReferenceQuery query = lookup.enrich(this.queryFactory).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).sourceTypes(ReferenceSourceType.Internal); + ExternalDataResult remoteRepos = this.getReferenceData(data, externalReferenceCriteria, lookup.getKey()); + + List externalModels = new ArrayList<>(); + if (remoteRepos != null && this.conventionService.isListNullOrEmpty(remoteRepos.getResults())){ + List referenceEntities = new ArrayList<>(); + for (Map result : remoteRepos.getResults()){ + if (result == null || result.isEmpty()) continue;; + ReferenceEntity referenceEntity = buildReferenceEntityFromExternalData(result, data, remoteRepos); + referenceEntities.add(referenceEntity); + } + externalModels = this.builderFactory.builder(ReferenceBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(lookup.getProject(), referenceEntities); + } + + List models = this.fetchReferenceFromDb(lookup); + + for (Reference externalReference : externalModels){ + if (models.stream().noneMatch(x-> x.getReference() != null && x.getSource() != null &&x.getReference().equals(externalReference.getReference()) && x.getSource().equals(externalReference.getSource()))) models.add(externalReference); + } + + if (!this.conventionService.isNullOrEmpty(lookup.getLike())) { models = models.stream().filter(x -> x.getLabel().toLowerCase().contains(lookup.getLike().toLowerCase())).toList(); } + models.sort(Comparator.comparing(Reference::getLabel)); + + if (lookup.getPage() != null && !lookup.getPage().isEmpty()){ + models = models.stream().skip(initialOffset).limit(lookup.getPage().getSize()).toList(); + } + + return models; + } + + @NotNull + private ReferenceEntity buildReferenceEntityFromExternalData(Map result, ReferenceTypeEntity data, ExternalDataResult remoteRepos) { + ReferenceEntity referenceEntity = new ReferenceEntity(); //TODO new reference logic + referenceEntity.setTypeId(data.getId()); + referenceEntity.setIsActive(IsActive.Active); + referenceEntity.setReference(result.getOrDefault("key", null) + ":" + remoteRepos.getResults().getFirst().getOrDefault("pid", null)); + referenceEntity.setSource(result.getOrDefault("tag", null)); + referenceEntity.setAbbreviation(result.getOrDefault("abbreviation", null)); + referenceEntity.setDescription(result.getOrDefault("description", null)); + referenceEntity.setLabel(result.getOrDefault("name", null)); + referenceEntity.setSourceType(ReferenceSourceType.External); + DefinitionEntity definitionEntity = new DefinitionEntity(); + definitionEntity.setFields(new ArrayList<>()); + for (Map.Entry resultValue : result.entrySet()){ + FieldEntity fieldEntity = new FieldEntity(); + fieldEntity.setCode(resultValue.getKey()); + fieldEntity.setValue(resultValue.getValue()); + fieldEntity.setDataType(ReferenceFieldDataType.Text); + definitionEntity.getFields().add(fieldEntity); + } + referenceEntity.setDefinition(this.xmlHandlingService.toXmlSafe(definitionEntity)); + return referenceEntity; + } + + private List fetchReferenceFromDb(ReferenceSearchLookup lookup){ + ReferenceQuery query = lookup.enrich(this.queryFactory).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).sourceTypes(ReferenceSourceType.Internal).typeIds(lookup.getTypeId()); List data = query.collectAs(lookup.getProject()); return this.builderFactory.builder(ReferenceBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(lookup.getProject(), data); } -// private List fetchFromDb(ReferenceType externalType, String query, String type, List> remoteRepos) throws InvalidApplicationException { -// List list = new LinkedList<>(); -// switch (externalType) { -// case DataRepositories: -// case PubRepositories: -// case Journals: { -// DataRepositoryCriteria criteria = new DataRepositoryCriteria(); -// if (!query.isEmpty()) criteria.setLike(query); -// criteria.setCreationUserId(this.userScope.getUserId()); -// if (type.equals("")) { -// List dataRepositoryList = (this.apiContext.getOperationsContext().getDatabaseRepository().getDataRepositoryDao().getWithCriteria(criteria)).toList(); -// list = dataRepositoryList.stream().map(item -> new FetcherReference().fromDataRepository(item)).collect(Collectors.toList()); -// } -// } -// case Registries: { -// RegistryCriteria criteria = new RegistryCriteria(); -// if (!query.isEmpty()) criteria.setLike(query); -// criteria.setCreationUserId(this.userScope.getUserId()); -// if (type.equals("")) { -// List registryList = (this.apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao().getWithCriteria(criteria)).toList(); -// list = registryList.stream().map(item -> new FetcherReference().fromRegistry(item)).collect(Collectors.toList()); -// } -// } -// case Services: -// { -// ServiceCriteria criteria = new ServiceCriteria(); -// -// if (!query.isEmpty()) criteria.setLike(query); -// criteria.setCreationUserId(this.userScope.getUserId()); -// -// if (type.equals("")) { -// List serviceList = (this.apiContext.getOperationsContext().getDatabaseRepository().getServiceDao().getWithCriteria(criteria)).toList(); -// list = serviceList.stream().map(item -> new FetcherReference().fromService(item)).collect(Collectors.toList()); -// } -// } -// case Datasets:{ -// -// ExternalDatasetCriteria criteria = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ExternalDatasetCriteriaBuilder.class).like(query).build(); -// -// criteria.setCreationUserId(this.userScope.getUserId()); -// QueryableList items = apiContext.getOperationsContext().getDatabaseRepository().getExternalDatasetDao().getWithCriteria(criteria); -// -// list = items.select(item -> new FetcherReference().fromDataset(item)); -// } -// case Taxonomies: -// case Publications: -// case Licenses: -// break; -// } -// -// return list; -// } - - @Override - public List searchReferenceWithDefinition(ReferenceDefinitionSearchLookup lookup) throws HugeResultSetException, MyNotFoundException, InvalidApplicationException { - - ReferenceTypeQuery query = this.queryFactory.query(ReferenceTypeQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).ids(lookup.getReferenceTypeId()); - List datas = query.collectAs(lookup.getProject()); - if (datas.size() != 1 ){ - return null; + private ExternalDataResult getReferenceData(ReferenceTypeEntity referenceType, ExternalReferenceCriteria externalReferenceCriteria, String key) { + ReferenceTypeDefinitionEntity referenceTypeDefinition = this.xmlHandlingService.fromXmlSafe(ReferenceTypeDefinitionEntity.class, referenceType.getDefinition()); + if (referenceTypeDefinition == null || this.conventionService.isListNullOrEmpty(referenceTypeDefinition.getSources())) return new ExternalDataResult(); + + ExternalDataResult results = this.remoteFetcherService.getExternalData(referenceTypeDefinition.getSources().stream().map(x -> (SourceBaseConfiguration)x).toList(), externalReferenceCriteria, key, null); + for (Map result: results.getResults()) { + result.put("referenceType", referenceType.getName()); } - ReferenceTypeDefinitionEntity definition = this.xmlHandlingService.fromXmlSafe(ReferenceTypeDefinitionEntity.class, datas.get(0).getDefinition()); - List> remoteRepos = this.getAll(definition.getSources(), lookup); - - return null; - } - - private List> getAll ( List sources, ReferenceDefinitionSearchLookup lookup){ - List> results = new LinkedList<>(); - - if (sources == null || sources.isEmpty()) { - return results; - } - - sources.sort(Comparator.comparing(ReferenceTypeSourceBaseConfigurationEntity::getOrdinal)); - - List apiSources = sources.stream().filter(x-> ReferenceTypeSourceType.API.equals(x.getType())).map(x-> (ReferenceTypeSourceExternalApiConfigurationEntity)x).toList(); - apiSources.forEach(source -> { - try { - String auth = null; - if (source.getAuth()!= null) { - //auth = this.getAuthentication(source.getAuth()); - } - results.addAll(getAllApiResultsFromUrl(source.getUrl(), null, source.getResults(), source.getPaginationPath(), lookup, source.getLabel(), source.getKey(), source.getContentType(), source.getFirstPage(), source.getRequestBody(), source.getHttpMethod(), source.getFilterType(), source.getQueries(), auth)); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - } - }); - List staticSources = sources.stream().filter(x-> ReferenceTypeSourceType.STATIC.equals(x.getType())).map(x-> (ReferenceTypeSourceStaticOptionConfigurationEntity)x).toList(); - staticSources.forEach(source -> { - Map map = new HashMap<>(); - source.getOptions().forEach(option -> { - map.put(option.getCode(), option.getValue()); - map.put("tag", source.getLabel()); - map.put("key", source.getKey()); - }); - results.add(map); - }); - return results; } - private String getAuthentication(AuthenticationConfigurationEntity authenticationConfiguration) { - HttpMethod method = HttpMethod.valueOf(authenticationConfiguration.getAuthMethod().name()); - Map response = this.client.method(method).uri(authenticationConfiguration.getAuthUrl()) - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(this.parseBodyString(authenticationConfiguration.getAuthRequestBody())) - .exchangeToMono(mono -> mono.bodyToMono(new ParameterizedTypeReference>() { - })).block(); +// private List> getAll ( List sources, ReferenceDefinitionSearchLookup lookup){ +// List> results = new LinkedList<>(); +// +// if (sources == null || sources.isEmpty()) { +// return results; +// } +// +// sources.sort(Comparator.comparing(ReferenceTypeSourceBaseConfigurationEntity::getOrdinal)); +// +// List apiSources = sources.stream().filter(x-> ReferenceTypeSourceType.API.equals(x.getType())).map(x-> (ReferenceTypeSourceExternalApiConfigurationEntity)x).toList(); +// apiSources.forEach(source -> { +// try { +// String auth = null; +// if (source.getAuth()!= null) { +// //auth = this.getAuthentication(source.getAuth()); +// } +// results.addAll(getAllApiResultsFromUrl(source.getUrl(), null, source.getResults(), source.getPaginationPath(), lookup, source.getLabel(), source.getKey(), source.getContentType(), source.getFirstPage(), source.getRequestBody(), source.getHttpMethod(), source.getFilterType(), source.getQueries(), auth)); +// } catch (Exception e) { +// logger.error(e.getLocalizedMessage(), e); +// } +// }); +// List staticSources = sources.stream().filter(x-> ReferenceTypeSourceType.STATIC.equals(x.getType())).map(x-> (ReferenceTypeSourceStaticOptionConfigurationEntity)x).toList(); +// staticSources.forEach(source -> { +// Map map = new HashMap<>(); +// source.getOptions().forEach(option -> { +// map.put(option.getCode(), option.getValue()); +// map.put("tag", source.getLabel()); +// map.put("key", source.getKey()); +// }); +// results.add(map); +// }); +// +// return results; +// } + +// private String getAuthentication(AuthenticationConfigurationEntity authenticationConfiguration) { +// HttpMethod method = HttpMethod.valueOf(authenticationConfiguration.getAuthMethod().name()); +// Map response = this.client.method(method).uri(authenticationConfiguration.getAuthUrl()) +// .contentType(MediaType.APPLICATION_JSON) +// .bodyValue(this.parseBodyString(authenticationConfiguration.getAuthRequestBody())) +// .exchangeToMono(mono -> mono.bodyToMono(new ParameterizedTypeReference>() { +// })).block(); +// +// +// +// return authenticationConfiguration.getType() + " " + response.get(authenticationConfiguration.getAuthTokenPath()); +// } + +// private String parseBodyString(String bodyString) { +// String finalBodyString = bodyString; +// if (bodyString.contains("{env:")) { +// int index = bodyString.indexOf("{env: "); +// while (index >= 0) { +// int endIndex = bodyString.indexOf("}", index + 6); +// String envName = bodyString.substring(index + 6, endIndex); +// finalBodyString = finalBodyString.replace("{env: " + envName + "}", System.getenv(envName)); +// index = bodyString.indexOf("{env: ", index + 6); +// } +// } +// return finalBodyString; +// } + +// private List> getAllApiResultsFromUrl(String urlPath, FetchStrategy fetchStrategy, final ResultsConfigurationEntity resultsEntity, final String jsonPaginationPath, ReferenceDefinitionSearchLookup lookup, String label, String key, String contentType, String firstPage, String requestBody, ReferenceTypeExternalApiHTTPMethodType requestType, String filterType, List queries, String auth) throws Exception { +// Set pages = new HashSet<>(); +// +// String replacedUrlPath = replaceLookupFields(urlPath, lookup, firstPage, queries); +// String replacedUrlBody = replaceLookupFields(requestBody, lookup, firstPage, queries); +// +// ExternalDataResult externalRefernceResult = getResultsFromUrl(replacedUrlPath, resultsEntity, jsonPaginationPath, contentType, replacedUrlBody, requestType, auth); +// if(externalRefernceResult != null) { +// if (filterType != null && filterType.equals("local") && (lookup.getLike() != null && !lookup.getLike().isEmpty())) { +// externalRefernceResult.setResults(externalRefernceResult.getResults().stream() +// .filter(r -> r.get("name").toLowerCase().contains(lookup.getLike().toLowerCase())) +// .collect(Collectors.toList())); +// } +// if (fetchStrategy == FetchStrategy.FIRST) +// return externalRefernceResult.getResults().stream().peek(x -> x.put("tag", label)).peek(x -> x.put("key", key)).collect(Collectors.toList()); +// +// //Long maxResults = configLoader.getExternalUrls().getMaxresults(); +// Long maxResults = Long.valueOf(1000); +// if (externalRefernceResult.getResults().size() > maxResults) +// throw new HugeResultSetException("The submitted search query " + lookup.getLike() + " is about to return " + externalRefernceResult.getResults().size() + " results... Please submit a more detailed search query"); +// +// Optional optionalResults = pages.parallelStream() +// .map(page -> getResultsFromUrl(urlPath + "&page=" + page, resultsEntity, jsonPaginationPath, contentType, replacedUrlBody, requestType, auth)) +// .filter(Objects::nonNull) +// .reduce((result1, result2) -> { +// result1.getResults().addAll(result2.getResults()); +// return result1; +// }); +// ExternalDataResult remainingExternalDataResult = optionalResults.orElseGet(ExternalDataResult::new); +// remainingExternalDataResult.getResults().addAll(externalRefernceResult.getResults()); +// +// return remainingExternalDataResult.getResults().stream().peek(x -> x.put("tag", label)).peek(x -> x.put("key", key)).collect(Collectors.toList()); +// } +// else { +// return new LinkedList<>(); +// } +// } + +// private String replaceLookupFields(String urlPath, ReferenceDefinitionSearchLookup lookup, String firstPage, List queries){ +// String completedPath = urlPath; +// +// if (urlPath.contains("openaire") || urlPath.contains("orcid") ){ +// if (lookup.getLike() != null) { +// completedPath = completedPath.replace("{like}", lookup.getLike()); +// } else { +// completedPath = completedPath.replace("{like}", "*"); +// } +// } +// +// if (urlPath.contains("{like}")){ +// if (lookup.getLike() != null) { +// completedPath = completedPath.replace("{like}", lookup.getLike()); +// } else { +// completedPath = completedPath.replace("{like}", ""); +// } +// } +// +// if (urlPath.contains("{page}")) { +// if (lookup.getPage() != null && lookup.getPage().getOffset() > 0) { +// completedPath = completedPath.replace("{page}", String.valueOf(lookup.getPage().getOffset())); +// } else if (firstPage != null) { +// completedPath = completedPath.replace("{page}", firstPage); +// } else { +// completedPath = completedPath.replace("{page}", "1"); +// } +// } +// +// if (urlPath.contains("{pageSize}")){ +// if (lookup.getPage() != null && lookup.getPage().getSize() > 0) { +// completedPath = completedPath.replace("{pageSize}", String.valueOf(lookup.getPage().getSize())); +// } else { +// completedPath = completedPath.replace("{pageSize}", "100"); +// } +// } +// +// +// return completedPath; +// } + +// protected ExternalDataResult getResultsFromUrl(String urlString, ResultsConfigurationEntity resultsEntity, String jsonPaginationPath, String contentType, String requestBody, ReferenceTypeExternalApiHTTPMethodType httpMethod, String auth) { +// +// try { +// ResponseEntity response; +// JsonNode jsonBody = new ObjectMapper().readTree(requestBody); +// +// response = this.client.method(HttpMethod.valueOf(httpMethod.name())).uri(urlString).headers(httpHeaders -> { +// if (contentType != null && !contentType.isEmpty()) { +// httpHeaders.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); +// httpHeaders.setContentType(MediaType.valueOf(contentType)); +// } +// if (auth != null) { +// httpHeaders.set("Authorization", auth); +// } +// }).bodyValue(jsonBody).retrieve().toEntity(String.class).block(); +// if (response.getStatusCode() == HttpStatus.OK) { // success +// ExternalDataResult externalDataResult = new ExternalDataResult(); +// if (response.getHeaders().get("Content-Type").get(0).contains("json")) { +// DocumentContext jsonContext = JsonPath.parse(response.getBody()); +// externalDataResult = this.getFromJson(jsonContext, resultsEntity); +// } +// +// return externalDataResult; +// } +// } catch (Exception exception) { +// logger.error(exception.getMessage(), exception); +// } +// +// return null; +// } - - return authenticationConfiguration.getType() + " " + response.get(authenticationConfiguration.getAuthTokenPath()); - } - - private String parseBodyString(String bodyString) { - String finalBodyString = bodyString; - if (bodyString.contains("{env:")) { - int index = bodyString.indexOf("{env: "); - while (index >= 0) { - int endIndex = bodyString.indexOf("}", index + 6); - String envName = bodyString.substring(index + 6, endIndex); - finalBodyString = finalBodyString.replace("{env: " + envName + "}", System.getenv(envName)); - index = bodyString.indexOf("{env: ", index + 6); - } - } - return finalBodyString; - } - - private List> getAllApiResultsFromUrl(String urlPath, FetchStrategy fetchStrategy, final ResultsConfigurationEntity resultsEntity, final String jsonPaginationPath, ReferenceDefinitionSearchLookup lookup, String label, String key, String contentType, String firstPage, String requestBody, ReferenceTypeExternalApiHTTPMethodType requestType, String filterType, List queries, String auth) throws Exception { - Set pages = new HashSet<>(); - - String replacedUrlPath = replaceLookupFields(urlPath, lookup, firstPage, queries); - String replacedUrlBody = replaceLookupFields(requestBody, lookup, firstPage, queries); - - ExternalRefernceResult externalRefernceResult = getResultsFromUrl(replacedUrlPath, resultsEntity, jsonPaginationPath, contentType, replacedUrlBody, requestType, auth); - if(externalRefernceResult != null) { - if (filterType != null && filterType.equals("local") && (lookup.getLike() != null && !lookup.getLike().isEmpty())) { - externalRefernceResult.setResults(externalRefernceResult.getResults().stream() - .filter(r -> r.get("name").toLowerCase().contains(lookup.getLike().toLowerCase())) - .collect(Collectors.toList())); - } - if (fetchStrategy == FetchStrategy.FIRST) - return externalRefernceResult.getResults().stream().peek(x -> x.put("tag", label)).peek(x -> x.put("key", key)).collect(Collectors.toList()); - - if (externalRefernceResult.getPagination() != null && externalRefernceResult.getPagination().get("pages") != null) //if has more pages, add them to the pages set - for (int i = 2; i <= externalRefernceResult.getPagination().get("pages"); i++) - pages.add(i); - - //Long maxResults = configLoader.getExternalUrls().getMaxresults(); - Long maxResults = Long.valueOf(1000); - if ((maxResults > 0) && (externalRefernceResult.getPagination().get("count") > maxResults)) - throw new HugeResultSetException("The submitted search query " + lookup.getLike() + " is about to return " + externalRefernceResult.getPagination().get("count") + " results... Please submit a more detailed search query"); - - Optional optionalResults = pages.parallelStream() - .map(page -> getResultsFromUrl(urlPath + "&page=" + page, resultsEntity, jsonPaginationPath, contentType, replacedUrlBody, requestType, auth)) - .filter(Objects::nonNull) - .reduce((result1, result2) -> { - result1.getResults().addAll(result2.getResults()); - return result1; - }); - ExternalRefernceResult remainingExternalRefernceResult = optionalResults.orElseGet(ExternalRefernceResult::new); - remainingExternalRefernceResult.getResults().addAll(externalRefernceResult.getResults()); - - return remainingExternalRefernceResult.getResults().stream().peek(x -> x.put("tag", label)).peek(x -> x.put("key", key)).collect(Collectors.toList()); - } - else { - return new LinkedList<>(); - } - } - - private String replaceLookupFields(String urlPath, ReferenceDefinitionSearchLookup lookup, String firstPage, List queries){ - String completedPath = urlPath; - - if (urlPath.contains("openaire") || urlPath.contains("orcid") ){ - if (lookup.getLike() != null) { - completedPath = completedPath.replace("{like}", lookup.getLike()); - } else { - completedPath = completedPath.replace("{like}", "*"); - } - } - - if (urlPath.contains("{like}")){ - if (lookup.getLike() != null) { - completedPath = completedPath.replace("{like}", lookup.getLike()); - } else { - completedPath = completedPath.replace("{like}", ""); - } - } - - if (urlPath.contains("{page}")) { - if (lookup.getPage() != null && lookup.getPage().getOffset() > 0) { - completedPath = completedPath.replace("{page}", String.valueOf(lookup.getPage().getOffset())); - } else if (firstPage != null) { - completedPath = completedPath.replace("{page}", firstPage); - } else { - completedPath = completedPath.replace("{page}", "1"); - } - } - - if (urlPath.contains("{pageSize}")){ - if (lookup.getPage() != null && lookup.getPage().getSize() > 0) { - completedPath = completedPath.replace("{pageSize}", String.valueOf(lookup.getPage().getSize())); - } else { - completedPath = completedPath.replace("{pageSize}", "100"); - } - } +// public static ExternalDataResult getFromJson(DocumentContext jsonContext, ResultsConfigurationEntity resultsEntity) { +// return new ExternalDataResult(parseData(jsonContext, resultsEntity)); +// } - return completedPath; - } - - protected ExternalRefernceResult getResultsFromUrl(String urlString, ResultsConfigurationEntity resultsEntity, String jsonPaginationPath, String contentType, String requestBody, ReferenceTypeExternalApiHTTPMethodType httpMethod, String auth) { - - try { - ResponseEntity response; - JsonNode jsonBody = new ObjectMapper().readTree(requestBody); - - response = this.client.method(HttpMethod.valueOf(httpMethod.name())).uri(urlString).headers(httpHeaders -> { - if (contentType != null && !contentType.isEmpty()) { - httpHeaders.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); - httpHeaders.setContentType(MediaType.valueOf(contentType)); - } - if (auth != null) { - httpHeaders.set("Authorization", auth); - } - }).bodyValue(jsonBody).retrieve().toEntity(String.class).block(); - if (response.getStatusCode() == HttpStatus.OK) { // success - ExternalRefernceResult externalRefernceResult = new ExternalRefernceResult(); - if (response.getHeaders().get("Content-Type").get(0).contains("json")) { - DocumentContext jsonContext = JsonPath.parse(response.getBody()); - externalRefernceResult = this.getFromJson(jsonContext, resultsEntity); - } - - - if (externalRefernceResult.getPagination().size() == 0) { - externalRefernceResult.getPagination().put("pages", 1); - externalRefernceResult.getPagination().put("count", externalRefernceResult.getResults().size()); - } - return externalRefernceResult; - } - } catch (Exception exception) { - logger.error(exception.getMessage(), exception); - } - - return null; - } - - - public static ExternalRefernceResult getFromJson(DocumentContext jsonContext, ResultsConfigurationEntity resultsEntity) { - return new ExternalRefernceResult(parseData(jsonContext, resultsEntity), - new HashMap<>(1, 1)); - } - - - private static List> parseData (DocumentContext jsonContext, ResultsConfigurationEntity resultsEntity) { - List > rawData = jsonContext.read(resultsEntity.getResultsArrayPath()); - List> parsedData = new ArrayList<>(); - - for (Map stringObjectMap: rawData){ - Map map = new HashMap<>(); - for(ResultFieldsMappingConfigurationEntity field: resultsEntity.getFieldsMapping()){ - String pathValue = field.getResponsePath(); - if (!pathValue.contains(".")){ - if (stringObjectMap.containsKey(pathValue)) { - //map.put(field.getCode(), stringObjectMap.get(pathValue)); - map.put(field.getCode(), normalizeValue(stringObjectMap.get(pathValue))); - } - }else { - if (stringObjectMap.containsKey(pathValue.split("\\.")[0])){ - String value = null; - Object fieldObj = stringObjectMap.get(pathValue.split("\\.")[0]); - if (fieldObj != null){ - if (fieldObj instanceof Map){ - Object o = ((Map) fieldObj).get(pathValue.split("\\.")[1]); - if(o instanceof String){ - value = (String)o; - } - else if(o instanceof Integer){ - value = String.valueOf(o); - } - } else if (fieldObj instanceof List) { - Object o = ((List>) fieldObj).get(0).get(pathValue.split("\\.")[1]); - if(o instanceof String){ - value = (String)o; - } - else if(o instanceof Integer){ - value = String.valueOf(o); - } - } - } - if (value != null){ - map.put(field.getCode(), value); - } - } - } - } - parsedData.add(map); - } - return parsedData; - } - - - private static String normalizeValue(Object value) { - if (value instanceof JSONArray) { - JSONArray jarr = (JSONArray) value; - if (jarr.get(0) instanceof String) { - return jarr.get(0).toString(); - } else { - for (Object o : jarr) { - if ((o instanceof Map) && ((Map) o).containsKey("content")) { - try { - return ((Map) o).get("content"); - } - catch (ClassCastException e){ - if(((Map) o).get("content") instanceof Integer) { - return String.valueOf(((Map) o).get("content")); - } - return null; - } - } - } - } - } else if (value instanceof Map) { - String key = ((Map)value).containsKey("$") ? "$" : "content"; - return ((Map)value).get(key); - } - return value != null ? value.toString() : null; - } +// private static List> parseData (DocumentContext jsonContext, ResultsConfigurationEntity resultsEntity) { +// List > rawData = jsonContext.read(resultsEntity.getResultsArrayPath()); +// List> parsedData = new ArrayList<>(); +// +// for (Map stringObjectMap: rawData){ +// Map map = new HashMap<>(); +// for(ResultFieldsMappingConfigurationEntity field: resultsEntity.getFieldsMapping()){ +// String pathValue = field.getResponsePath(); +// if (!pathValue.contains(".")){ +// if (stringObjectMap.containsKey(pathValue)) { +// //map.put(field.getCode(), stringObjectMap.get(pathValue)); +// map.put(field.getCode(), normalizeValue(stringObjectMap.get(pathValue))); +// } +// }else { +// if (stringObjectMap.containsKey(pathValue.split("\\.")[0])){ +// String value = null; +// Object fieldObj = stringObjectMap.get(pathValue.split("\\.")[0]); +// if (fieldObj != null){ +// if (fieldObj instanceof Map){ +// Object o = ((Map) fieldObj).get(pathValue.split("\\.")[1]); +// if(o instanceof String){ +// value = (String)o; +// } +// else if(o instanceof Integer){ +// value = String.valueOf(o); +// } +// } else if (fieldObj instanceof List) { +// Object o = ((List>) fieldObj).get(0).get(pathValue.split("\\.")[1]); +// if(o instanceof String){ +// value = (String)o; +// } +// else if(o instanceof Integer){ +// value = String.valueOf(o); +// } +// } +// } +// if (value != null){ +// map.put(field.getCode(), value); +// } +// } +// } +// } +// parsedData.add(map); +// } +// return parsedData; +// } +// +// +// private static String normalizeValue(Object value) { +// if (value instanceof JSONArray) { +// JSONArray jarr = (JSONArray) value; +// if (jarr.get(0) instanceof String) { +// return jarr.get(0).toString(); +// } else { +// for (Object o : jarr) { +// if ((o instanceof Map) && ((Map) o).containsKey("content")) { +// try { +// return ((Map) o).get("content"); +// } +// catch (ClassCastException e){ +// if(((Map) o).get("content") instanceof Integer) { +// return String.valueOf(((Map) o).get("content")); +// } +// return null; +// } +// } +// } +// } +// } else if (value instanceof Map) { +// String key = ((Map)value).containsKey("$") ? "$" : "content"; +// return ((Map)value).get(key); +// } +// return value != null ? value.toString() : null; +// } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/referencetype/ReferenceTypeServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/referencetype/ReferenceTypeServiceImpl.java index adcdbefa0..f10296d6d 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/referencetype/ReferenceTypeServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/referencetype/ReferenceTypeServiceImpl.java @@ -18,7 +18,6 @@ import eu.eudat.service.dmpblueprint.DmpBlueprintServiceImpl; import gr.cite.commons.web.authz.service.AuthorizationService; import gr.cite.tools.data.builder.BuilderFactory; import gr.cite.tools.data.deleter.DeleterFactory; -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; diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherService.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherService.java index 4e9164c82..c5aae3ef1 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherService.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherService.java @@ -1,21 +1,14 @@ -//package eu.eudat.service.remotefetcher; -// -//import eu.eudat.commons.exceptions.HugeResultSetException; -//import eu.eudat.service.remotefetcher.config.entities.GenericUrls; -//import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; -//import gr.cite.tools.exception.MyNotFoundException; -// -//import java.util.List; -//import java.util.Map; -// -//public interface RemoteFetcherService { -// List> getReferences(ReferenceType referenceType, ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException; -// -// GenericUrls getExternalUrls(ReferenceType referenceType); -// -// Integer countEntries(ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException; -// -// List> getExternalGeneric(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls); -// -// List> getExternalGenericWithData(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls); -//} +package eu.eudat.service.remotefetcher; + +import eu.eudat.data.ReferenceTypeEntity; +import eu.eudat.service.remotefetcher.config.entities.SourceBaseConfiguration; +import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; +import eu.eudat.service.remotefetcher.criteria.FetchStrategy; +import eu.eudat.service.remotefetcher.models.ExternalDataResult; + +import java.util.List; + +public interface RemoteFetcherService { + ExternalDataResult getExternalData(List sources, ExternalReferenceCriteria externalReferenceCriteria, String key, FetchStrategy fetchStrategy); + Integer countExternalData(List sources, ExternalReferenceCriteria externalReferenceCriteria, String key); +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherServiceImpl.java index bd270a2af..ec47510c7 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherServiceImpl.java @@ -1,533 +1,388 @@ -//package eu.eudat.service.remotefetcher; -// -//import com.fasterxml.jackson.core.type.TypeReference; -//import com.fasterxml.jackson.databind.JsonNode; -//import com.fasterxml.jackson.databind.ObjectMapper; -//import com.jayway.jsonpath.DocumentContext; -//import com.jayway.jsonpath.JsonPath; -//import eu.eudat.commons.exceptions.HugeResultSetException; -//import eu.eudat.service.remotefetcher.config.AuthenticationConfiguration; -//import eu.eudat.service.remotefetcher.config.DataUrlConfiguration; -//import eu.eudat.service.remotefetcher.config.QueryConfig; -//import eu.eudat.service.remotefetcher.config.UrlConfiguration; -//import eu.eudat.service.remotefetcher.config.entities.GenericUrls; -//import eu.eudat.service.remotefetcher.models.ExternalRefernceResult; -//import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; -//import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -//import gr.cite.tools.exception.MyNotFoundException; -//import jakarta.xml.bind.JAXBContext; -//import jakarta.xml.bind.Unmarshaller; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.core.ParameterizedTypeReference; -//import org.springframework.http.*; -//import org.springframework.http.client.reactive.ReactorClientHttpConnector; -//import org.springframework.http.codec.json.Jackson2JsonDecoder; -//import org.springframework.stereotype.Service; -//import org.springframework.web.client.RestTemplate; -//import org.springframework.web.reactive.function.client.WebClient; -//import reactor.netty.http.client.HttpClient; -// -//import java.io.File; -//import java.io.StringReader; -//import java.lang.reflect.Method; -//import java.nio.file.Paths; -//import java.util.*; -//import java.util.stream.Collectors; -// -//@Service -//public class RemoteFetcherServiceImpl implements RemoteFetcherService { -// private static final Logger logger = LoggerFactory.getLogger(RemoteFetcherServiceImpl.class); -// -// private WebClient webClient; -// private final ExternalUrlConfigProvider externalUrlConfigProvider; -// @Autowired -// public RemoteFetcherServiceImpl(ExternalUrlConfigProvider externalUrlConfigProvider) { -// this.externalUrlConfigProvider = externalUrlConfigProvider; -// } -// -// private WebClient getWebClient(){ -// if (this.webClient == null) { -// this.webClient = WebClient.builder().codecs(clientCodecConfigurer -> { -// clientCodecConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(new ObjectMapper(), MediaType.APPLICATION_JSON)); -// clientCodecConfigurer.defaultCodecs().maxInMemorySize(2 * ((int) Math.pow(1024, 3))); //GK: Why here??? -// } -// ).clientConnector(new ReactorClientHttpConnector(HttpClient.create().followRedirect(true))).build(); -// } -// return webClient; -// } -// -// @Override -// public List> getReferences(ReferenceType referenceType, ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException { -// FetchStrategy fetchStrategy = null; -// -//// GenericUrls exGenericUrls = this.getExternalUrls(referenceType); -// List urlConfigs = key != null && !key.isEmpty() ? exGenericUrls.getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) -// : exGenericUrls.getUrls(); -// -// List> results = getAll(urlConfigs, fetchStrategy, externalReferenceCriteria); -// for (Map result: results) { -// result.put("referenceType", referenceType.name()); -// } -// return results; -// } -// -// @Override -// public GenericUrls getExternalUrls(ReferenceType referenceType) { -// return switch (referenceType) { -// case Taxonomies -> this.externalUrlConfigProvider.getExternalUrls().getTaxonomies(); -// case Licenses -> this.externalUrlConfigProvider.getExternalUrls().getLicenses(); -// case Publications -> this.externalUrlConfigProvider.getExternalUrls().getPublications(); -// case Journals -> this.externalUrlConfigProvider.getExternalUrls().getJournals(); -// case PubRepositories -> this.externalUrlConfigProvider.getExternalUrls().getPubRepositories(); -// case DataRepositories -> this.externalUrlConfigProvider.getExternalUrls().getRepositories(); -// case Registries -> this.externalUrlConfigProvider.getExternalUrls().getRegistries(); -// case Services -> this.externalUrlConfigProvider.getExternalUrls().getServices(); -// case Grants -> this.externalUrlConfigProvider.getExternalUrls().getGrants(); -// case Organizations -> this.externalUrlConfigProvider.getExternalUrls().getOrganisations(); -// case Datasets -> this.externalUrlConfigProvider.getExternalUrls().getDatasets(); -// case Funder -> this.externalUrlConfigProvider.getExternalUrls().getFunders(); -// case Project -> this.externalUrlConfigProvider.getExternalUrls().getProjects(); -// case Researcher -> this.externalUrlConfigProvider.getExternalUrls().getResearchers(); -// default -> throw new IllegalArgumentException("Type not found" + referenceType); -// }; -// } -// -// @Override -// public Integer countEntries(ExternalReferenceCriteria externalReferenceCriteria, String key) throws MyNotFoundException, HugeResultSetException { -// List urlConfigs = -// key != null && !key.isEmpty() ? this.externalUrlConfigProvider.getExternalUrls().getValidations().getUrls().stream().filter(item -> item.getKey().equals(key)).collect(Collectors.toList()) -// : this.externalUrlConfigProvider.getExternalUrls().getValidations().getUrls(); -// FetchStrategy fetchStrategy = this.externalUrlConfigProvider.getExternalUrls().getValidations().getFetchMode(); -// List> data = this.getAll(urlConfigs, fetchStrategy, externalReferenceCriteria); -// return data.size(); -// } -// -// @Override -// public List> getExternalGeneric(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls) { -// List urlConfigurations = genericUrls.getUrls(); -// FetchStrategy fetchStrategy = genericUrls.getFetchMode(); -// return getAll(urlConfigurations, fetchStrategy, externalReferenceCriteria); -// } -// -// @Override -// public List> getExternalGenericWithData(ExternalReferenceCriteria externalReferenceCriteria, GenericUrls genericUrls) { -// List urlConfigurations = genericUrls.getUrls(); -// return getAllWithData(urlConfigurations, externalReferenceCriteria); -// } -// -// private List> getAll(List urlConfigs, FetchStrategy fetchStrategy, ExternalReferenceCriteria externalReferenceCriteria) { -// -// List> results = new LinkedList<>(); -// -// if (urlConfigs == null || urlConfigs.isEmpty()) { -// return results; -// } -//// throw new MyNotFoundException("No Repository urls found in configuration"); -// -// urlConfigs.sort(Comparator.comparing(UrlConfiguration::getOrdinal)); -// for (UrlConfiguration urlConfiguration : urlConfigs) { -// applyFunderQuery(urlConfiguration, externalReferenceCriteria); -// if (urlConfiguration.getType() == null || urlConfiguration.getType().equals("External")) { -// try { -// String auth = null; -// if (urlConfiguration.getAuth() != null) { -// auth = this.getAuthentication(urlConfiguration.getAuth()); -// } -// results.addAll(getAllResultsFromUrl(urlConfiguration.getUrl(), fetchStrategy, urlConfiguration.getData(), urlConfiguration.getPaginationPath(), externalReferenceCriteria, urlConfiguration.getLabel(), urlConfiguration.getKey(), urlConfiguration.getContentType(), urlConfiguration.getFirstpage(), urlConfiguration.getRequestBody(), urlConfiguration.getRequestType(), urlConfiguration.getFilterType(), urlConfiguration.getQueries(), auth)); -// } catch (Exception e) { -// logger.error(e.getLocalizedMessage(), e); -// } -// } else if (urlConfiguration.getType() != null && urlConfiguration.getType().equals("Internal")) { -// results.addAll(getAllResultsFromMockUpJson(urlConfiguration.getUrl(), externalReferenceCriteria.getLike())); +package eu.eudat.service.remotefetcher; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.JsonPath; +import eu.eudat.commons.XmlHandlingService; +import eu.eudat.commons.enums.ReferenceTypeSourceType; +import eu.eudat.commons.exceptions.HugeResultSetException; +import eu.eudat.convention.ConventionService; +import eu.eudat.service.remotefetcher.config.entities.*; +import eu.eudat.service.remotefetcher.models.ExternalDataResult; +import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; +import eu.eudat.service.remotefetcher.criteria.FetchStrategy; +import gr.cite.tools.exception.MyApplicationException; +import net.minidev.json.JSONArray; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.*; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.http.codec.json.Jackson2JsonDecoder; +import org.springframework.stereotype.Service; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.netty.http.client.HttpClient; + +import java.io.File; +import java.nio.file.Paths; +import java.util.*; +import java.util.stream.Collectors; + +@Service +public class RemoteFetcherServiceImpl implements RemoteFetcherService { + private static final Logger logger = LoggerFactory.getLogger(RemoteFetcherServiceImpl.class); + + private WebClient webClient; + private final ExternalUrlConfigProvider externalUrlConfigProvider; + private final ConventionService conventionService; + private final XmlHandlingService xmlHandlingService; + @Autowired + public RemoteFetcherServiceImpl(ExternalUrlConfigProvider externalUrlConfigProvider, ConventionService conventionService, XmlHandlingService xmlHandlingService) { + this.externalUrlConfigProvider = externalUrlConfigProvider; + this.conventionService = conventionService; + this.xmlHandlingService = xmlHandlingService; + } + + private WebClient getWebClient(){ + if (this.webClient == null) { + this.webClient = WebClient.builder().codecs(clientCodecConfigurer -> { + clientCodecConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(new ObjectMapper(), MediaType.APPLICATION_JSON)); + clientCodecConfigurer.defaultCodecs().maxInMemorySize(2 * ((int) Math.pow(1024, 3))); //GK: Why here??? + } + ).clientConnector(new ReactorClientHttpConnector(HttpClient.create().followRedirect(true))).build(); + } + return webClient; + } + + + + @Override + public ExternalDataResult getExternalData(List sources, ExternalReferenceCriteria externalReferenceCriteria, String key, FetchStrategy fetchStrategy) { + List apiSourcesToUse = sources.stream().map(x -> (SourceBaseConfiguration)x).toList(); + if (!this.conventionService.isNullOrEmpty(key)){ + apiSourcesToUse = sources.stream().filter(x-> x.getKey().equals(key)).map(x -> (SourceBaseConfiguration)x).toList(); + } + if (this.conventionService.isListNullOrEmpty(apiSourcesToUse)) return new ExternalDataResult(); + + apiSourcesToUse.sort(Comparator.comparing(SourceBaseConfiguration::getOrdinal)); + + return this.queryExternalData(sources, fetchStrategy, externalReferenceCriteria); + } + + @Override + public Integer countExternalData(List sources, ExternalReferenceCriteria externalReferenceCriteria, String key) { + return getExternalData(sources, externalReferenceCriteria, key, null).getResults().size(); + } + + private ExternalDataResult queryExternalData(List sources, FetchStrategy fetchStrategy, ExternalReferenceCriteria externalReferenceCriteria) { + + ExternalDataResult results = new ExternalDataResult(); + + if (this.conventionService.isListNullOrEmpty(sources)) return new ExternalDataResult(); + + for (SourceBaseConfiguration source : sources) { + if (source.getType() == null || source.getType().equals(ReferenceTypeSourceType.API)) { + try { + SourceExternalApiConfiguration, AuthenticationConfiguration, QueryConfig> apiSource = (SourceExternalApiConfiguration)source; + this.applyFunderToQuery(apiSource, externalReferenceCriteria); + + String auth = null; + if (apiSource.getAuth() != null) { + auth = this.buildAuthentication(apiSource.getAuth()); + } + results.addAll(this.queryExternalData(fetchStrategy, apiSource, externalReferenceCriteria, auth)); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + } else if (source.getType() != null && source.getType().equals(ReferenceTypeSourceType.STATIC)) { + SourceStaticOptionConfiguration staticSource = (SourceStaticOptionConfiguration)source; + results.addAll(getAllResultsFromMockUpJson(staticSource.getKey(), externalReferenceCriteria.getLike())); //TODO: + } + } + return results; + } + + private String buildAuthentication(AuthenticationConfiguration authenticationConfiguration) { + HttpMethod method; + switch (authenticationConfiguration.getAuthMethod()) { + case GET -> method = HttpMethod.GET; + case POST -> method =HttpMethod.POST; + default -> throw new MyApplicationException("unrecognized type " + authenticationConfiguration.getAuthMethod()); + } + + Map response = this.getWebClient().method(method).uri(authenticationConfiguration.getAuthUrl()) + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(this.parseBodyString(authenticationConfiguration.getAuthRequestBody())) + .exchangeToMono(mono -> mono.bodyToMono(new ParameterizedTypeReference>() { + })).block(); + if (response == null) throw new MyApplicationException("Authentication " + authenticationConfiguration.getAuthUrl() + " failed"); + + return authenticationConfiguration.getType() + " " + response.getOrDefault(authenticationConfiguration.getAuthTokenPath(), null); + } + + + private void applyFunderToQuery(SourceExternalApiConfiguration, AuthenticationConfiguration, QueryConfig> apiSource, ExternalReferenceCriteria externalReferenceCriteria) { + //TODO new reference logic +// if (apiSource.getFunderQuery() != null) { +// if (externalReferenceCriteria.getFunderId() != null && !apiSource.getFunderQuery().startsWith("dmp:")) { +// apiSource.setUrl(apiSource.getUrl().replace("{funderQuery}", apiSource.getFunderQuery())); +// } +// else { +// apiSource.setUrl(apiSource.getUrl().replace("{funderQuery}", "")); // } // } -// /* for (UrlConfiguration urlConfig : urlConfigs) { -// ifFunderQueryExist(urlConfig, externalUrlCriteria); -// if (urlConfig.getType() == null || urlConfig.getType().equals("External")) { -// results.addAll(getAllResultsFromUrl(urlConfig.getUrl(), fetchStrategy, urlConfig.getData(), urlConfig.getPaginationPath(), externalUrlCriteria, urlConfig.getLabel(), urlConfig.getKey(), urlConfig.getContentType(), urlConfig.getFirstpage(), urlConfig.getRequestBody(), urlConfig.getRequestType())); -// } else if (urlConfig.getType() != null && urlConfig.getType().equals("Internal")) { -// results.addAll(getAllResultsFromMockUpJson(urlConfig.getUrl(), externalUrlCriteria.getLike())); -// } -// }*/ -// return results; -// } -// -// private String getAuthentication(AuthenticationConfiguration authenticationConfiguration) { -// HttpMethod method = HttpMethod.valueOf(authenticationConfiguration.getAuthMethod()); -// Map response = this.getWebClient().method(method).uri(authenticationConfiguration.getAuthUrl()) -// .contentType(MediaType.APPLICATION_JSON) -// .bodyValue(this.parseBodyString(authenticationConfiguration.getAuthRequestBody())) -// .exchangeToMono(mono -> mono.bodyToMono(new ParameterizedTypeReference>() { -// })).block(); -// -// -// -// return authenticationConfiguration.getType() + " " + response.get(authenticationConfiguration.getAuthTokenPath()); -// } -// -// private List> getAllWithData(List urlConfigs, ExternalReferenceCriteria externalReferenceCriteria) { -// -// List> results = new LinkedList<>(); -// -// if (urlConfigs == null || urlConfigs.isEmpty()) { -// return results; -// } -// -// urlConfigs.sort(Comparator.comparing(UrlConfiguration::getOrdinal)); -// urlConfigs.forEach(urlConfiguration -> { -// applyFunderQuery(urlConfiguration, externalReferenceCriteria); -// if (urlConfiguration.getType() == null || urlConfiguration.getType().equals("External")) { -// try { -// results.addAll(getAllResultsFromUrlWithData(urlConfiguration.getUrl(), urlConfiguration.getData(), externalReferenceCriteria, urlConfiguration.getContentType(), urlConfiguration.getFirstpage(), urlConfiguration.getRequestBody(), urlConfiguration.getRequestType(), urlConfiguration.getQueries())); -// } catch (Exception e) { -// logger.error(e.getLocalizedMessage(), e); -// } -// } -// }); -// return results; -// -// } -// -// private void applyFunderQuery(UrlConfiguration urlConfiguration, ExternalReferenceCriteria externalReferenceCriteria) { -// if (urlConfiguration.getFunderQuery() != null) { -// if (externalReferenceCriteria.getFunderId() != null && !urlConfiguration.getFunderQuery().startsWith("dmp:")) { -// urlConfiguration.setUrl(urlConfiguration.getUrl().replace("{funderQuery}", urlConfiguration.getFunderQuery())); -// } -// else { -// urlConfiguration.setUrl(urlConfiguration.getUrl().replace("{funderQuery}", "")); -// } -// } -// } -// -// private String calculateQuery(ExternalReferenceCriteria externalReferenceCriteria, List queryConfigs) { -// String finalQuery = ""; -// QueryConfig queryConfig = queryConfigs.stream().filter(queryConfigl -> externalReferenceCriteria.getLike().matches(queryConfigl.getCondition())) -// .min((Comparator.comparing(QueryConfig::getOrdinal))).orElse(null); -// if (queryConfig != null) { -// if (queryConfig.getSeparator() != null) { -// String[] likes = externalReferenceCriteria.getLike().split(queryConfig.getSeparator()); -// finalQuery = queryConfig.getValue(); -// for (int i = 0; i < likes.length; i++) { -// finalQuery = finalQuery.replaceAll("\\{like" + (i+1) + "}", likes[i]); -// } -// } else { -// finalQuery = queryConfig.getValue().replaceAll("\\{like}", externalReferenceCriteria.getLike()); -// } -// -// } -// return finalQuery; -// } -// -// protected String replaceCriteriaOnUrl(String path, ExternalReferenceCriteria externalReferenceCriteria, String firstPage, List queries) { -// String completedPath = path; -// if (externalReferenceCriteria.getLike() != null) { -// if ((path.contains("openaire") || path.contains("orcid") || path.contains("ror") || path.contains("fairsharing")) && externalReferenceCriteria.getLike().equals("")) { -// completedPath = completedPath.replaceAll("\\{like}", "*"); -// completedPath = completedPath.replaceAll("\\{query}", "*"); -// } else { -// if (completedPath.contains("{query}")) { -// completedPath = completedPath.replaceAll("\\{query}", this.calculateQuery(externalReferenceCriteria, queries)); -// } else { -// completedPath = completedPath.replaceAll("\\{like}", externalReferenceCriteria.getLike()); -// } -// } -// } else { -// completedPath = completedPath.replace("{like}", ""); -// } -// if (externalReferenceCriteria.getFunderId() != null) { -// String funderPrefix = externalReferenceCriteria.getFunderId().split(":")[0]; -// String funderId = externalReferenceCriteria.getFunderId().replace(funderPrefix + ":", ""); -// if (funderId.toCharArray()[0] == ':') { -// funderId = externalReferenceCriteria.getFunderId(); -// } -// /* -// try { funderId = URLEncoder.encode(funderId, "UTF-8"); } catch -// (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } -// */ -// completedPath = completedPath.replace("{funderId}", funderId); -// } -// else if(completedPath.contains("{funderId}")){ -// logger.warn("FunderId is null."); -// completedPath = completedPath.replace("{funderId}", " "); -// } -// if (externalReferenceCriteria.getPage() != null) { -// completedPath = completedPath.replace("{page}", externalReferenceCriteria.getPage()); -// } else { -// if (firstPage != null) { -// completedPath = completedPath.replace("{page}", firstPage); -// } else { -// completedPath = completedPath.replace("{page}", "1"); -// } -// } -// if (externalReferenceCriteria.getPageSize() != null) { -// completedPath = completedPath.replace("{pageSize}", externalReferenceCriteria.getPageSize()); -// } else { -// completedPath = completedPath.replace("{pageSize}", "60"); -// } -// if (externalReferenceCriteria.getHost() != null) { -// completedPath = completedPath.replace("{host}", externalReferenceCriteria.getHost()); -// } else { -// completedPath = completedPath.replace("{host}", ""); -// } -// if (externalReferenceCriteria.getPath() != null) { -// completedPath = completedPath.replace("{path}", externalReferenceCriteria.getPath()); -// } else { -// completedPath = completedPath.replace("{path}", ""); -// } -// return completedPath; -// } -// -// private List> getAllResultsFromUrl(String path, FetchStrategy fetchStrategy, final DataUrlConfiguration jsonDataPath, final String jsonPaginationPath, ExternalReferenceCriteria externalReferenceCriteria, String tag, String key, String contentType, String firstPage, String requestBody, String requestType, String filterType, List queries, String auth) throws Exception { -// Set pages = new HashSet<>(); -// -// String replacedPath = replaceCriteriaOnUrl(path, externalReferenceCriteria, firstPage, queries); -// String replacedBody = replaceCriteriaOnUrl(requestBody, externalReferenceCriteria, firstPage, queries); -// -// ExternalRefernceResult externalRefernceResult = getResultsFromUrl(replacedPath, jsonDataPath, jsonPaginationPath, contentType, replacedBody, requestType, auth); -// if(externalRefernceResult != null) { -// if (filterType != null && filterType.equals("local") && (externalReferenceCriteria.getLike() != null && !externalReferenceCriteria.getLike().isEmpty())) { -// externalRefernceResult.setResults(externalRefernceResult.getResults().stream() -// .filter(r -> r.get("name").toLowerCase().contains(externalReferenceCriteria.getLike().toLowerCase())) -// .collect(Collectors.toList())); -// } -// if (fetchStrategy == FetchStrategy.FIRST) -// return externalRefernceResult.getResults().stream().peek(x -> x.put("tag", tag)).peek(x -> x.put("key", key)).collect(Collectors.toList()); -// -// if (externalRefernceResult.getPagination() != null && externalRefernceResult.getPagination().get("pages") != null) //if has more pages, add them to the pages set -// for (int i = 2; i <= externalRefernceResult.getPagination().get("pages"); i++) -// pages.add(i); -// -// Long maxResults = this.externalUrlConfigProvider.getExternalUrls().getMaxresults(); -// if ((maxResults > 0) && (externalRefernceResult.getPagination().get("count") > maxResults)) -// throw new HugeResultSetException("The submitted search query " + externalReferenceCriteria.getLike() + " is about to return " + externalRefernceResult.getPagination().get("count") + " results... Please submit a more detailed search query"); -// -// Optional optionalResults = pages.parallelStream() -// .map(page -> getResultsFromUrl(path + "&page=" + page, jsonDataPath, jsonPaginationPath, contentType, replacedBody, requestType, auth)) -// .filter(Objects::nonNull) -// .reduce((result1, result2) -> { -// result1.getResults().addAll(result2.getResults()); -// return result1; -// }); -// ExternalRefernceResult remainingExternalRefernceResult = optionalResults.orElseGet(ExternalRefernceResult::new); -// remainingExternalRefernceResult.getResults().addAll(externalRefernceResult.getResults()); -// -// return remainingExternalRefernceResult.getResults().stream().peek(x -> x.put("tag", tag)).peek(x -> x.put("key", key)).collect(Collectors.toList()); -// } -// else { -// return new LinkedList<>(); -// } -// } -// -// private List> getAllResultsFromUrlWithData(String path, final DataUrlConfiguration jsonDataPath, ExternalReferenceCriteria externalReferenceCriteria, String contentType, String firstPage, String requestBody, String requestType, List queries) { -// -// String replacedPath = replaceCriteriaOnUrl(path, externalReferenceCriteria, firstPage, queries); -// String replacedBody = replaceCriteriaOnUrl(requestBody, externalReferenceCriteria, firstPage, queries); -// -// try { -// RestTemplate restTemplate = new RestTemplate(); -// HttpHeaders headers = new HttpHeaders(); -// HttpEntity entity; -// ResponseEntity response; -// if (contentType != null && !contentType.isEmpty()) { -// headers.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); -// headers.setContentType(MediaType.valueOf(contentType)); -// } -// JsonNode jsonBody = new ObjectMapper().readTree(replacedBody); -// entity = new HttpEntity<>(jsonBody, headers); -// -// response = restTemplate.exchange(replacedPath, HttpMethod.valueOf(requestType), entity, String.class); -// if (response.getStatusCode() == HttpStatus.OK) { -// if (response.getHeaders().get("Content-Type").get(0).contains("json")) { -// DocumentContext jsonContext = JsonPath.parse(response.getBody()); -// return jsonContext.read(jsonDataPath.getPath()); -// } -// } -// } -// catch (Exception exception) { -// logger.error(exception.getMessage(), exception); -// } -// -// return new LinkedList<>(); -// } -// -// -// protected ExternalRefernceResult getResultsFromUrl(String urlString, DataUrlConfiguration jsonDataPath, String jsonPaginationPath, String contentType, String requestBody, String requestType, String auth) { -// -// try { -// //RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory()); -// //HttpHeaders headers = new HttpHeaders(); -// //HttpEntity entity; -// ResponseEntity response; -// /* -// * URL url = new URL(urlString.replaceAll(" ", "%20")); -// * -// * HttpURLConnection con = (HttpURLConnection) url.openConnection(); -// * con.setRequestMethod("GET"); -// */ -// /* if (contentType != null && !contentType.isEmpty()) { -// headers.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); -// headers.setContentType(MediaType.valueOf(contentType)); -// } -// if (auth != null) { -// headers.set("Authorization", auth); -// }*/ -// JsonNode jsonBody = new ObjectMapper().readTree(requestBody); -//// entity = new HttpEntity<>(jsonBody, headers); -// -// -// response = this.getWebClient().method(HttpMethod.valueOf(requestType)).uri(urlString).headers(httpHeaders -> { -// if (contentType != null && !contentType.isEmpty()) { -// httpHeaders.setAccept(Collections.singletonList(MediaType.valueOf(contentType))); -// httpHeaders.setContentType(MediaType.valueOf(contentType)); -// } -// if (auth != null) { -// httpHeaders.set("Authorization", auth); -// } -// }).bodyValue(jsonBody).retrieve().toEntity(String.class).block(); -// //response = restTemplate.exchange(urlString, HttpMethod.resolve(requestType), entity, String.class); -// if (response.getStatusCode() == HttpStatus.OK) { // success -// //do here all the parsing -// ExternalRefernceResult externalRefernceResult = new ExternalRefernceResult(); -// if (response.getHeaders().get("Content-Type").get(0).contains("json")) { -// DocumentContext jsonContext = JsonPath.parse(response.getBody()); -// -// if (jsonDataPath.getFieldsUrlConfiguration().getPath() != null) { -// externalRefernceResult = RemoteFetcherUtils.getFromJsonWithRecursiveFetching(jsonContext, jsonDataPath, this, requestBody, requestType, auth); -// } else if (jsonDataPath.getFieldsUrlConfiguration().getFirstName() != null) { -// externalRefernceResult = RemoteFetcherUtils.getFromJsonWithFirstAndLastName(jsonContext, jsonDataPath); -// } else { -// externalRefernceResult = RemoteFetcherUtils.getFromJson(jsonContext, jsonDataPath); -// } -// externalRefernceResult.setResults(externalRefernceResult.getResults().stream().map(e -> e.entrySet().stream().collect(Collectors.toMap(x -> this.transformKey(jsonDataPath,x.getKey()), Map.Entry::getValue))) -// .collect(Collectors.toList())); -// } -// else if (response.getHeaders().get("Content-Type").get(0).contains("xml")) { -// Class aClass = Class.forName(jsonDataPath.getParseClass()); -// JAXBContext jaxbContext = JAXBContext.newInstance(aClass); -// Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); -// StringReader stringReader = new StringReader(response.getBody()); -// Object data = unmarshaller.unmarshal(stringReader); -// Method reader = null; -// if (jsonDataPath.getParseField() != null && !jsonDataPath.getParseField().isEmpty()) { -// String camelCaseGetter = jsonDataPath.getParseField() != null && !jsonDataPath.getParseField().isEmpty() ? "get" + jsonDataPath.getParseField().substring(0, 1).toUpperCase() + jsonDataPath.getParseField().substring(1) : ""; -// reader = aClass.getMethod(camelCaseGetter); -// } -// ObjectMapper objectMapper = new ObjectMapper(); -// List> values = new ArrayList<>(); -// int max = 1; -// if (reader != null) { -// Object invokedField = reader.invoke(data); -// if (invokedField instanceof Collection) { -// max = ((Collection) invokedField).size(); -// } -// } -// for (int i = 0; i< max; i++) { -// Object value; -// if (reader != null) { -// Object invokedField = reader.invoke(data); -// if (invokedField instanceof Collection) { -// value = ((Collection) invokedField).toArray()[i]; -// } else { -// value = invokedField; -// } -// } else { -// value = data; -// } -// Map map = objectMapper.convertValue(value, Map.class); -// if (jsonDataPath.getMergedFields() != null && !jsonDataPath.getMergedFields().isEmpty() && jsonDataPath.getMergedFieldName() != null && !jsonDataPath.getMergedFieldName().isEmpty()) { -// Map finalMap = new HashMap<>(); -// for (Map.Entry entry : map.entrySet()) { -// if (jsonDataPath.getMergedFields().contains(entry.getKey())) { -// if (!finalMap.containsKey(jsonDataPath.getMergedFieldName())) { -// finalMap.put(jsonDataPath.getMergedFieldName(), entry.getValue()); -// } else { -// finalMap.put(jsonDataPath.getMergedFieldName(), finalMap.get(jsonDataPath.getMergedFieldName()) + " " + entry.getValue()); -// } -// } else { -// finalMap.put(entry.getKey(), entry.getValue()); -// } -// } -// values.add(finalMap); -// } else { -// values.add(map); -// } -// } -// externalRefernceResult = new ExternalRefernceResult(values, new HashMap<>(1, 1)); -// } -// -// if (externalRefernceResult.getPagination().isEmpty()) { -// externalRefernceResult.getPagination().put("pages", 1); -// externalRefernceResult.getPagination().put("count", externalRefernceResult.getResults().size()); -// } -// return externalRefernceResult; -// } -// } catch (Exception exception) { -// logger.error(exception.getMessage(), exception); -// } //maybe print smth... -// -// return null; -// } -// -// private List> getAllResultsFromMockUpJson(String path, String query) { -// List> internalResults; -// try { -// String filePath = Paths.get(path).toUri().toURL().toString(); -// ObjectMapper mapper = new ObjectMapper(); -// internalResults = mapper.readValue(new File(filePath), new TypeReference>>(){}); -// return searchListMap(internalResults, query); -// } catch (Exception e) { -// logger.error(e.getMessage(), e); -// return new LinkedList<>(); -// } -// } -// -// private List> searchListMap(List> internalResults, String query) { -// List> list = new LinkedList<>(); -// for (Map map : internalResults) -// { -// if (map.get("name") != null && map.get("name").toUpperCase().contains(query.toUpperCase())) { -// list.add(map); -// } -// if (map.get("label") != null && map.get("label").toUpperCase().contains(query.toUpperCase())) { -// list.add(map); -// } -// } -// return list; -// } -// -// private String transformKey(DataUrlConfiguration dataUrlConfiguration, String key) { -// if (dataUrlConfiguration.getFieldsUrlConfiguration().getId() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getId().replace("'",""))) { -// if(dataUrlConfiguration.getFieldsUrlConfiguration().getPid() == null) -// return "pid"; -// else -// return "originalId"; -// } -// if (dataUrlConfiguration.getFieldsUrlConfiguration().getPid() != null && key.equals("pid")) return "pid"; -// if (dataUrlConfiguration.getFieldsUrlConfiguration().getPidTypeField() != null && key.equals("pidTypeField")) return "pidTypeField"; -// if (dataUrlConfiguration.getFieldsUrlConfiguration().getDescription() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getDescription().replace("'",""))) return "description"; -// if (dataUrlConfiguration.getFieldsUrlConfiguration().getUri() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getUri().replace("'",""))) return "uri"; -// if (dataUrlConfiguration.getFieldsUrlConfiguration().getName() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getName().replace("'",""))) return "name"; -// if (dataUrlConfiguration.getFieldsUrlConfiguration().getSource() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getSource().replace("'",""))) return "source"; -// if (dataUrlConfiguration.getFieldsUrlConfiguration().getCount() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getCount().replace("'",""))) return "count"; -// if (dataUrlConfiguration.getFieldsUrlConfiguration().getPath() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getPath().replace("'",""))) return "path"; -// if (dataUrlConfiguration.getFieldsUrlConfiguration().getHost() != null && key.equals(dataUrlConfiguration.getFieldsUrlConfiguration().getHost().replace("'",""))) return "host"; -// return null; -// } -// -// private String parseBodyString(String bodyString) { -// String finalBodyString = bodyString; -// if (bodyString.contains("{env:")) { -// int index = bodyString.indexOf("{env: "); -// while (index >= 0) { -// int endIndex = bodyString.indexOf("}", index + 6); -// String envName = bodyString.substring(index + 6, endIndex); -// finalBodyString = finalBodyString.replace("{env: " + envName + "}", System.getenv(envName)); -// index = bodyString.indexOf("{env: ", index + 6); -// } -// } -// return finalBodyString; -// } -// -//} + } + + private String replaceLookupFieldQuery(ExternalReferenceCriteria externalReferenceCriteria, List queryConfigs) { + String finalQuery = ""; + if (this.conventionService.isNullOrEmpty(externalReferenceCriteria.getLike())) return finalQuery; + QueryConfig queryConfig = queryConfigs.stream().filter(x -> !this.conventionService.isNullOrEmpty(x.getCondition()) && externalReferenceCriteria.getLike().matches(x.getCondition())) + .min((Comparator.comparing(QueryConfig::getOrdinal))).orElse(null); + if (queryConfig != null) { + if (queryConfig.getSeparator() != null) { + String[] likes = externalReferenceCriteria.getLike().split(queryConfig.getSeparator()); + finalQuery = queryConfig.getValue(); + for (int i = 0; i < likes.length; i++) { + finalQuery = finalQuery.replaceAll("\\{like" + (i + 1) + "}", likes[i]); + } + } else { + finalQuery = queryConfig.getValue().replaceAll("\\{like}", externalReferenceCriteria.getLike()); + } + + } + return finalQuery; + } + + protected String replaceLookupFields(String path, ExternalReferenceCriteria externalReferenceCriteria, String firstPage, List queries) { + if (!this.conventionService.isNullOrEmpty(path)) return path; + String completedPath = path; + + if (externalReferenceCriteria.getLike() != null) { + if ((path.contains("openaire") || path.contains("orcid") || path.contains("ror") || path.contains("fairsharing")) && externalReferenceCriteria.getLike().isEmpty()) { + completedPath = completedPath.replaceAll("\\{like}", "*"); + completedPath = completedPath.replaceAll("\\{query}", "*"); + } else { + if (completedPath.contains("{query}")) { + completedPath = completedPath.replaceAll("\\{query}", this.replaceLookupFieldQuery(externalReferenceCriteria, queries)); + } else { + completedPath = completedPath.replaceAll("\\{like}", externalReferenceCriteria.getLike()); + } + } + } else { + completedPath = completedPath.replace("{like}", ""); + } + if (!this.conventionService.isNullOrEmpty(externalReferenceCriteria.getFunderId())) { + String[] founderParts = externalReferenceCriteria.getFunderId().split(":"); + String funderPrefix = founderParts.length > 0 ? founderParts[0] : ""; + String funderId = externalReferenceCriteria.getFunderId().replace(funderPrefix + ":", ""); + if (!funderId.isEmpty() && funderId.toCharArray()[0] == ':') { + funderId = externalReferenceCriteria.getFunderId(); + } + completedPath = completedPath.replace("{funderId}", funderId); + } else if(completedPath.contains("{funderId}")){ + logger.warn("FunderId is null."); + completedPath = completedPath.replace("{funderId}", " "); + } + + if (!this.conventionService.isNullOrEmpty(externalReferenceCriteria.getPage())) completedPath = completedPath.replace("{page}", externalReferenceCriteria.getPage()); + else if (!this.conventionService.isNullOrEmpty(firstPage)) completedPath = completedPath.replace("{page}", firstPage); + else completedPath = completedPath.replace("{page}", "1"); + + completedPath = completedPath.replace("{pageSize}", !this.conventionService.isNullOrEmpty(externalReferenceCriteria.getPageSize()) ? externalReferenceCriteria.getPageSize() : "60"); + completedPath = completedPath.replace("{host}", !this.conventionService.isNullOrEmpty(externalReferenceCriteria.getHost()) ? externalReferenceCriteria.getHost() : ""); + completedPath = completedPath.replace("{path}", !this.conventionService.isNullOrEmpty(externalReferenceCriteria.getPath()) ? externalReferenceCriteria.getPath() : ""); + + + return completedPath; + } + + private ExternalDataResult queryExternalData(FetchStrategy fetchStrategy, final SourceExternalApiConfiguration, AuthenticationConfiguration, QueryConfig> apiSource, ExternalReferenceCriteria externalReferenceCriteria, String auth) throws Exception { + String replacedPath = replaceLookupFields(apiSource.getUrl(), externalReferenceCriteria, apiSource.getFirstPage(), apiSource.getQueries()); + String replacedBody = replaceLookupFields(apiSource.getRequestBody(), externalReferenceCriteria, apiSource.getFirstPage(), apiSource.getQueries()); + + ExternalDataResult externalDataResult = this.getExternalDataResults(replacedPath, apiSource, replacedBody, auth); + if(externalDataResult != null) { + if (apiSource.getFilterType() != null && apiSource.getFilterType().equals("local") && (externalReferenceCriteria.getLike() != null && !externalReferenceCriteria.getLike().isEmpty())) { + externalDataResult.setResults(externalDataResult.getResults().stream() + .filter(r -> r.get("name").toLowerCase().contains(externalReferenceCriteria.getLike().toLowerCase())) + .collect(Collectors.toList())); + } + externalDataResult.setResults(externalDataResult.getResults().stream().peek(x -> x.put("tag", apiSource.getLabel())).peek(x -> x.put("key", apiSource.getKey())).toList()); + if (fetchStrategy == FetchStrategy.FIRST) return externalDataResult; + + Long maxResults = this.externalUrlConfigProvider.getExternalUrls().getMaxresults(); + if (externalDataResult.getResults().size() > maxResults) + throw new HugeResultSetException("The submitted search query " + externalReferenceCriteria.getLike() + " is about to return " + externalDataResult.getResults().size() + " results... Please submit a more detailed search query"); + + return externalDataResult; + } + else { + return new ExternalDataResult(); + } + } + + protected ExternalDataResult getExternalDataResults(String urlString, final SourceExternalApiConfiguration, AuthenticationConfiguration, QueryConfig> apiSource, String requestBody, String auth) { + + try { + JsonNode jsonBody = new ObjectMapper().readTree(requestBody); + HttpMethod method; + switch (apiSource.getHttpMethod()) { + case GET -> method = HttpMethod.GET; + case POST -> method =HttpMethod.POST; + default -> throw new MyApplicationException("unrecognized type " + apiSource.getHttpMethod()); + } + + ResponseEntity response = this.getWebClient().method(method).uri(urlString).headers(httpHeaders -> { + if (this.conventionService.isNullOrEmpty(apiSource.getContentType())) { + httpHeaders.setAccept(Collections.singletonList(MediaType.valueOf(apiSource.getContentType()))); + httpHeaders.setContentType(MediaType.valueOf(apiSource.getContentType())); + } + if (auth != null) { + httpHeaders.set("Authorization", auth); + } + }).bodyValue(jsonBody).retrieve().toEntity(String.class).block(); + if (response == null || !response.getStatusCode().isSameCodeAs(HttpStatus.OK) || !response.hasBody() || response.getBody() == null) return null; + + //do here all the parsing + List responseContentTypeHeader = response.getHeaders().getOrDefault("Content-Type", null); + String responseContentType = !this.conventionService.isListNullOrEmpty(responseContentTypeHeader) && responseContentTypeHeader.getFirst() != null ? responseContentTypeHeader.getFirst() : ""; + + if (responseContentType.contains("json") ) { + DocumentContext jsonContext = JsonPath.parse(response.getBody()); + return this.parseData(jsonContext, apiSource.getResults()); + } else { + throw new MyApplicationException("Unsupported response type" + responseContentType); + } + + } catch (Exception exception) { + logger.error(exception.getMessage(), exception); + } + + return null; + } + + private ExternalDataResult parseData (DocumentContext jsonContext, ResultsConfiguration resultsConfigurationEntity) { + ExternalDataResult result = new ExternalDataResult(); + if (this.conventionService.isNullOrEmpty(resultsConfigurationEntity.getResultsArrayPath())) return new ExternalDataResult(); + List> rawData = jsonContext.read(resultsConfigurationEntity.getResultsArrayPath()); + + result.setRawData(rawData); + + if (this.conventionService.isListNullOrEmpty(rawData) || this.conventionService.isListNullOrEmpty(resultsConfigurationEntity.getFieldsMapping())) return new ExternalDataResult(); + + List> parsedData = new ArrayList<>(); + for (Map stringObjectMap: rawData){ + Map map = new HashMap<>(); + for(ResultFieldsMappingConfiguration field : resultsConfigurationEntity.getFieldsMapping()){ + String pathValue = field.getResponsePath(); + if (!pathValue.contains(".")){ + if (stringObjectMap.containsKey(pathValue)) { + map.put(field.getCode(), normalizeValue(stringObjectMap.get(pathValue))); + } + }else { + if (stringObjectMap.containsKey(pathValue.split("\\.")[0])){ + String value = null; + Object fieldObj = stringObjectMap.get(pathValue.split("\\.")[0]); + if (fieldObj != null){ + if (fieldObj instanceof Map){ + Object o = ((Map) fieldObj).get(pathValue.split("\\.")[1]); + if(o instanceof String){ + value = (String)o; + } + else if(o instanceof Integer){ + value = String.valueOf(o); + } + } else if (fieldObj instanceof List) { + Object o = ((List>) fieldObj).get(0).get(pathValue.split("\\.")[1]); + if(o instanceof String){ + value = (String)o; + } + else if(o instanceof Integer){ + value = String.valueOf(o); + } + } + } + if (value != null){ + map.put(field.getCode(), value); + } + } + } + } + parsedData.add(map); + } + result.setResults(parsedData); + return result; + } + + private static String normalizeValue(Object value) { + if (value instanceof JSONArray jsonArray) { + + if (!jsonArray.isEmpty() && jsonArray.getFirst() instanceof String) { + return jsonArray.getFirst().toString(); + } else { + for (Object o : jsonArray) { + if ((o instanceof Map) && ((Map) o).containsKey("content")) { + try { + return ((Map) o).get("content"); + } + catch (ClassCastException e){ + if(((Map) o).get("content") instanceof Integer) { + return String.valueOf(((Map) o).get("content")); + } + return null; + } + } + } + } + } else if (value instanceof Map) { + String key = ((Map)value).containsKey("$") ? "$" : "content"; + return ((Map)value).get(key); + } + return value != null ? value.toString() : null; + } + + private ExternalDataResult getAllResultsFromMockUpJson(String path, String query) { + List> internalResults; + try { + String filePath = Paths.get(path).toUri().toURL().toString(); + ObjectMapper mapper = new ObjectMapper(); + internalResults = mapper.readValue(new File(filePath), new TypeReference>>(){}); + return new ExternalDataResult(searchListMap(internalResults, query)); + } catch (Exception e) { + logger.error(e.getMessage(), e); + return new ExternalDataResult(); + } + } + + private List> searchListMap(List> internalResults, String query) { + List> list = new LinkedList<>(); + for (Map map : internalResults) + { + if (map.get("name") != null && map.get("name").toUpperCase().contains(query.toUpperCase())) { + list.add(map); + } + if (map.get("label") != null && map.get("label").toUpperCase().contains(query.toUpperCase())) { + list.add(map); + } + } + return list; + } + + private String parseBodyString(String bodyString) { + String finalBodyString = bodyString; + if (bodyString.contains("{env:")) { + int index = bodyString.indexOf("{env: "); + while (index >= 0) { + int endIndex = bodyString.indexOf("}", index + 6); + String envName = bodyString.substring(index + 6, endIndex); + finalBodyString = finalBodyString.replace("{env: " + envName + "}", System.getenv(envName)); + index = bodyString.indexOf("{env: ", index + 6); + } + } + return finalBodyString; + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherUtils.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherUtils.java deleted file mode 100644 index 081a1c1f1..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/RemoteFetcherUtils.java +++ /dev/null @@ -1,152 +0,0 @@ -//package eu.eudat.service.remotefetcher; -// -//import com.fasterxml.jackson.databind.ObjectMapper; -//import com.jayway.jsonpath.DocumentContext; -//import eu.eudat.service.remotefetcher.config.DataUrlConfiguration; -//import eu.eudat.service.remotefetcher.criteria.ExternalReferenceCriteria; -//import eu.eudat.service.remotefetcher.models.ExternalRefernceResult; -//import net.minidev.json.JSONArray; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -// -//import java.lang.reflect.InvocationTargetException; -//import java.lang.reflect.Method; -//import java.util.*; -//import java.util.stream.Collectors; -// -//public class RemoteFetcherUtils { -// private final static Logger logger = LoggerFactory.getLogger(RemoteFetcherUtils.class); -// private static final ObjectMapper mapper = new ObjectMapper(); -// -// public static ExternalRefernceResult getFromJson(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { -// return new ExternalRefernceResult(parseData(jsonContext, jsonDataPath), -// new HashMap<>(1, 1)); -// } -// -// public static ExternalRefernceResult getFromJsonWithRecursiveFetching(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath, RemoteFetcherServiceImpl remoteFetcherService, String requestBody, String requestType, String auth) { -// ExternalRefernceResult externalRefernceResult = new ExternalRefernceResult(parseData(jsonContext, jsonDataPath), -// new HashMap<>(1, 1)); -// -// List> multiResults = externalRefernceResult.getResults().stream().map(result -> { -// ExternalReferenceCriteria externalReferenceCriteria = new ExternalReferenceCriteria(); -// externalReferenceCriteria.setPath(result.get("path")); -// externalReferenceCriteria.setHost(result.get("host")); -// String replacedPath = remoteFetcherService.replaceCriteriaOnUrl(jsonDataPath.getUrlConfiguration().getUrl(), externalReferenceCriteria, jsonDataPath.getUrlConfiguration().getFirstpage(), jsonDataPath.getUrlConfiguration().getQueries()); -// return remoteFetcherService.getResultsFromUrl(replacedPath, jsonDataPath.getUrlConfiguration().getData(), jsonDataPath.getUrlConfiguration().getData().getPath(), jsonDataPath.getUrlConfiguration().getContentType(), requestBody, requestType, auth); -// }).filter(Objects::nonNull).map(externalRefernceResult1 -> externalRefernceResult1.getResults().get(0)).collect(Collectors.toList()); -// return new ExternalRefernceResult(multiResults, new HashMap<>(1, 1)); -// } -// -// public static ExternalRefernceResult getFromJsonWithFirstAndLastName(DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { -// ExternalRefernceResult externalRefernceResult = new ExternalRefernceResult(parseData(jsonContext, jsonDataPath), -// new HashMap<>(1, 1)); -// externalRefernceResult.getResults().stream().forEach(entry -> { -// String name = entry.get(jsonDataPath.getFieldsUrlConfiguration().getFirstName().replace("'", "")) + " " + entry.get(jsonDataPath.getFieldsUrlConfiguration().getLastName().replace("'", "")); -// entry.put("name", name); -// entry.remove(jsonDataPath.getFieldsUrlConfiguration().getFirstName().replace("'", "")); -// entry.remove(jsonDataPath.getFieldsUrlConfiguration().getLastName().replace("'", "")); -// }); -// return externalRefernceResult; -// } -// -// private static List> parseData (DocumentContext jsonContext, DataUrlConfiguration jsonDataPath) { -// List > rawData = jsonContext.read(jsonDataPath.getPath()); -// List> parsedData = new ArrayList<>(); -// rawData.forEach(stringObjectMap -> { -// parsedData.add(new LinkedHashMap<>()); -// Arrays.stream(jsonDataPath.getFieldsUrlConfiguration().getClass().getDeclaredFields()).forEach(field -> { -// String getterMethodName = "get" + field.getName().substring(0, 1).toUpperCase(Locale.ROOT) + field.getName().substring(1); -// Method getterMethod = Arrays.stream(jsonDataPath.getFieldsUrlConfiguration().getClass().getDeclaredMethods()).filter(method -> method.getName().equals(getterMethodName)).collect(Collectors.toList()).get(0); -// try { -// String value = ((String) getterMethod.invoke(jsonDataPath.getFieldsUrlConfiguration())); -// if (value != null) { -// if (field.getName().equals("pid") || field.getName().equals("pidTypeField")) { -// String pid = null; -// Object pidObj = stringObjectMap.get(value.split("\\.")[0]); -// if(pidObj != null){ -// if(pidObj instanceof Map){ -// Object o = ((Map) pidObj).get(value.split("\\.")[1]); -// if(o instanceof String){ -// pid = (String)o; -// } -// else if(o instanceof Integer){ -// pid = String.valueOf(o); -// } -// } -// else if(pidObj instanceof List){ -// Object o = ((List>) pidObj).get(0).get(value.split("\\.")[1]); -// if(o instanceof String){ -// pid = (String)o; -// } -// else if(o instanceof Integer){ -// pid = String.valueOf(o); -// } -// } -// } -// if(pid != null) { -// if ((field.getName().equals("pid"))){ -// parsedData.get(parsedData.size() - 1).put("pid", pid); -// } -// else{ -// parsedData.get(parsedData.size() - 1).put("pidTypeField", pid); -// } -// } -// } else { -// value = value.replace("'", ""); -// if (value.contains(".")) { -// String[] parts = value.split("\\."); -// Map tempMap = stringObjectMap; -// for (int i = 0; i < parts.length; i++) { -// if (tempMap.containsKey(parts[i])) { -// if (i + 1 < parts.length) { -// tempMap = (Map) tempMap.get(parts[i]); -// } else { -// parsedData.get(parsedData.size() - 1).put(field.getName().equals("types") ? "tags" : value, normalizeValue(tempMap.get(parts[i]), (field.getName().equals("types") || field.getName().equals("uri")))); -// } -// } -// } -// } else { -// if (stringObjectMap.containsKey(value)) { -// parsedData.get(parsedData.size() - 1).put(field.getName().equals("types") ? "tags" : value, normalizeValue(stringObjectMap.get(value), (field.getName().equals("types") || field.getName().equals("uri")))); -// } -// } -// } -// } -// } catch (IllegalAccessException | InvocationTargetException e) { -// logger.error(e.getLocalizedMessage(), e); -// } -// }); -// }); -// return parsedData; -// } -// -// private static String normalizeValue(Object value, boolean jsonString) { -// if (value instanceof JSONArray) { -// if (jsonString) { -// return ((JSONArray)value).toJSONString(); -// } -// JSONArray jarr = (JSONArray) value; -// if (jarr.get(0) instanceof String) { -// return jarr.get(0).toString(); -// } else { -// for (Object o : jarr) { -// if ((o instanceof Map) && ((Map) o).containsKey("content")) { -// try { -// return ((Map) o).get("content"); -// } -// catch (ClassCastException e){ -// if(((Map) o).get("content") instanceof Integer) { -// return String.valueOf(((Map) o).get("content")); -// } -// return null; -// } -// } -// } -// } -// } else if (value instanceof Map) { -// String key = ((Map)value).containsKey("$") ? "$" : "content"; -// return ((Map)value).get(key); -// } -// return value != null ? value.toString() : null; -// } -//} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/AuthenticationConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/AuthenticationConfiguration.java deleted file mode 100644 index 4d18e08b1..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/AuthenticationConfiguration.java +++ /dev/null @@ -1,57 +0,0 @@ -package eu.eudat.service.remotefetcher.config; - -import jakarta.xml.bind.annotation.XmlElement; - -public class AuthenticationConfiguration { - - private String authUrl; - private String authMethod = "GET"; - private String authTokenPath; - private String authRequestBody; - private String type; - - public String getAuthUrl() { - return authUrl; - } - - @XmlElement(name = "authUrl") - public void setAuthUrl(String authUrl) { - this.authUrl = authUrl; - } - - public String getAuthMethod() { - return authMethod; - } - - @XmlElement(name = "authUrlMethod") - public void setAuthMethod(String authMethod) { - this.authMethod = authMethod; - } - - public String getAuthTokenPath() { - return authTokenPath; - } - - @XmlElement(name = "authTokenJpath") - public void setAuthTokenPath(String authTokenPath) { - this.authTokenPath = authTokenPath; - } - - public String getAuthRequestBody() { - return authRequestBody; - } - - @XmlElement(name = "authUrlBody") - public void setAuthRequestBody(String authRequestBody) { - this.authRequestBody = authRequestBody; - } - - public String getType() { - return type; - } - - @XmlElement(name = "authType") - public void setType(String type) { - this.type = type; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/DataFieldsUrlConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/DataFieldsUrlConfiguration.java deleted file mode 100644 index 10ab09f80..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/DataFieldsUrlConfiguration.java +++ /dev/null @@ -1,134 +0,0 @@ -package eu.eudat.service.remotefetcher.config; - -import jakarta.xml.bind.annotation.XmlElement; - -/** - * Created by ikalyvas on 6/29/2018. - */ -public class DataFieldsUrlConfiguration { - private String id; - private String name; - private String pid; - private String pidTypeField; - private String uri; - private String description; - private String source; - private String count; - private String path; - private String host; - private String types; - private String firstName; - private String lastName; - - public String getId() { - return id; - } - - @XmlElement(name = "id") - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - @XmlElement(name = "name") - public void setName(String name) { - this.name = name; - } - - public String getPid() { - return pid; - } - - @XmlElement(name = "pid") - public void setPid(String pid) { - this.pid = pid; - } - - public String getPidTypeField() { - return pidTypeField; - } - - @XmlElement(name = "pidTypeField") - public void setPidTypeField(String pidTypeField) { - this.pidTypeField = pidTypeField; - } - - public String getUri() { - return uri; - } - - @XmlElement(name = "uri") - public void setUri(String uri) { - this.uri = uri; - } - - public String getDescription() { - return description; - } - - @XmlElement(name = "description") - public void setDescription(String description) { - this.description = description; - } - - public String getSource() { - return source; - } - - @XmlElement(name = "source") - public void setSource(String source) { - this.source = source; - } - - public String getCount() { - return count; - } - - @XmlElement(name = "count") - public void setCount(String count) { - this.count = count; - } - - public String getPath() { - return path; - } - @XmlElement(name = "path") - public void setPath(String path) { - this.path = path; - } - - public String getHost() { - return host; - } - @XmlElement(name = "host") - public void setHost(String host) { - this.host = host; - } - - @XmlElement(name = "types") - public String getTypes() { - return types; - } - public void setTypes(String types) { - this.types = types; - } - - @XmlElement(name = "firstName") - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - @XmlElement(name = "lastName") - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/DataUrlConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/DataUrlConfiguration.java deleted file mode 100644 index b4d8d10b0..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/DataUrlConfiguration.java +++ /dev/null @@ -1,82 +0,0 @@ -package eu.eudat.service.remotefetcher.config; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - -/** - * Created by ikalyvas on 6/29/2018. - */ -public class DataUrlConfiguration { - private String path; - private DataFieldsUrlConfiguration fieldsUrlConfiguration; - private UrlConfiguration urlConfiguration; - private String parseClass; - private String parseField; - private List mergedFields; - private String mergedFieldName; - - public String getPath() { - return path; - } - - @XmlElement(name = "path") - public void setPath(String path) { - this.path = path; - } - - public DataFieldsUrlConfiguration getFieldsUrlConfiguration() { - return fieldsUrlConfiguration; - } - - @XmlElement(name = "fields") - public void setFieldsUrlConfiguration(DataFieldsUrlConfiguration fieldsUrlConfiguration) { - this.fieldsUrlConfiguration = fieldsUrlConfiguration; - } - - public UrlConfiguration getUrlConfiguration() { - return urlConfiguration; - } - - @XmlElement(name = "urlConfig") - public void setUrlConfiguration(UrlConfiguration urlConfiguration) { - this.urlConfiguration = urlConfiguration; - } - - public String getParseClass() { - return parseClass; - } - - @XmlElement(name = "parse-class") - public void setParseClass(String parseClass) { - this.parseClass = parseClass; - } - - public String getParseField() { - return parseField; - } - - @XmlElement(name = "parse-field") - public void setParseField(String parseField) { - this.parseField = parseField; - } - - public List getMergedFields() { - return mergedFields; - } - - @XmlElementWrapper(name = "merge-fields") - @XmlElement(name = "field") - public void setMergedFields(List mergedFields) { - this.mergedFields = mergedFields; - } - - public String getMergedFieldName() { - return mergedFieldName; - } - - @XmlElement(name = "merge-field-name") - public void setMergedFieldName(String mergedFieldName) { - this.mergedFieldName = mergedFieldName; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/ExternalUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/ExternalUrls.java index 669525a75..80e27c9b6 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/ExternalUrls.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/ExternalUrls.java @@ -17,153 +17,8 @@ public class ExternalUrls implements Serializable { Long maxresults; - GrantUrls grants; - ProjectUrls projects; - RegistryUrls registries; - RepositoryUrls repositories; - PubRepositoryUrls pubRepositories; - JournalUrls journals; - TaxonomiesUrls taxonomies; - PublicationsUrls publications; - ServiceUrls services; - ResearcherUrls researchers; - OrganisationUrls organisations; - DatasetUrls datasets; - /*TagUrls tags;*/ - FunderUrls funders; - LicenseUrls licenses; - ValidationUrls validations; Map prefillings; - - public RegistryUrls getRegistries() { - return registries; - } - - @XmlElement(name = "registries") - public void setRegistries(RegistryUrls registries) { - this.registries = registries; - } - - - public RepositoryUrls getRepositories() { - return repositories; - } - - @XmlElement(name = "repositories") - public void setRepositories(RepositoryUrls repositories) { - this.repositories = repositories; - } - - public PubRepositoryUrls getPubRepositories() { - return pubRepositories; - } - - public void setPubRepositories(PubRepositoryUrls pubRepositories) { - this.pubRepositories = pubRepositories; - } - - public void setJournals(JournalUrls journals) { - this.journals = journals; - } - - public JournalUrls getJournals() { - return journals; - } - - public JournalUrls getJournal() { - return journals; - } - @XmlElement(name = "journals") - public void setJournal(JournalUrls journal) { - this.journals = journal; - } - - public TaxonomiesUrls getTaxonomies() { - return taxonomies; - } - @XmlElement(name = "taxonomies") - public void setTaxonomies(TaxonomiesUrls taxonomies) { - this.taxonomies = taxonomies; - } - - public PublicationsUrls getPublications() { - return publications; - } - - public void setPublications(PublicationsUrls publications) { - this.publications = publications; - } - - public ServiceUrls getServices() { - return services; - } - - @XmlElement(name = "services") - public void setServices(ServiceUrls services) { - this.services = services; - } - - - public ResearcherUrls getResearchers() { - return researchers; - } - - @XmlElement(name = "researchers") - public void setResearchers(ResearcherUrls researchers) { - this.researchers = researchers; - } - - - /*public TagUrls getTags() { - return tags; - } - - @XmlElement(name = "tags") - public void setTags(TagUrls tags) { - this.tags = tags; - }*/ - - - public OrganisationUrls getOrganisations() { - return organisations; - } - - @XmlElement(name = "organisations") - public void setOrganisations(OrganisationUrls organisations) { - this.organisations = organisations; - } - - - public GrantUrls getGrants() { - return grants; - } - - @XmlElement(name = "grants") - public void setGrants(GrantUrls grants) { - this.grants = grants; - } - - - public ProjectUrls getProjects() { - return projects; - } - - @XmlElement(name = "projects") - public void setProjects(ProjectUrls projects) { - this.projects = projects; - } - - - public FunderUrls getFunders() { - return funders; - } - - public void setFunders(FunderUrls funders) { - this.funders = funders; - } - - public Long getMaxresults() { return maxresults; } @@ -173,34 +28,6 @@ public class ExternalUrls implements Serializable { this.maxresults = maxresults; } - - public DatasetUrls getDatasets() { - return datasets; - } - - @XmlElement(name = "datasets") - public void setDatasets(DatasetUrls datasets) { - this.datasets = datasets; - } - - public LicenseUrls getLicenses() { - return licenses; - } - - @XmlElement(name = "licenses") - public void setLicenses(LicenseUrls licenses) { - this.licenses = licenses; - } - - public ValidationUrls getValidations() { - return validations; - } - - @XmlElement(name = "validators") - public void setValidations(ValidationUrls validations) { - this.validations = validations; - } - public Map getPrefillings() { return prefillings; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/QueryConfig.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/QueryConfig.java deleted file mode 100644 index c7281d73c..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/QueryConfig.java +++ /dev/null @@ -1,48 +0,0 @@ -package eu.eudat.service.remotefetcher.config; - -import jakarta.xml.bind.annotation.XmlElement; - -public class QueryConfig { - - private String condition; - private String separator; - private String value; - private Integer ordinal; - - - public String getCondition() { - return condition; - } - - @XmlElement(name = "condition") - public void setCondition(String condition) { - this.condition = condition; - } - - public String getSeparator() { - return separator; - } - - @XmlElement(name = "separator") - public void setSeparator(String separator) { - this.separator = separator; - } - - public String getValue() { - return value; - } - - @XmlElement(name = "value") - public void setValue(String value) { - this.value = value; - } - - public Integer getOrdinal() { - return ordinal; - } - - @XmlElement(name = "ordinal") - public void setOrdinal(Integer ordinal) { - this.ordinal = ordinal; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/UrlConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/UrlConfiguration.java index 7211f5956..1682f6aad 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/UrlConfiguration.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/UrlConfiguration.java @@ -1,34 +1,23 @@ package eu.eudat.service.remotefetcher.config; +import eu.eudat.commons.enums.ReferenceTypeSourceType; +import eu.eudat.service.remotefetcher.config.entities.SourceBaseConfiguration; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElementWrapper; import java.util.List; -public class UrlConfiguration { +public class UrlConfiguration implements SourceBaseConfiguration { private String key; private String label; private Integer ordinal; - private String url; - private boolean dataInListing; - private DataUrlConfiguration data; - private String type; - private String paginationPath; - private String contentType; - private String funderQuery; - private String firstpage; - private String requestType = "GET"; - private String requestBody = ""; - private String filterType = "remote"; - private AuthenticationConfiguration auth; - - private List queries; + private ReferenceTypeSourceType type; public String getKey() { return key; } - @XmlElement(name = "key") + public void setKey(String key) { this.key = key; } @@ -36,121 +25,24 @@ public class UrlConfiguration { public String getLabel() { return label; } - @XmlElement(name = "label") + public void setLabel(String label) { this.label = label; } - public String getUrl() { - return url; - } - @XmlElement(name = "url") - public void setUrl(String url) { - this.url = url; - } - - public boolean isDataInListing() { - return dataInListing; - } - @XmlElement(name = "dataInListing") - public void setDataInListing(boolean dataInListing) { - this.dataInListing = dataInListing; - } - public Integer getOrdinal() { return ordinal; } - @XmlElement(name = "ordinal") + public void setOrdinal(Integer ordinal) { this.ordinal = ordinal; } - public DataUrlConfiguration getData() { - return data; - } - @XmlElement(name = "data") - public void setData(DataUrlConfiguration data) { - this.data = data; - } - - public String getPaginationPath() { - return paginationPath; - } - @XmlElement(name = "paginationpath") - public void setPaginationPath(String paginationPath) { - this.paginationPath = paginationPath; - } - - public String getType() { + public ReferenceTypeSourceType getType() { return type; } - @XmlElement(name = "type") - public void setType(String type) { + + public void setType(ReferenceTypeSourceType type) { this.type = type; } - - public String getContentType() { - return contentType; - } - @XmlElement(name = "contenttype") - public void setContentType(String contentType) { - this.contentType = contentType; - } - - public String getFunderQuery() { - return funderQuery; - } - @XmlElement(name = "funderQuery") - public void setFunderQuery(String funderQuery) { - this.funderQuery = funderQuery; - } - - public String getFirstpage() { - return firstpage; - } - @XmlElement(name = "firstPage") - public void setFirstpage(String firstpage) { - this.firstpage = firstpage; - } - - public String getRequestType() { - return requestType; - } - @XmlElement(name = "request") - public void setRequestType(String requestType) { - this.requestType = requestType != null ? requestType : "GET"; - } - public String getRequestBody() { - return requestBody; - } - @XmlElement(name = "requestBody") - public void setRequestBody(String requestBody) { - this.requestBody = requestBody != null ? requestBody : ""; - } - public String getFilterType() { - return filterType; - } - @XmlElement(name = "filterType") - public void setFilterType(String filterType) { - this.filterType = filterType; - } - - public List getQueries() { - return queries; - } - - @XmlElementWrapper - @XmlElement(name = "query") - public void setQueries(List queries) { - this.queries = queries; - } - - public AuthenticationConfiguration getAuth() { - return auth; - } - - @XmlElement(name="authentication") - public void setAuth(AuthenticationConfiguration auth) { - this.auth = auth; - } } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/AuthenticationConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/AuthenticationConfiguration.java new file mode 100644 index 000000000..306a03052 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/AuthenticationConfiguration.java @@ -0,0 +1,18 @@ +package eu.eudat.service.remotefetcher.config.entities; + +import eu.eudat.commons.enums.ReferenceTypeExternalApiHTTPMethodType; + +public interface AuthenticationConfiguration { + + Boolean getEnabled(); + + String getAuthUrl(); + + ReferenceTypeExternalApiHTTPMethodType getAuthMethod(); + + String getAuthTokenPath(); + + String getAuthRequestBody(); + + String getType(); +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/DatasetUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/DatasetUrls.java deleted file mode 100644 index 7bd5310e8..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/DatasetUrls.java +++ /dev/null @@ -1,33 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - - -public class DatasetUrls extends GenericUrls{ - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/FunderUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/FunderUrls.java deleted file mode 100644 index cfc3efb8e..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/FunderUrls.java +++ /dev/null @@ -1,33 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - -public class FunderUrls extends GenericUrls{ - - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GeneralUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GeneralUrls.java deleted file mode 100644 index cf1094605..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GeneralUrls.java +++ /dev/null @@ -1,31 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import java.util.ArrayList; -import java.util.List; - -public class GeneralUrls extends GenericUrls { - - List urls; - FetchStrategy fetchMode; - - public GeneralUrls() { - this.urls = new ArrayList<>(); - } - - @Override - public List getUrls() { - return urls; - } - - @Override - public FetchStrategy getFetchMode() { - return fetchMode; - } - - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GenericUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GenericUrls.java index a350e9964..7c8d0e13a 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GenericUrls.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GenericUrls.java @@ -1,12 +1,13 @@ package eu.eudat.service.remotefetcher.config.entities; import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; import java.util.List; public abstract class GenericUrls { - public abstract List getUrls(); + public abstract List getUrls(); public abstract FetchStrategy getFetchMode(); } + + diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GrantUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GrantUrls.java deleted file mode 100644 index dff4148e2..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/GrantUrls.java +++ /dev/null @@ -1,35 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - - -public class GrantUrls extends GenericUrls{ - - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } - -} \ No newline at end of file diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/JournalUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/JournalUrls.java deleted file mode 100644 index ba2a7d2a1..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/JournalUrls.java +++ /dev/null @@ -1,34 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - -public class JournalUrls extends GenericUrls{ - - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } - -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/LicenseUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/LicenseUrls.java deleted file mode 100644 index 4cce39881..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/LicenseUrls.java +++ /dev/null @@ -1,33 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - - -public class LicenseUrls extends GenericUrls{ - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/OrganisationUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/OrganisationUrls.java deleted file mode 100644 index dbb0e8909..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/OrganisationUrls.java +++ /dev/null @@ -1,34 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - -public class OrganisationUrls extends GenericUrls{ - - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } - -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PrefillingSearch.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PrefillingSearch.java index 29f448e8c..74f88052e 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PrefillingSearch.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PrefillingSearch.java @@ -20,8 +20,8 @@ public class PrefillingSearch extends GenericUrls { } @Override - public List getUrls() { - List urls = new ArrayList<>(); + public List getUrls() { + List urls = new ArrayList<>(); urls.add(urlConfig); return urls; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ProjectUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ProjectUrls.java deleted file mode 100644 index 5695fa678..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ProjectUrls.java +++ /dev/null @@ -1,33 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - -public class ProjectUrls extends GenericUrls{ - - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PubRepositoryUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PubRepositoryUrls.java deleted file mode 100644 index 762cc4c27..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PubRepositoryUrls.java +++ /dev/null @@ -1,34 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - -public class PubRepositoryUrls extends GenericUrls{ - - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } - -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PublicationsUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PublicationsUrls.java deleted file mode 100644 index 7a1c8ceea..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/PublicationsUrls.java +++ /dev/null @@ -1,34 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - -public class PublicationsUrls extends GenericUrls{ - - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } - -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/QueryConfig.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/QueryConfig.java new file mode 100644 index 000000000..4d8b7cd4c --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/QueryConfig.java @@ -0,0 +1,11 @@ +package eu.eudat.service.remotefetcher.config.entities; + +public interface QueryConfig { + String getCondition(); + + String getSeparator(); + + String getValue(); + + Integer getOrdinal(); +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/RegistryUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/RegistryUrls.java deleted file mode 100644 index d27893d83..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/RegistryUrls.java +++ /dev/null @@ -1,35 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - -public class RegistryUrls extends GenericUrls{ - - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } - - -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/RepositoryUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/RepositoryUrls.java deleted file mode 100644 index d4b0ffec8..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/RepositoryUrls.java +++ /dev/null @@ -1,34 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - -public class RepositoryUrls extends GenericUrls { - - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } - -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResearcherUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResearcherUrls.java deleted file mode 100644 index ec78860f5..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResearcherUrls.java +++ /dev/null @@ -1,35 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - -public class ResearcherUrls extends GenericUrls{ - - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } - - -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResultFieldsMappingConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResultFieldsMappingConfiguration.java new file mode 100644 index 000000000..0d57682d5 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResultFieldsMappingConfiguration.java @@ -0,0 +1,6 @@ +package eu.eudat.service.remotefetcher.config.entities; + +public interface ResultFieldsMappingConfiguration { + String getResponsePath(); + String getCode(); +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResultsConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResultsConfiguration.java new file mode 100644 index 000000000..f731d3295 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ResultsConfiguration.java @@ -0,0 +1,9 @@ +package eu.eudat.service.remotefetcher.config.entities; + +import java.util.List; + +public interface ResultsConfiguration { + String getResultsArrayPath(); + + List getFieldsMapping(); +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ServiceUrls.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ServiceUrls.java deleted file mode 100644 index 49513761e..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/ServiceUrls.java +++ /dev/null @@ -1,35 +0,0 @@ -package eu.eudat.service.remotefetcher.config.entities; - -import eu.eudat.service.remotefetcher.criteria.FetchStrategy; -import eu.eudat.service.remotefetcher.config.UrlConfiguration; - -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import java.util.List; - -public class ServiceUrls extends GenericUrls{ - - List urls; - FetchStrategy fetchMode; - - public List getUrls() { - return urls; - } - - @XmlElementWrapper - @XmlElement(name = "urlConfig") - public void setUrls(List urls) { - this.urls = urls; - } - - public FetchStrategy getFetchMode() { - return fetchMode; - } - - @XmlElement(name = "fetchMode") - public void setFetchMode(FetchStrategy fetchMode) { - this.fetchMode = fetchMode; - } - - -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceBaseConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceBaseConfiguration.java new file mode 100644 index 000000000..af3af135f --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceBaseConfiguration.java @@ -0,0 +1,10 @@ +package eu.eudat.service.remotefetcher.config.entities; + +import eu.eudat.commons.enums.ReferenceTypeSourceType; + +public interface SourceBaseConfiguration { + String getKey(); + String getLabel(); + Integer getOrdinal(); + ReferenceTypeSourceType getType(); +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceExternalApiConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceExternalApiConfiguration.java new file mode 100644 index 000000000..14359dd34 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceExternalApiConfiguration.java @@ -0,0 +1,29 @@ +package eu.eudat.service.remotefetcher.config.entities; + +import eu.eudat.commons.enums.ReferenceTypeExternalApiHTTPMethodType; + +import java.util.List; + +public interface SourceExternalApiConfiguration, AuthConfig extends AuthenticationConfiguration, QConfig extends QueryConfig> extends SourceBaseConfiguration { + String getUrl(); + + RsConfig getResults(); + + String getPaginationPath(); + + String getContentType(); + + String getFirstPage(); + + ReferenceTypeExternalApiHTTPMethodType getHttpMethod(); + + String getRequestBody(); + + String getFilterType(); + + AuthConfig getAuth(); + + List getQueries(); +} + + diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceStaticOptionConfiguration.java b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceStaticOptionConfiguration.java new file mode 100644 index 000000000..d6d72adef --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/remotefetcher/config/entities/SourceStaticOptionConfiguration.java @@ -0,0 +1,7 @@ +package eu.eudat.service.remotefetcher.config.entities; + +import java.util.List; + +public interface SourceStaticOptionConfiguration