Search in sources :

Example 71 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project dhis2-core by dhis2.

the class JdbcEventStore method getEvents.

// -------------------------------------------------------------------------
// EventStore implementation
// -------------------------------------------------------------------------
@Override
public List<Event> getEvents(EventSearchParams params, List<OrganisationUnit> organisationUnits, Map<String, Set<String>> psdesWithSkipSyncTrue) {
    User user = currentUserService.getCurrentUser();
    setAccessiblePrograms(user, params);
    Map<String, Event> eventUidToEventMap = new HashMap<>(params.getPageSizeWithDefault());
    List<Event> events = new ArrayList<>();
    List<Long> relationshipIds = new ArrayList<>();
    final Gson gson = new Gson();
    String sql = buildSql(params, organisationUnits, user);
    SqlRowSet rowSet = jdbcTemplate.queryForRowSet(sql);
    log.debug("Event query SQL: " + sql);
    Set<String> notes = new HashSet<>();
    while (rowSet.next()) {
        if (rowSet.getString("psi_uid") == null || (params.getCategoryOptionCombo() == null && !isSuper(user) && !userHasAccess(rowSet))) {
            continue;
        }
        String psiUid = rowSet.getString("psi_uid");
        Event event;
        if (!eventUidToEventMap.containsKey(psiUid)) {
            validateIdentifiersPresence(rowSet, params.getIdSchemes(), true);
            event = new Event();
            eventUidToEventMap.put(psiUid, event);
            if (!params.isSkipEventId()) {
                event.setUid(psiUid);
                event.setEvent(psiUid);
            }
            event.setTrackedEntityInstance(rowSet.getString("tei_uid"));
            event.setStatus(EventStatus.valueOf(rowSet.getString("psi_status")));
            ProgramType programType = ProgramType.fromValue(rowSet.getString("p_type"));
            event.setProgram(rowSet.getString("p_identifier"));
            event.setProgramType(programType);
            event.setProgramStage(rowSet.getString("ps_identifier"));
            event.setOrgUnit(rowSet.getString("ou_identifier"));
            event.setDeleted(rowSet.getBoolean("psi_deleted"));
            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"));
            }
            if (params.getCategoryOptionCombo() == null && !isSuper(user)) {
                event.setOptionSize(rowSet.getInt("option_size"));
            }
            event.setAttributeOptionCombo(rowSet.getString("coc_identifier"));
            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.setCreatedByUserInfo(jsonToUserInfo(rowSet.getString("psi_createdbyuserinfo"), jsonMapper));
            event.setLastUpdated(DateUtils.getIso8601NoTz(rowSet.getDate("psi_lastupdated")));
            event.setLastUpdatedByUserInfo(jsonToUserInfo(rowSet.getString("psi_lastupdatedbyuserinfo"), jsonMapper));
            event.setCompletedBy(rowSet.getString("psi_completedby"));
            event.setCompletedDate(DateUtils.getIso8601NoTz(rowSet.getDate("psi_completeddate")));
            if (rowSet.getObject("psi_geometry") != null) {
                try {
                    Geometry geom = new WKTReader().read(rowSet.getString("psi_geometry"));
                    event.setGeometry(geom);
                } catch (ParseException e) {
                    log.error("Unable to read geometry for event '" + event.getUid() + "': ", e);
                }
            }
            if (rowSet.getObject("user_assigned") != null) {
                event.setAssignedUser(rowSet.getString("user_assigned"));
                event.setAssignedUserUsername(rowSet.getString("user_assigned_username"));
                event.setAssignedUserDisplayName(rowSet.getString("user_assigned_name"));
            }
            events.add(event);
        } else {
            event = eventUidToEventMap.get(psiUid);
            String attributeCategoryCombination = event.getAttributeCategoryOptions();
            String currentAttributeCategoryCombination = rowSet.getString("deco_uid");
            if (!attributeCategoryCombination.contains(currentAttributeCategoryCombination)) {
                event.setAttributeCategoryOptions(attributeCategoryCombination + ";" + currentAttributeCategoryCombination);
            }
        }
        if (!StringUtils.isEmpty(rowSet.getString("psi_eventdatavalues"))) {
            Set<EventDataValue> eventDataValues = convertEventDataValueJsonIntoSet(rowSet.getString("psi_eventdatavalues"));
            for (EventDataValue dv : eventDataValues) {
                DataValue dataValue = convertEventDataValueIntoDtoDataValue(dv);
                if (params.isSynchronizationQuery()) {
                    if (psdesWithSkipSyncTrue.containsKey(rowSet.getString("ps_uid")) && psdesWithSkipSyncTrue.get(rowSet.getString("ps_uid")).contains(dv.getDataElement())) {
                        dataValue.setSkipSynchronization(true);
                    } else {
                        dataValue.setSkipSynchronization(false);
                    }
                }
                event.getDataValues().add(dataValue);
            }
        }
        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"));
            if (rowSet.getObject("usernote_id") != null) {
                note.setLastUpdatedBy(UserInfoSnapshot.of(rowSet.getLong("usernote_id"), rowSet.getString("usernote_code"), rowSet.getString("usernote_uid"), rowSet.getString("usernote_username"), rowSet.getString("userinfo_firstname"), rowSet.getString("userinfo_surname")));
            }
            note.setLastUpdated(rowSet.getDate("psinote_lastupdated"));
            event.getNotes().add(note);
            notes.add(rowSet.getString("psinote_id"));
        }
        if (params.isIncludeRelationships() && rowSet.getObject("psi_rl") != null) {
            PGobject pGobject = (PGobject) rowSet.getObject("psi_rl");
            if (pGobject != null) {
                String value = pGobject.getValue();
                relationshipIds.addAll(Lists.newArrayList(gson.fromJson(value, Long[].class)));
            }
        }
    }
    final Multimap<String, Relationship> map = eventStore.getRelationshipsByIds(relationshipIds);
    if (!map.isEmpty()) {
        events.forEach(e -> e.getRelationships().addAll(map.get(e.getEvent())));
    }
    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 = events.stream().map(Event::getDataValues).collect(Collectors.toList());
        populateCache(dataElementIdScheme, dataValuesList, dataElementUidToIdentifierCache);
        convertDataValuesIdentifiers(dataElementIdScheme, dataValuesList, dataElementUidToIdentifierCache);
    }
    if (params.getCategoryOptionCombo() == null && !isSuper(user)) {
        return events.stream().filter(ev -> ev.getAttributeCategoryOptions() != null && splitToArray(ev.getAttributeCategoryOptions(), TextUtils.SEMICOLON).size() == ev.getOptionSize()).collect(Collectors.toList());
    }
    return events;
}
Also used : SqlRowSet(org.springframework.jdbc.support.rowset.SqlRowSet) EventUtils.userInfoToJson(org.hisp.dhis.dxf2.events.event.EventUtils.userInfoToJson) WKTReader(org.locationtech.jts.io.WKTReader) UID(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.UID) CREATEDCLIENT(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.CREATEDCLIENT) EventRow(org.hisp.dhis.dxf2.events.report.EventRow) DELETED(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.DELETED) UPDATED(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.UPDATED) StringUtils(org.apache.commons.lang3.StringUtils) EVENT_CREATED_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_CREATED_ID) EVENT_EXECUTION_DATE_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_EXECUTION_DATE_ID) Relationship(org.hisp.dhis.dxf2.events.trackedentity.Relationship) EnrollmentStatus(org.hisp.dhis.dxf2.events.enrollment.EnrollmentStatus) STATIC_EVENT_COLUMNS(org.hisp.dhis.dxf2.events.event.AbstractEventService.STATIC_EVENT_COLUMNS) CREATED(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.CREATED) Map(java.util.Map) SqlUtils.castToNumber(org.hisp.dhis.system.util.SqlUtils.castToNumber) EventDataValue(org.hisp.dhis.eventdatavalue.EventDataValue) SqlUtils.lower(org.hisp.dhis.system.util.SqlUtils.lower) SqlRowSet(org.springframework.jdbc.support.rowset.SqlRowSet) Repository(org.springframework.stereotype.Repository) EVENT_STATUS_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_STATUS_ID) OrganisationUnitSelectionMode(org.hisp.dhis.common.OrganisationUnitSelectionMode) JpaQueryUtils(org.hisp.dhis.query.JpaQueryUtils) DateUtils.getMediumDateString(org.hisp.dhis.util.DateUtils.getMediumDateString) Set(java.util.Set) STATUS(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.STATUS) EXECUTION_DATE(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.EXECUTION_DATE) PreparedStatement(java.sql.PreparedStatement) Attribute(org.hisp.dhis.dxf2.events.trackedentity.Attribute) TextUtils.removeLastComma(org.hisp.dhis.commons.util.TextUtils.removeLastComma) Slf4j(lombok.extern.slf4j.Slf4j) ParseException(org.locationtech.jts.io.ParseException) ProgramType(org.hisp.dhis.program.ProgramType) QueryFilter(org.hisp.dhis.common.QueryFilter) EVENT_STORED_BY_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_STORED_BY_ID) Joiner(com.google.common.base.Joiner) QueryItem(org.hisp.dhis.common.QueryItem) ProgramStageInstance(org.hisp.dhis.program.ProgramStageInstance) EVENT_GEOMETRY(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_GEOMETRY) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) Lists(com.google.common.collect.Lists) IdentifiableObjectManager(org.hisp.dhis.common.IdentifiableObjectManager) STOREDBY(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.STOREDBY) SqlHelper(org.hisp.dhis.commons.util.SqlHelper) OrderParam(org.hisp.dhis.webapi.controller.event.mapper.OrderParam) EVENT_ENROLLMENT_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_ENROLLMENT_ID) IdSchemes(org.hisp.dhis.common.IdSchemes) QueryOperator(org.hisp.dhis.common.QueryOperator) ID(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.ID) IOException(java.io.IOException) StatementBuilder(org.hisp.dhis.jdbc.StatementBuilder) ObjectUtils(org.hisp.dhis.util.ObjectUtils) GEOMETRY(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.GEOMETRY) COMPLETEDBY(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.COMPLETEDBY) DateUtils(org.hisp.dhis.util.DateUtils) TextUtils(org.hisp.dhis.commons.util.TextUtils) EVENT_PROGRAM_STAGE_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_PROGRAM_STAGE_ID) Date(java.util.Date) ValueType(org.hisp.dhis.common.ValueType) DateUtils.getDateAfterAddition(org.hisp.dhis.util.DateUtils.getDateAfterAddition) RequiredArgsConstructor(lombok.RequiredArgsConstructor) EVENT_LAST_UPDATED_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_LAST_UPDATED_ID) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) Gson(com.google.gson.Gson) SqlUtils.escapeSql(org.hisp.dhis.system.util.SqlUtils.escapeSql) TextUtils.getQuotedCommaDelimitedString(org.hisp.dhis.commons.util.TextUtils.getQuotedCommaDelimitedString) TypeReference(com.fasterxml.jackson.core.type.TypeReference) EVENT_PROGRAM_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_PROGRAM_ID) EventUtils.eventDataValuesToJson(org.hisp.dhis.dxf2.events.event.EventUtils.eventDataValuesToJson) EVENT_DUE_DATE_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_DUE_DATE_ID) ImmutableMap(com.google.common.collect.ImmutableMap) DateUtils.getLongGmtDateString(org.hisp.dhis.util.DateUtils.getLongGmtDateString) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) UserInfoSnapshot(org.hisp.dhis.program.UserInfoSnapshot) EventStatus(org.hisp.dhis.event.EventStatus) Collectors(java.util.stream.Collectors) TextUtils.splitToArray(org.hisp.dhis.commons.util.TextUtils.splitToArray) List(java.util.List) CollectionUtils.isNotEmpty(org.apache.commons.collections4.CollectionUtils.isNotEmpty) Environment(org.springframework.core.env.Environment) AclService(org.hisp.dhis.security.acl.AclService) Optional(java.util.Optional) Geometry(org.locationtech.jts.geom.Geometry) BatchPreparedStatementSetterWithKeyHolder(org.hisp.dhis.jdbc.BatchPreparedStatementSetterWithKeyHolder) EVENT_ORG_UNIT_NAME(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_ORG_UNIT_NAME) EVENT_CREATED_BY_USER_INFO_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_CREATED_BY_USER_INFO_ID) EVENT_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_ID) DataAccessException(org.springframework.dao.DataAccessException) HashMap(java.util.HashMap) Multimap(com.google.common.collect.Multimap) Program(org.hisp.dhis.program.Program) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) HashSet(java.util.HashSet) DataElement(org.hisp.dhis.dataelement.DataElement) PGobject(org.postgresql.util.PGobject) ImmutableList(com.google.common.collect.ImmutableList) UPDATEDCLIENT(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.UPDATEDCLIENT) Qualifier(org.springframework.beans.factory.annotation.Qualifier) User(org.hisp.dhis.user.User) EVENT_ORG_UNIT_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_ORG_UNIT_ID) EVENT_LAST_UPDATED_BY_USER_INFO_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_LAST_UPDATED_BY_USER_INFO_ID) EVENT_DELETED(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_DELETED) JdbcUtils(org.hisp.dhis.jdbc.JdbcUtils) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) EventUtils.jsonToUserInfo(org.hisp.dhis.dxf2.events.event.EventUtils.jsonToUserInfo) ProgramStage(org.hisp.dhis.program.ProgramStage) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) ProgramStatus(org.hisp.dhis.program.ProgramStatus) Collectors.toList(java.util.stream.Collectors.toList) CollectionUtils(org.hisp.dhis.commons.collection.CollectionUtils) EVENT_ATTRIBUTE_OPTION_COMBO_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_ATTRIBUTE_OPTION_COMBO_ID) JsonEventDataValueSetBinaryType(org.hisp.dhis.hibernate.jsonb.type.JsonEventDataValueSetBinaryType) CurrentUserService(org.hisp.dhis.user.CurrentUserService) COMPLETEDDATE(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.COMPLETEDDATE) CachingMap(org.hisp.dhis.commons.collection.CachingMap) DUE_DATE(org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.DUE_DATE) Comparator(java.util.Comparator) EVENT_COMPLETED_BY_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_COMPLETED_BY_ID) EVENT_COMPLETED_DATE_ID(org.hisp.dhis.dxf2.events.event.EventSearchParams.EVENT_COMPLETED_DATE_ID) IdScheme(org.hisp.dhis.common.IdScheme) User(org.hisp.dhis.user.User) IdSchemes(org.hisp.dhis.common.IdSchemes) HashMap(java.util.HashMap) EventDataValue(org.hisp.dhis.eventdatavalue.EventDataValue) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) 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) WKTReader(org.locationtech.jts.io.WKTReader) PGobject(org.postgresql.util.PGobject) CachingMap(org.hisp.dhis.commons.collection.CachingMap) ProgramType(org.hisp.dhis.program.ProgramType) EventDataValue(org.hisp.dhis.eventdatavalue.EventDataValue) HashSet(java.util.HashSet) IdScheme(org.hisp.dhis.common.IdScheme) Geometry(org.locationtech.jts.geom.Geometry) Relationship(org.hisp.dhis.dxf2.events.trackedentity.Relationship) Collection(java.util.Collection) ParseException(org.locationtech.jts.io.ParseException)

