Search in sources :

Example 1 with IdSchemes

use of org.hisp.dhis.common.IdSchemes in project dhis2-core by dhis2.

the class ExportDataValueAction method execute.

// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
@Override
public String execute() throws Exception {
    //TODO re-implement using Web API
    IdSchemes idSchemes = new IdSchemes();
    idSchemes.setDataElementIdScheme(StringUtils.trimToNull(dataElementIdScheme));
    idSchemes.setOrgUnitIdScheme(StringUtils.trimToNull(orgUnitIdScheme));
    idSchemes.setCategoryOptionComboIdScheme(StringUtils.trimToNull(categoryOptionComboIdScheme));
    Set<String> orgUnits = new HashSet<>(IdentifiableObjectUtils.getUids(selectionTreeManager.getSelectedOrganisationUnits()));
    HttpServletResponse response = ServletActionContext.getResponse();
    OutputStream out = response.getOutputStream();
    DataExportParams params = dataValueSetService.getFromUrl(selectedDataSets, null, null, getMediumDate(startDate), getMediumDate(endDate), orgUnits, true, null, null, false, null, null, null, idSchemes);
    boolean isCompression = compression == null || COMPRESSION_ZIP.equals(compression);
    if (FORMAT_CSV.equals(exportFormat)) {
        ContextUtils.configureResponse(response, CONTENT_TYPE_CSV, true, getFileName(EXTENSION_CSV_ZIP), true);
        dataValueSetService.writeDataValueSetCsv(params, new OutputStreamWriter(getZipOut(out, getFileName(EXTENSION_CSV))));
    } else if (FORMAT_JSON.equals(exportFormat)) {
        ContextUtils.configureResponse(response, CONTENT_TYPE_JSON, true, getFileName(EXTENSION_JSON_ZIP), isCompression);
        dataValueSetService.writeDataValueSetJson(params, isCompression ? getZipOut(out, getFileName(EXTENSION_JSON)) : out);
    } else {
        ContextUtils.configureResponse(response, CONTENT_TYPE_XML, true, getFileName(EXTENSION_XML_ZIP), isCompression);
        dataValueSetService.writeDataValueSetXml(params, isCompression ? getZipOut(out, getFileName(EXTENSION_XML)) : out);
    }
    return SUCCESS;
}
Also used : IdSchemes(org.hisp.dhis.common.IdSchemes) DataExportParams(org.hisp.dhis.datavalue.DataExportParams) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) OutputStreamWriter(java.io.OutputStreamWriter) HashSet(java.util.HashSet)

Example 2 with IdSchemes

use of org.hisp.dhis.common.IdSchemes in project dhis2-core by dhis2.

the class JdbcEventStore method getEvents.

