Search in sources :

Example 26 with WebOptions

use of org.hisp.dhis.webapi.webdomain.WebOptions in project dhis2-core by dhis2.

the class AbstractCrudController method updateObjectProperty.

@RequestMapping(value = "/{uid}/{property}", method = { RequestMethod.PUT, RequestMethod.PATCH })
public void updateObjectProperty(@PathVariable("uid") String pvUid, @PathVariable("property") String pvProperty, @RequestParam Map<String, String> rpParameters, HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebOptions options = new WebOptions(rpParameters);
    List<T> entities = getEntity(pvUid, options);
    if (entities.isEmpty()) {
        throw new WebMessageException(WebMessageUtils.notFound(getEntityClass(), pvUid));
    }
    if (!getSchema().haveProperty(pvProperty)) {
        throw new WebMessageException(WebMessageUtils.notFound("Property " + pvProperty + " does not exist on " + getEntityName()));
    }
    Property property = getSchema().getProperty(pvProperty);
    T persistedObject = entities.get(0);
    if (!aclService.canUpdate(currentUserService.getCurrentUser(), persistedObject)) {
        throw new UpdateAccessDeniedException("You don't have the proper permissions to update this object.");
    }
    if (!property.isWritable()) {
        throw new UpdateAccessDeniedException("This property is read-only.");
    }
    T object = deserialize(request);
    if (object == null) {
        throw new WebMessageException(WebMessageUtils.badRequest("Unknown payload format."));
    }
    Object value = property.getGetterMethod().invoke(object);
    property.getSetterMethod().invoke(persistedObject, value);
    manager.update(persistedObject);
    postPatchEntity(persistedObject);
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) Property(org.hisp.dhis.schema.Property) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 27 with WebOptions

use of org.hisp.dhis.webapi.webdomain.WebOptions 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 28 with WebOptions

use of org.hisp.dhis.webapi.webdomain.WebOptions in project dhis2-core by dhis2.

the class AbstractFullReadOnlyController method getObjectListCsv.