Example 72 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project dhis2-core by dhis2.

the class DataValueCheck method validateMandatoryAttributes.

public void validateMandatoryAttributes(ImportConflicts importConflicts, WorkContext ctx, ImmutableEvent event) {
    if (StringUtils.isEmpty(event.getProgramStage()))
        return;
    final IdScheme programStageIdScheme = ctx.getImportOptions().getIdSchemes().getProgramStageIdScheme();
    final IdScheme dataElementIdScheme = ctx.getImportOptions().getIdSchemes().getDataElementIdScheme();
    final Map<String, Set<EventDataValue>> eventDataValueMap = ctx.getEventDataValueMap();
    final boolean allowSingleUpdates = ctx.getImportOptions().isMergeDataValues();
    ProgramStage programStage = ctx.getProgramStage(programStageIdScheme, event.getProgramStage());
    final Set<ProgramStageDataElement> mandatoryDataElements = getMandatoryProgramStageDataElements(programStage);
    // Data Element IDs associated to the current event
    Set<String> dataValues = eventDataValueMap.get(event.getUid()).stream().map(EventDataValue::getDataElement).collect(Collectors.toSet());
    if (allowSingleUpdates) {
        final ProgramStageInstance programStageInstance = ctx.getProgramStageInstanceMap().get(event.getUid());
        dataValues.addAll(programStageInstance.getEventDataValues().stream().filter(dv -> !StringUtils.isEmpty(dv.getValue().trim())).map(EventDataValue::getDataElement).collect(Collectors.toSet()));
    }
    for (ProgramStageDataElement mandatoryDataElement : mandatoryDataElements) {
        String resolvedDataElementId = getIdentifierBasedOnIdScheme(mandatoryDataElement.getDataElement(), dataElementIdScheme);
        if (!dataValues.contains(resolvedDataElementId)) {
            importConflicts.addConflict(resolvedDataElementId, "value_required_but_not_provided");
        }
    }
}
Also used : ProgramStageDataElement(org.hisp.dhis.program.ProgramStageDataElement) DataValue(org.hisp.dhis.dxf2.events.event.DataValue) Authorities(org.hisp.dhis.security.Authorities) ValueType(org.hisp.dhis.common.ValueType) ValidationUtils(org.hisp.dhis.system.util.ValidationUtils) ProgramStageDataElement(org.hisp.dhis.program.ProgramStageDataElement) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) ProgramStageInstance(org.hisp.dhis.program.ProgramStageInstance) IdentifiableObjectUtils.getIdentifierBasedOnIdScheme(org.hisp.dhis.common.IdentifiableObjectUtils.getIdentifierBasedOnIdScheme) StringUtils(org.apache.commons.lang3.StringUtils) DataElement(org.hisp.dhis.dataelement.DataElement) WorkContext(org.hisp.dhis.dxf2.events.importer.context.WorkContext) SQLException(java.sql.SQLException) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) ImportConflicts(org.hisp.dhis.dxf2.importsummary.ImportConflicts) Map(java.util.Map) Checker(org.hisp.dhis.dxf2.events.importer.Checker) ImageIO(javax.imageio.ImageIO) EventDataValue(org.hisp.dhis.eventdatavalue.EventDataValue) User(org.hisp.dhis.user.User) ImportStatus(org.hisp.dhis.dxf2.importsummary.ImportStatus) EventUtils.eventDataValuesToJson(org.hisp.dhis.dxf2.events.event.EventUtils.eventDataValuesToJson) ImmutableSet(com.google.common.collect.ImmutableSet) FileResource(org.hisp.dhis.fileresource.FileResource) Set(java.util.Set) EventStatus(org.hisp.dhis.event.EventStatus) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Collectors(java.util.stream.Collectors) ProgramStage(org.hisp.dhis.program.ProgramStage) Component(org.springframework.stereotype.Component) OptionSet(org.hisp.dhis.option.OptionSet) ImmutableEvent(org.hisp.dhis.dxf2.events.importer.shared.ImmutableEvent) Optional(java.util.Optional) ValidationStrategy(org.hisp.dhis.program.ValidationStrategy) Collections(java.util.Collections) IdScheme(org.hisp.dhis.common.IdScheme) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) OptionSet(org.hisp.dhis.option.OptionSet) IdentifiableObjectUtils.getIdentifierBasedOnIdScheme(org.hisp.dhis.common.IdentifiableObjectUtils.getIdentifierBasedOnIdScheme) IdScheme(org.hisp.dhis.common.IdScheme) ProgramStage(org.hisp.dhis.program.ProgramStage) EventDataValue(org.hisp.dhis.eventdatavalue.EventDataValue) ProgramStageInstance(org.hisp.dhis.program.ProgramStageInstance)

