Search in sources :

Example 46 with ImportSummary

use of org.hisp.dhis.dxf2.importsummary.ImportSummary in project dhis2-core by dhis2.

the class AdxPipedImporter method call.

@Override
public ImportSummary call() {
    ImportSummary result = null;
    SecurityContextHolder.getContext().setAuthentication(authentication);
    DbmsUtils.bindSessionToThread(sessionFactory);
    try {
        result = dataValueSetService.saveDataValueSet(pipeIn, importOptions, id);
    } catch (Exception ex) {
        result = new ImportSummary();
        result.setStatus(ImportStatus.ERROR);
        result.setDescription("Exception: " + ex.getMessage());
    } finally {
        IOUtils.closeQuietly(pipeIn);
        DbmsUtils.unbindSessionFromThread(sessionFactory);
    }
    return result;
}
Also used : ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) IOException(java.io.IOException)

Example 47 with ImportSummary

use of org.hisp.dhis.dxf2.importsummary.ImportSummary in project dhis2-core by dhis2.

the class DefaultAdxDataService method saveDataValueSetInternal.

private ImportSummary saveDataValueSetInternal(InputStream in, ImportOptions importOptions, TaskId id) {
    notifier.clear(id).notify(id, "ADX parsing process started");
    ImportOptions adxImportOptions = ObjectUtils.firstNonNull(importOptions, ImportOptions.getDefaultImportOptions()).instance().setNotificationLevel(NotificationLevel.OFF);
    // Get import options
    IdScheme dataSetIdScheme = importOptions.getIdSchemes().getDataSetIdScheme();
    IdScheme dataElementIdScheme = 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, dataSetIdScheme, null);
    IdentifiableObjectCallable<DataElement> dataElementCallable = new IdentifiableObjectCallable<>(identifiableObjectManager, DataElement.class, dataElementIdScheme, null);
    // Heat cache
    if (importOptions.isPreheatCacheDefaultFalse()) {
        dataSetMap.load(identifiableObjectManager.getAll(DataSet.class), o -> o.getPropertyValue(dataSetIdScheme));
        dataElementMap.load(identifiableObjectManager.getAll(DataElement.class), o -> o.getPropertyValue(dataElementIdScheme));
    }
    XMLReader adxReader = XMLFactory.getXMLReader(in);
    ImportSummary importSummary;
    adxReader.moveToStartElement(AdxDataService.ROOT, AdxDataService.NAMESPACE);
    ExecutorService executor = Executors.newSingleThreadExecutor();
    // Give the DXF import a different notification task ID so it doesn't conflict with notifications from this level.
    TaskId dxfTaskId = new TaskId(TaskCategory.DATAVALUE_IMPORT_INTERNAL, id.getUser());
    int groupCount = 0;
    try (PipedOutputStream pipeOut = new PipedOutputStream()) {
        Future<ImportSummary> futureImportSummary = executor.submit(new AdxPipedImporter(dataValueSetService, adxImportOptions, dxfTaskId, 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.getConflicts().addAll(adxConflicts);
        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.getConflicts().add(ex.getImportConflict());
        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).addTaskSummary(id, importSummary);
    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) TaskId(org.hisp.dhis.scheduling.TaskId) 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) 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 48 with ImportSummary

use of org.hisp.dhis.dxf2.importsummary.ImportSummary in project dhis2-core by dhis2.

the class MetadataSyncPreProcessorTest method testhandleAggregateDataPushShouldThrowExceptionWhenDataPushIsUnsuccessful.

@Test(expected = MetadataSyncServiceException.class)
public void testhandleAggregateDataPushShouldThrowExceptionWhenDataPushIsUnsuccessful() throws Exception {
    MetadataRetryContext mockRetryContext = mock(MetadataRetryContext.class);
    ImportSummary expectedSummary = new ImportSummary();
    expectedSummary.setStatus(ImportStatus.ERROR);
    AvailabilityStatus availabilityStatus = new AvailabilityStatus(true, "test_message", null);
    when(synchronizationManager.isRemoteServerAvailable()).thenReturn(availabilityStatus);
    when(metadataSyncPreProcessor.handleAggregateDataPush(mockRetryContext)).thenReturn(expectedSummary);
    ImportSummary actualSummary = metadataSyncPreProcessor.handleAggregateDataPush(mockRetryContext);
    assertEquals(expectedSummary.getStatus(), actualSummary.getStatus());
}
Also used : AvailabilityStatus(org.hisp.dhis.dxf2.synch.AvailabilityStatus) MetadataRetryContext(org.hisp.dhis.dxf2.metadata.tasks.MetadataRetryContext) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) IntegrationTest(org.hisp.dhis.IntegrationTest) Test(org.junit.Test) DhisSpringTest(org.hisp.dhis.DhisSpringTest)

Example 49 with ImportSummary

use of org.hisp.dhis.dxf2.importsummary.ImportSummary in project dhis2-core by dhis2.

