Search in sources :

Example 56 with ERROR

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

the class DataValueController method getDataValueFile.

// ---------------------------------------------------------------------
// GET file
// ---------------------------------------------------------------------
@GetMapping("/files")
public void getDataValueFile(@RequestParam String de, @RequestParam(required = false) String co, @RequestParam(required = false) String cc, @RequestParam(required = false) String cp, @RequestParam String pe, @RequestParam String ou, @RequestParam(defaultValue = "original") String dimension, HttpServletResponse response, HttpServletRequest request) throws WebMessageException {
    // ---------------------------------------------------------------------
    // Input validation
    // ---------------------------------------------------------------------
    DataElement dataElement = dataValueValidation.getAndValidateDataElement(de);
    if (!dataElement.isFileType()) {
        throw new WebMessageException(conflict("DataElement must be of type file"));
    }
    CategoryOptionCombo categoryOptionCombo = dataValueValidation.getAndValidateCategoryOptionCombo(co, false);
    CategoryOptionCombo attributeOptionCombo = dataValueValidation.getAndValidateAttributeOptionCombo(cc, cp);
    Period period = dataValueValidation.getAndValidatePeriod(pe);
    OrganisationUnit organisationUnit = dataValueValidation.getAndValidateOrganisationUnit(ou);
    dataValueValidation.validateOrganisationUnitPeriod(organisationUnit, period);
    // ---------------------------------------------------------------------
    // Get data value
    // ---------------------------------------------------------------------
    DataValue dataValue = dataValueService.getDataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo);
    if (dataValue == null) {
        throw new WebMessageException(conflict("Data value does not exist"));
    }
    // ---------------------------------------------------------------------
    // Get file resource
    // ---------------------------------------------------------------------
    String uid = dataValue.getValue();
    FileResource fileResource = fileResourceService.getFileResource(uid);
    if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
        throw new WebMessageException(notFound("A data value file resource with id " + uid + " does not exist."));
    }
    FileResourceStorageStatus storageStatus = fileResource.getStorageStatus();
    if (storageStatus != FileResourceStorageStatus.STORED) {
        // HTTP 409, for lack of a more suitable status code
        throw new WebMessageException(conflict("The content is being processed and is not available yet. Try again later.", "The content requested is in transit to the file store and will be available at a later time.").setResponse(new FileResourceWebMessageResponse(fileResource)));
    }
    response.setContentType(fileResource.getContentType());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileResource.getName());
    response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(fileResourceService.getFileResourceContentLength(fileResource)));
    setNoStore(response);
    try {
        fileResourceService.copyFileResourceContent(fileResource, response.getOutputStream());
    } catch (IOException e) {
        throw new WebMessageException(error("Failed fetching the file from storage", "There was an exception when trying to fetch the file from the storage backend, could be network or filesystem related"));
    }
}
Also used : DataElement(org.hisp.dhis.dataelement.DataElement) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) FileResourceWebMessageResponse(org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DataValue(org.hisp.dhis.datavalue.DataValue) FileResourceStorageStatus(org.hisp.dhis.fileresource.FileResourceStorageStatus) FileResource(org.hisp.dhis.fileresource.FileResource) Period(org.hisp.dhis.period.Period) IOException(java.io.IOException) CategoryOptionCombo(org.hisp.dhis.category.CategoryOptionCombo) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 57 with ERROR

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

the class EventController method getEventDataValueFile.

@GetMapping("/files")
public void getEventDataValueFile(@RequestParam String eventUid, @RequestParam String dataElementUid, @RequestParam(required = false) ImageFileDimension dimension, HttpServletResponse response, HttpServletRequest request) throws Exception {
    Event event = eventService.getEvent(programStageInstanceService.getProgramStageInstance(eventUid));
    if (event == null) {
        throw new WebMessageException(notFound("Event not found for ID " + eventUid));
    }
    DataElement dataElement = dataElementService.getDataElement(dataElementUid);
    if (dataElement == null) {
        throw new WebMessageException(notFound("DataElement not found for ID " + dataElementUid));
    }
    if (!dataElement.isFileType()) {
        throw new WebMessageException(conflict("DataElement must be of type file"));
    }
    // ---------------------------------------------------------------------
    // Get file resource
    // ---------------------------------------------------------------------
    String uid = null;
    for (DataValue value : event.getDataValues()) {
        if (value.getDataElement() != null && value.getDataElement().equals(dataElement.getUid())) {
            uid = value.getValue();
            break;
        }
    }
    if (uid == null) {
        throw new WebMessageException(conflict("DataElement must be of type file"));
    }
    FileResource fileResource = fileResourceService.getFileResource(uid);
    if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
        throw new WebMessageException(notFound("A data value file resource with id " + uid + " does not exist."));
    }
    if (fileResource.getStorageStatus() != FileResourceStorageStatus.STORED) {
        throw new WebMessageException(conflict("The content is being processed and is not available yet. Try again later.", "The content requested is in transit to the file store and will be available at a later time.").setResponse(new FileResourceWebMessageResponse(fileResource)));
    }
    FileResourceUtils.setImageFileDimensions(fileResource, MoreObjects.firstNonNull(dimension, ImageFileDimension.ORIGINAL));
    response.setContentType(fileResource.getContentType());
    response.setContentLength(new Long(fileResource.getContentLength()).intValue());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileResource.getName());
    try {
        fileResourceService.copyFileResourceContent(fileResource, response.getOutputStream());
    } catch (IOException e) {
        throw new WebMessageException(error("Failed fetching the file from storage", "There was an exception when trying to fetch the file from the storage backend, could be network or filesystem related"));
    }
}
Also used : DataElement(org.hisp.dhis.dataelement.DataElement) FileResourceWebMessageResponse(org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DataValue(org.hisp.dhis.dxf2.events.event.DataValue) FileResource(org.hisp.dhis.fileresource.FileResource) Event(org.hisp.dhis.dxf2.events.event.Event) IOException(java.io.IOException) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 58 with ERROR

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

the class StaticContentController method getStaticContent.

/**
 * Serves the PNG associated with the key. If custom logo is not used the
 * request will redirect to the default.
 *
 * @param key key associated with the file.
 */
@GetMapping("/{key}")
public void getStaticContent(@PathVariable("key") String key, HttpServletRequest request, HttpServletResponse response) throws WebMessageException {
    if (!KEY_WHITELIST_MAP.containsKey(key)) {
        throw new WebMessageException(notFound("Key does not exist."));
    }
    boolean useCustomFile = systemSettingManager.getBoolSetting(KEY_WHITELIST_MAP.get(key));
    if (// Serve default
    !useCustomFile) {
        try {
            response.sendRedirect(getDefaultLogoUrl(request, key));
        } catch (IOException e) {
            throw new WebMessageException(error("Can't read the file."));
        }
    } else // Serve custom
    {
        try {
            response.setContentType(IMAGE_PNG_VALUE);
            contentStore.copyContent(makeKey(DEFAULT_RESOURCE_DOMAIN, Optional.of(key)), response.getOutputStream());
        } catch (NoSuchElementException e) {
            throw new WebMessageException(notFound(e.getMessage()));
        } catch (IOException e) {
            throw new WebMessageException(error("Failed to retrieve image", e.getMessage()));
        }
    }
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) IOException(java.io.IOException) NoSuchElementException(java.util.NoSuchElementException) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 59 with ERROR

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

the class TrackedEntityInstanceController method getAttributeImage.

@GetMapping("/{teiId}/{attributeId}/image")
public void getAttributeImage(@PathVariable("teiId") String teiId, @PathVariable("attributeId") String attributeId, @RequestParam(required = false) Integer width, @RequestParam(required = false) Integer height, @RequestParam(required = false) ImageFileDimension dimension, HttpServletResponse response) throws WebMessageException {
    User user = currentUserService.getCurrentUser();
    org.hisp.dhis.trackedentity.TrackedEntityInstance trackedEntityInstance = instanceService.getTrackedEntityInstance(teiId);
    List<String> trackerAccessErrors = trackerAccessManager.canRead(user, trackedEntityInstance);
    List<TrackedEntityAttributeValue> attribute = trackedEntityInstance.getTrackedEntityAttributeValues().stream().filter(val -> val.getAttribute().getUid().equals(attributeId)).collect(Collectors.toList());
    if (!trackerAccessErrors.isEmpty()) {
        throw new WebMessageException(unauthorized("You're not authorized to access the TrackedEntityInstance with id: " + teiId));
    }
    if (attribute.size() == 0) {
        throw new WebMessageException(notFound("Attribute not found for ID " + attributeId));
    }
    TrackedEntityAttributeValue value = attribute.get(0);
    if (value == null) {
        throw new WebMessageException(notFound("Value not found for ID " + attributeId));
    }
    if (value.getAttribute().getValueType() != ValueType.IMAGE) {
        throw new WebMessageException(conflict("Attribute must be of type image"));
    }
    // ---------------------------------------------------------------------
    // Get file resource
    // ---------------------------------------------------------------------
    FileResource fileResource = fileResourceService.getFileResource(value.getValue());
    if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
        throw new WebMessageException(notFound("A data value file resource with id " + value.getValue() + " does not exist."));
    }
    if (fileResource.getStorageStatus() != FileResourceStorageStatus.STORED) {
        throw new WebMessageException(conflict("The content is being processed and is not available yet. Try again later.", "The content requested is in transit to the file store and will be available at a later time."));
    }
    // ---------------------------------------------------------------------
    // Build response and return
    // ---------------------------------------------------------------------
    FileResourceUtils.setImageFileDimensions(fileResource, MoreObjects.firstNonNull(dimension, ImageFileDimension.ORIGINAL));
    response.setContentType(fileResource.getContentType());
    response.setContentLength((int) fileResource.getContentLength());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileResource.getName());
    try (InputStream inputStream = fileResourceService.getFileResourceContent(fileResource)) {
        BufferedImage img = ImageIO.read(inputStream);
        height = height == null ? img.getHeight() : height;
        width = width == null ? img.getWidth() : width;
        BufferedImage resizedImg = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D canvas = resizedImg.createGraphics();
        canvas.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        canvas.drawImage(img, 0, 0, width, height, null);
        canvas.dispose();
        ImageIO.write(resizedImg, fileResource.getFormat(), response.getOutputStream());
    } catch (IOException ex) {
        throw new WebMessageException(error("Failed fetching the file from storage", "There was an exception when trying to fetch the file from the storage backend."));
    }
}
Also used : ImportStrategy(org.hisp.dhis.importexport.ImportStrategy) PathVariable(org.springframework.web.bind.annotation.PathVariable) APPLICATION_XML_VALUE(org.springframework.http.MediaType.APPLICATION_XML_VALUE) RequestParam(org.springframework.web.bind.annotation.RequestParam) ValueType(org.hisp.dhis.common.ValueType) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) StringUtils(org.apache.commons.lang3.StringUtils) FileResourceStorageStatus(org.hisp.dhis.fileresource.FileResourceStorageStatus) TEI_IMPORT(org.hisp.dhis.scheduling.JobType.TEI_IMPORT) NodeUtils(org.hisp.dhis.node.NodeUtils) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) PutMapping(org.springframework.web.bind.annotation.PutMapping) FileResourceService(org.hisp.dhis.fileresource.FileResourceService) ImageIO(javax.imageio.ImageIO) GridUtils(org.hisp.dhis.system.grid.GridUtils) JobConfiguration(org.hisp.dhis.scheduling.JobConfiguration) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) PostMapping(org.springframework.web.bind.annotation.PostMapping) ContextService(org.hisp.dhis.webapi.service.ContextService) DxfNamespaces(org.hisp.dhis.common.DxfNamespaces) BufferedImage(java.awt.image.BufferedImage) TrackedEntityInstanceQueryParams(org.hisp.dhis.trackedentity.TrackedEntityInstanceQueryParams) HttpHeaders(org.springframework.http.HttpHeaders) FieldFilterService(org.hisp.dhis.fieldfilter.FieldFilterService) CacheStrategy(org.hisp.dhis.common.cache.CacheStrategy) TrackedEntityInstanceCriteria(org.hisp.dhis.webapi.controller.event.webrequest.TrackedEntityInstanceCriteria) Collectors(java.util.stream.Collectors) TrackedEntityInstanceSchemaDescriptor(org.hisp.dhis.schema.descriptors.TrackedEntityInstanceSchemaDescriptor) ImageFileDimension(org.hisp.dhis.fileresource.ImageFileDimension) List(java.util.List) FileResourceUtils(org.hisp.dhis.webapi.utils.FileResourceUtils) FieldFilterParams(org.hisp.dhis.fieldfilter.FieldFilterParams) TrackerAccessManager(org.hisp.dhis.trackedentity.TrackerAccessManager) WebMessageUtils.conflict(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.conflict) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RootNode(org.hisp.dhis.node.types.RootNode) Joiner(com.google.common.base.Joiner) DhisApiVersion(org.hisp.dhis.common.DhisApiVersion) WebMessageUtils.notFound(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound) TrackerEntityInstanceRequest(org.hisp.dhis.webapi.strategy.old.tracker.imports.request.TrackerEntityInstanceRequest) TrackedEntityInstanceStrategyHandler(org.hisp.dhis.webapi.strategy.old.tracker.imports.TrackedEntityInstanceStrategyHandler) CollectionNode(org.hisp.dhis.node.types.CollectionNode) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Controller(org.springframework.stereotype.Controller) StreamUtils(org.hisp.dhis.commons.util.StreamUtils) ApiVersion(org.hisp.dhis.webapi.mvc.annotation.ApiVersion) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) WebMessageUtils.importSummaries(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.importSummaries) WebMessageUtils.importSummary(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.importSummary) WebMessageUtils.error(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.error) User(org.hisp.dhis.user.User) GetMapping(org.springframework.web.bind.annotation.GetMapping) WebMessageUtils.jobConfigurationReport(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.jobConfigurationReport) BadRequestException(org.hisp.dhis.webapi.controller.exception.BadRequestException) ImportStatus(org.hisp.dhis.dxf2.importsummary.ImportStatus) WebMessageUtils.unauthorized(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.unauthorized) TrackedEntityCriteriaMapper(org.hisp.dhis.webapi.controller.event.mapper.TrackedEntityCriteriaMapper) TrackedEntityInstance(org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance) TrackedEntityInstanceSupportService(org.hisp.dhis.webapi.service.TrackedEntityInstanceSupportService) TrackedEntityInstanceService(org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstanceService) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) Pager(org.hisp.dhis.common.Pager) FileResource(org.hisp.dhis.fileresource.FileResource) HttpServletResponse(javax.servlet.http.HttpServletResponse) TrackedEntityInstanceParams(org.hisp.dhis.dxf2.events.TrackedEntityInstanceParams) MoreObjects(com.google.common.base.MoreObjects) IOException(java.io.IOException) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) 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) java.awt(java.awt) CurrentUserService(org.hisp.dhis.user.CurrentUserService) FileResourceDomain(org.hisp.dhis.fileresource.FileResourceDomain) InputStream(java.io.InputStream) User(org.hisp.dhis.user.User) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) InputStream(java.io.InputStream) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) FileResource(org.hisp.dhis.fileresource.FileResource) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 60 with ERROR

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