// -------------------------------------------------------------------------
// EventStore implementation
// -------------------------------------------------------------------------
@Override
public List<Event> getEvents(EventSearchParams params, List<OrganisationUnit> organisationUnits) {
    List<Event> events = new ArrayList<>();
    String sql = buildSql(params, organisationUnits);
    SqlRowSet rowSet = jdbcTemplate.queryForRowSet(sql);
    log.debug("Event query SQL: " + sql);
    Event event = new Event();
    event.setEvent("not_valid");
    Set<String> notes = new HashSet<>();
    IdSchemes idSchemes = ObjectUtils.firstNonNull(params.getIdSchemes(), new IdSchemes());
    while (rowSet.next()) {
        if (rowSet.getString("psi_uid") == null) {
            continue;
        }
        if (event.getUid() == null || !event.getUid().equals(rowSet.getString("psi_uid"))) {
            event = new Event();
            event.setUid(rowSet.getString("psi_uid"));
            event.setEvent(IdSchemes.getValue(rowSet.getString("psi_uid"), rowSet.getString("psi_code"), idSchemes.getProgramStageInstanceIdScheme()));
            event.setTrackedEntityInstance(rowSet.getString("tei_uid"));
            event.setStatus(EventStatus.valueOf(rowSet.getString("psi_status")));
            event.setProgram(IdSchemes.getValue(rowSet.getString("p_uid"), rowSet.getString("p_code"), idSchemes.getProgramIdScheme()));
            event.setProgramStage(IdSchemes.getValue(rowSet.getString("ps_uid"), rowSet.getString("ps_code"), idSchemes.getProgramStageIdScheme()));
            event.setOrgUnit(IdSchemes.getValue(rowSet.getString("ou_uid"), rowSet.getString("ou_code"), idSchemes.getOrgUnitIdScheme()));
            event.setDeleted(rowSet.getBoolean("psi_deleted"));
            ProgramType programType = ProgramType.fromValue(rowSet.getString("p_type"));
            if (programType != ProgramType.WITHOUT_REGISTRATION) {
                event.setEnrollment(rowSet.getString("pi_uid"));
                event.setEnrollmentStatus(EnrollmentStatus.fromProgramStatus(ProgramStatus.valueOf(rowSet.getString("pi_status"))));
                event.setFollowup(rowSet.getBoolean("pi_followup"));
            }
            event.setAttributeOptionCombo(rowSet.getString("coc_categoryoptioncombouid"));
            event.setAttributeCategoryOptions(rowSet.getString("deco_uid"));
            event.setTrackedEntityInstance(rowSet.getString("tei_uid"));
            event.setStoredBy(rowSet.getString("psi_storedby"));
            event.setOrgUnitName(rowSet.getString("ou_name"));
            event.setDueDate(DateUtils.getIso8601NoTz(rowSet.getDate("psi_duedate")));
            event.setEventDate(DateUtils.getIso8601NoTz(rowSet.getDate("psi_executiondate")));
            event.setCreated(DateUtils.getIso8601NoTz(rowSet.getDate("psi_created")));
            event.setLastUpdated(DateUtils.getIso8601NoTz(rowSet.getDate("psi_lastupdated")));
            event.setCompletedBy(rowSet.getString("psi_completedby"));
            event.setCompletedDate(DateUtils.getIso8601NoTz(rowSet.getDate("psi_completeddate")));
            Double longitude = rowSet.getDouble("psi_longitude");
            Double latitude = rowSet.getDouble("psi_latitude");
            if (longitude != null && latitude != null) {
                Coordinate coordinate = new Coordinate(longitude, latitude);
                try {
                    List<Double> list = OBJECT_MAPPER.readValue(coordinate.getCoordinateString(), new TypeReference<List<Double>>() {
                    });
                    coordinate.setLongitude(list.get(0));
                    coordinate.setLatitude(list.get(1));
                } catch (IOException ignored) {
                }
                if (coordinate.isValid()) {
                    event.setCoordinate(coordinate);
                }
            }
            events.add(event);
        } else {
            String attributeCategoryCombination = event.getAttributeCategoryOptions();
            String currentAttributeCategoryCombination = rowSet.getString("deco_uid");
            if (!attributeCategoryCombination.contains(currentAttributeCategoryCombination)) {
                event.setAttributeCategoryOptions(attributeCategoryCombination + ";" + currentAttributeCategoryCombination);
            }
        }
        if (rowSet.getString("pdv_value") != null && rowSet.getString("de_uid") != null && isNewDataValue(rowSet, event.getDataValues())) {
            DataValue dataValue = new DataValue();
            dataValue.setCreated(DateUtils.getIso8601NoTz(rowSet.getDate("pdv_created")));
            dataValue.setLastUpdated(DateUtils.getIso8601NoTz(rowSet.getDate("pdv_lastupdated")));
            dataValue.setValue(rowSet.getString("pdv_value"));
            dataValue.setProvidedElsewhere(rowSet.getBoolean("pdv_providedelsewhere"));
            dataValue.setDataElement(IdSchemes.getValue(rowSet.getString("de_uid"), rowSet.getString("de_code"), idSchemes.getDataElementIdScheme()));
            dataValue.setStoredBy(rowSet.getString("pdv_storedby"));
            event.getDataValues().add(dataValue);
        }
        if (rowSet.getString("psinote_value") != null && !notes.contains(rowSet.getString("psinote_id"))) {
            Note note = new Note();
            note.setValue(rowSet.getString("psinote_value"));
            note.setStoredDate(rowSet.getString("psinote_storeddate"));
            note.setStoredBy(rowSet.getString("psinote_storedby"));
            event.getNotes().add(note);
            notes.add(rowSet.getString("psinote_id"));
        }
    }
    return events;
}
Also used : SqlRowSet(org.springframework.jdbc.support.rowset.SqlRowSet) IdSchemes(org.hisp.dhis.common.IdSchemes) ArrayList(java.util.ArrayList) DateUtils.getMediumDateString(org.hisp.dhis.system.util.DateUtils.getMediumDateString) IOException(java.io.IOException) ArrayList(java.util.ArrayList) List(java.util.List) ProgramType(org.hisp.dhis.program.ProgramType) HashSet(java.util.HashSet)

