Search in sources :

Example 6 with JobConfiguration

use of org.hisp.dhis.scheduling.JobConfiguration in project dhis2-core by dhis2.

the class DefaultAdxDataService method saveDataValueSetInternal.

private ImportSummary saveDataValueSetInternal(InputStream in, ImportOptions importOptions, JobConfiguration id) {
    notifier.clear(id).notify(id, "ADX parsing process started");
    ImportOptions adxImportOptions = firstNonNull(importOptions, ImportOptions.getDefaultImportOptions()).instance().setNotificationLevel(NotificationLevel.OFF);
    // Get import options
    IdScheme dsScheme = importOptions.getIdSchemes().getDataSetIdScheme();
    IdScheme deScheme = importOptions.getIdSchemes().getDataElementIdScheme();
    // Create meta-data maps
    CachingMap<String, DataSet> dataSetMap = new CachingMap<>();
    CachingMap<String, DataElement> dataElementMap = new CachingMap<>();
    // Get meta-data maps
    IdentifiableObjectCallable<DataSet> dataSetCallable = new IdentifiableObjectCallable<>(identifiableObjectManager, DataSet.class, dsScheme, null);
    IdentifiableObjectCallable<DataElement> dataElementCallable = new IdentifiableObjectCallable<>(identifiableObjectManager, DataElement.class, deScheme, null);
    // Heat cache
    if (importOptions.isPreheatCacheDefaultFalse()) {
        dataSetMap.load(identifiableObjectManager.getAll(DataSet.class), o -> o.getPropertyValue(dsScheme));
        dataElementMap.load(identifiableObjectManager.getAll(DataElement.class), o -> o.getPropertyValue(deScheme));
    }
    XMLReader adxReader = XMLFactory.getXMLReader(in);
    ImportSummary importSummary;
    adxReader.moveToStartElement(AdxDataService.ROOT, AdxDataService.NAMESPACE);
    ExecutorService executor = Executors.newSingleThreadExecutor();
    // For Async runs, give the DXF import a different notification task ID
    // so it doesn't conflict with notifications from this level.
    JobConfiguration dxfJobId = (id == null) ? null : new JobConfiguration("dxfJob", JobType.DATAVALUE_IMPORT_INTERNAL, id.getUserUid(), true);
    int groupCount = 0;
    try (PipedOutputStream pipeOut = new PipedOutputStream()) {
        Future<ImportSummary> futureImportSummary = executor.submit(new AdxPipedImporter(dataValueSetService, adxImportOptions, dxfJobId, pipeOut, sessionFactory));
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        XMLStreamWriter dxfWriter = factory.createXMLStreamWriter(pipeOut);
        List<ImportConflict> adxConflicts = new LinkedList<>();
        dxfWriter.writeStartDocument("1.0");
        dxfWriter.writeStartElement("dataValueSet");
        dxfWriter.writeDefaultNamespace("http://dhis2.org/schema/dxf/2.0");
        notifier.notify(id, "Starting to import ADX data groups.");
        while (adxReader.moveToStartElement(AdxDataService.GROUP, AdxDataService.NAMESPACE)) {
            notifier.update(id, "Importing ADX data group: " + groupCount);
            // note this returns conflicts which are detected at ADX level
            adxConflicts.addAll(parseAdxGroupToDxf(adxReader, dxfWriter, adxImportOptions, dataSetMap, dataSetCallable, dataElementMap, dataElementCallable));
            groupCount++;
        }
        // end dataValueSet
        dxfWriter.writeEndElement();
        dxfWriter.writeEndDocument();
        pipeOut.flush();
        importSummary = futureImportSummary.get(TOTAL_MINUTES_TO_WAIT, TimeUnit.MINUTES);
        ImportSummary summary = importSummary;
        adxConflicts.forEach(conflict -> summary.addConflict(conflict.getObject(), conflict.getValue()));
        importSummary.getImportCount().incrementIgnored(adxConflicts.size());
    } catch (AdxException ex) {
        importSummary = new ImportSummary();
        importSummary.setStatus(ImportStatus.ERROR);
        importSummary.setDescription("Data set import failed within group number: " + groupCount);
        importSummary.addConflict(ex.getObject(), ex.getMessage());
        notifier.update(id, NotificationLevel.ERROR, "ADX data import done", true);
        log.warn("Import failed: " + DebugUtils.getStackTrace(ex));
    } catch (IOException | XMLStreamException | InterruptedException | ExecutionException | TimeoutException ex) {
        importSummary = new ImportSummary();
        importSummary.setStatus(ImportStatus.ERROR);
        importSummary.setDescription("Data set import failed within group number: " + groupCount);
        notifier.update(id, NotificationLevel.ERROR, "ADX data import done", true);
        log.warn("Import failed: " + DebugUtils.getStackTrace(ex));
    }
    executor.shutdown();
    notifier.update(id, INFO, "ADX data import done", true).addJobSummary(id, importSummary, ImportSummary.class);
    ImportCount c = importSummary.getImportCount();
    log.info("ADX data import done, imported: " + c.getImported() + ", updated: " + c.getUpdated() + ", deleted: " + c.getDeleted() + ", ignored: " + c.getIgnored());
    return importSummary;
}
Also used : XMLOutputFactory(javax.xml.stream.XMLOutputFactory) DataSet(org.hisp.dhis.dataset.DataSet) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) PipedOutputStream(java.io.PipedOutputStream) DataElement(org.hisp.dhis.dataelement.DataElement) CachingMap(org.hisp.dhis.commons.collection.CachingMap) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) ExecutionException(java.util.concurrent.ExecutionException) XMLReader(org.hisp.staxwax.reader.XMLReader) JobConfiguration(org.hisp.dhis.scheduling.JobConfiguration) ImportConflict(org.hisp.dhis.dxf2.importsummary.ImportConflict) TimeoutException(java.util.concurrent.TimeoutException) ImportCount(org.hisp.dhis.dxf2.importsummary.ImportCount) IdScheme(org.hisp.dhis.common.IdScheme) IOException(java.io.IOException) IdentifiableObjectCallable(org.hisp.dhis.system.callable.IdentifiableObjectCallable) LinkedList(java.util.LinkedList) XMLStreamException(javax.xml.stream.XMLStreamException) ExecutorService(java.util.concurrent.ExecutorService) ImportOptions(org.hisp.dhis.dxf2.common.ImportOptions)

