Search in sources :

Example 31 with WebMessageUtils.conflict

use of org.hisp.dhis.dxf2.webmessage.WebMessageUtils.conflict in project dhis2-core by dhis2.

the class EventController method getEventsGrid.

// -------------------------------------------------------------------------
// READ
// -------------------------------------------------------------------------
@RequestMapping(value = "/query", method = RequestMethod.GET, produces = { ContextUtils.CONTENT_TYPE_JSON, ContextUtils.CONTENT_TYPE_JAVASCRIPT })
@PreAuthorize("hasRole('ALL') or hasRole('F_TRACKED_ENTITY_DATAVALUE_ADD') or hasRole('F_TRACKED_ENTITY_DATAVALUE_READ')")
@ResponseBody
public Grid getEventsGrid(@RequestParam(required = false) String program, @RequestParam(required = false) String programStage, @RequestParam(required = false) ProgramStatus programStatus, @RequestParam(required = false) Boolean followUp, @RequestParam(required = false) String trackedEntityInstance, @RequestParam(required = false) String orgUnit, @RequestParam(required = false) OrganisationUnitSelectionMode ouMode, @RequestParam(required = false) Date startDate, @RequestParam(required = false) Date endDate, @RequestParam(required = false) Date dueDateStart, @RequestParam(required = false) Date dueDateEnd, @RequestParam(required = false) Date lastUpdated, @RequestParam(required = false) Date lastUpdatedStartDate, @RequestParam(required = false) Date lastUpdatedEndDate, @RequestParam(required = false) EventStatus status, @RequestParam(required = false) String attributeCc, @RequestParam(required = false) String attributeCos, @RequestParam(required = false) boolean skipMeta, @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize, @RequestParam(required = false) boolean totalPages, @RequestParam(required = false) boolean skipPaging, @RequestParam(required = false) String order, @RequestParam(required = false) String attachment, @RequestParam(required = false, defaultValue = "false") boolean includeDeleted, @RequestParam(required = false) String event, @RequestParam(required = false) Set<String> filter, @RequestParam(required = false) Set<String> dataElement, @RequestParam Map<String, String> parameters, IdSchemes idSchemes, Model model, HttpServletResponse response, HttpServletRequest request) throws WebMessageException {
    List<String> fields = Lists.newArrayList(contextService.getParameterValues("fields"));
    if (fields.isEmpty()) {
        fields.addAll(Preset.ALL.getFields());
    }
    boolean allowNoAttrOptionCombo = trackedEntityInstance != null && entityInstanceService.getTrackedEntityInstance(trackedEntityInstance) != null;
    DataElementCategoryOptionCombo attributeOptionCombo = inputUtils.getAttributeOptionCombo(attributeCc, attributeCos, allowNoAttrOptionCombo);
    if (attributeOptionCombo == null && !allowNoAttrOptionCombo) {
        throw new WebMessageException(WebMessageUtils.conflict("Illegal attribute option combo identifier: " + attributeCc + " " + attributeCos));
    }
    Set<String> eventIds = TextUtils.splitToArray(event, TextUtils.SEMICOLON);
    lastUpdatedStartDate = lastUpdatedStartDate != null ? lastUpdatedStartDate : lastUpdated;
    EventSearchParams params = eventService.getFromUrl(program, programStage, programStatus, followUp, orgUnit, ouMode, trackedEntityInstance, startDate, endDate, dueDateStart, dueDateEnd, lastUpdatedStartDate, lastUpdatedEndDate, status, attributeOptionCombo, idSchemes, page, pageSize, totalPages, skipPaging, null, getGridOrderParams(order), false, eventIds, filter, dataElement, includeDeleted);
    contextUtils.configureResponse(response, ContextUtils.CONTENT_TYPE_JSON, CacheStrategy.NO_CACHE);
    return eventService.getEventsGrid(params);
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) EventSearchParams(org.hisp.dhis.dxf2.events.event.EventSearchParams) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 32 with WebMessageUtils.conflict

use of org.hisp.dhis.dxf2.webmessage.WebMessageUtils.conflict in project dhis2-core by dhis2.

the class UserSettingController method setUserSetting.

