Search in sources :

Example 1 with FileResource

use of org.hisp.dhis.fileresource.FileResource in project dhis2-core by dhis2.

the class DataValueController method saveDataValue.

// ---------------------------------------------------------------------
// POST
// ---------------------------------------------------------------------
@PreAuthorize("hasRole('ALL') or hasRole('F_DATAVALUE_ADD')")
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void saveDataValue(@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(required = false) String value, @RequestParam(required = false) String comment, @RequestParam(required = false) boolean followUp, HttpServletResponse response) throws WebMessageException {
    boolean strictPeriods = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_STRICT_PERIODS);
    boolean strictCategoryOptionCombos = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_STRICT_CATEGORY_OPTION_COMBOS);
    boolean strictOrgUnits = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_STRICT_ORGANISATION_UNITS);
    boolean requireCategoryOptionCombo = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_REQUIRE_CATEGORY_OPTION_COMBO);
    // ---------------------------------------------------------------------
    // Input validation
    // ---------------------------------------------------------------------
    DataElement dataElement = getAndValidateDataElement(de);
    DataElementCategoryOptionCombo categoryOptionCombo = getAndValidateCategoryOptionCombo(co, requireCategoryOptionCombo);
    DataElementCategoryOptionCombo attributeOptionCombo = getAndValidateAttributeOptionCombo(cc, cp);
    Period period = getAndValidatePeriod(pe);
    OrganisationUnit organisationUnit = getAndValidateOrganisationUnit(ou);
    validateInvalidFuturePeriod(period, dataElement);
    validateAttributeOptionComboWithOrgUnitAndPeriod(attributeOptionCombo, organisationUnit, period);
    String valueValid = ValidationUtils.dataValueIsValid(value, dataElement);
    if (valueValid != null) {
        throw new WebMessageException(WebMessageUtils.conflict("Invalid value: " + value + ", must match data element type: " + dataElement.getValueType()));
    }
    String commentValid = ValidationUtils.commentIsValid(comment);
    if (commentValid != null) {
        throw new WebMessageException(WebMessageUtils.conflict("Invalid comment: " + comment));
    }
    OptionSet optionSet = dataElement.getOptionSet();
    if (!Strings.isNullOrEmpty(value) && optionSet != null && !optionSet.getOptionCodesAsSet().contains(value)) {
        throw new WebMessageException(WebMessageUtils.conflict("Data value is not a valid option of the data element option set: " + dataElement.getUid()));
    }
    if (strictPeriods && !dataElement.getPeriodTypes().contains(period.getPeriodType())) {
        throw new WebMessageException(WebMessageUtils.conflict("Period type of period: " + period.getIsoDate() + " not valid for data element: " + dataElement.getUid()));
    }
    if (strictCategoryOptionCombos && !dataElement.getCategoryOptionCombos().contains(categoryOptionCombo)) {
        throw new WebMessageException(WebMessageUtils.conflict("Category option combo: " + categoryOptionCombo.getUid() + " must be part of category combo of data element: " + dataElement.getUid()));
    }
    if (strictOrgUnits && !organisationUnit.hasDataElement(dataElement)) {
        throw new WebMessageException(WebMessageUtils.conflict("Data element: " + dataElement.getUid() + " must be assigned through data sets to organisation unit: " + organisationUnit.getUid()));
    }
    // ---------------------------------------------------------------------
    // Locking validation
    // ---------------------------------------------------------------------
    validateDataSetNotLocked(dataElement, period, organisationUnit, attributeOptionCombo);
    // ---------------------------------------------------------------------
    // Period validation
    // ---------------------------------------------------------------------
    validateDataInputPeriodForDataElementAndPeriod(dataElement, period);
    // ---------------------------------------------------------------------
    // Assemble and save data value
    // ---------------------------------------------------------------------
    String storedBy = currentUserService.getCurrentUsername();
    Date now = new Date();
    DataValue dataValue = dataValueService.getDataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo);
    FileResource fileResource = null;
    if (dataValue == null) {
        if (dataElement.getValueType() == ValueType.FILE_RESOURCE) {
            if (value != null) {
                fileResource = fileResourceService.getFileResource(value);
                if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
                    throw new WebMessageException(WebMessageUtils.notFound(FileResource.class, value));
                }
                if (fileResource.isAssigned()) {
                    throw new WebMessageException(WebMessageUtils.conflict("File resource already assigned or linked to another data value"));
                }
                fileResource.setAssigned(true);
            } else {
                throw new WebMessageException(WebMessageUtils.conflict("Missing parameter 'value'"));
            }
        }
        dataValue = new DataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo, StringUtils.trimToNull(value), storedBy, now, StringUtils.trimToNull(comment));
        dataValueService.addDataValue(dataValue);
    } else {
        if (value == null && ValueType.TRUE_ONLY.equals(dataElement.getValueType())) {
            if (comment == null) {
                dataValueService.deleteDataValue(dataValue);
                return;
            } else {
                value = "false";
            }
        }
        if (dataElement.isFileType()) {
            fileResourceService.deleteFileResource(dataValue.getValue());
        }
        if (value != null) {
            dataValue.setValue(StringUtils.trimToNull(value));
        }
        if (comment != null) {
            dataValue.setComment(StringUtils.trimToNull(comment));
        }
        if (followUp) {
            dataValue.toggleFollowUp();
        }
        dataValue.setLastUpdated(now);
        dataValue.setStoredBy(storedBy);
        dataValueService.updateDataValue(dataValue);
    }
    if (fileResource != null) {
        fileResourceService.updateFileResource(fileResource);
    }
}
Also used : DataElement(org.hisp.dhis.dataelement.DataElement) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DataValue(org.hisp.dhis.datavalue.DataValue) FileResource(org.hisp.dhis.fileresource.FileResource) Period(org.hisp.dhis.period.Period) OptionSet(org.hisp.dhis.option.OptionSet) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo) Date(java.util.Date) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with FileResource

