Search in sources :

Example 46 with DataValueSet

use of org.hisp.dhis.dxf2.datavalueset.DataValueSet in project dhis2-core by dhis2.

the class DefaultDataValueSetService method saveDataValueSet.

@Override
public ImportSummary saveDataValueSet(InputStream in, ImportOptions importOptions, TaskId id) {
    try {
        in = StreamUtils.wrapAndCheckCompressionFormat(in);
        DataValueSet dataValueSet = new StreamingXmlDataValueSet(XMLFactory.getXMLReader(in));
        return saveDataValueSet(importOptions, id, dataValueSet);
    } catch (Exception ex) {
        log.error(DebugUtils.getStackTrace(ex));
        notifier.notify(id, ERROR, "Process failed: " + ex.getMessage(), true);
        return new ImportSummary(ImportStatus.ERROR, "The import process failed: " + ex.getMessage());
    }
}
Also used : ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary)

Example 47 with DataValueSet

use of org.hisp.dhis.dxf2.datavalueset.DataValueSet in project dhis2-core by dhis2.

the class SpringDataValueSetStore method writeDataValueSet.

private void writeDataValueSet(String sql, DataExportParams params, Date completeDate, final DataValueSet dataValueSet) {
    if (params.isSingleDataValueSet()) {
        IdSchemes idScheme = params.getOutputIdSchemes() != null ? params.getOutputIdSchemes() : new IdSchemes();
        IdScheme ouScheme = idScheme.getOrgUnitIdScheme();
        IdScheme dataSetScheme = idScheme.getDataSetIdScheme();
        dataValueSet.setDataSet(params.getFirstDataSet().getPropertyValue(dataSetScheme));
        dataValueSet.setCompleteDate(getLongGmtDateString(completeDate));
        dataValueSet.setPeriod(params.getFirstPeriod().getIsoDate());
        dataValueSet.setOrgUnit(params.getFirstOrganisationUnit().getPropertyValue(ouScheme));
    }
    final Calendar calendar = PeriodType.getCalendar();
    jdbcTemplate.query(sql, new RowCallbackHandler() {

        @Override
        public void processRow(ResultSet rs) throws SQLException {
            DataValue dataValue = dataValueSet.getDataValueInstance();
            PeriodType pt = PeriodType.getPeriodTypeByName(rs.getString("ptname"));
            boolean deleted = rs.getBoolean("deleted");
            dataValue.setDataElement(rs.getString("deid"));
            dataValue.setPeriod(pt.createPeriod(rs.getDate("pestart"), calendar).getIsoDate());
            dataValue.setOrgUnit(rs.getString("ouid"));
            dataValue.setCategoryOptionCombo(rs.getString("cocid"));
            dataValue.setAttributeOptionCombo(rs.getString("aocid"));
            dataValue.setValue(rs.getString("value"));
            dataValue.setStoredBy(rs.getString("storedby"));
            dataValue.setCreated(getLongGmtDateString(rs.getTimestamp("created")));
            dataValue.setLastUpdated(getLongGmtDateString(rs.getTimestamp("lastupdated")));
            dataValue.setComment(rs.getString("comment"));
            dataValue.setFollowup(rs.getBoolean("followup"));
            if (deleted) {
                dataValue.setDeleted(deleted);
            }
            dataValue.close();
        }
    });
    dataValueSet.close();
}
Also used : PeriodType(org.hisp.dhis.period.PeriodType) IdSchemes(org.hisp.dhis.common.IdSchemes) SQLException(java.sql.SQLException) DataValue(org.hisp.dhis.dxf2.datavalue.DataValue) Calendar(org.hisp.dhis.calendar.Calendar) ResultSet(java.sql.ResultSet) IdScheme(org.hisp.dhis.common.IdScheme) RowCallbackHandler(org.springframework.jdbc.core.RowCallbackHandler)

Example 48 with DataValueSet

use of org.hisp.dhis.dxf2.datavalueset.DataValueSet in project dhis2-core by dhis2.

the class DefaultDataValueSetService method createDataValueSetImportContext.

