Search in sources :

Example 21 with ImportErrorException

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

the class CampaignFormDataImporter method executeDefaultInvoke.

@Override
protected boolean executeDefaultInvoke(PropertyDescriptor pd, Object element, String entry, String[] entryHeaderPath) throws InvocationTargetException, IllegalAccessException, ImportErrorException {
    final boolean invokingSuccessful = super.executeDefaultInvoke(pd, element, entry, entryHeaderPath);
    final Class<?> propertyType = pd.getPropertyType();
    if (propertyType.isAssignableFrom(RegionReferenceDto.class)) {
        final UserDto currentUserDto = userFacade.getByUuid(currentUser.getUuid());
        final JurisdictionLevel jurisdictionLevel = UserRole.getJurisdictionLevel(currentUserDto.getUserRoles());
        if (jurisdictionLevel == JurisdictionLevel.REGION && !currentUserDto.getRegion().getCaption().equals(entry)) {
            throw new ImportErrorException(I18nProperties.getValidationError(Validations.importEntryRegionNotInUsersJurisdiction, entry, buildEntityProperty(entryHeaderPath)));
        }
    }
    return invokingSuccessful;
}
Also used : ImportErrorException(de.symeda.sormas.api.importexport.ImportErrorException) UserDto(de.symeda.sormas.api.user.UserDto) JurisdictionLevel(de.symeda.sormas.api.user.JurisdictionLevel)

Example 22 with ImportErrorException

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

the class CampaignFormDataImporter method importDataFromCsvLine.

@Override
protected ImportLineResult importDataFromCsvLine(String[] values, String[] entityClasses, String[] entityProperties, String[][] entityPropertyPaths, boolean firstLine) throws IOException, InterruptedException {
    if (values.length > entityProperties.length) {
        writeImportError(values, I18nProperties.getValidationError(Validations.importLineTooLong));
        return ImportLineResult.ERROR;
    }
    CampaignFormDataDto campaignFormData = CampaignFormDataDto.build();
    campaignFormData.setCreatingUser(userFacade.getCurrentUserAsReference());
    try {
        insertImportRowIntoData(campaignFormData, values, entityProperties);
        campaignFormData.setCampaign(campaignReferenceDto);
        CampaignFormDataDto existingData = FacadeProvider.getCampaignFormDataFacade().getExistingData(new CampaignFormDataCriteria().campaign(campaignFormData.getCampaign()).campaignFormMeta(campaignFormData.getCampaignFormMeta()).community(campaignFormData.getCommunity()).formDate(campaignFormData.getFormDate()));
        if (existingData != null) {
            final CampaignFormDataImportLock lock = new CampaignFormDataImportLock();
            synchronized (lock) {
                handleDetectedDuplicate(campaignFormData, existingData, lock);
                try {
                    if (!lock.wasNotified) {
                        lock.wait();
                    }
                } catch (InterruptedException e) {
                    logger.error("InterruptedException when trying to perform LOCK.wait() in campaign form data import: " + e.getMessage());
                    throw e;
                }
                if (lock.similarityChoice == CampaignFormDataSimilarityChoice.CANCEL) {
                    cancelImport();
                    return ImportLineResult.SKIPPED;
                } else if (lock.similarityChoice == CampaignFormDataSimilarityChoice.SKIP) {
                    return ImportLineResult.SKIPPED;
                } else {
                    FacadeProvider.getCampaignFormDataFacade().overwriteCampaignFormData(existingData, campaignFormData);
                }
            }
        } else {
            FacadeProvider.getCampaignFormDataFacade().saveCampaignFormData(campaignFormData);
        }
    } catch (ImportErrorException | InvalidColumnException | ValidationRuntimeException e) {
        writeImportError(values, e.getLocalizedMessage());
        return ImportLineResult.ERROR;
    }
    return ImportLineResult.SUCCESS;
}
Also used : CampaignFormDataDto(de.symeda.sormas.api.campaign.data.CampaignFormDataDto) ImportErrorException(de.symeda.sormas.api.importexport.ImportErrorException) InvalidColumnException(de.symeda.sormas.api.importexport.InvalidColumnException) CampaignFormDataCriteria(de.symeda.sormas.api.campaign.data.CampaignFormDataCriteria) ValidationRuntimeException(de.symeda.sormas.api.utils.ValidationRuntimeException)

Example 23 with ImportErrorException

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

the class CountryImporter method importDataFromCsvLine.

