Search in sources :

Example 26 with InvalidColumnException

use of de.symeda.sormas.api.importexport.InvalidColumnException in project SORMAS-Project by hzi-braunschweig.

the class EventParticipantImporter method importDataFromCsvLine.

@Override
protected ImportLineResult importDataFromCsvLine(String[] values, String[] entityClasses, String[] entityProperties, String[][] entityPropertyPaths, boolean firstLine) throws IOException, InterruptedException {
    // Check whether the new line has the same length as the header line
    if (values.length > entityProperties.length) {
        writeImportError(values, I18nProperties.getValidationError(Validations.importLineTooLong));
        return ImportLineResult.ERROR;
    }
    // regenerate the UUID to prevent overwrite in case of export and import of the same entities
    int uuidIndex = ArrayUtils.indexOf(entityProperties, EventParticipantDto.UUID);
    if (uuidIndex >= 0) {
        values[uuidIndex] = DataHelper.createUuid();
    }
    int personUuidIndex = ArrayUtils.indexOf(entityProperties, String.join(".", EventParticipantDto.PERSON, PersonDto.UUID));
    if (personUuidIndex >= 0) {
        values[personUuidIndex] = DataHelper.createUuid();
    }
    final PersonDto newPersonTemp = PersonDto.buildImportEntity();
    final EventParticipantDto newEventParticipantTemp = EventParticipantDto.build(event.toReference(), currentUser.toReference());
    newEventParticipantTemp.setPerson(newPersonTemp);
    final List<VaccinationDto> vaccinations = new ArrayList<>();
    ImportRelatedObjectsMapper.Builder relatedObjectsMapperBuilder = new ImportRelatedObjectsMapper.Builder();
    if (FacadeProvider.getFeatureConfigurationFacade().isPropertyValueTrue(FeatureType.IMMUNIZATION_MANAGEMENT, FeatureTypeProperty.REDUCED) && event.getDisease() != null) {
        relatedObjectsMapperBuilder.addMapper(VaccinationDto.class, vaccinations, () -> VaccinationDto.build(currentUser.toReference()), this::insertColumnEntryIntoRelatedObject);
    }
    ImportRelatedObjectsMapper relatedMapper = relatedObjectsMapperBuilder.build();
    boolean eventParticipantHasImportError = insertRowIntoData(values, entityClasses, entityPropertyPaths, true, importColumnInformation -> {
        try {
            if (!relatedMapper.map(importColumnInformation)) {
                // If the cell entry is not empty, try to insert it into the current contact or person object
                if (!StringUtils.isEmpty(importColumnInformation.getValue())) {
                    insertColumnEntryIntoData(newEventParticipantTemp, newPersonTemp, importColumnInformation.getValue(), importColumnInformation.getEntityPropertyPath());
                }
            }
        } catch (ImportErrorException | InvalidColumnException e) {
            return e;
        }
        return null;
    });
    // If the row does not have any import errors, call the backend validation of all associated entities
    if (!eventParticipantHasImportError) {
        try {
            personFacade.validate(newPersonTemp);
            eventParticipantFacade.validate(newEventParticipantTemp);
        } catch (ValidationRuntimeException e) {
            eventParticipantHasImportError = true;
            writeImportError(values, e.getMessage());
        }
    }
    PersonDto newPerson = newPersonTemp;
    // Sanitize non-HOME address
    PersonHelper.sanitizeNonHomeAddress(newPerson);
    // if there are any, display a window to resolve the conflict to the user
    if (!eventParticipantHasImportError) {
        EventParticipantDto newEventParticipant = newEventParticipantTemp;
        try {
            EventParticipantImportConsumer consumer = new EventParticipantImportConsumer();
            ImportSimilarityResultOption resultOption = null;
            EventParticipantImportLock personSelectLock = new EventParticipantImportLock();
            // We need to pause the current thread to prevent the import from continuing until the user has acted
            synchronized (personSelectLock) {
                // Call the logic that allows the user to handle the similarity; once this has been done, the LOCK should be notified
                // to allow the importer to resume
                handlePersonSimilarity(newPerson, result -> consumer.onImportResult(result, personSelectLock), (person, similarityResultOption) -> new PersonImportSimilarityResult(person, similarityResultOption), Strings.infoSelectOrCreatePersonForImport, currentUI);
                try {
                    if (!personSelectLock.wasNotified) {
                        personSelectLock.wait();
                    }
                } catch (InterruptedException e) {
                    logger.error("InterruptedException when trying to perform LOCK.wait() in eventparticipant import: " + e.getMessage());
                    throw e;
                }
                if (consumer.result != null) {
                    resultOption = consumer.result.getResultOption();
                }
                // If the user picked an existing person, override the eventparticipant person with it
                if (ImportSimilarityResultOption.PICK.equals(resultOption)) {
                    newPerson = personFacade.getPersonByUuid(consumer.result.getMatchingPerson().getUuid());
                    // get first eventparticipant for event and person
                    EventParticipantCriteria eventParticipantCriteria = new EventParticipantCriteria().withPerson(newPerson.toReference()).withEvent(event.toReference());
                    EventParticipantDto pickedEventParticipant = eventParticipantFacade.getFirst(eventParticipantCriteria);
                    if (pickedEventParticipant != null) {
                        // re-apply import on pickedEventParticipant
                        insertRowIntoData(values, entityClasses, entityPropertyPaths, true, importColumnInformation -> {
                            // If the cell entry is not empty, try to insert it into the current contact or person object
                            if (!StringUtils.isEmpty(importColumnInformation.getValue())) {
                                try {
                                    insertColumnEntryIntoData(pickedEventParticipant, newPersonTemp, importColumnInformation.getValue(), importColumnInformation.getEntityPropertyPath());
                                } catch (ImportErrorException | InvalidColumnException e) {
                                    return e;
                                }
                            }
                            return null;
                        });
                        newEventParticipant = pickedEventParticipant;
                    }
                }
            }
            // or an existing person was picked, save the eventparticipant and person to the database
            if (ImportSimilarityResultOption.SKIP.equals(resultOption)) {
                return ImportLineResult.SKIPPED;
            } else {
                // Workaround: Reset the change date to avoid OutdatedEntityExceptions
                newPerson.setChangeDate(new Date());
                boolean skipPersonValidation = ImportSimilarityResultOption.PICK.equals(resultOption);
                final PersonDto savedPerson = personFacade.savePerson(newPerson, skipPersonValidation);
                newEventParticipant.setPerson(savedPerson);
                newEventParticipant.setChangeDate(new Date());
                eventParticipantFacade.saveEventParticipant(newEventParticipant);
                for (VaccinationDto vaccination : vaccinations) {
                    FacadeProvider.getVaccinationFacade().createWithImmunization(vaccination, newEventParticipant.getRegion(), newEventParticipant.getDistrict(), newEventParticipant.getPerson().toReference(), event.getDisease());
                }
                consumer.result = null;
                return ImportLineResult.SUCCESS;
            }
        } catch (ValidationRuntimeException e) {
            writeImportError(values, e.getMessage());
            return ImportLineResult.ERROR;
        }
    } else {
        return ImportLineResult.ERROR;
    }
}
Also used : ImportErrorException(de.symeda.sormas.api.importexport.ImportErrorException) PersonDto(de.symeda.sormas.api.person.PersonDto) ArrayList(java.util.ArrayList) EventParticipantDto(de.symeda.sormas.api.event.EventParticipantDto) VaccinationDto(de.symeda.sormas.api.vaccination.VaccinationDto) ValidationRuntimeException(de.symeda.sormas.api.utils.ValidationRuntimeException) Date(java.util.Date) InvalidColumnException(de.symeda.sormas.api.importexport.InvalidColumnException) ImportSimilarityResultOption(de.symeda.sormas.ui.importer.ImportSimilarityResultOption) EventParticipantCriteria(de.symeda.sormas.api.event.EventParticipantCriteria) ImportRelatedObjectsMapper(de.symeda.sormas.api.importexport.ImportRelatedObjectsMapper) PersonImportSimilarityResult(de.symeda.sormas.ui.importer.PersonImportSimilarityResult)