Example 73 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project dhis2-core by dhis2.

the class AbstractTrackerPersister method handleTrackedEntityAttributeValues.

protected void handleTrackedEntityAttributeValues(Session session, TrackerPreheat preheat, List<Attribute> payloadAttributes, TrackedEntityInstance trackedEntityInstance) {
    if (payloadAttributes.isEmpty()) {
        return;
    }
    Map<String, TrackedEntityAttributeValue> attributeValueByUid = trackedEntityInstance.getTrackedEntityAttributeValues().stream().collect(Collectors.toMap(teav -> teav.getAttribute().getUid(), Function.identity()));
    payloadAttributes.forEach(attribute -> {
        // We cannot get the value from attributeToStore because it uses
        // encryption logic, so we need to use the one from payload
        boolean isDelete = StringUtils.isEmpty(attribute.getValue());
        TrackedEntityAttributeValue trackedEntityAttributeValue = attributeValueByUid.get(attribute.getAttribute());
        boolean isUpdated = false;
        boolean isNew = Objects.isNull(trackedEntityAttributeValue);
        if (isDelete && isNew) {
            return;
        }
        if (isDelete) {
            delete(session, preheat, trackedEntityAttributeValue, trackedEntityInstance);
        } else {
            if (!isNew) {
                isUpdated = !trackedEntityAttributeValue.getPlainValue().equals(attribute.getValue());
            }
            trackedEntityAttributeValue = Optional.ofNullable(trackedEntityAttributeValue).orElseGet(() -> new TrackedEntityAttributeValue().setAttribute(getTrackedEntityAttributeFromPreheat(preheat, attribute.getAttribute())).setEntityInstance(trackedEntityInstance)).setStoredBy(attribute.getStoredBy()).setValue(attribute.getValue());
            saveOrUpdate(session, preheat, isNew, trackedEntityInstance, trackedEntityAttributeValue, isUpdated);
        }
        handleReservedValue(trackedEntityAttributeValue);
    });
}
Also used : ValueType(org.hisp.dhis.common.ValueType) Attribute(org.hisp.dhis.tracker.domain.Attribute) RequiredArgsConstructor(lombok.RequiredArgsConstructor) ReservedValueService(org.hisp.dhis.reservedvalue.ReservedValueService) Session(org.hibernate.Session) AuditType(org.hisp.dhis.common.AuditType) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) TrackerObjectReport(org.hisp.dhis.tracker.report.TrackerObjectReport) Function(java.util.function.Function) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) TrackedEntityAttributeValueAuditService(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValueAuditService) AtomicMode(org.hisp.dhis.tracker.AtomicMode) AccessLevel(lombok.AccessLevel) Map(java.util.Map) FlushMode(org.hisp.dhis.tracker.FlushMode) TrackerSideEffectDataBundle(org.hisp.dhis.tracker.job.TrackerSideEffectDataBundle) TrackedEntityAttributeValueAudit(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValueAudit) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) FileResource(org.hisp.dhis.fileresource.FileResource) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) TrackedEntityInstance(org.hisp.dhis.trackedentity.TrackedEntityInstance) Set(java.util.Set) TrackerType(org.hisp.dhis.tracker.TrackerType) TrackerBundle(org.hisp.dhis.tracker.bundle.TrackerBundle) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Optional(java.util.Optional) TrackerDto(org.hisp.dhis.tracker.domain.TrackerDto) TrackedEntityAttribute(org.hisp.dhis.trackedentity.TrackedEntityAttribute) TrackerPreheat(org.hisp.dhis.tracker.preheat.TrackerPreheat) TrackerTypeReport(org.hisp.dhis.tracker.report.TrackerTypeReport) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue)