@Override
protected ImportLineResult importDataFromCsvLine(String[] values, String[] entityClasses, String[] entityProperties, String[][] entityPropertyPaths, boolean firstLine) throws IOException, InvalidColumnException {
    if (values.length > entityProperties.length) {
        writeImportError(values, I18nProperties.getValidationError(Validations.importLineTooLong));
        return ImportLineResult.ERROR;
    }
    CountryDto newEntityDto = CountryDto.build();
    boolean iHasImportError = insertRowIntoData(values, entityClasses, entityPropertyPaths, false, (cellData) -> {
        try {
            if (!StringUtils.isEmpty(cellData.getValue())) {
                insertColumnEntryIntoData(newEntityDto, cellData.getValue(), cellData.getEntityPropertyPath());
            }
        } catch (ImportErrorException | InvalidColumnException e) {
            return e;
        }
        return null;
    });
    if (!iHasImportError) {
        try {
            FacadeProvider.getCountryFacade().save(newEntityDto, allowOverwrite);
            return ImportLineResult.SUCCESS;
        } catch (EmptyValueException e) {
            writeImportError(values, e.getMessage());
            return ImportLineResult.ERROR;
        } catch (ValidationRuntimeException e) {
            writeImportError(values, e.getMessage());
            return ImportLineResult.DUPLICATE;
        }
    } else {
        return ImportLineResult.ERROR;
    }
}
Also used : ImportErrorException(de.symeda.sormas.api.importexport.ImportErrorException) CountryDto(de.symeda.sormas.api.infrastructure.country.CountryDto) InvalidColumnException(de.symeda.sormas.api.importexport.InvalidColumnException) EmptyValueException(de.symeda.sormas.api.utils.EmptyValueException) ValidationRuntimeException(de.symeda.sormas.api.utils.ValidationRuntimeException)

Example 24 with ImportErrorException

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

the class ContactImporter method insertColumnEntryIntoData.

/**
 * Inserts the entry of a single cell into the contact or its person.
 */