Example 3 with IdSchemes

use of org.hisp.dhis.common.IdSchemes in project dhis2-core by dhis2.

the class DefaultSynchronizationManager method executeDataPush.

/**
     * Executes a push of data values to the given remote instance.
     *
     * @param instance the remote system instance.
     * @return an ImportSummary.
     */
private ImportSummary executeDataPush(SystemInstance instance) throws WebMessageParseException {
    // ---------------------------------------------------------------------
    // Set time for last success to start of process to make data saved
    // subsequently part of next synch process without being ignored
    // ---------------------------------------------------------------------
    final Date startTime = new Date();
    final Date lastSuccessTime = getLastDataSynchSuccessFallback();
    final int lastUpdatedCount = dataValueService.getDataValueCountLastUpdatedAfter(lastSuccessTime, true);
    log.info("Values: " + lastUpdatedCount + " since last synch success: " + lastSuccessTime);
    if (lastUpdatedCount == 0) {
        log.debug("Skipping synch, no new or updated data values");
        return null;
    }
    log.info("Values: " + lastUpdatedCount + " since last synch success: " + lastSuccessTime);
    log.info("Remote server POST URL: " + instance.getUrl());
    final RequestCallback requestCallback = request -> {
        request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        request.getHeaders().add(HEADER_AUTHORIZATION, CodecUtils.getBasicAuthString(instance.getUsername(), instance.getPassword()));
        dataValueSetService.writeDataValueSetJson(lastSuccessTime, request.getBody(), new IdSchemes());
    };
    ResponseExtractor<ImportSummary> responseExtractor = new ImportSummaryResponseExtractor();
    ImportSummary summary = null;
    try {
        summary = restTemplate.execute(instance.getUrl(), HttpMethod.POST, requestCallback, responseExtractor);
    } catch (HttpClientErrorException ex) {
        String responseBody = ex.getResponseBodyAsString();
        summary = WebMessageParseUtils.fromWebMessageResponse(responseBody, ImportSummary.class);
    } catch (HttpServerErrorException ex) {
        String responseBody = ex.getResponseBodyAsString();
        log.error("Internal error happened during event data push: " + responseBody, ex);
        throw ex;
    } catch (ResourceAccessException ex) {
        log.error("Exception during event data push: " + ex.getMessage(), ex);
        throw ex;
    }
    log.info("Synch summary: " + summary);
    if (summary != null && ImportStatus.SUCCESS.equals(summary.getStatus())) {
        setLastDataSynchSuccess(startTime);
        log.info("Synch successful, setting last success time: " + startTime);
    } else {
        log.warn("Sync failed: " + summary);
    }
    return summary;
}
Also used : AtomicMode(org.hisp.dhis.dxf2.metadata.AtomicMode) WebMessageParseException(org.hisp.dhis.dxf2.webmessage.WebMessageParseException) EventService(org.hisp.dhis.dxf2.events.event.EventService) ImportReport(org.hisp.dhis.dxf2.metadata.feedback.ImportReport) Date(java.util.Date) RenderService(org.hisp.dhis.render.RenderService) Autowired(org.springframework.beans.factory.annotation.Autowired) Configuration(org.hisp.dhis.configuration.Configuration) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) ImportSummaryResponseExtractor(org.hisp.dhis.dxf2.common.ImportSummaryResponseExtractor) DataValueService(org.hisp.dhis.datavalue.DataValueService) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) Metadata(org.hisp.dhis.dxf2.metadata.Metadata) MetadataImportService(org.hisp.dhis.dxf2.metadata.MetadataImportService) User(org.hisp.dhis.user.User) ImportStatus(org.hisp.dhis.dxf2.importsummary.ImportStatus) StringUtils.isEmpty(org.apache.commons.lang3.StringUtils.isEmpty) WebMessageParseUtils(org.hisp.dhis.dxf2.webmessage.utils.WebMessageParseUtils) SystemSettingManager(org.hisp.dhis.setting.SystemSettingManager) RestTemplate(org.springframework.web.client.RestTemplate) DefaultRenderService(org.hisp.dhis.render.DefaultRenderService) ResponseExtractor(org.springframework.web.client.ResponseExtractor) HttpHeaders(org.springframework.http.HttpHeaders) IdSchemes(org.hisp.dhis.common.IdSchemes) DataValueSetService(org.hisp.dhis.dxf2.datavalueset.DataValueSetService) MediaType(org.springframework.http.MediaType) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) DateTime(org.joda.time.DateTime) HttpMethod(org.springframework.http.HttpMethod) SchemaService(org.hisp.dhis.schema.SchemaService) ResourceAccessException(org.springframework.web.client.ResourceAccessException) IOException(java.io.IOException) MetadataImportParams(org.hisp.dhis.dxf2.metadata.MetadataImportParams) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries) RequestCallback(org.springframework.web.client.RequestCallback) CodecUtils(org.hisp.dhis.system.util.CodecUtils) HttpStatus(org.springframework.http.HttpStatus) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) ImportSummariesResponseExtractor(org.hisp.dhis.dxf2.common.ImportSummariesResponseExtractor) HttpEntity(org.springframework.http.HttpEntity) Events(org.hisp.dhis.dxf2.events.event.Events) CurrentUserService(org.hisp.dhis.user.CurrentUserService) ConfigurationService(org.hisp.dhis.configuration.ConfigurationService) Log(org.apache.commons.logging.Log) ResponseEntity(org.springframework.http.ResponseEntity) LogFactory(org.apache.commons.logging.LogFactory) SettingKey(org.hisp.dhis.setting.SettingKey) ImportSummaryResponseExtractor(org.hisp.dhis.dxf2.common.ImportSummaryResponseExtractor) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) RequestCallback(org.springframework.web.client.RequestCallback) IdSchemes(org.hisp.dhis.common.IdSchemes) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) Date(java.util.Date) ResourceAccessException(org.springframework.web.client.ResourceAccessException)