use of org.hisp.dhis.fileresource.FileResource in project dhis2-core by dhis2.

the class DefaultTrackedEntityDataValueService method handleFileDataValueUpdate.

private void handleFileDataValueUpdate(TrackedEntityDataValue dataValue) {
    String previousFileResourceUid = dataValue.getAuditValue();
    if (previousFileResourceUid == null || previousFileResourceUid.equals(dataValue.getValue())) {
        return;
    }
    FileResource fileResource = fetchFileResource(dataValue);
    if (fileResource == null) {
        return;
    }
    fileResourceService.deleteFileResource(previousFileResourceUid);
    setAssigned(fileResource);
}
Also used : FileResource(org.hisp.dhis.fileresource.FileResource)

Example 3 with FileResource

use of org.hisp.dhis.fileresource.FileResource in project dhis2-core by dhis2.

the class DefaultTrackedEntityDataValueService method handleFileDataValueDelete.

/**
     * Delete associated FileResource if it exists.
     */
private void handleFileDataValueDelete(TrackedEntityDataValue dataValue) {
    FileResource fileResource = fetchFileResource(dataValue);
    if (fileResource == null) {
        return;
    }
    fileResourceService.deleteFileResource(fileResource.getUid());
}
Also used : FileResource(org.hisp.dhis.fileresource.FileResource)

Example 4 with FileResource

use of org.hisp.dhis.fileresource.FileResource in project dhis2-core by dhis2.

the class DefaultTrackedEntityDataValueService method handleFileDataValueSave.

/**
     * Update FileResource with 'assigned' status.
     */
private void handleFileDataValueSave(TrackedEntityDataValue dataValue) {
    FileResource fileResource = fetchFileResource(dataValue);
    if (fileResource == null) {
        return;
    }
    setAssigned(fileResource);
}
Also used : FileResource(org.hisp.dhis.fileresource.FileResource)

Example 5 with FileResource

use of org.hisp.dhis.fileresource.FileResource in project dhis2-core by dhis2.

the class EventController method getEventDataValueFile.