Example 27 with InvalidColumnException

use of de.symeda.sormas.api.importexport.InvalidColumnException in project SORMAS-Project by hzi-braunschweig.

the class EventImporterTest method testImportAllEvents.

@Test
public void testImportAllEvents() throws IOException, InvalidColumnException, InterruptedException, CsvValidationException, URISyntaxException {
    TestDataCreator creator = new TestDataCreator();
    TestDataCreator.RDCF rdcf = creator.createRDCF("Bourgogne-Franche-Comté", "Côte d'Or", "Dijon", "CHU Dijon Bourgogne");
    UserDto user = creator.createUser(rdcf.region.getUuid(), rdcf.district.getUuid(), rdcf.facility.getUuid(), "Surv", "Sup", UserRole.SURVEILLANCE_SUPERVISOR);
    // Successful import of 5 cases
    File csvFile = new File(getClass().getClassLoader().getResource("sormas_event_import_test_success.csv").toURI());
    EventImporterExtension eventImporter = new EventImporterExtension(csvFile, true, user);
    ImportResultStatus importResult = eventImporter.runImport();
    assertEquals(eventImporter.errors.toString(), ImportResultStatus.COMPLETED, importResult);
    assertEquals(4, getEventFacade().count(null));
    assertEquals(3, getPersonFacade().count(null));
    List<EventDto> events = getEventFacade().getAllAfter(null);
    Optional<EventDto> optionalEventWith2Participants = events.stream().filter(event -> "Event title with 2 participants".equals(event.getEventTitle())).findFirst();
    assertTrue(optionalEventWith2Participants.isPresent());
    optionalEventWith2Participants.ifPresent(event -> {
        List<EventParticipantDto> participants = getEventParticipantFacade().getAllActiveEventParticipantsByEvent(event.getUuid());
        assertEquals(2, participants.size());
    });
    // Similarity: skip
    csvFile = new File(getClass().getClassLoader().getResource("sormas_event_import_test_similarities.csv").toURI());
    eventImporter = new EventImporterExtension(csvFile, true, user) {

        @Override
        protected void handlePersonSimilarity(PersonDto newPerson, Consumer<PersonImportSimilarityResult> resultConsumer) {
            resultConsumer.accept(new PersonImportSimilarityResult(null, ImportSimilarityResultOption.SKIP));
        }
    };
    importResult = eventImporter.runImport();
    assertEquals(ImportResultStatus.COMPLETED, importResult);
    assertEquals(4, getEventFacade().count(null));
    assertEquals(3, getPersonFacade().count(null));
    // Similarity: pick
    List<SimilarPersonDto> persons = FacadeProvider.getPersonFacade().getSimilarPersonDtos(new PersonSimilarityCriteria());
    csvFile = new File(getClass().getClassLoader().getResource("sormas_event_import_test_similarities.csv").toURI());
    eventImporter = new EventImporterExtension(csvFile, true, user) {

        @Override
        protected void handlePersonSimilarity(PersonDto newPerson, Consumer<PersonImportSimilarityResult> resultConsumer) {
            List<SimilarPersonDto> entries = new ArrayList<>();
            for (SimilarPersonDto person : persons) {
                if (PersonHelper.areNamesSimilar(newPerson.getFirstName(), newPerson.getLastName(), person.getFirstName(), person.getLastName(), null)) {
                    entries.add(person);
                }
            }
            resultConsumer.accept(new PersonImportSimilarityResult(entries.get(0), ImportSimilarityResultOption.PICK));
        }
    };
    importResult = eventImporter.runImport();
    assertEquals(ImportResultStatus.COMPLETED, importResult);
    assertEquals(6, getEventFacade().count(null));
    assertEquals(3, getPersonFacade().count(null));
    // Similarity: cancel
    csvFile = new File(getClass().getClassLoader().getResource("sormas_event_import_test_similarities.csv").toURI());
    eventImporter = new EventImporterExtension(csvFile, true, user) {

        @Override
        protected void handlePersonSimilarity(PersonDto newPerson, Consumer<PersonImportSimilarityResult> resultConsumer) {
            resultConsumer.accept(new PersonImportSimilarityResult(null, ImportSimilarityResultOption.CANCEL));
        }
    };
    importResult = eventImporter.runImport();
    assertEquals(ImportResultStatus.CANCELED, importResult);
    assertEquals(6, getEventFacade().count(null));
    assertEquals(3, getPersonFacade().count(null));
    // Similarity: create
    csvFile = new File(getClass().getClassLoader().getResource("sormas_event_import_test_similarities.csv").toURI());
    eventImporter = new EventImporterExtension(csvFile, true, user) {

        @Override
        protected void handlePersonSimilarity(PersonDto newPerson, Consumer<PersonImportSimilarityResult> resultConsumer) {
            resultConsumer.accept(new PersonImportSimilarityResult(null, ImportSimilarityResultOption.CREATE));
        }
    };
    importResult = eventImporter.runImport();
    assertEquals(ImportResultStatus.COMPLETED, importResult);
    assertEquals(8, getEventFacade().count(null));
    assertEquals(6, getPersonFacade().count(null));
    // Successful import of 5 cases from a commented CSV file
    csvFile = new File(getClass().getClassLoader().getResource("sormas_event_import_test_comment_success.csv").toURI());
    eventImporter = new EventImporterExtension(csvFile, true, user);
    importResult = eventImporter.runImport();
    assertEquals(eventImporter.errors.toString(), ImportResultStatus.COMPLETED, importResult);
    assertEquals(10, getEventFacade().count(null));
}
Also used : FacadeProvider(de.symeda.sormas.api.FacadeProvider) ValueSeparator(de.symeda.sormas.api.importexport.ValueSeparator) URISyntaxException(java.net.URISyntaxException) RunWith(org.junit.runner.RunWith) EventParticipantDto(de.symeda.sormas.api.event.EventParticipantDto) PersonDto(de.symeda.sormas.api.person.PersonDto) InvalidColumnException(de.symeda.sormas.api.importexport.InvalidColumnException) ArrayList(java.util.ArrayList) StringBuilderWriter(org.apache.commons.io.output.StringBuilderWriter) PersonImportSimilarityResult(de.symeda.sormas.ui.importer.PersonImportSimilarityResult) UserRole(de.symeda.sormas.api.user.UserRole) Path(java.nio.file.Path) ImportResultStatus(de.symeda.sormas.ui.importer.ImportResultStatus) AbstractBeanTest(de.symeda.sormas.ui.AbstractBeanTest) CsvValidationException(com.opencsv.exceptions.CsvValidationException) UserDto(de.symeda.sormas.api.user.UserDto) ImportSimilarityResultOption(de.symeda.sormas.ui.importer.ImportSimilarityResultOption) SimilarPersonDto(de.symeda.sormas.api.person.SimilarPersonDto) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) EventDto(de.symeda.sormas.api.event.EventDto) PersonHelper(de.symeda.sormas.api.person.PersonHelper) File(java.io.File) EventImporter(de.symeda.sormas.ui.events.importer.EventImporter) Consumer(java.util.function.Consumer) List(java.util.List) Paths(java.nio.file.Paths) TestDataCreator(de.symeda.sormas.ui.TestDataCreator) Writer(java.io.Writer) Optional(java.util.Optional) PersonSimilarityCriteria(de.symeda.sormas.api.person.PersonSimilarityCriteria) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Assert.assertEquals(org.junit.Assert.assertEquals) PersonDto(de.symeda.sormas.api.person.PersonDto) SimilarPersonDto(de.symeda.sormas.api.person.SimilarPersonDto) UserDto(de.symeda.sormas.api.user.UserDto) EventDto(de.symeda.sormas.api.event.EventDto) EventParticipantDto(de.symeda.sormas.api.event.EventParticipantDto) PersonSimilarityCriteria(de.symeda.sormas.api.person.PersonSimilarityCriteria) SimilarPersonDto(de.symeda.sormas.api.person.SimilarPersonDto) TestDataCreator(de.symeda.sormas.ui.TestDataCreator) ImportResultStatus(de.symeda.sormas.ui.importer.ImportResultStatus) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) PersonImportSimilarityResult(de.symeda.sormas.ui.importer.PersonImportSimilarityResult) AbstractBeanTest(de.symeda.sormas.ui.AbstractBeanTest) Test(org.junit.Test)