@GetMapping(produces = "application/csv")
public void getObjectListCsv(@RequestParam Map<String, String> rpParameters, OrderParams orderParams, @CurrentUser User currentUser, @RequestParam(defaultValue = ",") char separator, @RequestParam(defaultValue = "false") boolean skipHeader, HttpServletResponse response) throws IOException {
    List<Order> orders = orderParams.getOrders(getSchema());
    List<String> fields = Lists.newArrayList(contextService.getParameterValues("fields"));
    List<String> filters = Lists.newArrayList(contextService.getParameterValues("filter"));
    WebOptions options = new WebOptions(rpParameters);
    WebMetadata metadata = new WebMetadata();
    if (fields.isEmpty()) {
        fields.addAll(Preset.defaultPreset().getFields());
    }
    // only support metadata
    if (!getSchema().isMetadata()) {
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
    }
    if (!aclService.canRead(currentUser, getEntityClass())) {
        throw new ReadAccessDeniedException("You don't have the proper permissions to read objects of this type.");
    }
    List<T> entities = getEntityList(metadata, options, filters, orders);
    CsvSchema schema;
    CsvSchema.Builder schemaBuilder = CsvSchema.builder();
    List<Property> properties = new ArrayList<>();
    for (String field : fields) {
        // then the group[id] part is simply ignored.
        for (String splitField : field.split(",")) {
            Property property = getSchema().getProperty(splitField);
            if (property == null || !property.isSimple()) {
                continue;
            }
            schemaBuilder.addColumn(property.getName());
            properties.add(property);
        }
    }
    schema = schemaBuilder.build().withColumnSeparator(separator);
    if (!skipHeader) {
        schema = schema.withHeader();
    }
    CsvMapper csvMapper = new CsvMapper();
    csvMapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
    List<Map<String, Object>> csvObjects = entities.stream().map(e -> {
        Map<String, Object> map = new HashMap<>();
        for (Property property : properties) {
            Object value = ReflectionUtils.invokeMethod(e, property.getGetterMethod());
            map.put(property.getName(), value);
        }
        return map;
    }).collect(toList());
    csvMapper.writer(schema).writeValue(response.getWriter(), csvObjects);
    response.flushBuffer();
}
Also used : Order(org.hisp.dhis.query.Order) PathVariable(org.springframework.web.bind.annotation.PathVariable) Order(org.hisp.dhis.query.Order) RequestParam(org.springframework.web.bind.annotation.RequestParam) ReflectionUtils(org.hisp.dhis.system.util.ReflectionUtils) UserContext(org.hisp.dhis.common.UserContext) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) InclusionStrategy(org.hisp.dhis.node.config.InclusionStrategy) Pagination(org.hisp.dhis.query.Pagination) UserSettingKey(org.hisp.dhis.user.UserSettingKey) Autowired(org.springframework.beans.factory.annotation.Autowired) CurrentUser(org.hisp.dhis.user.CurrentUser) PaginationUtils(org.hisp.dhis.webapi.utils.PaginationUtils) NodeUtils(org.hisp.dhis.node.NodeUtils) UserSettingService(org.hisp.dhis.user.UserSettingService) Locale(java.util.Locale) Optional(com.google.common.base.Optional) Map(java.util.Map) Preset(org.hisp.dhis.node.Preset) Query(org.hisp.dhis.query.Query) ContextService(org.hisp.dhis.webapi.service.ContextService) LinkService(org.hisp.dhis.webapi.service.LinkService) FieldFilterService(org.hisp.dhis.fieldfilter.FieldFilterService) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) CacheControl.noCache(org.springframework.http.CacheControl.noCache) QueryService(org.hisp.dhis.query.QueryService) Property(org.hisp.dhis.schema.Property) Defaults(org.hisp.dhis.fieldfilter.Defaults) SimpleNode(org.hisp.dhis.node.types.SimpleNode) List(java.util.List) Include(org.hisp.dhis.node.config.InclusionStrategy.Include) ComplexNode(org.hisp.dhis.node.types.ComplexNode) AttributeService(org.hisp.dhis.attribute.AttributeService) FieldFilterParams(org.hisp.dhis.fieldfilter.FieldFilterParams) AclService(org.hisp.dhis.security.acl.AclService) Schema(org.hisp.dhis.schema.Schema) RootNode(org.hisp.dhis.node.types.RootNode) Joiner(com.google.common.base.Joiner) DhisApiVersion(org.hisp.dhis.common.DhisApiVersion) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) WebMessageUtils.notFound(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound) CollectionNode(org.hisp.dhis.node.types.CollectionNode) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) HashMap(java.util.HashMap) ApiVersion(org.hisp.dhis.webapi.mvc.annotation.ApiVersion) ArrayList(java.util.ArrayList) Enums(com.google.common.base.Enums) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) IdentifiableObjectManager(org.hisp.dhis.common.IdentifiableObjectManager) WebMetadata(org.hisp.dhis.webapi.webdomain.WebMetadata) User(org.hisp.dhis.user.User) GetMapping(org.springframework.web.bind.annotation.GetMapping) QueryParserException(org.hisp.dhis.query.QueryParserException) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) Node(org.hisp.dhis.node.Node) Pager(org.hisp.dhis.common.Pager) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) HttpStatus(org.springframework.http.HttpStatus) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Collectors.toList(java.util.stream.Collectors.toList) OrderParams(org.hisp.dhis.dxf2.common.OrderParams) CurrentUserService(org.hisp.dhis.user.CurrentUserService) TranslateParams(org.hisp.dhis.dxf2.common.TranslateParams) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) ArrayList(java.util.ArrayList) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) WebMetadata(org.hisp.dhis.webapi.webdomain.WebMetadata) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) Property(org.hisp.dhis.schema.Property) Map(java.util.Map) HashMap(java.util.HashMap) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 29 with WebOptions

use of org.hisp.dhis.webapi.webdomain.WebOptions in project dhis2-core by dhis2.

the class AbstractCrudController method updateObjectProperty.