Example 7 with JobConfiguration

use of org.hisp.dhis.scheduling.JobConfiguration in project dhis2-core by dhis2.

the class TrackerCrudTest method shouldUpdateTrackedEntityWithUpdateStrategy.

@Test
void shouldUpdateTrackedEntityWithUpdateStrategy() {
    List<TrackedEntityInstance> trackedEntityInstanceList = Collections.singletonList(trackedEntityInstance);
    when(importOptions.getImportStrategy()).thenReturn(ImportStrategy.UPDATE);
    ImportSummaries importSummaries = trackedEntityInstanceService.mergeOrDeleteTrackedEntityInstances(trackedEntityInstanceList, importOptions, jobConfiguration);
    assertFalse(importSummaries.getImportSummaries().stream().anyMatch(is -> is.isStatus(ImportStatus.ERROR)));
    verify(defaultTrackedEntityInstanceService, times(1)).getTrackedEntityInstance(trackedEntityInstanceUid, user);
    verify(defaultTrackedEntityInstanceService, times(1)).updateTrackedEntityInstance(any());
}
Also used : ImportStrategy(org.hisp.dhis.importexport.ImportStrategy) Strictness(org.mockito.quality.Strictness) BeforeEach(org.junit.jupiter.api.BeforeEach) MockitoSettings(org.mockito.junit.jupiter.MockitoSettings) TrackedEntityAttributeValueService(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValueService) Mock(org.mockito.Mock) DefaultTrackedEntityInstanceService(org.hisp.dhis.trackedentity.DefaultTrackedEntityInstanceService) ArrayList(java.util.ArrayList) Notifier(org.hisp.dhis.system.notification.Notifier) CALLS_REAL_METHODS(org.mockito.Mockito.CALLS_REAL_METHODS) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) IdentifiableObjectManager(org.hisp.dhis.common.IdentifiableObjectManager) DbmsManager(org.hisp.dhis.dbms.DbmsManager) Mockito.anyBoolean(org.mockito.Mockito.anyBoolean) User(org.hisp.dhis.user.User) Mockito.anyString(org.mockito.Mockito.anyString) ImportStatus(org.hisp.dhis.dxf2.importsummary.ImportStatus) JobConfiguration(org.hisp.dhis.scheduling.JobConfiguration) EnrollmentService(org.hisp.dhis.dxf2.events.enrollment.EnrollmentService) TrackedEntityInstance(org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance) UserService(org.hisp.dhis.user.UserService) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) IdSchemes(org.hisp.dhis.common.IdSchemes) RelationshipService(org.hisp.dhis.dxf2.events.relationship.RelationshipService) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) Mockito.times(org.mockito.Mockito.times) AbstractTrackedEntityInstanceService(org.hisp.dhis.dxf2.events.trackedentity.AbstractTrackedEntityInstanceService) SchemaService(org.hisp.dhis.schema.SchemaService) Mockito.when(org.mockito.Mockito.when) ImportOptions(org.hisp.dhis.dxf2.common.ImportOptions) QueryService(org.hisp.dhis.query.QueryService) Mockito.verify(org.mockito.Mockito.verify) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) Test(org.junit.jupiter.api.Test) List(java.util.List) NotificationLevel(org.hisp.dhis.system.notification.NotificationLevel) Mockito.anyList(org.mockito.Mockito.anyList) TrackerAccessManager(org.hisp.dhis.trackedentity.TrackerAccessManager) CachingMap(org.hisp.dhis.commons.collection.CachingMap) TrackedEntityType(org.hisp.dhis.trackedentity.TrackedEntityType) Mockito.any(org.mockito.Mockito.any) Collections(java.util.Collections) IdScheme(org.hisp.dhis.common.IdScheme) Mockito.mock(org.mockito.Mockito.mock) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries) TrackedEntityInstance(org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance) Test(org.junit.jupiter.api.Test)