@RequestMapping(value = "/files", method = RequestMethod.GET)
@PreAuthorize("hasRole('ALL') or hasRole('F_TRACKED_ENTITY_DATAVALUE_ADD') or hasRole('F_TRACKED_ENTITY_DATAVALUE_READ')")
public void getEventDataValueFile(@RequestParam String eventUid, @RequestParam String dataElementUid, HttpServletResponse response, HttpServletRequest request) throws Exception {
    Event event = eventService.getEvent(eventUid);
    if (event == null) {
        throw new WebMessageException(WebMessageUtils.notFound("Event not found for ID " + eventUid));
    }
    DataElement dataElement = dataElementService.getDataElement(dataElementUid);
    if (dataElement == null) {
        throw new WebMessageException(WebMessageUtils.notFound("DataElement not found for ID " + dataElementUid));
    }
    if (!dataElement.isFileType()) {
        throw new WebMessageException(WebMessageUtils.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(WebMessageUtils.conflict("DataElement must be of type file"));
    }
    FileResource fileResource = fileResourceService.getFileResource(uid);
    if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
        throw new WebMessageException(WebMessageUtils.notFound("A data value file resource with id " + uid + " does not exist."));
    }
    if (fileResource.getStorageStatus() != FileResourceStorageStatus.STORED) {
        // -----------------------------------------------------------------
        // The FileResource exists and is tied to DataValue, however the 
        // underlying file content still not stored to external file store
        // -----------------------------------------------------------------
        WebMessage webMessage = WebMessageUtils.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.");
        webMessage.setResponse(new FileResourceWebMessageResponse(fileResource));
        throw new WebMessageException(webMessage);
    }
    ByteSource content = fileResourceService.getFileResourceContent(fileResource);
    if (content == null) {
        throw new WebMessageException(WebMessageUtils.notFound("The referenced file could not be found"));
    }
    // ---------------------------------------------------------------------
    // Attempt to build signed URL request for content and redirect
    // ---------------------------------------------------------------------
    URI signedGetUri = fileResourceService.getSignedGetFileResourceContentUri(uid);
    if (signedGetUri != null) {
        response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
        response.setHeader(HttpHeaders.LOCATION, signedGetUri.toASCIIString());
        return;
    }
    // ---------------------------------------------------------------------
    // Build response and return
    // ---------------------------------------------------------------------
    response.setContentType(fileResource.getContentType());
    response.setContentLength(new Long(fileResource.getContentLength()).intValue());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileResource.getName());
    // ---------------------------------------------------------------------
    // Request signing is not available, stream content back to client
    // ---------------------------------------------------------------------
    InputStream inputStream = null;
    try {
        inputStream = content.openStream();
        IOUtils.copy(inputStream, response.getOutputStream());
    } catch (IOException e) {
        throw new WebMessageException(WebMessageUtils.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."));
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DataValue(org.hisp.dhis.dxf2.events.event.DataValue) InputStream(java.io.InputStream) FileResource(org.hisp.dhis.fileresource.FileResource) IOException(java.io.IOException) URI(java.net.URI) DataElement(org.hisp.dhis.dataelement.DataElement) FileResourceWebMessageResponse(org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse) Event(org.hisp.dhis.dxf2.events.event.Event) ByteSource(com.google.common.io.ByteSource) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

FileResource (org.hisp.dhis.fileresource.FileResource)11 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 ByteSource (com.google.common.io.ByteSource)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 URI (java.net.URI)3 Date (java.util.Date)3 DataElement (org.hisp.dhis.dataelement.DataElement)3 WebMessage (org.hisp.dhis.dxf2.webmessage.WebMessage)3 FileResourceWebMessageResponse (org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse)3 DataElementCategoryOptionCombo (org.hisp.dhis.dataelement.DataElementCategoryOptionCombo)2 DataValue (org.hisp.dhis.datavalue.DataValue)2 ExternalFileResource (org.hisp.dhis.fileresource.ExternalFileResource)2 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)2 Period (org.hisp.dhis.period.Period)2 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)2 File (java.io.File)1 DataValue (org.hisp.dhis.dxf2.events.event.DataValue)1 Event (org.hisp.dhis.dxf2.events.event.Event)1