@PatchMapping("/{uid}/{property}")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void updateObjectProperty(@PathVariable("uid") String pvUid, @PathVariable("property") String pvProperty, @RequestParam Map<String, String> rpParameters, @CurrentUser User currentUser, HttpServletRequest request) throws Exception {
    WebOptions options = new WebOptions(rpParameters);
    List<T> entities = getEntity(pvUid, options);
    if (entities.isEmpty()) {
        throw new WebMessageException(notFound(getEntityClass(), pvUid));
    }
    if (!getSchema().haveProperty(pvProperty)) {
        throw new WebMessageException(notFound("Property " + pvProperty + " does not exist on " + getEntityName()));
    }
    Property property = getSchema().getProperty(pvProperty);
    T persistedObject = entities.get(0);
    if (!aclService.canUpdate(currentUser, persistedObject)) {
        throw new UpdateAccessDeniedException("You don't have the proper permissions to update this object.");
    }
    if (!property.isWritable()) {
        throw new UpdateAccessDeniedException("This property is read-only.");
    }
    T object = deserialize(request);
    if (object == null) {
        throw new WebMessageException(badRequest("Unknown payload format."));
    }
    prePatchEntity(persistedObject);
    Object value = property.getGetterMethod().invoke(object);
    property.getSetterMethod().invoke(persistedObject, value);
    Map<String, List<String>> parameterValuesMap = contextService.getParameterValuesMap();
    MetadataImportParams params = importService.getParamsFromMap(parameterValuesMap);
    params.setUser(currentUser).setImportStrategy(ImportStrategy.UPDATE).addObject(persistedObject);
    ImportReport importReport = importService.importMetadata(params);
    if (importReport.getStatus() != Status.OK) {
        throw new WebMessageException(objectReport(importReport));
    }
    postPatchEntity(persistedObject);
}
Also used : MetadataImportParams(org.hisp.dhis.dxf2.metadata.MetadataImportParams) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) ImportReport(org.hisp.dhis.dxf2.metadata.feedback.ImportReport) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) SubscribableObject(org.hisp.dhis.common.SubscribableObject) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) Property(org.hisp.dhis.schema.Property) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) PatchMapping(org.springframework.web.bind.annotation.PatchMapping)

Example 30 with WebOptions

use of org.hisp.dhis.webapi.webdomain.WebOptions in project dhis2-core by dhis2.

the class AbstractCrudController method replaceTranslations.

@PutMapping(value = "/{uid}/translations")
@ResponseStatus(HttpStatus.NO_CONTENT)
@ResponseBody
public WebMessage replaceTranslations(@PathVariable("uid") String pvUid, @RequestParam Map<String, String> rpParameters, @CurrentUser User currentUser, HttpServletRequest request) throws Exception {
    WebOptions options = new WebOptions(rpParameters);
    List<T> entities = getEntity(pvUid, options);
    if (entities.isEmpty()) {
        return notFound(getEntityClass(), pvUid);
    }
    BaseIdentifiableObject persistedObject = (BaseIdentifiableObject) entities.get(0);
    if (!aclService.canUpdate(currentUser, persistedObject)) {
        throw new UpdateAccessDeniedException("You don't have the proper permissions to update this object.");
    }
    T inputObject = renderService.fromJson(request.getInputStream(), getEntityClass());
    HashSet<Translation> translations = new HashSet<>(inputObject.getTranslations());
    persistedObject.setTranslations(translations);
    MetadataImportParams params = importService.getParamsFromMap(contextService.getParameterValuesMap());
    params.setUser(currentUser).setImportStrategy(ImportStrategy.UPDATE).addObject(persistedObject).setImportMode(ObjectBundleMode.VALIDATE);
    ImportReport importReport = importService.importMetadata(params);
    if (!importReport.hasErrorReports()) {
        manager.save(persistedObject);
        return null;
    }
    return importReport(importReport);
}
Also used : Translation(org.hisp.dhis.translation.Translation) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) MetadataImportParams(org.hisp.dhis.dxf2.metadata.MetadataImportParams) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) ImportReport(org.hisp.dhis.dxf2.metadata.feedback.ImportReport) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) HashSet(java.util.HashSet) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) PutMapping(org.springframework.web.bind.annotation.PutMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

WebOptions (org.hisp.dhis.webapi.webdomain.WebOptions)45 RootNode (org.hisp.dhis.node.types.RootNode)21 Test (org.junit.jupiter.api.Test)18 Pager (org.hisp.dhis.common.Pager)16 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)14 BaseIdentifiableObject (org.hisp.dhis.common.BaseIdentifiableObject)13 GetMapping (org.springframework.web.bind.annotation.GetMapping)13 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)12 DataItem (org.hisp.dhis.dataitem.DataItem)10 FieldFilterParams (org.hisp.dhis.fieldfilter.FieldFilterParams)10 User (org.hisp.dhis.user.User)9 WebMetadata (org.hisp.dhis.webapi.webdomain.WebMetadata)9 List (java.util.List)8 UpdateAccessDeniedException (org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException)7 Order (org.hisp.dhis.query.Order)7 Query (org.hisp.dhis.query.Query)7 ArrayList (java.util.ArrayList)6 CollectionNode (org.hisp.dhis.node.types.CollectionNode)6 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)6 HashMap (java.util.HashMap)5