Example 8 with JobConfiguration

use of org.hisp.dhis.scheduling.JobConfiguration in project dhis2-core by dhis2.

the class EventController method startAsyncImport.

// -------------------------------------------------------------------------
// Supportive methods
// -------------------------------------------------------------------------
/**
 * Starts an asynchronous import task.
 *
 * @param importOptions the ImportOptions.
 * @param events the events to import.
 */
private WebMessage startAsyncImport(ImportOptions importOptions, List<Event> events) {
    JobConfiguration jobId = new JobConfiguration("inMemoryEventImport", EVENT_IMPORT, currentUserService.getCurrentUser().getUid(), true);
    taskExecutor.executeTask(new ImportEventsTask(events, eventService, importOptions, jobId));
    return jobConfigurationReport(jobId).setLocation("/system/tasks/" + EVENT_IMPORT);
}
Also used : ImportEventsTask(org.hisp.dhis.dxf2.events.event.ImportEventsTask) JobConfiguration(org.hisp.dhis.scheduling.JobConfiguration)

Example 9 with JobConfiguration

use of org.hisp.dhis.scheduling.JobConfiguration in project dhis2-core by dhis2.

the class NotificationMapTest method testFirstSummaryToBeCreatedIsTheFirstOneToBeRemoved.

@Test
void testFirstSummaryToBeCreatedIsTheFirstOneToBeRemoved() {
    // Fill the map with jobs
    JobConfiguration jobConfiguration = new JobConfiguration(null, DATAVALUE_IMPORT, "userId", false);
    for (int i = 0; i < MAX_POOL_TYPE_SIZE; i++) {
        jobConfiguration.setUid(String.valueOf(i));
        mapToTest.addSummary(jobConfiguration, i);
    }
    // Add one more
    jobConfiguration.setUid(String.valueOf(MAX_POOL_TYPE_SIZE));
    mapToTest.addSummary(jobConfiguration, MAX_POOL_TYPE_SIZE);
    // Check that oldest job is not in the map anymore
    Optional<String> notPresentSummary = mapToTest.getJobSummariesForJobType(DATAVALUE_IMPORT).keySet().stream().filter(object -> object.equals("0")).findAny();
    Assertions.assertFalse(notPresentSummary.isPresent());
    // Add one more
    jobConfiguration.setUid(String.valueOf(MAX_POOL_TYPE_SIZE + 1));
    mapToTest.addSummary(jobConfiguration, MAX_POOL_TYPE_SIZE + 1);
    // Check that oldest job is not in the map anymore
    notPresentSummary = mapToTest.getJobSummariesForJobType(DATAVALUE_IMPORT).keySet().stream().filter(object -> object.equals("1")).findAny();
    Assertions.assertFalse(notPresentSummary.isPresent());
}
Also used : Test(org.junit.jupiter.api.Test) MAX_POOL_TYPE_SIZE(org.hisp.dhis.system.notification.NotificationMap.MAX_POOL_TYPE_SIZE) Assertions(org.junit.jupiter.api.Assertions) Optional(java.util.Optional) DATAVALUE_IMPORT(org.hisp.dhis.scheduling.JobType.DATAVALUE_IMPORT) JobConfiguration(org.hisp.dhis.scheduling.JobConfiguration) JobConfiguration(org.hisp.dhis.scheduling.JobConfiguration) Test(org.junit.jupiter.api.Test)