the class MetadataSyncPreProcessorTest method testHandleEventDataPushShouldNotThrowExceptionWhenDataPushIsSuccessful.

@Test
public void testHandleEventDataPushShouldNotThrowExceptionWhenDataPushIsSuccessful() throws Exception {
    MetadataRetryContext mockRetryContext = mock(MetadataRetryContext.class);
    ImportSummaries expectedSummary = new ImportSummaries();
    ImportSummary summary = new ImportSummary();
    summary.setStatus(ImportStatus.SUCCESS);
    expectedSummary.addImportSummary(summary);
    AvailabilityStatus availabilityStatus = new AvailabilityStatus(true, "test_message", null);
    when(synchronizationManager.isRemoteServerAvailable()).thenReturn(availabilityStatus);
    when(metadataSyncPreProcessor.handleEventDataPush(mockRetryContext)).thenReturn(expectedSummary);
    ImportSummaries actualSummary = metadataSyncPreProcessor.handleEventDataPush(mockRetryContext);
    assertEquals(expectedSummary.getImportSummaries().get(0).getStatus(), actualSummary.getImportSummaries().get(0).getStatus());
}
Also used : AvailabilityStatus(org.hisp.dhis.dxf2.synch.AvailabilityStatus) MetadataRetryContext(org.hisp.dhis.dxf2.metadata.tasks.MetadataRetryContext) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries) IntegrationTest(org.hisp.dhis.IntegrationTest) Test(org.junit.Test) DhisSpringTest(org.hisp.dhis.DhisSpringTest)

Example 50 with ImportSummary

use of org.hisp.dhis.dxf2.importsummary.ImportSummary in project dhis2-core by dhis2.

the class EventController method postJsonEvent.