Example 4 with IdSchemes

use of org.hisp.dhis.common.IdSchemes in project dhis2-core by dhis2.

the class JdbcEventStore method getEventRows.

@Override
public List<EventRow> getEventRows(EventSearchParams params, List<OrganisationUnit> organisationUnits) {
    User user = currentUserService.getCurrentUser();
    setAccessiblePrograms(user, params);
    List<EventRow> eventRows = new ArrayList<>();
    String sql = buildSql(params, organisationUnits, user);
    SqlRowSet rowSet = jdbcTemplate.queryForRowSet(sql);
    log.debug("Event query SQL: " + sql);
    EventRow eventRow = new EventRow();
    eventRow.setEvent("not_valid");
    Set<String> notes = new HashSet<>();
    Map<String, List<DataValue>> processedDataValues = new HashMap<>();
    while (rowSet.next()) {
        if (rowSet.getString("psi_uid") == null || (params.getCategoryOptionCombo() == null && !isSuper(user) && !userHasAccess(rowSet))) {
            continue;
        }
        if (eventRow.getUid() == null || !eventRow.getUid().equals(rowSet.getString("psi_uid"))) {
            validateIdentifiersPresence(rowSet, params.getIdSchemes(), false);
            eventRow = new EventRow();
            eventRow.setUid(rowSet.getString("psi_uid"));
            eventRow.setEvent(rowSet.getString("psi_uid"));
            eventRow.setTrackedEntityInstance(rowSet.getString("tei_uid"));
            eventRow.setTrackedEntityInstanceOrgUnit(rowSet.getString("tei_ou"));
            eventRow.setTrackedEntityInstanceOrgUnitName(rowSet.getString("tei_ou_name"));
            eventRow.setTrackedEntityInstanceCreated(rowSet.getString("tei_created"));
            eventRow.setTrackedEntityInstanceInactive(rowSet.getBoolean("tei_inactive"));
            eventRow.setDeleted(rowSet.getBoolean("psi_deleted"));
            eventRow.setProgram(rowSet.getString("p_identifier"));
            eventRow.setProgramStage(rowSet.getString("ps_identifier"));
            eventRow.setOrgUnit(rowSet.getString("ou_identifier"));
            ProgramType programType = ProgramType.fromValue(rowSet.getString("p_type"));
            if (programType == ProgramType.WITHOUT_REGISTRATION) {
                eventRow.setEnrollment(rowSet.getString("pi_uid"));
                eventRow.setFollowup(rowSet.getBoolean("pi_followup"));
            }
            eventRow.setTrackedEntityInstance(rowSet.getString("tei_uid"));
            eventRow.setOrgUnitName(rowSet.getString("ou_name"));
            eventRow.setDueDate(DateUtils.getIso8601NoTz(rowSet.getDate("psi_duedate")));
            eventRow.setEventDate(DateUtils.getIso8601NoTz(rowSet.getDate("psi_executiondate")));
            eventRows.add(eventRow);
        }
        if (rowSet.getString("pav_value") != null && rowSet.getString("ta_uid") != null) {
            String valueType = rowSet.getString("ta_valuetype");
            Attribute attribute = new Attribute();
            attribute.setCreated(DateUtils.getIso8601NoTz(rowSet.getDate("pav_created")));
            attribute.setLastUpdated(DateUtils.getIso8601NoTz(rowSet.getDate("pav_lastupdated")));
            attribute.setValue(rowSet.getString("pav_value"));
            attribute.setDisplayName(rowSet.getString("ta_name"));
            attribute.setValueType(valueType != null ? ValueType.valueOf(valueType.toUpperCase()) : null);
            attribute.setAttribute(rowSet.getString("ta_uid"));
            eventRow.getAttributes().add(attribute);
        }
        if (!StringUtils.isEmpty(rowSet.getString("psi_eventdatavalues")) && !processedDataValues.containsKey(rowSet.getString("psi_uid"))) {
            List<DataValue> dataValues = new ArrayList<>();
            Set<EventDataValue> eventDataValues = convertEventDataValueJsonIntoSet(rowSet.getString("psi_eventdatavalues"));
            for (EventDataValue dv : eventDataValues) {
                dataValues.add(convertEventDataValueIntoDtoDataValue(dv));
            }
            processedDataValues.put(rowSet.getString("psi_uid"), dataValues);
        }
        if (rowSet.getString("psinote_value") != null && !notes.contains(rowSet.getString("psinote_id"))) {
            Note note = new Note();
            note.setNote(rowSet.getString("psinote_uid"));
            note.setValue(rowSet.getString("psinote_value"));
            note.setStoredDate(DateUtils.getIso8601NoTz(rowSet.getDate("psinote_storeddate")));
            note.setStoredBy(rowSet.getString("psinote_storedby"));
            eventRow.getNotes().add(note);
            notes.add(rowSet.getString("psinote_id"));
        }
    }
    eventRows.forEach(e -> e.setDataValues(processedDataValues.get(e.getUid())));
    IdSchemes idSchemes = ObjectUtils.firstNonNull(params.getIdSchemes(), new IdSchemes());
    IdScheme dataElementIdScheme = idSchemes.getDataElementIdScheme();
    if (dataElementIdScheme != IdScheme.ID && dataElementIdScheme != IdScheme.UID) {
        CachingMap<String, String> dataElementUidToIdentifierCache = new CachingMap<>();
        List<Collection<DataValue>> dataValuesList = eventRows.stream().map(EventRow::getDataValues).collect(Collectors.toList());
        populateCache(dataElementIdScheme, dataValuesList, dataElementUidToIdentifierCache);
        convertDataValuesIdentifiers(dataElementIdScheme, dataValuesList, dataElementUidToIdentifierCache);
    }
    return eventRows;
}
Also used : SqlRowSet(org.springframework.jdbc.support.rowset.SqlRowSet) User(org.hisp.dhis.user.User) IdSchemes(org.hisp.dhis.common.IdSchemes) HashMap(java.util.HashMap) Attribute(org.hisp.dhis.dxf2.events.trackedentity.Attribute) EventDataValue(org.hisp.dhis.eventdatavalue.EventDataValue) ArrayList(java.util.ArrayList) DateUtils.getMediumDateString(org.hisp.dhis.util.DateUtils.getMediumDateString) TextUtils.getQuotedCommaDelimitedString(org.hisp.dhis.commons.util.TextUtils.getQuotedCommaDelimitedString) DateUtils.getLongGmtDateString(org.hisp.dhis.util.DateUtils.getLongGmtDateString) IdScheme(org.hisp.dhis.common.IdScheme) EventRow(org.hisp.dhis.dxf2.events.report.EventRow) CachingMap(org.hisp.dhis.commons.collection.CachingMap) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Collectors.toList(java.util.stream.Collectors.toList) ProgramType(org.hisp.dhis.program.ProgramType) EventDataValue(org.hisp.dhis.eventdatavalue.EventDataValue) HashSet(java.util.HashSet)