// -------------------------------------------------------------------------
// Resources
// -------------------------------------------------------------------------
@RequestMapping(value = "/{key}", method = RequestMethod.POST)
public void setUserSetting(@PathVariable(value = "key") String key, @RequestParam(value = "user", required = false) String username, @RequestParam(value = "value", required = false) String value, @RequestBody(required = false) String valuePayload, HttpServletResponse response, HttpServletRequest request) throws WebMessageException {
    if (key == null) {
        throw new WebMessageException(WebMessageUtils.conflict("Key must be specified"));
    }
    if (value == null && valuePayload == null) {
        throw new WebMessageException(WebMessageUtils.conflict("Value must be specified as query param or as payload"));
    }
    value = ObjectUtils.firstNonNull(value, valuePayload);
    Optional<UserSettingKey> keyEnum = UserSettingKey.getByName(key);
    if (!keyEnum.isPresent()) {
        throw new WebMessageException(WebMessageUtils.conflict("Key is not supported: " + key));
    }
    Serializable valueObject = UserSettingKey.getAsRealClass(key, value);
    if (username == null) {
        userSettingService.saveUserSetting(keyEnum.get(), valueObject);
    } else {
        userSettingService.saveUserSetting(keyEnum.get(), valueObject, username);
    }
    webMessageService.send(WebMessageUtils.ok("User setting saved"), response, request);
}
Also used : Serializable(java.io.Serializable) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) UserSettingKey(org.hisp.dhis.user.UserSettingKey) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 33 with WebMessageUtils.conflict

use of org.hisp.dhis.dxf2.webmessage.WebMessageUtils.conflict in project dhis2-core by dhis2.

the class EventController method getEvents.

@RequestMapping(value = "", method = RequestMethod.GET)
@PreAuthorize("hasRole('ALL') or hasRole('F_TRACKED_ENTITY_DATAVALUE_ADD') or hasRole('F_TRACKED_ENTITY_DATAVALUE_READ')")
@ResponseBody
public RootNode getEvents(@RequestParam(required = false) String program, @RequestParam(required = false) String programStage, @RequestParam(required = false) ProgramStatus programStatus, @RequestParam(required = false) Boolean followUp, @RequestParam(required = false) String trackedEntityInstance, @RequestParam(required = false) String orgUnit, @RequestParam(required = false) OrganisationUnitSelectionMode ouMode, @RequestParam(required = false) Date startDate, @RequestParam(required = false) Date endDate, @RequestParam(required = false) Date dueDateStart, @RequestParam(required = false) Date dueDateEnd, @RequestParam(required = false) Date lastUpdated, @RequestParam(required = false) Date lastUpdatedStartDate, @RequestParam(required = false) Date lastUpdatedEndDate, @RequestParam(required = false) EventStatus status, @RequestParam(required = false) String attributeCc, @RequestParam(required = false) String attributeCos, @RequestParam(required = false) boolean skipMeta, @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize, @RequestParam(required = false) boolean totalPages, @RequestParam(required = false) boolean skipPaging, @RequestParam(required = false) String order, @RequestParam(required = false) String attachment, @RequestParam(required = false, defaultValue = "false") boolean includeDeleted, @RequestParam(required = false) String event, @RequestParam Map<String, String> parameters, IdSchemes idSchemes, Model model, HttpServletResponse response, HttpServletRequest request) throws WebMessageException {
    WebOptions options = new WebOptions(parameters);
    List<String> fields = Lists.newArrayList(contextService.getParameterValues("fields"));
    if (fields.isEmpty()) {
        fields.addAll(Preset.ALL.getFields());
    }
    boolean allowNoAttrOptionCombo = trackedEntityInstance != null && entityInstanceService.getTrackedEntityInstance(trackedEntityInstance) != null;
    DataElementCategoryOptionCombo attributeOptionCombo = inputUtils.getAttributeOptionCombo(attributeCc, attributeCos, allowNoAttrOptionCombo);
    if (attributeOptionCombo == null && !allowNoAttrOptionCombo) {
        throw new WebMessageException(WebMessageUtils.conflict("Illegal attribute option combo identifier: " + attributeCc + " " + attributeCos));
    }
    Set<String> eventIds = TextUtils.splitToArray(event, TextUtils.SEMICOLON);
    lastUpdatedStartDate = lastUpdatedStartDate != null ? lastUpdatedStartDate : lastUpdated;
    EventSearchParams params = eventService.getFromUrl(program, programStage, programStatus, followUp, orgUnit, ouMode, trackedEntityInstance, startDate, endDate, dueDateStart, dueDateEnd, lastUpdatedStartDate, lastUpdatedEndDate, status, attributeOptionCombo, idSchemes, page, pageSize, totalPages, skipPaging, getOrderParams(order), null, false, eventIds, null, null, includeDeleted);
    Events events = eventService.getEvents(params);
    if (hasHref(fields)) {
        events.getEvents().forEach(e -> e.setHref(ContextUtils.getRootPath(request) + RESOURCE_PATH + "/" + e.getEvent()));
    }
    if (!skipMeta && params.getProgram() != null) {
        events.setMetaData(getMetaData(params.getProgram()));
    }
    model.addAttribute("model", events);
    model.addAttribute("viewClass", options.getViewClass("detailed"));
    RootNode rootNode = NodeUtils.createMetadata();
    if (events.getPager() != null) {
        rootNode.addChild(NodeUtils.createPager(events.getPager()));
    }
    if (!StringUtils.isEmpty(attachment)) {
        response.addHeader(ContextUtils.HEADER_CONTENT_DISPOSITION, "attachment; filename=" + attachment);
        response.addHeader(ContextUtils.HEADER_CONTENT_TRANSFER_ENCODING, "binary");
    }
    rootNode.addChild(fieldFilterService.filter(Event.class, events.getEvents(), fields));
    return rootNode;
}
Also used : RootNode(org.hisp.dhis.node.types.RootNode) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) Events(org.hisp.dhis.dxf2.events.event.Events) EventSearchParams(org.hisp.dhis.dxf2.events.event.EventSearchParams) Event(org.hisp.dhis.dxf2.events.event.Event) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 34 with WebMessageUtils.conflict