@RequestMapping(method = RequestMethod.POST, consumes = "application/json")
@PreAuthorize("hasRole('ALL') or hasRole('F_TRACKED_ENTITY_DATAVALUE_ADD')")
public void postJsonEvent(@RequestParam(defaultValue = "CREATE") ImportStrategy strategy, HttpServletResponse response, HttpServletRequest request, ImportOptions importOptions) throws Exception {
    importOptions.setImportStrategy(strategy);
    InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat(request.getInputStream());
    importOptions.setIdSchemes(getIdSchemesFromParameters(importOptions.getIdSchemes(), contextService.getParameterValuesMap()));
    if (!importOptions.isAsync()) {
        ImportSummaries importSummaries = eventService.addEventsJson(inputStream, importOptions);
        importSummaries.setImportOptions(importOptions);
        importSummaries.getImportSummaries().stream().filter(importSummary -> !importOptions.isDryRun() && !importSummary.getStatus().equals(ImportStatus.ERROR) && !importOptions.getImportStrategy().isDelete()).forEach(importSummary -> importSummary.setHref(ContextUtils.getRootPath(request) + RESOURCE_PATH + "/" + importSummary.getReference()));
        if (importSummaries.getImportSummaries().size() == 1) {
            ImportSummary importSummary = importSummaries.getImportSummaries().get(0);
            importSummary.setImportOptions(importOptions);
            if (!importOptions.isDryRun()) {
                if (!importSummary.getStatus().equals(ImportStatus.ERROR)) {
                    response.setHeader("Location", ContextUtils.getRootPath(request) + RESOURCE_PATH + "/" + importSummary.getReference());
                }
            }
        }
        webMessageService.send(WebMessageUtils.importSummaries(importSummaries), response, request);
    } else {
        TaskId taskId = new TaskId(TaskCategory.EVENT_IMPORT, currentUserService.getCurrentUser());
        List<Event> events = eventService.getEventsJson(inputStream);
        scheduler.executeTask(new ImportEventTask(events, eventService, importOptions, taskId));
        response.setHeader("Location", ContextUtils.getRootPath(request) + "/system/tasks/" + TaskCategory.EVENT_IMPORT);
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
Also used : ImportStrategy(org.hisp.dhis.importexport.ImportStrategy) PathVariable(org.springframework.web.bind.annotation.PathVariable) DataValue(org.hisp.dhis.dxf2.events.event.DataValue) EventRowService(org.hisp.dhis.dxf2.events.report.EventRowService) Order(org.hisp.dhis.query.Order) RequestParam(org.springframework.web.bind.annotation.RequestParam) Arrays(java.util.Arrays) EventService(org.hisp.dhis.dxf2.events.event.EventService) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) Date(java.util.Date) RenderService(org.hisp.dhis.render.RenderService) Autowired(org.springframework.beans.factory.annotation.Autowired) WebMessageService(org.hisp.dhis.webapi.service.WebMessageService) StringUtils(org.apache.commons.lang3.StringUtils) FileResourceStorageStatus(org.hisp.dhis.fileresource.FileResourceStorageStatus) ProgramStageInstanceService(org.hisp.dhis.program.ProgramStageInstanceService) NodeUtils(org.hisp.dhis.node.NodeUtils) Model(org.springframework.ui.Model) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) FileResourceService(org.hisp.dhis.fileresource.FileResourceService) Map(java.util.Map) Preset(org.hisp.dhis.node.Preset) URI(java.net.URI) InputUtils(org.hisp.dhis.dxf2.utils.InputUtils) Scheduler(org.hisp.dhis.system.scheduling.Scheduler) ImportEventTask(org.hisp.dhis.dxf2.events.event.ImportEventTask) ImportEventsTask(org.hisp.dhis.dxf2.events.event.ImportEventsTask) ContextService(org.hisp.dhis.webapi.service.ContextService) CsvEventService(org.hisp.dhis.dxf2.events.event.csv.CsvEventService) OrganisationUnitSelectionMode(org.hisp.dhis.common.OrganisationUnitSelectionMode) HttpHeaders(org.springframework.http.HttpHeaders) FieldFilterService(org.hisp.dhis.fieldfilter.FieldFilterService) CacheStrategy(org.hisp.dhis.common.cache.CacheStrategy) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Set(java.util.Set) EventStatus(org.hisp.dhis.event.EventStatus) SchemaService(org.hisp.dhis.schema.SchemaService) Sets(com.google.common.collect.Sets) Event(org.hisp.dhis.dxf2.events.event.Event) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo) EventRows(org.hisp.dhis.dxf2.events.report.EventRows) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) Events(org.hisp.dhis.dxf2.events.event.Events) Schema(org.hisp.dhis.schema.Schema) GZIPOutputStream(java.util.zip.GZIPOutputStream) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RootNode(org.hisp.dhis.node.types.RootNode) TaskId(org.hisp.dhis.scheduling.TaskId) DhisApiVersion(org.hisp.dhis.common.DhisApiVersion) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) DataElementService(org.hisp.dhis.dataelement.DataElementService) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) Controller(org.springframework.stereotype.Controller) StreamUtils(org.hisp.dhis.commons.util.StreamUtils) ApiVersion(org.hisp.dhis.webapi.mvc.annotation.ApiVersion) Program(org.hisp.dhis.program.Program) DataElement(org.hisp.dhis.dataelement.DataElement) EventSearchParams(org.hisp.dhis.dxf2.events.event.EventSearchParams) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) ByteSource(com.google.common.io.ByteSource) ImportStatus(org.hisp.dhis.dxf2.importsummary.ImportStatus) WebMessageUtils(org.hisp.dhis.dxf2.webmessage.WebMessageUtils) OutputStream(java.io.OutputStream) TrackedEntityInstanceService(org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstanceService) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) IdSchemes(org.hisp.dhis.common.IdSchemes) FileResource(org.hisp.dhis.fileresource.FileResource) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Grid(org.hisp.dhis.common.Grid) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) ImportOptions(org.hisp.dhis.dxf2.common.ImportOptions) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries) ProgramStatus(org.hisp.dhis.program.ProgramStatus) OrderParams(org.hisp.dhis.dxf2.common.OrderParams) FileResourceWebMessageResponse(org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse) CurrentUserService(org.hisp.dhis.user.CurrentUserService) TaskCategory(org.hisp.dhis.scheduling.TaskCategory) FileResourceDomain(org.hisp.dhis.fileresource.FileResourceDomain) TextUtils(org.hisp.dhis.commons.util.TextUtils) InputStream(java.io.InputStream) TaskId(org.hisp.dhis.scheduling.TaskId) ImportEventTask(org.hisp.dhis.dxf2.events.event.ImportEventTask) InputStream(java.io.InputStream) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) Event(org.hisp.dhis.dxf2.events.event.Event) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

ImportSummary (org.hisp.dhis.dxf2.importsummary.ImportSummary)102 Test (org.junit.Test)58 DhisSpringTest (org.hisp.dhis.DhisSpringTest)49 ClassPathResource (org.springframework.core.io.ClassPathResource)39 ImportOptions (org.hisp.dhis.dxf2.common.ImportOptions)29 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)25 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)22 DataValue (org.hisp.dhis.datavalue.DataValue)18 Event (org.hisp.dhis.dxf2.events.event.Event)17 InputStream (java.io.InputStream)14 Date (java.util.Date)11 ImportConflict (org.hisp.dhis.dxf2.importsummary.ImportConflict)11 ImportSummaries (org.hisp.dhis.dxf2.importsummary.ImportSummaries)11 IOException (java.io.IOException)10 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)10 DhisTest (org.hisp.dhis.DhisTest)9 DhisApiVersion (org.hisp.dhis.common.DhisApiVersion)7 DataElement (org.hisp.dhis.dataelement.DataElement)7 ImportStatus (org.hisp.dhis.dxf2.importsummary.ImportStatus)7 ApiVersion (org.hisp.dhis.webapi.mvc.annotation.ApiVersion)7