Search in sources :

Example 1 with TextPattern

use of org.hisp.dhis.textpattern.TextPattern in project dhis2-core by dhis2.

the class TrackedEntityAttributeObjectBundleHook method textPatternValid.

private void textPatternValid(TrackedEntityAttribute attr, Consumer<ErrorReport> addReports) {
    if (attr.isGenerated()) {
        try {
            TextPattern tp = TextPatternParser.parse(attr.getPattern());
            long generatedSegments = tp.getSegments().stream().filter((s) -> s.getMethod().isGenerated()).count();
            if (generatedSegments != 1) {
                addReports.accept(new ErrorReport(TrackedEntityAttribute.class, ErrorCode.E4021));
            }
            if (!TextPatternValidationUtils.validateValueType(tp, attr.getValueType())) {
                addReports.accept(new ErrorReport(TrackedEntityAttribute.class, ErrorCode.E4022, attr.getPattern(), attr.getValueType().name()));
            }
        } catch (TextPatternParser.TextPatternParsingException e) {
            addReports.accept(new ErrorReport(TrackedEntityAttribute.class, ErrorCode.E4019, attr.getPattern(), e.getMessage()));
        }
    }
}
Also used : Consumer(java.util.function.Consumer) TextPatternValidationUtils(org.hisp.dhis.textpattern.TextPatternValidationUtils) TextPatternParser(org.hisp.dhis.textpattern.TextPatternParser) Component(org.springframework.stereotype.Component) ObjectBundle(org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle) ErrorReport(org.hisp.dhis.feedback.ErrorReport) ValueType(org.hisp.dhis.common.ValueType) TextPattern(org.hisp.dhis.textpattern.TextPattern) Objects(org.hisp.dhis.common.Objects) ErrorCode(org.hisp.dhis.feedback.ErrorCode) TrackedEntityAttribute(org.hisp.dhis.trackedentity.TrackedEntityAttribute) ErrorReport(org.hisp.dhis.feedback.ErrorReport) TextPattern(org.hisp.dhis.textpattern.TextPattern) TrackedEntityAttribute(org.hisp.dhis.trackedentity.TrackedEntityAttribute) TextPatternParser(org.hisp.dhis.textpattern.TextPatternParser)

Example 2 with TextPattern

use of org.hisp.dhis.textpattern.TextPattern in project dhis2-core by dhis2.

the class TrackedEntityInstanceServiceTest method setUpTest.