Aggregations

InvalidColumnException (de.symeda.sormas.api.importexport.InvalidColumnException)27 ImportErrorException (de.symeda.sormas.api.importexport.ImportErrorException)26 ValidationRuntimeException (de.symeda.sormas.api.utils.ValidationRuntimeException)20 IntrospectionException (java.beans.IntrospectionException)16 InvocationTargetException (java.lang.reflect.InvocationTargetException)16 ArrayList (java.util.ArrayList)15 PropertyDescriptor (java.beans.PropertyDescriptor)11 IOException (java.io.IOException)11 ParseException (java.text.ParseException)11 List (java.util.List)11 CommunityReferenceDto (de.symeda.sormas.api.infrastructure.community.CommunityReferenceDto)9 DistrictReferenceDto (de.symeda.sormas.api.infrastructure.district.DistrictReferenceDto)9 CsvValidationException (com.opencsv.exceptions.CsvValidationException)8 FacilityReferenceDto (de.symeda.sormas.api.infrastructure.facility.FacilityReferenceDto)6 ImportCellData (de.symeda.sormas.api.importexport.ImportCellData)5 PersonDto (de.symeda.sormas.api.person.PersonDto)5 EventParticipantDto (de.symeda.sormas.api.event.EventParticipantDto)4 DataHelper (de.symeda.sormas.api.utils.DataHelper)4 Optional (java.util.Optional)4 FacadeProvider (de.symeda.sormas.api.FacadeProvider)3