Example 10 with JobConfiguration

use of org.hisp.dhis.scheduling.JobConfiguration in project dhis2-core by dhis2.

the class JobConfigurationObjectBundleHookTest method validateInternalNonConfigurableIgnoredValidationErrorE7010.

@Test
void validateInternalNonConfigurableIgnoredValidationErrorE7010() {
    Mockito.when(jobConfigurationService.getJobConfigurationByUid(Mockito.eq("jsdhJSJHD"))).thenReturn(analyticsTableJobConfig);
    Mockito.when(jobService.getJob(Mockito.eq(JobType.ANALYTICSTABLE_UPDATE))).thenReturn(job);
    Mockito.when(job.validate()).thenReturn(new ErrorReport(Class.class, ErrorCode.E7010));
    JobConfiguration jobConfiguration = new JobConfiguration();
    jobConfiguration.setUid("jsdhJSJHD");
    jobConfiguration.setJobType(JobType.ANALYTICSTABLE_UPDATE);
    jobConfiguration.setCronExpression(CRON_HOURLY);
    jobConfiguration.setEnabled(true);
    List<ErrorReport> errorReports = hook.validate(jobConfiguration, null);
    Assertions.assertEquals(0, errorReports.size());
}
Also used : ErrorReport(org.hisp.dhis.feedback.ErrorReport) JobConfiguration(org.hisp.dhis.scheduling.JobConfiguration) Test(org.junit.jupiter.api.Test)

Aggregations

JobConfiguration (org.hisp.dhis.scheduling.JobConfiguration)55 Test (org.junit.jupiter.api.Test)23 ErrorReport (org.hisp.dhis.feedback.ErrorReport)10 List (java.util.List)7 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)6 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)6 ArrayList (java.util.ArrayList)5 ImportOptions (org.hisp.dhis.dxf2.common.ImportOptions)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 InputStream (java.io.InputStream)4 IdScheme (org.hisp.dhis.common.IdScheme)4 CachingMap (org.hisp.dhis.commons.collection.CachingMap)4 ImportSummaries (org.hisp.dhis.dxf2.importsummary.ImportSummaries)4 ImportStrategy (org.hisp.dhis.importexport.ImportStrategy)4 Collections (java.util.Collections)3 HashMap (java.util.HashMap)3 IdSchemes (org.hisp.dhis.common.IdSchemes)3 IdentifiableObjectManager (org.hisp.dhis.common.IdentifiableObjectManager)3 TrackerTrigramIndexJobParameters (org.hisp.dhis.scheduling.parameters.TrackerTrigramIndexJobParameters)3 BeforeEach (org.junit.jupiter.api.BeforeEach)3