@Override
protected void setUpTest() throws Exception {
    organisationUnitA = createOrganisationUnit('A');
    organisationUnitB = createOrganisationUnit('B');
    organisationUnitB.setParent(organisationUnitA);
    uniqueIdAttribute = createTrackedEntityAttribute('A');
    uniqueIdAttribute.setGenerated(true);
    // uniqueIdAttribute.setPattern( "RANDOM(#####)" );
    TextPattern textPattern = new TextPattern(Lists.newArrayList(new TextPatternSegment(TextPatternMethod.RANDOM, "RANDOM(#####)")));
    textPattern.setOwnerObject(Objects.TRACKEDENTITYATTRIBUTE);
    textPattern.setOwnerUid(uniqueIdAttribute.getUid());
    uniqueIdAttribute.setTextPattern(textPattern);
    trackedEntityAttributeService.addTrackedEntityAttribute(uniqueIdAttribute);
    trackedEntityAttributeB = createTrackedEntityAttribute('B');
    trackedEntityAttributeService.addTrackedEntityAttribute(trackedEntityAttributeB);
    trackedEntityType = createTrackedEntityType('A');
    TrackedEntityTypeAttribute trackedEntityTypeAttribute = new TrackedEntityTypeAttribute();
    trackedEntityTypeAttribute.setTrackedEntityAttribute(uniqueIdAttribute);
    trackedEntityTypeAttribute.setTrackedEntityType(trackedEntityType);
    trackedEntityType.setTrackedEntityTypeAttributes(Lists.newArrayList(trackedEntityTypeAttribute));
    trackedEntityTypeService.addTrackedEntityType(trackedEntityType);
    maleA = createTrackedEntityInstance(organisationUnitA);
    maleB = createTrackedEntityInstance(organisationUnitB);
    femaleA = createTrackedEntityInstance(organisationUnitA);
    femaleB = createTrackedEntityInstance(organisationUnitB);
    dateConflictsMaleA = createTrackedEntityInstance(organisationUnitA);
    TrackedEntityAttributeValue uniqueId = createTrackedEntityAttributeValue('A', maleA, uniqueIdAttribute);
    uniqueId.setValue("12345");
    maleA.setTrackedEntityType(trackedEntityType);
    maleA.setTrackedEntityAttributeValues(Sets.newHashSet(uniqueId));
    maleB.setTrackedEntityType(trackedEntityType);
    femaleA.setTrackedEntityType(trackedEntityType);
    femaleB.setTrackedEntityType(trackedEntityType);
    dateConflictsMaleA.setTrackedEntityType(trackedEntityType);
    programA = createProgram('A', new HashSet<>(), organisationUnitA);
    programA.setProgramType(ProgramType.WITH_REGISTRATION);
    programStageA1 = createProgramStage('1', programA);
    programStageA2 = createProgramStage('2', programA);
    programA.setProgramStages(Stream.of(programStageA1, programStageA2).collect(Collectors.toCollection(HashSet::new)));
    manager.save(organisationUnitA);
    manager.save(organisationUnitB);
    manager.save(maleA);
    manager.save(maleB);
    manager.save(femaleA);
    manager.save(femaleB);
    manager.save(dateConflictsMaleA);
    manager.save(programA);
    manager.save(programStageA1);
    manager.save(programStageA2);
    teiMaleA = trackedEntityInstanceService.getTrackedEntityInstance(maleA);
    teiMaleB = trackedEntityInstanceService.getTrackedEntityInstance(maleB);
    teiFemaleA = trackedEntityInstanceService.getTrackedEntityInstance(femaleA);
    trackedEntityAttributeValueService.addTrackedEntityAttributeValue(uniqueId);
    programInstanceService.enrollTrackedEntityInstance(maleA, programA, null, null, organisationUnitA);
    programInstanceService.enrollTrackedEntityInstance(femaleA, programA, DateTime.now().plusMonths(1).toDate(), null, organisationUnitA);
    programInstanceService.enrollTrackedEntityInstance(dateConflictsMaleA, programA, DateTime.now().plusMonths(1).toDate(), DateTime.now().plusMonths(2).toDate(), organisationUnitA);
    manager.flush();
}
Also used : TextPattern(org.hisp.dhis.textpattern.TextPattern) TextPatternSegment(org.hisp.dhis.textpattern.TextPatternSegment) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) TrackedEntityTypeAttribute(org.hisp.dhis.trackedentity.TrackedEntityTypeAttribute) HashSet(java.util.HashSet)

Example 3 with TextPattern

use of org.hisp.dhis.textpattern.TextPattern in project dhis2-core by dhis2.

the class TrackedEntityInstanceServiceTest method testUpdateTeiAfterChangingTextPatternForGeneratedAttribute.