Example 5 with IdSchemes

use of org.hisp.dhis.common.IdSchemes in project dhis2-core by dhis2.

the class AbstractTrackedEntityInstanceService method filterOutSkipSyncAttributesIfApplies.

private Set<TrackedEntityAttribute> filterOutSkipSyncAttributesIfApplies(TrackedEntityInstanceParams params, TrackedEntityInstance trackedEntityInstance, Set<TrackedEntityAttribute> readableAttributes) {
    Set<TrackedEntityAttribute> readableAttributesCopy;
    if (params.isDataSynchronizationQuery()) {
        List<String> programs = trackedEntityInstance.getEnrollments().stream().map(Enrollment::getProgram).collect(Collectors.toList());
        readableAttributesCopy = readableAttributes.stream().filter(att -> !att.getSkipSynchronization()).collect(Collectors.toSet());
        IdSchemes idSchemes = new IdSchemes();
        for (String programUid : programs) {
            Program program = getProgram(idSchemes, programUid);
            if (program != null) {
                readableAttributesCopy.addAll(program.getTrackedEntityAttributes().stream().filter(att -> !att.getSkipSynchronization()).collect(Collectors.toSet()));
            }
        }
    } else {
        readableAttributesCopy = new HashSet<>(readableAttributes);
    }
    return readableAttributesCopy;
}
Also used : Program(org.hisp.dhis.program.Program) IdSchemes(org.hisp.dhis.common.IdSchemes) TrackedEntityAttribute(org.hisp.dhis.trackedentity.TrackedEntityAttribute)

Aggregations

IdSchemes (org.hisp.dhis.common.IdSchemes)25 DataExportParams (org.hisp.dhis.datavalue.DataExportParams)9 Date (java.util.Date)8 Test (org.junit.jupiter.api.Test)7 ArrayList (java.util.ArrayList)6 IdScheme (org.hisp.dhis.common.IdScheme)6 User (org.hisp.dhis.user.User)6 HashSet (java.util.HashSet)5 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 IOException (java.io.IOException)4 List (java.util.List)4 CategoryOptionCombo (org.hisp.dhis.category.CategoryOptionCombo)4 DataSet (org.hisp.dhis.dataset.DataSet)4 DataValue (org.hisp.dhis.datavalue.DataValue)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 HashMap (java.util.HashMap)3 Slf4j (lombok.extern.slf4j.Slf4j)3 CachingMap (org.hisp.dhis.commons.collection.CachingMap)3 DataValueService (org.hisp.dhis.datavalue.DataValueService)3