private ImportContext createDataValueSetImportContext(ImportOptions options, DataValueSet data) {
    options = ObjectUtils.firstNonNull(options, ImportOptions.getDefaultImportOptions());
    final User currentUser = currentUserService.getCurrentUser();
    boolean auditEnabled = config.isEnabled(CHANGELOG_AGGREGATE);
    boolean hasSkipAuditAuth = currentUser != null && currentUser.isAuthorized(Authorities.F_SKIP_DATA_IMPORT_AUDIT);
    boolean skipAudit = (options.isSkipAudit() && hasSkipAuditAuth) || !auditEnabled;
    SystemSettingManager settings = systemSettingManager;
    IdScheme dataElementIdScheme = createIdScheme(data.getDataElementIdSchemeProperty(), options, IdSchemes::getDataElementIdScheme);
    IdScheme orgUnitIdScheme = createIdScheme(data.getOrgUnitIdSchemeProperty(), options, IdSchemes::getOrgUnitIdScheme);
    IdScheme categoryOptComboIdScheme = createIdScheme(data.getCategoryOptionComboIdSchemeProperty(), options, IdSchemes::getCategoryOptionComboIdScheme);
    IdScheme dataSetIdScheme = createIdScheme(data.getDataSetIdSchemeProperty(), options, IdSchemes::getDataSetIdScheme);
    return ImportContext.builder().importOptions(options).summary(new ImportSummary().setImportOptions(options)).isIso8601(calendarService.getSystemCalendar().isIso8601()).skipLockExceptionCheck(!lockExceptionStore.anyExists()).i18n(i18nManager.getI18n()).currentUser(currentUser).currentOrgUnits(currentUserService.getCurrentUserOrganisationUnits()).hasSkipAuditAuth(hasSkipAuditAuth).skipAudit(skipAudit).idScheme(createIdScheme(data.getIdSchemeProperty(), options, IdSchemes::getIdScheme)).dataElementIdScheme(dataElementIdScheme).orgUnitIdScheme(orgUnitIdScheme).categoryOptComboIdScheme(categoryOptComboIdScheme).dataSetIdScheme(dataSetIdScheme).strategy(data.getStrategy() != null ? ImportStrategy.valueOf(data.getStrategy()) : options.getImportStrategy()).dryRun(data.getDryRun() != null ? data.getDryRun() : options.isDryRun()).skipExistingCheck(options.isSkipExistingCheck()).strictPeriods(options.isStrictPeriods() || settings.getBoolSetting(SettingKey.DATA_IMPORT_STRICT_PERIODS)).strictDataElements(options.isStrictDataElements() || settings.getBoolSetting(SettingKey.DATA_IMPORT_STRICT_DATA_ELEMENTS)).strictCategoryOptionCombos(options.isStrictCategoryOptionCombos() || settings.getBoolSetting(SettingKey.DATA_IMPORT_STRICT_CATEGORY_OPTION_COMBOS)).strictAttrOptionCombos(options.isStrictAttributeOptionCombos() || settings.getBoolSetting(SettingKey.DATA_IMPORT_STRICT_ATTRIBUTE_OPTION_COMBOS)).strictOrgUnits(options.isStrictOrganisationUnits() || settings.getBoolSetting(SettingKey.DATA_IMPORT_STRICT_ORGANISATION_UNITS)).requireCategoryOptionCombo(options.isRequireCategoryOptionCombo() || settings.getBoolSetting(SettingKey.DATA_IMPORT_REQUIRE_CATEGORY_OPTION_COMBO)).requireAttrOptionCombo(options.isRequireAttributeOptionCombo() || settings.getBoolSetting(SettingKey.DATA_IMPORT_REQUIRE_ATTRIBUTE_OPTION_COMBO)).forceDataInput(inputUtils.canForceDataInput(currentUser, options.isForce())).dataElementCallable(new IdentifiableObjectCallable<>(identifiableObjectManager, DataElement.class, dataElementIdScheme, null)).orgUnitCallable(new IdentifiableObjectCallable<>(identifiableObjectManager, OrganisationUnit.class, orgUnitIdScheme, trimToNull(data.getOrgUnit()))).categoryOptionComboCallable(new CategoryOptionComboAclCallable(categoryService, categoryOptComboIdScheme, null)).attributeOptionComboCallable(new CategoryOptionComboAclCallable(categoryService, categoryOptComboIdScheme, null)).periodCallable(new PeriodCallable(periodService, null, trimToNull(data.getPeriod()))).dataValueBatchHandler(batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class).init()).auditBatchHandler(skipAudit ? null : batchHandlerFactory.createBatchHandler(DataValueAuditBatchHandler.class).init()).singularNameForType(klass -> schemaService.getDynamicSchema(klass).getSingular()).build();
}
Also used : DataValueAuditBatchHandler(org.hisp.dhis.jdbc.batchhandler.DataValueAuditBatchHandler) ImportStrategy(org.hisp.dhis.importexport.ImportStrategy) CategoryService(org.hisp.dhis.category.CategoryService) Authorities(org.hisp.dhis.security.Authorities) ValidationUtils.dataValueIsZeroAndInsignificant(org.hisp.dhis.system.util.ValidationUtils.dataValueIsZeroAndInsignificant) Date(java.util.Date) PeriodService(org.hisp.dhis.period.PeriodService) ValidationUtils(org.hisp.dhis.system.util.ValidationUtils) CompleteDataSetRegistrationService(org.hisp.dhis.dataset.CompleteDataSetRegistrationService) OrganisationUnitService(org.hisp.dhis.organisationunit.OrganisationUnitService) ErrorMessage(org.hisp.dhis.feedback.ErrorMessage) ImportCount(org.hisp.dhis.dxf2.importsummary.ImportCount) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) CurrentUserServiceTarget(org.hisp.dhis.user.CurrentUserServiceTarget) FileResourceService(org.hisp.dhis.fileresource.FileResourceService) IdentifiableProperty(org.hisp.dhis.common.IdentifiableProperty) DataExportParams(org.hisp.dhis.datavalue.DataExportParams) XMLFactory(org.hisp.staxwax.factory.XMLFactory) InputUtils(org.hisp.dhis.dxf2.util.InputUtils) JobConfiguration(org.hisp.dhis.scheduling.JobConfiguration) Period(org.hisp.dhis.period.Period) StringUtils.trimToNull(org.apache.commons.lang3.StringUtils.trimToNull) CollectionUtils.isEmpty(org.hisp.dhis.commons.collection.CollectionUtils.isEmpty) DxfNamespaces(org.hisp.dhis.common.DxfNamespaces) CHANGELOG_AGGREGATE(org.hisp.dhis.external.conf.ConfigurationKey.CHANGELOG_AGGREGATE) OrganisationUnitGroup(org.hisp.dhis.organisationunit.OrganisationUnitGroup) StreamUtils.wrapAndCheckCompressionFormat(org.hisp.dhis.commons.util.StreamUtils.wrapAndCheckCompressionFormat) DataValueAudit(org.hisp.dhis.datavalue.DataValueAudit) WARN(org.hisp.dhis.system.notification.NotificationLevel.WARN) SchemaService(org.hisp.dhis.schema.SchemaService) Objects(java.util.Objects) SimpleNode(org.hisp.dhis.node.types.SimpleNode) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Clock(org.hisp.dhis.system.util.Clock) ComplexNode(org.hisp.dhis.node.types.ComplexNode) CategoryOptionCombo(org.hisp.dhis.category.CategoryOptionCombo) Writer(java.io.Writer) AclService(org.hisp.dhis.security.acl.AclService) RootNode(org.hisp.dhis.node.types.RootNode) BatchHandlerFactory(org.hisp.quick.BatchHandlerFactory) CollectionNode(org.hisp.dhis.node.types.CollectionNode) BatchHandlerFactoryTarget(org.hisp.dhis.common.BatchHandlerFactoryTarget) DataSet(org.hisp.dhis.dataset.DataSet) DateUtils.parseDate(org.hisp.dhis.util.DateUtils.parseDate) Callable(java.util.concurrent.Callable) BooleanUtils(org.apache.commons.lang3.BooleanUtils) AuditType(org.hisp.dhis.common.AuditType) DataSetContext(org.hisp.dhis.dxf2.datavalueset.ImportContext.DataSetContext) IllegalQueryException(org.hisp.dhis.common.IllegalQueryException) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) DataElement(org.hisp.dhis.dataelement.DataElement) PeriodCallable(org.hisp.dhis.system.callable.PeriodCallable) Notifier(org.hisp.dhis.system.notification.Notifier) DataValueService(org.hisp.dhis.datavalue.DataValueService) DataValueBatchHandler(org.hisp.dhis.jdbc.batchhandler.DataValueBatchHandler) CategoryOptionComboAclCallable(org.hisp.dhis.system.callable.CategoryOptionComboAclCallable) IdentifiableObjectManager(org.hisp.dhis.common.IdentifiableObjectManager) Service(org.springframework.stereotype.Service) User(org.hisp.dhis.user.User) ErrorCode(org.hisp.dhis.feedback.ErrorCode) IdentifiableObjectCallable(org.hisp.dhis.system.callable.IdentifiableObjectCallable) ImportStatus(org.hisp.dhis.dxf2.importsummary.ImportStatus) I18nManager(org.hisp.dhis.i18n.I18nManager) DataValueAuditBatchHandler(org.hisp.dhis.jdbc.batchhandler.DataValueAuditBatchHandler) SystemSettingManager(org.hisp.dhis.setting.SystemSettingManager) OutputStream(java.io.OutputStream) CsvUtils(org.hisp.dhis.system.util.CsvUtils) CompleteDataSetRegistration(org.hisp.dhis.dataset.CompleteDataSetRegistration) DhisConfigurationProvider(org.hisp.dhis.external.conf.DhisConfigurationProvider) IdSchemes(org.hisp.dhis.common.IdSchemes) FileResource(org.hisp.dhis.fileresource.FileResource) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) CalendarService(org.hisp.dhis.calendar.CalendarService) INFO(org.hisp.dhis.system.notification.NotificationLevel.INFO) ImportOptions(org.hisp.dhis.dxf2.common.ImportOptions) DebugUtils(org.hisp.dhis.commons.util.DebugUtils) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) ObjectUtils(org.hisp.dhis.util.ObjectUtils) NotificationLevel(org.hisp.dhis.system.notification.NotificationLevel) LockExceptionStore(org.hisp.dhis.dataset.LockExceptionStore) CurrentUserService(org.hisp.dhis.user.CurrentUserService) ERROR(org.hisp.dhis.system.notification.NotificationLevel.ERROR) DataValue(org.hisp.dhis.datavalue.DataValue) SettingKey(org.hisp.dhis.setting.SettingKey) AllArgsConstructor(lombok.AllArgsConstructor) DataElementGroup(org.hisp.dhis.dataelement.DataElementGroup) IdScheme(org.hisp.dhis.common.IdScheme) DateUtils(org.hisp.dhis.util.DateUtils) InputStream(java.io.InputStream) Transactional(org.springframework.transaction.annotation.Transactional) User(org.hisp.dhis.user.User) DataValueBatchHandler(org.hisp.dhis.jdbc.batchhandler.DataValueBatchHandler) IdSchemes(org.hisp.dhis.common.IdSchemes) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) CategoryOptionComboAclCallable(org.hisp.dhis.system.callable.CategoryOptionComboAclCallable) PeriodCallable(org.hisp.dhis.system.callable.PeriodCallable) IdScheme(org.hisp.dhis.common.IdScheme) IdentifiableObjectCallable(org.hisp.dhis.system.callable.IdentifiableObjectCallable) DataElement(org.hisp.dhis.dataelement.DataElement) SystemSettingManager(org.hisp.dhis.setting.SystemSettingManager)