@Test
void testUpdateTeiAfterChangingTextPatternForGeneratedAttribute() {
    TrackedEntityInstance trackedEntityInstance = trackedEntityInstanceService.getTrackedEntityInstance(maleA.getUid());
    assertNotNull(trackedEntityInstance.getEnrollments());
    assertEquals(1, trackedEntityInstance.getEnrollments().size());
    Enrollment enrollment1 = trackedEntityInstance.getEnrollments().get(0);
    enrollment1.setStatus(EnrollmentStatus.COMPLETED);
    enrollment1.setCompletedBy("test");
    enrollment1.setCompletedDate(new Date());
    Enrollment enrollment2 = new Enrollment();
    enrollment2.setTrackedEntityInstance(maleA.getUid());
    TextPattern textPattern = new TextPattern(Lists.newArrayList(new TextPatternSegment(TextPatternMethod.RANDOM, "RANDOM(#######)")));
    textPattern.setOwnerUid("owneruid");
    textPattern.setOwnerObject(Objects.CONSTANT);
    uniqueIdAttribute.setTextPattern(textPattern);
    trackedEntityAttributeService.updateTrackedEntityAttribute(uniqueIdAttribute);
    enrollment2.setEnrollmentDate(new Date());
    enrollment2.setOrgUnit(organisationUnitA.getUid());
    enrollment2.setProgram(programA.getUid());
    enrollment2.setStatus(EnrollmentStatus.ACTIVE);
    trackedEntityInstance.getEnrollments().add(enrollment2);
    ImportSummary importSummary = trackedEntityInstanceService.updateTrackedEntityInstance(trackedEntityInstance, null, null, true);
    assertEquals(ImportStatus.SUCCESS, importSummary.getStatus());
    assertEquals(ImportStatus.SUCCESS, importSummary.getEnrollments().getStatus());
}
Also used : TextPattern(org.hisp.dhis.textpattern.TextPattern) TextPatternSegment(org.hisp.dhis.textpattern.TextPatternSegment) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) Enrollment(org.hisp.dhis.dxf2.events.enrollment.Enrollment) TrackedEntityInstance(org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance) Date(java.util.Date) TransactionalIntegrationTest(org.hisp.dhis.TransactionalIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 4 with TextPattern

use of org.hisp.dhis.textpattern.TextPattern in project dhis2-core by dhis2.

the class DefaultReservedValueService method reserve.

@Override
@Transactional
public List<ReservedValue> reserve(TrackedEntityAttribute trackedEntityAttribute, int numberOfReservations, Map<String, String> values, Date expires) throws ReserveValueException, TextPatternGenerationException {
    long startTime = System.currentTimeMillis();
    int attemptsLeft = RESERVED_VALUE_GENERATION_ATTEMPT;
    List<ReservedValue> resultList = new ArrayList<>();
    TextPattern textPattern = trackedEntityAttribute.getTextPattern();
    TextPatternSegment generatedSegment = textPattern.getSegments().stream().filter((tp) -> tp.getMethod().isGenerated() && Boolean.TRUE.equals(trackedEntityAttribute.isGenerated())).findFirst().orElse(null);
    String key = textPatternService.resolvePattern(textPattern, values);
    // Used for searching value tables
    String valueKey = Optional.ofNullable(generatedSegment).map(gs -> key.replaceAll(Pattern.quote(gs.getRawSegment()), "%")).orElse(key);
    ReservedValue reservedValue = ReservedValue.builder().created(new Date()).ownerObject(textPattern.getOwnerObject().name()).ownerUid(textPattern.getOwnerUid()).key(key).value(valueKey).expiryDate(expires).build();
    checkIfEnoughValues(numberOfReservations, generatedSegment, reservedValue);
    if (generatedSegment == null) {
        if (numberOfReservations == 1) {
            List<ReservedValue> reservedValues = Collections.singletonList(reservedValue.toBuilder().value(key).build());
            reservedValueStore.reserveValues(reservedValues);
            return reservedValues;
        }
    } else {
        int numberOfValuesLeftToGenerate = numberOfReservations;
        boolean isPersistable = generatedSegment.getMethod().isPersistable();
        reservedValue.setTrackedEntityAttributeId(trackedEntityAttribute.getId());
        try {
            List<String> generatedValues = new ArrayList<>();
            while (attemptsLeft-- > 0 && numberOfValuesLeftToGenerate > 0) {
                checkTimeout(startTime);
                generatedValues.addAll(valueGeneratorService.generateValues(generatedSegment, textPattern, key, numberOfReservations - resultList.size()));
                List<String> resolvedPatterns = getResolvedPatterns(values, textPattern, generatedSegment, generatedValues);
                saveGeneratedValues(numberOfReservations, resultList, textPattern, reservedValue, isPersistable, resolvedPatterns);
                numberOfValuesLeftToGenerate = numberOfReservations - resultList.size();
                generatedValues = new ArrayList<>();
            }
        } catch (TimeoutException ex) {
            log.warn(String.format("Generation and reservation of values for %s wih uid %s timed out. %s values was reserved. You might be running low on available values", textPattern.getOwnerObject().name(), textPattern.getOwnerUid(), resultList.size()));
        } catch (ExecutionException e) {
            log.error(String.format("Generation and reservation of values error %s : ", e.getMessage()));
        } catch (InterruptedException e) {
            log.error(String.format("Generation and reservation of values error %s : ", e.getMessage()));
            Thread.currentThread().interrupt();
        }
    }
    return resultList;
}
Also used : ImmutableMap(com.google.common.collect.ImmutableMap) Date(java.util.Date) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TextPattern(org.hisp.dhis.textpattern.TextPattern) TimeoutException(java.util.concurrent.TimeoutException) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) ExecutionException(java.util.concurrent.ExecutionException) TextPatternValidationUtils(org.hisp.dhis.textpattern.TextPatternValidationUtils) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) TextPatternMethod(org.hisp.dhis.textpattern.TextPatternMethod) Service(org.springframework.stereotype.Service) Map(java.util.Map) TextPatternGenerationException(org.hisp.dhis.textpattern.TextPatternGenerationException) RESERVED_VALUE_GENERATION_ATTEMPT(org.hisp.dhis.util.Constants.RESERVED_VALUE_GENERATION_ATTEMPT) Optional(java.util.Optional) TextPatternService(org.hisp.dhis.textpattern.TextPatternService) Pattern(java.util.regex.Pattern) TextPatternSegment(org.hisp.dhis.textpattern.TextPatternSegment) Collections(java.util.Collections) TrackedEntityAttribute(org.hisp.dhis.trackedentity.TrackedEntityAttribute) RESERVED_VALUE_GENERATION_TIMEOUT(org.hisp.dhis.util.Constants.RESERVED_VALUE_GENERATION_TIMEOUT) Transactional(org.springframework.transaction.annotation.Transactional) TextPatternSegment(org.hisp.dhis.textpattern.TextPatternSegment) ArrayList(java.util.ArrayList) Date(java.util.Date) TextPattern(org.hisp.dhis.textpattern.TextPattern) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with TextPattern

