package eu.old.eudat.migration; import eu.eudat.commons.JsonHandlingService; import eu.eudat.commons.XmlHandlingService; import eu.eudat.commons.enums.DescriptionStatus; import eu.eudat.commons.enums.IsActive; import eu.eudat.commons.enums.ReferenceFieldDataType; import eu.eudat.commons.enums.ReferenceSourceType; import eu.eudat.commons.types.description.*; import eu.eudat.commons.types.descriptiontemplate.FieldSetEntity; import eu.eudat.commons.types.descriptiontemplate.fielddata.ReferenceTypeDataEntity; import eu.eudat.commons.types.dmpblueprint.DefinitionEntity; import eu.eudat.commons.types.externalfetcher.ExternalFetcherBaseSourceConfigurationEntity; import eu.eudat.commons.types.referencetype.ReferenceTypeDefinitionEntity; import eu.eudat.convention.ConventionService; import eu.eudat.data.*; import eu.eudat.model.Dmp; import eu.eudat.model.Reference; import eu.eudat.model.ReferenceType; import eu.eudat.query.*; import eu.old.eudat.data.dao.entities.DatasetDao; import eu.old.eudat.data.entities.Dataset; import eu.old.eudat.logic.services.operations.DatabaseRepository; import eu.old.eudat.models.data.user.components.datasetprofile.Field; import gr.cite.tools.data.query.QueryFactory; import gr.cite.tools.exception.MyApplicationException; import gr.cite.tools.fieldset.BaseFieldSet; import gr.cite.tools.logging.LoggerService; import jakarta.persistence.EntityManager; import jakarta.xml.bind.JAXBException; import org.json.JSONObject; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeParseException; import java.util.*; import java.util.stream.Collectors; @Service public class DatasetMigrationService { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpDatasetProfileMigrationService.class)); private final DatabaseRepository databaseRepository; private final JsonHandlingService jsonHandlingService; private final QueryFactory queryFactory; private final XmlHandlingService xmlHandlingService; private static final int PageSize = 500; private static final boolean TestMode = false; private final EntityManager entityManager; private final ConventionService conventionService; public DatasetMigrationService(DatabaseRepository databaseRepository, JsonHandlingService jsonHandlingService, QueryFactory queryFactory, XmlHandlingService xmlHandlingService, EntityManager entityManager, ConventionService conventionService) { this.databaseRepository = databaseRepository; this.jsonHandlingService = jsonHandlingService; this.queryFactory = queryFactory; this.xmlHandlingService = xmlHandlingService; this.entityManager = entityManager; this.conventionService = conventionService; } public void migrate() throws IOException, JAXBException, ParserConfigurationException, InstantiationException, IllegalAccessException, SAXException { DatasetDao datasetDao = databaseRepository.getDatasetDao(); long total = datasetDao.asQueryable().count(); logger.debug("Migrate Dataset Total : " + total); int page = 0; Map referenceTypeDefinitionEntityMap = new HashMap<>(); List referenceTypes = this.queryFactory.query(ReferenceTypeQuery.class).collectAs(new BaseFieldSet().ensure(ReferenceType._id).ensure(ReferenceType._definition)); for (ReferenceTypeEntity referenceType : referenceTypes){ referenceTypeDefinitionEntityMap.put(referenceType.getId(), this.xmlHandlingService.fromXml(ReferenceTypeDefinitionEntity.class, referenceType.getDefinition())); } Map referenceMap = new HashMap<>(); List references = this.queryFactory.query(ReferenceQuery.class).collectAs(new BaseFieldSet().ensure(Reference._id).ensure(Reference._source).ensure(Reference._type).ensure(Reference._reference)); for (ReferenceEntity reference : references){ if (reference.getCreatedById() == null) referenceMap.put(new ReferenceKey(reference), reference); } List items; do { items = datasetDao.asQueryable().orderBy((builder, root) -> builder.asc(root.get("created"))).orderBy((builder, root) -> builder.asc(root.get("ID"))).skip(page * PageSize).take(PageSize).toList(); if (items != null && !items.isEmpty()) { logger.debug("Migrate Dataset " + page * PageSize + " of " + total); List dmpBlueprints = this.queryFactory.query(DmpBlueprintQuery.class).ids(items.stream().map(x-> x.getDmp().getProfile().getId()).distinct().toList()).collect(); Map dmpBlueprintsMap = new HashMap<>(); for (DmpBlueprintEntity dmpBlueprint : dmpBlueprints) { DefinitionEntity definitionEntity = this.xmlHandlingService.fromXml(DefinitionEntity.class, dmpBlueprint.getDefinition()); dmpBlueprintsMap.put(dmpBlueprint.getId(), definitionEntity); } List dmpDescriptionTemplateEntities = this.queryFactory.query(DmpDescriptionTemplateQuery.class).dmpIds(items.stream().map(x-> x.getDmp().getId()).distinct().toList()).collect(); List descriptionTemplates = this.queryFactory.query(DescriptionTemplateQuery.class).ids(items.stream().map(x-> x.getProfile().getId()).distinct().toList()).collect(); Map creatorsByDmp = this.queryFactory.query(DmpQuery.class).ids(items.stream().map(x-> x.getDmp().getId()).distinct().toList()).collectAs(new BaseFieldSet().ensure(Dmp._id).ensure(Dmp._creator)).stream().collect(Collectors.toMap(DmpEntity::getId, DmpEntity::getCreatorId));; Map descriptionTemplateDefinitionMap = new HashMap<>(); for (DescriptionTemplateEntity descriptionTemplateEntity : descriptionTemplates){ descriptionTemplateDefinitionMap.put(descriptionTemplateEntity.getId(), this.xmlHandlingService.fromXml(eu.eudat.commons.types.descriptiontemplate.DefinitionEntity.class, descriptionTemplateEntity.getDefinition())); } for (Dataset item : items) { DefinitionEntity definition = dmpBlueprintsMap.getOrDefault(item.getDmp().getProfile().getId(), null); if (definition == null || definition.getSections() == null || definition.getSections().size() <= item.getDmpSectionIndex()) { logger.error("Migrate Dataset " + item.getId() + " cannot found section id for section " + item.getDmpSectionIndex()); throw new MyApplicationException("Migrate Dataset " + item.getId() + " cannot found section id for section " + item.getDmpSectionIndex()); } UUID sectionId = definition.getSections().get(item.getDmpSectionIndex()).getId(); if (sectionId == null) { logger.error("Migrate Dataset " + item.getId() + " cannot found section id for section " + item.getDmpSectionIndex()); throw new MyApplicationException("Migrate Dataset " + item.getId() + " cannot found section id for section " + item.getDmpSectionIndex()); } List itemDescriptionTemplates = this.getOrCreateDmpDescriptionTemplateEntity(item, sectionId, dmpDescriptionTemplateEntities); if (itemDescriptionTemplates.size() > 1) { logger.error("Migrate Dataset " + item.getId() + " multiple DmpDescriptionTemplateEntity for section " + item.getDmpSectionIndex()); //TODO CLEAN Duplicates dmp, DescriptionTemplate, SectionId } DescriptionEntity data = new DescriptionEntity(); data.setId(item.getId()); data.setDescription(item.getDescription()); if (item.getCreator() != null) { data.setCreatedById(item.getCreator().getId()); } else { data.setCreatedById(creatorsByDmp.getOrDefault(item.getDmp().getId(), null)); } data.setDmpId(item.getDmp().getId()); data.setLabel(item.getLabel()); data.setDmpDescriptionTemplateId(itemDescriptionTemplates.getFirst().getId()); data.setDescriptionTemplateId(item.getProfile().getId()); data.setCreatedAt(item.getCreated() != null ? item.getCreated().toInstant() : Instant.now()); data.setUpdatedAt(item.getModified() != null ? item.getModified().toInstant() : Instant.now()); if (item.getFinalizedAt() != null) data.setFinalizedAt(item.getFinalizedAt().toInstant()); if (item.getStatus() == 99) { data.setIsActive(IsActive.Inactive); data.setStatus(DescriptionStatus.Canceled); } else { data.setIsActive(IsActive.Active); data.setStatus(DescriptionStatus.of(item.getStatus())); } eu.eudat.commons.types.descriptiontemplate.DefinitionEntity descriptionTemplateDefinitionEntity = descriptionTemplateDefinitionMap.getOrDefault(item.getProfile().getId(), null); data.setProperties(this.jsonHandlingService.toJson(this.buildPropertyDefinitionEntity(item, descriptionTemplateDefinitionEntity, referenceTypeDefinitionEntityMap, referenceMap))); if (data.getCreatedById() == null){ logger.error("Migration skipped creator not found " + item.getId()); throw new MyApplicationException("Migration skipped creator not found " + item.getId()); } this.entityManager.persist(data); this.entityManager.flush(); } page++; } } while (items != null && !items.isEmpty() && !TestMode); throw new MyApplicationException(""); } private List getOrCreateDmpDescriptionTemplateEntity(Dataset item, UUID sectionId, List dmpDescriptionTemplateEntities){ List itemDescriptionTemplates = dmpDescriptionTemplateEntities.stream().filter(x-> x.getDescriptionTemplateGroupId().equals(item.getProfile().getGroupId()) && x.getDmpId().equals(item.getDmp().getId()) && x.getSectionId().equals(sectionId)).toList(); if (itemDescriptionTemplates.isEmpty()) { logger.error("Migrate Dataset " + item.getId() + " cannot found DmpDescriptionTemplateEntity for section " + item.getDmpSectionIndex()); if (dmpDescriptionTemplateEntities.stream().anyMatch(x -> x.getDmpId().equals(item.getDmp().getId()) && x.getSectionId().equals(sectionId))) { DmpDescriptionTemplateEntity dmpDescriptionTemplateEntity = new DmpDescriptionTemplateEntity(); dmpDescriptionTemplateEntity.setId(UUID.randomUUID()); dmpDescriptionTemplateEntity.setDescriptionTemplateGroupId(item.getProfile().getGroupId()); dmpDescriptionTemplateEntity.setDmpId(item.getDmp().getId()); dmpDescriptionTemplateEntity.setCreatedAt(item.getCreated() != null ? item.getCreated().toInstant() : Instant.now()); dmpDescriptionTemplateEntity.setUpdatedAt(item.getModified() != null ? item.getModified().toInstant() : Instant.now()); dmpDescriptionTemplateEntity.setSectionId(sectionId); dmpDescriptionTemplateEntity.setIsActive(IsActive.Active); this.entityManager.persist(dmpDescriptionTemplateEntity); itemDescriptionTemplates = List.of(dmpDescriptionTemplateEntity); } else { throw new MyApplicationException("Migrate Dataset " + item.getId() + " cannot found DmpDescriptionTemplateEntity for section " + item.getDmpSectionIndex()); } } return itemDescriptionTemplates; } private PropertyDefinitionEntity buildPropertyDefinitionEntity(Dataset item, eu.eudat.commons.types.descriptiontemplate.DefinitionEntity descriptionTemplateDefinitionEntity, Map referenceTypeDefinitionEntityMap, Map referenceMap) { if (this.conventionService.isNullOrEmpty(item.getProperties())) return null; JSONObject jObject = new JSONObject(item.getProperties()); Map properties = jObject.toMap(); PropertyDefinitionEntity propertyDefinitionEntity = new PropertyDefinitionEntity(); propertyDefinitionEntity.setFieldSets(new HashMap<>()); List fieldSetEntities = descriptionTemplateDefinitionEntity.getAllFieldSets(); for (String key : properties.keySet()) { if (key.toLowerCase(Locale.ROOT).trim().startsWith("commentfieldvalue")){ if (properties.get(key) != null && this.conventionService.isNullOrEmpty(properties.get(key).toString())) { continue; } FieldSetEntity currentFieldSet = fieldSetEntities.stream().filter(x-> x.getId().equals(key.trim().substring("commentfieldvalue".length()))).findFirst().orElse(null); if (currentFieldSet == null) { logger.error("Field set " + key + " not found for comment " + properties.get(key).toString()); continue; } this.addSimpleCommentField(propertyDefinitionEntity, currentFieldSet, properties.get(key).toString()); } else { if (!key.toLowerCase(Locale.ROOT).trim().startsWith("multiple_")) { FieldSetEntity currentFieldSet = null; eu.eudat.commons.types.descriptiontemplate.FieldEntity currentField = null; for (FieldSetEntity fieldSetEntity : fieldSetEntities) { List fieldEntities = fieldSetEntity.getFieldById(key.trim()); if (!fieldEntities.isEmpty()) { currentFieldSet = fieldSetEntity; currentField = fieldEntities.getFirst(); } } if (currentField == null) { logger.error("Field set not found for field " + key + " " + properties.get(key).toString()); continue; } this.addSimpleField(propertyDefinitionEntity, currentFieldSet, currentField, properties, referenceTypeDefinitionEntityMap, referenceMap); } } } this.addMultipleField(properties, descriptionTemplateDefinitionEntity, propertyDefinitionEntity, referenceTypeDefinitionEntityMap, referenceMap); for (PropertyDefinitionFieldSetEntity fieldSetEntity : propertyDefinitionEntity.getFieldSets().values()){ int newOrdinal = 0; for (PropertyDefinitionFieldSetItemEntity propertyDefinitionFieldSetItemEntity : fieldSetEntity.getItems().stream().filter(x-> x.getOrdinal() >= 0).sorted(Comparator.comparingInt(PropertyDefinitionFieldSetItemEntity::getOrdinal)).toList()){ propertyDefinitionFieldSetItemEntity.setOrdinal(newOrdinal); newOrdinal++; } for (PropertyDefinitionFieldSetItemEntity propertyDefinitionFieldSetItemEntity : fieldSetEntity.getItems().stream().filter(x-> x.getOrdinal() < 0).sorted(Comparator.comparingInt(PropertyDefinitionFieldSetItemEntity::getOrdinal)).toList()){ propertyDefinitionFieldSetItemEntity.setOrdinal(newOrdinal); newOrdinal++; } } return propertyDefinitionEntity; } private void addMultipleField(Map properties, eu.eudat.commons.types.descriptiontemplate.DefinitionEntity descriptionTemplateDefinitionEntity, PropertyDefinitionEntity propertyDefinitionEntity, Map referenceTypeDefinitionEntityMap, Map referenceMap){ Map groupOrdinalMapping = new HashMap<>(); for (String key : properties.keySet()) { if (key.trim().toLowerCase(Locale.ROOT).startsWith("multiple_")) { String newKey = key.trim().substring("multiple_".length()); String[] keyParts = newKey.split("_", 4); String fieldSetId = ""; String groupId = ""; int ordinal = Integer.MIN_VALUE; String fieldId = ""; if (keyParts.length == 4) { fieldSetId = keyParts[0].trim(); groupId = keyParts[1].trim(); fieldId = keyParts[3].trim(); } else if (keyParts.length == 3) { fieldSetId = keyParts[0].trim(); groupId = keyParts[1].trim(); fieldId = keyParts[2].trim(); } else { logger.error("Field group key has invalid format " + key + " " + properties.get(key).toString()); continue; } try { if (keyParts.length == 4) ordinal = Integer.parseInt(keyParts[2].trim()); } catch (Exception e){ logger.error("Field group key has invalid format " + key + " " + properties.get(key).toString()); continue; } eu.eudat.commons.types.descriptiontemplate.FieldEntity currentField = descriptionTemplateDefinitionEntity.getFieldById(fieldId).stream().findFirst().orElse(null); if (currentField == null) { logger.error("Field set not found for field " + key + " " + properties.get(key).toString()); continue; } PropertyDefinitionFieldSetEntity propertyDefinitionFieldSetEntity = propertyDefinitionEntity.getFieldSets().getOrDefault(fieldSetId, null); if (propertyDefinitionFieldSetEntity == null) { propertyDefinitionFieldSetEntity = new PropertyDefinitionFieldSetEntity(); propertyDefinitionFieldSetEntity.setItems(new ArrayList<>()); propertyDefinitionEntity.getFieldSets().put(fieldId, propertyDefinitionFieldSetEntity); } if (ordinal == Integer.MIN_VALUE) { if (groupOrdinalMapping.containsKey(new MultipleFieldKey(fieldSetId, groupId))){ ordinal = groupOrdinalMapping.get(new MultipleFieldKey(fieldSetId, groupId)); } else { ordinal = propertyDefinitionFieldSetEntity.getItems().stream().filter(x-> !x.getFields().isEmpty()).map(PropertyDefinitionFieldSetItemEntity::getOrdinal).min(Comparator.comparing(x -> x)).orElse(-1) - 1; ordinal = Math.min(ordinal, -1); } } if (!groupOrdinalMapping.containsKey(new MultipleFieldKey(fieldSetId, groupId))){ groupOrdinalMapping.put(new MultipleFieldKey(fieldSetId, groupId), ordinal); } else { if (groupOrdinalMapping.get(new MultipleFieldKey(fieldSetId, groupId)) != ordinal) throw new MyApplicationException("Invalid multiple key ordinal " + key); } this.addMultipleField(propertyDefinitionFieldSetEntity, ordinal, currentField, properties, referenceTypeDefinitionEntityMap, referenceMap); } } } private void addMultipleField(PropertyDefinitionFieldSetEntity propertyDefinitionFieldSetEntity, int ordinal, eu.eudat.commons.types.descriptiontemplate.FieldEntity currentField, Map properties, Map referenceTypeDefinitionEntityMap, Map referenceMap){ PropertyDefinitionFieldSetItemEntity propertyDefinitionFieldSetItemEntity = propertyDefinitionFieldSetEntity.getItems().stream().filter(x-> x.getOrdinal() == ordinal).findFirst().orElse(null); if (propertyDefinitionFieldSetItemEntity == null){ propertyDefinitionFieldSetItemEntity = new PropertyDefinitionFieldSetItemEntity(); propertyDefinitionFieldSetItemEntity.setFields(new HashMap<>()); propertyDefinitionFieldSetItemEntity.setOrdinal(ordinal); propertyDefinitionFieldSetEntity.getItems().add(propertyDefinitionFieldSetItemEntity); } propertyDefinitionFieldSetItemEntity.getFields().put(currentField.getId(), this.buildField(currentField, properties, referenceTypeDefinitionEntityMap, referenceMap)); } private void addSimpleField(PropertyDefinitionEntity propertyDefinitionEntity, FieldSetEntity currentFieldSet, eu.eudat.commons.types.descriptiontemplate.FieldEntity currentField, Map properties, Map referenceTypeDefinitionEntityMap, Map referenceMap){ PropertyDefinitionFieldSetEntity propertyDefinitionFieldSetEntity = propertyDefinitionEntity.getFieldSets().getOrDefault(currentFieldSet.getId(), null); if (propertyDefinitionFieldSetEntity == null) { propertyDefinitionFieldSetEntity = new PropertyDefinitionFieldSetEntity(); propertyDefinitionFieldSetEntity.setItems(new ArrayList<>()); propertyDefinitionEntity.getFieldSets().put(currentFieldSet.getId(), propertyDefinitionFieldSetEntity); } PropertyDefinitionFieldSetItemEntity propertyDefinitionFieldSetItemEntity = null; if (this.conventionService.isListNullOrEmpty(propertyDefinitionFieldSetEntity.getItems())){ propertyDefinitionFieldSetItemEntity = new PropertyDefinitionFieldSetItemEntity(); propertyDefinitionFieldSetItemEntity.setFields(new HashMap<>()); propertyDefinitionFieldSetItemEntity.setOrdinal(0); propertyDefinitionFieldSetEntity.getItems().add(propertyDefinitionFieldSetItemEntity); } else { propertyDefinitionFieldSetItemEntity = propertyDefinitionFieldSetEntity.getItems().getFirst(); } propertyDefinitionFieldSetItemEntity.getFields().put(currentField.getId(), this.buildField(currentField, properties, referenceTypeDefinitionEntityMap, referenceMap)); } private void addSimpleCommentField(PropertyDefinitionEntity propertyDefinitionEntity, FieldSetEntity currentFieldSet, String comment){ PropertyDefinitionFieldSetEntity propertyDefinitionFieldSetEntity = propertyDefinitionEntity.getFieldSets().getOrDefault(currentFieldSet.getId(), null); if (propertyDefinitionFieldSetEntity == null) { propertyDefinitionFieldSetEntity = new PropertyDefinitionFieldSetEntity(); propertyDefinitionFieldSetEntity.setItems(new ArrayList<>()); propertyDefinitionEntity.getFieldSets().put(currentFieldSet.getId(), propertyDefinitionFieldSetEntity); } PropertyDefinitionFieldSetItemEntity propertyDefinitionFieldSetItemEntity = null; if (this.conventionService.isListNullOrEmpty(propertyDefinitionFieldSetEntity.getItems())){ propertyDefinitionFieldSetItemEntity = new PropertyDefinitionFieldSetItemEntity(); propertyDefinitionFieldSetItemEntity.setFields(new HashMap<>()); propertyDefinitionFieldSetItemEntity.setOrdinal(0); propertyDefinitionFieldSetEntity.getItems().add(propertyDefinitionFieldSetItemEntity); } else { propertyDefinitionFieldSetItemEntity = propertyDefinitionFieldSetEntity.getItems().getFirst(); } propertyDefinitionFieldSetItemEntity.setComment(comment); } private FieldEntity buildField(eu.eudat.commons.types.descriptiontemplate.FieldEntity currentField, Map properties, Map referenceTypeDefinitionEntityMap, Map referenceMap){ FieldEntity fieldEntity = new FieldEntity(); String textValue = properties.get(currentField.getId()) != null ? properties.get(currentField.getId()).toString() : null; if (textValue == null || textValue.isEmpty()) return fieldEntity; switch (currentField.getData().getFieldType()){ case FREE_TEXT, TEXT_AREA, RICH_TEXT_AREA, RADIO_BOX -> fieldEntity.setTextValue(textValue.trim()); case CHECK_BOX, BOOLEAN_DECISION -> fieldEntity.setTextValue(textValue.trim().toLowerCase(Locale.ROOT)); case DATE_PICKER -> { Instant instant = null; if(!this.conventionService.isNullOrEmpty(textValue)) { try { instant = Instant.parse(textValue); } catch (DateTimeParseException ex) { instant = LocalDate.parse(textValue).atStartOfDay().toInstant(ZoneOffset.UTC); } } fieldEntity.setDateValue(instant); } case SELECT -> { if(!this.conventionService.isNullOrEmpty(textValue)) { String[] valuesParsed = this.jsonHandlingService.fromJsonSafe(String[].class, textValue); if (valuesParsed == null) valuesParsed = this.jsonHandlingService.fromJsonSafe(String[].class, this.cleanAsObjectString(textValue)); fieldEntity.setTextListValue(valuesParsed == null ? List.of(textValue) : Arrays.stream(valuesParsed).toList()); } } case DATASET_IDENTIFIER, VALIDATION -> { if(!this.conventionService.isNullOrEmpty(textValue)) { ExternalIdentifierEntity externalIdentifierEntity = this.jsonHandlingService.fromJsonSafe(ExternalIdentifierEntity.class, textValue); if (externalIdentifierEntity == null) externalIdentifierEntity = this.jsonHandlingService.fromJsonSafe(ExternalIdentifierEntity.class, this.cleanAsObjectString(textValue)); if (externalIdentifierEntity == null) throw new MyApplicationException("Could not parse dataset External Identifier : " + textValue); fieldEntity.setExternalIdentifier(externalIdentifierEntity); } } case UPLOAD -> { if(!this.conventionService.isNullOrEmpty(textValue)) { Map valuesParsed = this.jsonHandlingService.fromJsonSafe(Map.class, textValue); if (valuesParsed == null) { valuesParsed = (Map) properties.get(currentField.getId()); } if (valuesParsed == null) valuesParsed = this.jsonHandlingService.fromJsonSafe(Map.class, this.cleanAsObjectString(textValue)); if (valuesParsed == null) throw new MyApplicationException("Could not parse upload : " + textValue); String id = valuesParsed.getOrDefault("id", null); if (id == null) throw new MyApplicationException("Could not parse upload : " + textValue); fieldEntity.setTextValue(UUID.fromString(id).toString()); } } case CURRENCY -> { if(!this.conventionService.isNullOrEmpty(textValue)) { Currency currency = this.jsonHandlingService.fromJsonSafe(Currency.class, textValue); if (currency == null) currency = this.jsonHandlingService.fromJsonSafe(Currency.class, this.cleanAsObjectString(textValue)); if (currency == null && textValue.toUpperCase(Locale.ROOT).contains("EUR")) { currency = new Currency(); currency.setName("Euro"); currency.setValue("EUR"); } if (currency == null && textValue.toUpperCase(Locale.ROOT).contains("US DOLLAR")) { currency = new Currency(); currency.setName("US DOLLAR"); currency.setValue("USD"); } if (currency == null) throw new MyApplicationException("Could not parse Currency : " + textValue); //TODO: {"name":"Euro","value":"EUR"} what we want to keep ? fieldEntity.setTextValue(currency.getName()); } } case TAGS -> { if(!this.conventionService.isNullOrEmpty(textValue)) { Tag[] tags = this.jsonHandlingService.fromJsonSafe(Tag[].class, textValue); if (tags == null) tags = this.jsonHandlingService.fromJsonSafe(Tag[].class, this.cleanAsObjectString(textValue)); if (tags == null) { Tag tag = this.jsonHandlingService.fromJsonSafe(Tag.class, textValue); if (tag == null) tag = this.jsonHandlingService.fromJsonSafe(Tag.class, this.cleanAsObjectString(textValue)); if (tag != null) tags = List.of(tag).toArray(Tag[]::new); } if (tags == null) { //throw new MyApplicationException("Could not parse tag : " + textValue); //TODO logger.error("Could not parse tag : " + textValue); break; } fieldEntity.setTextListValue(Arrays.stream(tags).toList().stream().map(Tag::getName).toList()); } } case INTERNAL_ENTRIES_DMPS -> throw new MyApplicationException("Found INTERNAL_ENTRIES_DMPS into description"); case INTERNAL_ENTRIES_DESCRIPTIONS -> throw new MyApplicationException("Found INTERNAL_ENTRIES_DMPS into description"); case REFERENCE_TYPES -> { if(!this.conventionService.isNullOrEmpty(textValue)) { //TODO Map[] references = this.jsonHandlingService.fromJsonSafe(Map[].class, textValue); if (references == null) references = this.jsonHandlingService.fromJsonSafe(Map[].class, this.cleanAsObjectString(textValue)); if (references == null) { Map reference = this.jsonHandlingService.fromJsonSafe(Map.class, textValue); if (reference == null) reference = this.jsonHandlingService.fromJsonSafe(Map.class, this.cleanAsObjectString(textValue)); if (reference != null) references = List.of(reference).toArray(Map[]::new); } if (references == null){ logger.warn("Could not parse reference : " + textValue); //throw new MyApplicationException("Could not parse reference : " + textValue); break; } ReferenceTypeDataEntity referenceTypeDataEntity = (ReferenceTypeDataEntity)currentField.getData(); if (referenceTypeDataEntity == null) throw new MyApplicationException("Could not parse description template reference : " + textValue); fieldEntity.setTextListValue(new ArrayList<>()); for (Map item : references){ ReferenceEntity referenceEntity = this.geReferenceEntity(item, referenceTypeDefinitionEntityMap, referenceTypeDataEntity, textValue, referenceMap); fieldEntity.getTextListValue().add(referenceEntity.getId().toString()); } } } } return fieldEntity; } private ReferenceEntity geReferenceEntity(Map item, Map referenceTypeDefinitionEntityMap, ReferenceTypeDataEntity referenceTypeDataEntity, String textValue, Map referenceMap){ ReferenceTypeDefinitionEntity referenceTypeDefinition = referenceTypeDefinitionEntityMap.getOrDefault(referenceTypeDataEntity.getReferenceTypeId(), null); if (referenceTypeDefinition == null) throw new MyApplicationException("Could not find reference type for reference : " + textValue); if (this.conventionService.isListNullOrEmpty(referenceTypeDefinition.getSources())) throw new MyApplicationException("Could not find reference source for reference : " + textValue); ReferenceEntity data = new ReferenceEntity(); if (item.containsKey("name")) data.setLabel((String) item.get("name")); if (this.conventionService.isNullOrEmpty(data.getLabel()) && item.containsKey("label")) data.setLabel((String) item.get("label")); if (item.containsKey("abbreviation")) data.setAbbreviation((String) item.get("abbreviation")); if (item.containsKey("id")) data.setReference((String)item.get("id")); if (item.containsKey("reference")) data.setReference((String)item.get("reference")); if (this.conventionService.isNullOrEmpty(data.getReference()) && item.containsKey("pid")) data.setReference((String)item.get("pid")); data.setId(UUID.randomUUID()); data.setCreatedAt(Instant.now()); data.setUpdatedAt(Instant.now()); data.setSourceType(ReferenceSourceType.External); data.setTypeId(referenceTypeDataEntity.getReferenceTypeId()); data.setIsActive(IsActive.Active); eu.eudat.commons.types.reference.DefinitionEntity definitionEntity = new eu.eudat.commons.types.reference.DefinitionEntity(); definitionEntity.setFields(new ArrayList<>()); for (Map.Entry entries : item.entrySet()){ if (entries.getValue() != null && !entries.getKey().equals("name") && !entries.getKey().equals("label")&& !entries.getKey().equals("abbreviation") && !entries.getKey().equals("id") && !entries.getKey().equals("pid")&& !entries.getKey().equals("source")) { eu.eudat.commons.types.reference.FieldEntity field = new eu.eudat.commons.types.reference.FieldEntity(); field.setCode(entries.getKey()); field.setDataType(ReferenceFieldDataType.Text); field.setValue(entries.getValue().toString()); definitionEntity.getFields().add(field); } } if (!this.conventionService.isListNullOrEmpty(definitionEntity.getFields())) data.setDefinition(this.xmlHandlingService.toXmlSafe(definitionEntity)); if (this.conventionService.isNullOrEmpty(data.getLabel())) data.setLabel(data.getReference()); if (referenceTypeDefinition.getSources().size() == 1) data.setSource(referenceTypeDefinition.getSources().getFirst().getKey()); else { String key = referenceTypeDefinition.getSources().stream().filter(x-> x.getKey().equalsIgnoreCase((String) item.getOrDefault("source", null))).map(ExternalFetcherBaseSourceConfigurationEntity::getKey).findFirst().orElse(null); if (this.conventionService.isNullOrEmpty(key)) { logger.warn("Select first source for reference : " + textValue); data.setSourceType(ReferenceSourceType.Internal); data.setSource(referenceTypeDefinition.getSources().getFirst().getKey()); //throw new MyApplicationException("Could not find reference source for reference : " + textValue); //TODO } else { data.setSource(key); } } if (this.conventionService.isNullOrEmpty(data.getReference())) { data.setReference(this.queryFactory.query(ReferenceQuery.class).sources(data.getSource()).like(data.getLabel()).typeIds(data.getTypeId()).collectAs(new BaseFieldSet().ensure(Reference._reference, Reference._label)) .stream().filter(x-> x.getLabel().equals(data.getLabel())).map(ReferenceEntity::getReference).findFirst().orElse(null));//TODO } if (this.conventionService.isNullOrEmpty(data.getReference())) { logger.warn("Local reference created with random id" + textValue); data.setReference(data.getId().toString().replace("-", "")); data.setSourceType(ReferenceSourceType.Internal); //TODO } ReferenceEntity existingEntity = referenceMap.getOrDefault(new ReferenceKey(data), null); if(existingEntity == null){ referenceMap.put(new ReferenceKey(data), data); this.entityManager.persist(data); return data; } else { return existingEntity; } } private String cleanAsObjectString(String value){ value = value.trim().replace("\\", ""); value = value.trim().replace("[\"{", "[{"); value = value.trim().replace("}\"]", "}]"); value = value.trim().replace("}\", \"{", "}, {"); value = value.trim().replace("}\",\"{", "},{"); while (!this.conventionService.isNullOrEmpty(value) && value.startsWith("\"")) value = value.substring(1); while (!this.conventionService.isNullOrEmpty(value) && value.endsWith("\"")) value = value.substring(0, value.length() - 1); return value; } public static class Currency{ private String name; private String value; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } public static class Tag{ private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static class MultipleFieldKey{ private final String fieldSetId; private final String groupKey; private final int hashCode; public MultipleFieldKey(String fieldSetId, String groupKey) { this.fieldSetId = fieldSetId; this.groupKey = groupKey; this.hashCode = Objects.hash(this.fieldSetId, this.groupKey); } public String getFieldSetId() { return fieldSetId; } public String getGroupKey() { return groupKey; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MultipleFieldKey that = (MultipleFieldKey) o; return Objects.equals(fieldSetId, that.getFieldSetId()) && Objects.equals(groupKey, that.getGroupKey()); } @Override public int hashCode() { return this.hashCode; } } public static class ReferenceKey { private final UUID type; private final String source; private final String reference; private final int hashCode; public ReferenceKey(ReferenceEntity reference) { this.type = reference.getTypeId(); this.source = reference.getSource().trim(); this.reference = reference.getReference().trim(); hashCode = Objects.hash(this.type, this.source, this.reference); } public UUID getType() { return type; } public String getSource() { return source; } public String getReference() { return reference; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ReferenceKey that = (ReferenceKey) o; return Objects.equals(type, that.getType()) && Objects.equals(source, that.getSource()) && Objects.equals(reference, that.getReference()); } @Override public int hashCode() { return this.hashCode; } } }