Example 49 with DataValueSet

use of org.hisp.dhis.dxf2.datavalueset.DataValueSet in project dhis2-core by dhis2.

the class PdfDataEntryFormUtil method getDataValueSet.

/**
 * Creates data value set from Input Stream (PDF) for PDF data import
 */
public static DataValueSet getDataValueSet(InputStream in) {
    PdfReader reader = null;
    DataValueSet dataValueSet = new DataValueSet();
    List<org.hisp.dhis.dxf2.datavalue.DataValue> dataValueList = new ArrayList<>();
    try {
        reader = new PdfReader(in);
        AcroFields form = reader.getAcroFields();
        if (form != null) {
            // Process OrgUnitUID and PeriodID from the PDF Form
            String orgUnitUid = form.getField(PdfDataEntryFormUtil.LABELCODE_ORGID).trim();
            String periodId = form.getField(PdfDataEntryFormUtil.LABELCODE_PERIODID).trim();
            if (periodId == null || periodId.isEmpty()) {
                throw new InvalidIdentifierReferenceException(ERROR_EMPTY_PERIOD);
            }
            if (orgUnitUid == null || orgUnitUid.isEmpty()) {
                throw new InvalidIdentifierReferenceException(ERROR_EMPTY_ORG_UNIT);
            }
            Period period = PeriodType.getPeriodFromIsoString(periodId);
            if (period == null) {
                throw new InvalidIdentifierReferenceException(ERROR_INVALID_PERIOD + periodId);
            }
            // Loop Through the Fields and get data.
            @SuppressWarnings("unchecked") Set<String> fldNames = form.getFields().keySet();
            for (String fldName : fldNames) {
                if (fldName.startsWith(PdfDataEntryFormUtil.LABELCODE_DATAENTRYTEXTFIELD)) {
                    String[] strArrFldName = fldName.split("_");
                    org.hisp.dhis.dxf2.datavalue.DataValue dataValue = new org.hisp.dhis.dxf2.datavalue.DataValue();
                    dataValue.setDataElement(strArrFldName[1]);
                    dataValue.setCategoryOptionCombo(strArrFldName[2]);
                    dataValue.setOrgUnit(orgUnitUid);
                    dataValue.setPeriod(period.getIsoDate());
                    dataValue.setValue(fieldValueFormat(strArrFldName, form.getField(fldName)));
                    dataValue.setStoredBy(DATAVALUE_IMPORT_STOREBY);
                    dataValue.setComment(DATAVALUE_IMPORT_COMMENT);
                    dataValue.setFollowup(false);
                    dataValue.setLastUpdated(DateUtils.getMediumDateString());
                    dataValueList.add(dataValue);
                }
            }
            dataValueSet.setDataValues(dataValueList);
        } else {
            throw new RuntimeException("Could not generate PDF AcroFields form from input");
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
    return dataValueSet;
}
Also used : DataValueSet(org.hisp.dhis.dxf2.datavalueset.DataValueSet) ArrayList(java.util.ArrayList) Period(org.hisp.dhis.period.Period) PdfReader(com.lowagie.text.pdf.PdfReader) InvalidIdentifierReferenceException(org.hisp.dhis.common.exception.InvalidIdentifierReferenceException) AcroFields(com.lowagie.text.pdf.AcroFields) InvalidIdentifierReferenceException(org.hisp.dhis.common.exception.InvalidIdentifierReferenceException)

Example 50 with DataValueSet

use of org.hisp.dhis.dxf2.datavalueset.DataValueSet in project dhis2-core by dhis2.

the class DataValueSetImportValidatorTest method testValidateDataSetOrgUnitExists.

@Test
void testValidateDataSetOrgUnitExists() {
    when(aclService.canDataRead(any(), any())).thenReturn(true);
    DataValueSet dataValueSet = new DataValueSet();
    dataValueSet.setOrgUnit(CodeGenerator.generateUid());
    ImportContext context = createMinimalImportContext(null).build();
    DataSetContext dataSetContext = createMinimalDataSetContext().build();
    assertTrue(validator.abortDataSetImport(dataValueSet, context, dataSetContext));
    assertConflict(ErrorCode.E7603, "Org unit not found or not accessible: `<object1>`", context, dataValueSet.getOrgUnit(), dataValueSet.getDataSet());
}
Also used : DataSetContext(org.hisp.dhis.dxf2.datavalueset.ImportContext.DataSetContext) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)63 ImportSummary (org.hisp.dhis.dxf2.importsummary.ImportSummary)56 TransactionalIntegrationTest (org.hisp.dhis.TransactionalIntegrationTest)41 ClassPathResource (org.springframework.core.io.ClassPathResource)39 ImportOptions (org.hisp.dhis.dxf2.common.ImportOptions)24 DataValue (org.hisp.dhis.datavalue.DataValue)21 DhisTest (org.hisp.dhis.DhisTest)12 DataValueSet (org.hisp.dhis.dxf2.datavalueset.DataValueSet)9 DataValueAudit (org.hisp.dhis.datavalue.DataValueAudit)8 DataSetContext (org.hisp.dhis.dxf2.datavalueset.ImportContext.DataSetContext)8 DataSet (org.hisp.dhis.dataset.DataSet)6 Period (org.hisp.dhis.period.Period)6 DhisConvenienceTest (org.hisp.dhis.DhisConvenienceTest)5 ImportCount (org.hisp.dhis.dxf2.importsummary.ImportCount)5 ListGrid (org.hisp.dhis.system.grid.ListGrid)5 IdScheme (org.hisp.dhis.common.IdScheme)4 DataElement (org.hisp.dhis.dataelement.DataElement)4 IdentifiableObjectCallable (org.hisp.dhis.system.callable.IdentifiableObjectCallable)4 Date (java.util.Date)3 List (java.util.List)3