private void insertColumnEntryIntoData(ContactDto contact, PersonDto person, String entry, String[] entryHeaderPath) throws InvalidColumnException, ImportErrorException {
    Object currentElement = contact;
    for (int i = 0; i < entryHeaderPath.length; i++) {
        String headerPathElementName = entryHeaderPath[i];
        try {
            if (i != entryHeaderPath.length - 1) {
                currentElement = new PropertyDescriptor(headerPathElementName, currentElement.getClass()).getReadMethod().invoke(currentElement);
                // Set the current element to the created person
                if (currentElement instanceof PersonReferenceDto) {
                    currentElement = person;
                }
            } else if (ContactExportDto.BIRTH_DATE.equals(headerPathElementName)) {
                BirthDateDto birthDateDto = PersonHelper.parseBirthdate(entry, currentUser.getLanguage());
                if (birthDateDto != null) {
                    person.setBirthdateDD(birthDateDto.getDateOfBirthDD());
                    person.setBirthdateMM(birthDateDto.getDateOfBirthMM());
                    person.setBirthdateYYYY(birthDateDto.getDateOfBirthYYYY());
                }
            } else {
                PropertyDescriptor pd = new PropertyDescriptor(headerPathElementName, currentElement.getClass());
                Class<?> propertyType = pd.getPropertyType();
                // according to the types of the contact or person fields
                if (executeDefaultInvoke(pd, currentElement, entry, entryHeaderPath)) {
                    continue;
                } else if (propertyType.isAssignableFrom(DistrictReferenceDto.class)) {
                    List<DistrictReferenceDto> district = FacadeProvider.getDistrictFacade().getByName(entry, ImporterPersonHelper.getRegionBasedOnDistrict(pd.getName(), contact, person, currentElement), false);
                    if (district.isEmpty()) {
                        throw new ImportErrorException(I18nProperties.getValidationError(Validations.importEntryDoesNotExistDbOrRegion, entry, buildEntityProperty(entryHeaderPath)));
                    } else if (district.size() > 1) {
                        throw new ImportErrorException(I18nProperties.getValidationError(Validations.importDistrictNotUnique, entry, buildEntityProperty(entryHeaderPath)));
                    } else {
                        pd.getWriteMethod().invoke(currentElement, district.get(0));
                    }
                } else if (propertyType.isAssignableFrom(CommunityReferenceDto.class)) {
                    DistrictReferenceDto district = currentElement instanceof ContactDto ? ((ContactDto) currentElement).getDistrict() : (currentElement instanceof LocationDto ? ((LocationDto) currentElement).getDistrict() : null);
                    List<CommunityReferenceDto> community = FacadeProvider.getCommunityFacade().getByName(entry, district != null ? district : ImporterPersonHelper.getPersonDistrict(pd.getName(), person), false);
                    if (community.isEmpty()) {
                        throw new ImportErrorException(I18nProperties.getValidationError(Validations.importEntryDoesNotExistDbOrDistrict, entry, buildEntityProperty(entryHeaderPath)));
                    } else if (community.size() > 1) {
                        throw new ImportErrorException(I18nProperties.getValidationError(Validations.importCommunityNotUnique, entry, buildEntityProperty(entryHeaderPath)));
                    } else {
                        pd.getWriteMethod().invoke(currentElement, community.get(0));
                    }
                } else if (propertyType.isAssignableFrom(FacilityReferenceDto.class)) {
                    Pair<DistrictReferenceDto, CommunityReferenceDto> infrastructureData = ImporterPersonHelper.getPersonDistrictAndCommunity(pd.getName(), person);
                    List<FacilityReferenceDto> facility = FacadeProvider.getFacilityFacade().getByNameAndType(entry, infrastructureData.getElement0(), infrastructureData.getElement1(), getTypeOfFacility(pd.getName(), currentElement), false);
                    if (facility.isEmpty()) {
                        if (infrastructureData.getElement1() != null) {
                            throw new ImportErrorException(I18nProperties.getValidationError(Validations.importEntryDoesNotExistDbOrCommunity, entry, buildEntityProperty(entryHeaderPath)));
                        } else {
                            throw new ImportErrorException(I18nProperties.getValidationError(Validations.importEntryDoesNotExistDbOrDistrict, entry, buildEntityProperty(entryHeaderPath)));
                        }
                    } else if (facility.size() > 1 && infrastructureData.getElement1() == null) {
                        throw new ImportErrorException(I18nProperties.getValidationError(Validations.importFacilityNotUniqueInDistrict, entry, buildEntityProperty(entryHeaderPath)));
                    } else if (facility.size() > 1 && infrastructureData.getElement1() != null) {
                        throw new ImportErrorException(I18nProperties.getValidationError(Validations.importFacilityNotUniqueInCommunity, entry, buildEntityProperty(entryHeaderPath)));
                    } else {
                        pd.getWriteMethod().invoke(currentElement, facility.get(0));
                    }
                } else {
                    throw new UnsupportedOperationException(I18nProperties.getValidationError(Validations.importPropertyTypeNotAllowed, propertyType.getName()));
                }
            }
        } catch (IntrospectionException e) {
            throw new InvalidColumnException(buildEntityProperty(entryHeaderPath));
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new ImportErrorException(I18nProperties.getValidationError(Validations.importErrorInColumn, buildEntityProperty(entryHeaderPath)));
        } catch (IllegalArgumentException e) {
            throw new ImportErrorException(entry, buildEntityProperty(entryHeaderPath));
        } catch (ImportErrorException e) {
            throw e;
        } catch (Exception e) {
            logger.error("Unexpected error when trying to import a contact: " + e.getMessage());
            throw new ImportErrorException(I18nProperties.getValidationError(Validations.importUnexpectedError));
        }
    }
    ImportLineResultDto<ContactDto> contactErrors = validateConstraints(contact);
    if (contactErrors.isError()) {
        throw new ImportErrorException(contactErrors.getMessage());
    }
    ImportLineResultDto<PersonDto> personErrors = validateConstraints(person);
    if (personErrors.isError()) {
        throw new ImportErrorException(personErrors.getMessage());
    }
}
Also used : FacilityReferenceDto(de.symeda.sormas.api.infrastructure.facility.FacilityReferenceDto) PersonReferenceDto(de.symeda.sormas.api.person.PersonReferenceDto) IntrospectionException(java.beans.IntrospectionException) CommunityReferenceDto(de.symeda.sormas.api.infrastructure.community.CommunityReferenceDto) ContactDto(de.symeda.sormas.api.contact.ContactDto) SimilarContactDto(de.symeda.sormas.api.contact.SimilarContactDto) List(java.util.List) ArrayList(java.util.ArrayList) LocationDto(de.symeda.sormas.api.location.LocationDto) PropertyDescriptor(java.beans.PropertyDescriptor) ImportErrorException(de.symeda.sormas.api.importexport.ImportErrorException) PersonDto(de.symeda.sormas.api.person.PersonDto) DistrictReferenceDto(de.symeda.sormas.api.infrastructure.district.DistrictReferenceDto) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvalidColumnException(de.symeda.sormas.api.importexport.InvalidColumnException) CsvValidationException(com.opencsv.exceptions.CsvValidationException) ImportErrorException(de.symeda.sormas.api.importexport.ImportErrorException) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ValidationRuntimeException(de.symeda.sormas.api.utils.ValidationRuntimeException) IOException(java.io.IOException) InvalidColumnException(de.symeda.sormas.api.importexport.InvalidColumnException) BirthDateDto(de.symeda.sormas.api.caze.BirthDateDto)