the class FileResourceUtils method configureFileResourceResponse.

public void configureFileResourceResponse(HttpServletResponse response, FileResource fileResource) throws WebMessageException {
    response.setContentType(fileResource.getContentType());
    response.setContentLength(new Long(fileResource.getContentLength()).intValue());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileResource.getName());
    try {
        fileResourceService.copyFileResourceContent(fileResource, response.getOutputStream());
    } catch (IOException e) {
        throw new WebMessageException(error("Failed fetching the file from storage", "There was an exception when trying to fetch the file from the storage backend. " + "Depending on the provider the root cause could be network or file system related."));
    }
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) IOException(java.io.IOException)

Aggregations

ImportSummary (org.hisp.dhis.dxf2.importsummary.ImportSummary)33 Test (org.junit.jupiter.api.Test)25 User (org.hisp.dhis.user.User)21 TransactionalIntegrationTest (org.hisp.dhis.TransactionalIntegrationTest)20 IOException (java.io.IOException)15 Event (org.hisp.dhis.dxf2.events.event.Event)14 List (java.util.List)12 ImportSummaries (org.hisp.dhis.dxf2.importsummary.ImportSummaries)11 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)9 ImportStrategy (org.hisp.dhis.importexport.ImportStrategy)9 ClassPathResource (org.springframework.core.io.ClassPathResource)9 ImportReport (org.hisp.dhis.dxf2.metadata.feedback.ImportReport)8 ProgramStageInstance (org.hisp.dhis.program.ProgramStageInstance)7 GetMapping (org.springframework.web.bind.annotation.GetMapping)7 ArrayList (java.util.ArrayList)6 FileResource (org.hisp.dhis.fileresource.FileResource)6 SchemaService (org.hisp.dhis.schema.SchemaService)6 UserService (org.hisp.dhis.user.UserService)6 Autowired (org.springframework.beans.factory.annotation.Autowired)6 InputStream (java.io.InputStream)4