use of org.hisp.dhis.dxf2.webmessage.WebMessageUtils.conflict 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 35 with WebMessageUtils.conflict

use of org.hisp.dhis.dxf2.webmessage.WebMessageUtils.conflict in project dhis2-core by dhis2.

the class EventController method deleteEvent.

// -------------------------------------------------------------------------
// DELETE
// -------------------------------------------------------------------------
@RequestMapping(value = "/{uid}", method = RequestMethod.DELETE)
@PreAuthorize("hasRole('ALL') or hasRole('F_TRACKED_ENTITY_DATAVALUE_DELETE')")
public void deleteEvent(HttpServletResponse response, HttpServletRequest request, @PathVariable("uid") String uid) throws WebMessageException {
    if (!programStageInstanceService.programStageInstanceExists(uid)) {
        throw new WebMessageException(WebMessageUtils.notFound("Event not found for ID " + uid));
    }
    response.setStatus(HttpServletResponse.SC_OK);
    try {
        ImportSummary importSummary = eventService.deleteEvent(uid);
        webMessageService.send(WebMessageUtils.importSummary(importSummary), response, request);
    } catch (Exception ex) {
        webMessageService.send(WebMessageUtils.conflict("Unable to delete event " + uid, ex.getMessage()), response, request);
    }
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) IOException(java.io.IOException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)51 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)44 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)20 Period (org.hisp.dhis.period.Period)14 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)12 DataElementCategoryOptionCombo (org.hisp.dhis.dataelement.DataElementCategoryOptionCombo)11 DataSet (org.hisp.dhis.dataset.DataSet)10 Interpretation (org.hisp.dhis.interpretation.Interpretation)10 ArrayList (java.util.ArrayList)9 User (org.hisp.dhis.user.User)9 Date (java.util.Date)7 DataElement (org.hisp.dhis.dataelement.DataElement)7 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)7 WebMessage (org.hisp.dhis.dxf2.webmessage.WebMessage)6 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)6 Serializable (java.io.Serializable)4 IdentifiableObject (org.hisp.dhis.common.IdentifiableObject)4 DataValue (org.hisp.dhis.datavalue.DataValue)4 UpdateAccessDeniedException (org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException)4 ByteSource (com.google.common.io.ByteSource)3