Example 25 with ImportErrorException

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

the class DataImporter method insertRowIntoData.

/**
 * Provides the structure to insert a whole line into the object entity. The actual inserting has to take
 * place in a callback.
 *
 * @param ignoreEmptyEntries
 *            If true, invokes won't be performed for empty values
 * @param insertCallback
 *            The callback that is used to actually do the inserting
 *
 * @return True if the import succeeded without errors, false if not
 */
protected boolean insertRowIntoData(String[] values, String[] entityClasses, String[][] entityPropertyPaths, boolean ignoreEmptyEntries, Function<ImportCellData, Exception> insertCallback) throws IOException {
    boolean dataHasImportError = false;
    List<String> invalidColumns = new ArrayList<>();
    for (int i = 0; i < values.length; i++) {
        String value = StringUtils.trimToNull(values[i]);
        if (ignoreEmptyEntries && (value == null || value.isEmpty())) {
            continue;
        }
        String[] entityPropertyPath = entityPropertyPaths[i];
        // Error description column is ignored
        if (entityPropertyPath[0].equals(ERROR_COLUMN_NAME)) {
            continue;
        }
        if (!(ignoreEmptyEntries && StringUtils.isEmpty(value))) {
            Exception exception = insertCallback.apply(new ImportCellData(value, hasEntityClassRow ? entityClasses[i] : null, entityPropertyPath));
            if (exception != null) {
                if (exception instanceof ImportErrorException) {
                    dataHasImportError = true;
                    writeImportError(values, exception.getMessage());
                    break;
                } else if (exception instanceof InvalidColumnException) {
                    invalidColumns.add(((InvalidColumnException) exception).getColumnName());
                }
            }
        }
    }
    if (invalidColumns.size() > 0) {
        LoggerFactory.getLogger(getClass()).warn("Unhandled columns [{}]", String.join(", ", invalidColumns));
    }
    return dataHasImportError;
}
Also used : ImportCellData(de.symeda.sormas.api.importexport.ImportCellData) ImportErrorException(de.symeda.sormas.api.importexport.ImportErrorException) InvalidColumnException(de.symeda.sormas.api.importexport.InvalidColumnException) ArrayList(java.util.ArrayList) InvalidColumnException(de.symeda.sormas.api.importexport.InvalidColumnException) ParseException(java.text.ParseException) CsvValidationException(com.opencsv.exceptions.CsvValidationException) ImportErrorException(de.symeda.sormas.api.importexport.ImportErrorException) FileNotFoundException(java.io.FileNotFoundException) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException)

Aggregations

ImportErrorException (de.symeda.sormas.api.importexport.ImportErrorException)29 InvalidColumnException (de.symeda.sormas.api.importexport.InvalidColumnException)25 ValidationRuntimeException (de.symeda.sormas.api.utils.ValidationRuntimeException)20 IntrospectionException (java.beans.IntrospectionException)15 InvocationTargetException (java.lang.reflect.InvocationTargetException)15 ArrayList (java.util.ArrayList)14 PropertyDescriptor (java.beans.PropertyDescriptor)11 ParseException (java.text.ParseException)11 List (java.util.List)10 CommunityReferenceDto (de.symeda.sormas.api.infrastructure.community.CommunityReferenceDto)9 DistrictReferenceDto (de.symeda.sormas.api.infrastructure.district.DistrictReferenceDto)9 IOException (java.io.IOException)9 CsvValidationException (com.opencsv.exceptions.CsvValidationException)6 FacilityReferenceDto (de.symeda.sormas.api.infrastructure.facility.FacilityReferenceDto)6 ImportCellData (de.symeda.sormas.api.importexport.ImportCellData)5 PersonDto (de.symeda.sormas.api.person.PersonDto)4 UserDto (de.symeda.sormas.api.user.UserDto)4 DataHelper (de.symeda.sormas.api.utils.DataHelper)4 ImportRelatedObjectsMapper (de.symeda.sormas.api.importexport.ImportRelatedObjectsMapper)3 Date (java.util.Date)3