Example 74 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project dhis2-core by dhis2.

the class TrackerBundleParamsConverter method convert.

/**
 * Iterates over the collections of a dataBundle. If any objects in those
 * collections have objects nested within them, they are extracted. For each
 * object we process, we make sure all references are valid as well.
 *
 * @param dataBundle containing collections to check and update.
 * @return a dataBundle with a flattened data structure, and valid uid
 *         references.
 */
@Override
public TrackerBundleParams convert(TrackerBundleParams dataBundle) {
    Map<String, TrackedEntity> trackedEntityMap = new HashMap<>();
    Map<String, Enrollment> enrollmentHashMap = new HashMap<>();
    Map<String, Event> eventHashMap = new HashMap<>();
    Map<String, Relationship> relationshipHashMap = new HashMap<>();
    // Extract all enrollments and relationships, and set parent reference.
    for (TrackedEntity te : dataBundle.getTrackedEntities()) {
        updateTrackedEntityReferences(te);
        trackedEntityMap.put(te.getTrackedEntity(), te);
        extractEnrollments(te).forEach(enrollment -> enrollmentHashMap.put(enrollment.getEnrollment(), enrollment));
        extractRelationships(te).forEach(relationship -> relationshipHashMap.put(relationship.getRelationship(), relationship));
    }
    // Set UID for all enrollments and notes
    dataBundle.getEnrollments().stream().peek(enrollment -> updateEnrollmentReferences(enrollment, enrollment.getTrackedEntity())).forEach(enrollment -> enrollmentHashMap.put(enrollment.getEnrollment(), enrollment));
    // Extract all events and relationships, and set parent references
    for (Enrollment enrollment : enrollmentHashMap.values()) {
        extractEvents(enrollment).forEach(event -> eventHashMap.put(event.getEvent(), event));
        extractRelationships(enrollment).forEach(relationship -> relationshipHashMap.put(relationship.getRelationship(), relationship));
        enrollment.setNotes(enrollment.getNotes().stream().filter(note -> !StringUtils.isEmpty(note.getValue())).peek(this::updateNoteReferences).collect(Collectors.toList()));
    }
    // Set UID for all events and notes
    dataBundle.getEvents().stream().peek(event -> updateEventReferences(event, event.getEnrollment())).forEach(event -> eventHashMap.put(event.getEvent(), event));
    // Extract all relationships
    for (Event event : eventHashMap.values()) {
        extractRelationships(event).forEach(relationship -> relationshipHashMap.put(relationship.getRelationship(), relationship));
        event.setNotes(event.getNotes().stream().filter(note -> !StringUtils.isEmpty(note.getValue())).peek(this::updateNoteReferences).collect(Collectors.toList()));
    }
    // Set UID for all relationships
    dataBundle.getRelationships().stream().peek(this::updateRelationshipReferences).forEach(relationship -> relationshipHashMap.put(relationship.getRelationship(), relationship));
    return TrackerBundleParams.builder().trackedEntities(new ArrayList<>(trackedEntityMap.values())).enrollments(new ArrayList<>(enrollmentHashMap.values())).events(new ArrayList<>(eventHashMap.values())).relationships(new ArrayList<>(relationshipHashMap.values())).build();
}
Also used : Event(org.hisp.dhis.tracker.domain.Event) StdConverter(com.fasterxml.jackson.databind.util.StdConverter) TrackedEntity(org.hisp.dhis.tracker.domain.TrackedEntity) HashMap(java.util.HashMap) Relationship(org.hisp.dhis.tracker.domain.Relationship) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) Enrollment(org.hisp.dhis.tracker.domain.Enrollment) List(java.util.List) Note(org.hisp.dhis.tracker.domain.Note) Map(java.util.Map) CodeGenerator(org.hisp.dhis.common.CodeGenerator) HashMap(java.util.HashMap) TrackedEntity(org.hisp.dhis.tracker.domain.TrackedEntity) ArrayList(java.util.ArrayList) Relationship(org.hisp.dhis.tracker.domain.Relationship) Enrollment(org.hisp.dhis.tracker.domain.Enrollment) Event(org.hisp.dhis.tracker.domain.Event)

