Search in sources :

Example 1 with FileResourceWebMessageResponse

use of org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse 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)

Example 2 with FileResourceWebMessageResponse

use of org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse in project dhis2-core by dhis2.

the class DataValueController method getDataValueFile.

// ---------------------------------------------------------------------
// GET file
// ---------------------------------------------------------------------
@RequestMapping(value = "/files", method = RequestMethod.GET)
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, HttpServletResponse response, HttpServletRequest request) throws WebMessageException {
    // ---------------------------------------------------------------------
    // Input validation
    // ---------------------------------------------------------------------
    DataElement dataElement = getAndValidateDataElement(de);
    if (!dataElement.isFileType()) {
        throw new WebMessageException(WebMessageUtils.conflict("DataElement must be of type file"));
    }
    DataElementCategoryOptionCombo categoryOptionCombo = getAndValidateCategoryOptionCombo(co, false);
    DataElementCategoryOptionCombo attributeOptionCombo = getAndValidateAttributeOptionCombo(cc, cp);
    Period period = getAndValidatePeriod(pe);
    OrganisationUnit organisationUnit = getAndValidateOrganisationUnit(ou);
    // ---------------------------------------------------------------------
    // Get data value
    // ---------------------------------------------------------------------
    DataValue dataValue = dataValueService.getDataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo);
    if (dataValue == null) {
        throw new WebMessageException(WebMessageUtils.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(WebMessageUtils.notFound("A data value file resource with id " + uid + " does not exist."));
    }
    FileResourceStorageStatus storageStatus = fileResource.getStorageStatus();
    if (storageStatus != FileResourceStorageStatus.STORED) {
        // Special case:
        //  The FileResource exists and has been tied to this DataValue, however, the underlying file
        //  content is still not stored to the (most likely external) file store provider.
        // HTTP 409, for lack of a more suitable status code
        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 : OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DataValue(org.hisp.dhis.datavalue.DataValue) InputStream(java.io.InputStream) FileResourceStorageStatus(org.hisp.dhis.fileresource.FileResourceStorageStatus) FileResource(org.hisp.dhis.fileresource.FileResource) Period(org.hisp.dhis.period.Period) IOException(java.io.IOException) URI(java.net.URI) DataElement(org.hisp.dhis.dataelement.DataElement) FileResourceWebMessageResponse(org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse) ByteSource(com.google.common.io.ByteSource) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with FileResourceWebMessageResponse

use of org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse in project dhis2-core by dhis2.

the class FileResourceController method saveFileResource.

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public WebMessage saveFileResource(@RequestParam MultipartFile file) throws WebMessageException, IOException {
    String filename = StringUtils.defaultIfBlank(FilenameUtils.getName(file.getOriginalFilename()), DEFAULT_FILENAME);
    String contentType = file.getContentType();
    contentType = isValidContentType(contentType) ? contentType : DEFAULT_CONTENT_TYPE;
    long contentLength = file.getSize();
    if (contentLength <= 0) {
        throw new WebMessageException(WebMessageUtils.conflict("Could not read file or file is empty."));
    }
    ByteSource bytes = new MultipartFileByteSource(file);
    String contentMd5 = bytes.hash(Hashing.md5()).toString();
    FileResource fileResource = new FileResource(filename, contentType, contentLength, contentMd5, FileResourceDomain.DATA_VALUE);
    fileResource.setAssigned(false);
    fileResource.setCreated(new Date());
    fileResource.setUser(currentUserService.getCurrentUser());
    File tmpFile = toTempFile(file);
    String uid = fileResourceService.saveFileResource(fileResource, tmpFile);
    if (uid == null) {
        throw new WebMessageException(WebMessageUtils.error("Saving the file failed."));
    }
    WebMessage webMessage = new WebMessage(Status.OK, HttpStatus.ACCEPTED);
    webMessage.setResponse(new FileResourceWebMessageResponse(fileResource));
    return webMessage;
}
Also used : FileResourceWebMessageResponse(org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) FileResource(org.hisp.dhis.fileresource.FileResource) ByteSource(com.google.common.io.ByteSource) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) Date(java.util.Date) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 4 with FileResourceWebMessageResponse

use of org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse in project dhis2-core by dhis2.

the class AuditController method getFileAudit.

/**
 * Returns the file with the given uid
 *
 * @param uid the unique id of the file resource
 */
@GetMapping("/files/{uid}")
public void getFileAudit(@PathVariable String uid, HttpServletResponse response) throws WebMessageException {
    FileResource fileResource = fileResourceService.getFileResource(uid);
    if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
        throw new WebMessageException(notFound("No file found with uid '" + uid + "'"));
    }
    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.setContentLength(Long.valueOf(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 : FileResourceWebMessageResponse(org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) FileResourceStorageStatus(org.hisp.dhis.fileresource.FileResourceStorageStatus) FileResource(org.hisp.dhis.fileresource.FileResource) IOException(java.io.IOException) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 5 with FileResourceWebMessageResponse

use of org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse in project dhis2-core by dhis2.

the class FileResourceController method saveFileResource.

@PostMapping
public WebMessage saveFileResource(@RequestParam MultipartFile file, @RequestParam(defaultValue = "DATA_VALUE") FileResourceDomain domain) throws WebMessageException, IOException {
    FileResource fileResource = fileResourceUtils.saveFileResource(file, domain);
    WebMessage webMessage = new WebMessage(Status.OK, HttpStatus.ACCEPTED);
    webMessage.setResponse(new FileResourceWebMessageResponse(fileResource));
    return webMessage;
}
Also used : FileResourceWebMessageResponse(org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse) FileResource(org.hisp.dhis.fileresource.FileResource) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Aggregations

FileResourceWebMessageResponse (org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse)8 FileResource (org.hisp.dhis.fileresource.FileResource)8 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)6 IOException (java.io.IOException)5 WebMessage (org.hisp.dhis.dxf2.webmessage.WebMessage)5 DataElement (org.hisp.dhis.dataelement.DataElement)4 ByteSource (com.google.common.io.ByteSource)3 FileResourceStorageStatus (org.hisp.dhis.fileresource.FileResourceStorageStatus)3 GetMapping (org.springframework.web.bind.annotation.GetMapping)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 InputStream (java.io.InputStream)2 URI (java.net.URI)2 DataValue (org.hisp.dhis.datavalue.DataValue)2 DataValue (org.hisp.dhis.dxf2.events.event.DataValue)2 Event (org.hisp.dhis.dxf2.events.event.Event)2 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)2 Period (org.hisp.dhis.period.Period)2 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)2 PostMapping (org.springframework.web.bind.annotation.PostMapping)2 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)2