use of org.hisp.dhis.textpattern.TextPattern in project dhis2-core by dhis2.

the class ReservedValueServiceIntegrationTest method createTextPattern.

private static TrackedEntityAttribute createTextPattern(IdentifiableObject owner, String pattern) {
    try {
        TextPattern textPattern = TextPatternParser.parse(pattern);
        textPattern.setOwnerObject(Objects.fromClass(owner.getClass()));
        textPattern.setOwnerUid(owner.getUid());
        TrackedEntityAttribute trackedEntityAttribute = new TrackedEntityAttribute();
        trackedEntityAttribute.setTextPattern(textPattern);
        trackedEntityAttribute.setGenerated(true);
        return trackedEntityAttribute;
    } catch (TextPatternParser.TextPatternParsingException | IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : TextPattern(org.hisp.dhis.textpattern.TextPattern) TrackedEntityAttribute(org.hisp.dhis.trackedentity.TrackedEntityAttribute)

Aggregations

TextPattern (org.hisp.dhis.textpattern.TextPattern)8 TrackedEntityAttribute (org.hisp.dhis.trackedentity.TrackedEntityAttribute)5 Date (java.util.Date)3 TextPatternParser (org.hisp.dhis.textpattern.TextPatternParser)3 TextPatternSegment (org.hisp.dhis.textpattern.TextPatternSegment)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Objects (org.hisp.dhis.common.Objects)2 TextPatternValidationUtils (org.hisp.dhis.textpattern.TextPatternValidationUtils)2 TrackedEntityAttributeValue (org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue)2 Test (org.junit.jupiter.api.Test)2 ImmutableMap (com.google.common.collect.ImmutableMap)1 Lists (com.google.common.collect.Lists)1 Calendar (java.util.Calendar)1 Collections (java.util.Collections)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 Optional (java.util.Optional)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1