Example 75 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project mxisd by kamax-io.

the class RegistrationManager method execute.

public RegistrationReply execute(URI target, JsonObject request) {
    HttpPost registerProxyRq = RestClientUtils.post(resolveProxyUrl(target), GsonUtil.get(), request);
    try (CloseableHttpResponse response = client.execute(registerProxyRq)) {
        int status = response.getStatusLine().getStatusCode();
        if (status == 200) {
            // The user managed to register. We check if it had a session
            String sessionId = GsonUtil.findObj(request, "auth").flatMap(auth -> GsonUtil.findString(auth, "session")).orElse("");
            if (StringUtils.isEmpty(sessionId)) {
                // No session ID was provided. This is an edge case we do not support for now as investigation is needed
                // to ensure how and when this happens.
                HttpPost newSessReq = RestClientUtils.post(resolveProxyUrl(target), GsonUtil.get(), new JsonObject());
                try (CloseableHttpResponse newSessRes = client.execute(newSessReq)) {
                    RegistrationReply reply = new RegistrationReply();
                    reply.setStatus(newSessRes.getStatusLine().getStatusCode());
                    reply.setBody(GsonUtil.parseObj(EntityUtils.toString(newSessRes.getEntity())));
                    return reply;
                }
            }
        }
        throw new NotImplementedException("Registration");
    } catch (IOException e) {
        throw new RemoteHomeServerException(e.getMessage());
    }
}
Also used : JsonObject(com.google.gson.JsonObject) HttpPost(org.apache.http.client.methods.HttpPost) GsonUtil(io.kamax.matrix.json.GsonUtil) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Logger(org.slf4j.Logger) URIBuilder(org.apache.http.client.utils.URIBuilder) LoggerFactory(org.slf4j.LoggerFactory) RegisterConfig(io.kamax.mxisd.config.RegisterConfig) IOException(java.io.IOException) StringUtils(org.apache.commons.lang3.StringUtils) NotImplementedException(io.kamax.mxisd.exception.NotImplementedException) ThreePid(io.kamax.matrix.ThreePid) EntityUtils(org.apache.http.util.EntityUtils) RestClientUtils(io.kamax.mxisd.util.RestClientUtils) Objects(java.util.Objects) Matcher(java.util.regex.Matcher) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) InvitationManager(io.kamax.mxisd.invitation.InvitationManager) URI(java.net.URI) Pattern(java.util.regex.Pattern) ClientDnsOverwrite(io.kamax.mxisd.dns.ClientDnsOverwrite) RemoteHomeServerException(io.kamax.mxisd.exception.RemoteHomeServerException) HttpPost(org.apache.http.client.methods.HttpPost) RemoteHomeServerException(io.kamax.mxisd.exception.RemoteHomeServerException) NotImplementedException(io.kamax.mxisd.exception.NotImplementedException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)76 List (java.util.List)53 Collectors (java.util.stream.Collectors)40 ArrayList (java.util.ArrayList)39 Map (java.util.Map)39 HashMap (java.util.HashMap)28 IOException (java.io.IOException)26 Collections (java.util.Collections)25 Set (java.util.Set)25 Logger (org.slf4j.Logger)25 Arrays (java.util.Arrays)24 LoggerFactory (org.slf4j.LoggerFactory)24 Optional (java.util.Optional)22 HashSet (java.util.HashSet)18 Collection (java.util.Collection)14 Autowired (org.springframework.beans.factory.annotation.Autowired)13 Objects (java.util.Objects)12 UUID (java.util.UUID)11 java.util (java.util)10 Component (org.springframework.stereotype.Component)10