Search in sources :

Example 91 with ID

use of org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.ID 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 92 with ID

use of org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.ID 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 93 with ID

use of org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.ID 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 94 with ID

use of org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.ID in project dhis2-core by dhis2.

the class TrackedEntityInstanceController method updateTrackedEntityInstanceJson.

@PutMapping(value = "/{id}", consumes = APPLICATION_JSON_VALUE)
@ResponseBody
public WebMessage updateTrackedEntityInstanceJson(@PathVariable String id, @RequestParam(required = false) String program, ImportOptions importOptions, HttpServletRequest request) throws IOException {
    InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat(request.getInputStream());
    ImportSummary importSummary = trackedEntityInstanceService.updateTrackedEntityInstanceJson(id, program, inputStream, importOptions);
    importSummary.setImportOptions(importOptions);
    return importSummary(importSummary);
}
Also used : InputStream(java.io.InputStream) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) PutMapping(org.springframework.web.bind.annotation.PutMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 95 with ID

use of org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.ID in project dhis2-core by dhis2.

the class UserRoleController method removeUserFromRole.

@DeleteMapping("/{id}/users/{userId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void removeUserFromRole(@PathVariable(value = "id") String pvId, @PathVariable("userId") String pvUserId, @CurrentUser User currentUser, HttpServletResponse response) throws WebMessageException {
    UserAuthorityGroup userAuthorityGroup = userService.getUserAuthorityGroup(pvId);
    if (userAuthorityGroup == null) {
        throw new WebMessageException(notFound("UserRole does not exist: " + pvId));
    }
    User user = userService.getUser(pvUserId);
    if (user == null) {
        throw new WebMessageException(notFound("User does not exist: " + pvId));
    }
    if (!aclService.canUpdate(currentUser, userAuthorityGroup)) {
        throw new DeleteAccessDeniedException("You don't have the proper permissions to delete this object.");
    }
    if (user.getUserAuthorityGroups().contains(userAuthorityGroup)) {
        user.getUserAuthorityGroups().remove(userAuthorityGroup);
        userService.updateUser(user);
    }
}
Also used : CurrentUser(org.hisp.dhis.user.CurrentUser) User(org.hisp.dhis.user.User) UserAuthorityGroup(org.hisp.dhis.user.UserAuthorityGroup) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DeleteAccessDeniedException(org.hisp.dhis.hibernate.exception.DeleteAccessDeniedException) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus)

Aggregations

ImportSummary (org.hisp.dhis.dxf2.importsummary.ImportSummary)41 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)39 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)26 InputStream (java.io.InputStream)24 User (org.hisp.dhis.user.User)21 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)18 IOException (java.io.IOException)17 Event (org.hisp.dhis.dxf2.events.event.Event)16 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)15 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)13 ImportOptions (org.hisp.dhis.dxf2.common.ImportOptions)12 GetMapping (org.springframework.web.bind.annotation.GetMapping)12 ArrayList (java.util.ArrayList)11 List (java.util.List)11 DataElement (org.hisp.dhis.dataelement.DataElement)10 Test (org.junit.jupiter.api.Test)10 TrackedEntityInstanceParams (org.hisp.dhis.dxf2.events.TrackedEntityInstanceParams)9 Lists (com.google.common.collect.Lists)8 Collectors (java.util.stream.Collectors)8 HashMap (java.util.HashMap)7