Search in sources :

Example 51 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project scoold by Erudika.

the class PeopleController method bulkEdit.

@PostMapping("/bulk-edit")
public String bulkEdit(@RequestParam(required = false) String[] selectedUsers, @RequestParam(required = false) final String[] selectedSpaces, HttpServletRequest req) {
    Profile authUser = utils.getAuthUser(req);
    boolean isAdmin = utils.isAdmin(authUser);
    String operation = req.getParameter("operation");
    String selection = req.getParameter("selection");
    if (isAdmin && ("all".equals(selection) || selectedUsers != null)) {
        // find all user objects even if there are more than 10000 users in the system
        Pager pager = new Pager(1, "_docid", false, Config.MAX_ITEMS_PER_PAGE);
        List<Profile> profiles;
        LinkedList<Map<String, Object>> toUpdate = new LinkedList<>();
        List<String> spaces = (selectedSpaces == null || selectedSpaces.length == 0) ? Collections.emptyList() : Arrays.asList(selectedSpaces);
        do {
            String query = (selection == null || "selected".equals(selection)) ? Config._ID + ":(\"" + String.join("\" \"", selectedUsers) + "\")" : "*";
            profiles = pc.findQuery(Utils.type(Profile.class), query, pager);
            profiles.stream().filter(p -> !utils.isMod(p)).forEach(p -> {
                if ("add".equals(operation)) {
                    p.getSpaces().addAll(spaces);
                } else if ("remove".equals(operation)) {
                    p.getSpaces().removeAll(spaces);
                } else {
                    p.setSpaces(new HashSet<String>(spaces));
                }
                Map<String, Object> profile = new HashMap<>();
                profile.put(Config._ID, p.getId());
                profile.put("spaces", p.getSpaces());
                toUpdate.add(profile);
            });
        } while (!profiles.isEmpty());
        // always patch outside the loop because we modify _docid values!!!
        LinkedList<Map<String, Object>> batch = new LinkedList<>();
        while (!toUpdate.isEmpty()) {
            batch.add(toUpdate.pop());
            if (batch.size() >= 100) {
                // partial batch update
                pc.invokePatch("_batch", batch, Map.class);
                batch.clear();
            }
        }
        if (!batch.isEmpty()) {
            pc.invokePatch("_batch", batch, Map.class);
        }
    }
    return "redirect:" + PEOPLELINK + (isAdmin ? "?" + req.getQueryString() : "");
}
Also used : SIGNINLINK(com.erudika.scoold.ScooldServer.SIGNINLINK) Arrays(java.util.Arrays) RequestParam(org.springframework.web.bind.annotation.RequestParam) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) ParaClient(com.erudika.para.client.ParaClient) Pager(com.erudika.para.core.utils.Pager) Controller(org.springframework.stereotype.Controller) HashSet(java.util.HashSet) Inject(javax.inject.Inject) HttpServletRequest(javax.servlet.http.HttpServletRequest) Model(org.springframework.ui.Model) Map(java.util.Map) GetMapping(org.springframework.web.bind.annotation.GetMapping) LinkedList(java.util.LinkedList) Config(com.erudika.para.core.utils.Config) ScooldUtils(com.erudika.scoold.utils.ScooldUtils) PostMapping(org.springframework.web.bind.annotation.PostMapping) ParaObject(com.erudika.para.core.ParaObject) PEOPLELINK(com.erudika.scoold.ScooldServer.PEOPLELINK) HttpServletResponse(javax.servlet.http.HttpServletResponse) Utils(com.erudika.para.core.utils.Utils) HttpUtils(com.erudika.scoold.utils.HttpUtils) List(java.util.List) Collections(java.util.Collections) Profile(com.erudika.scoold.core.Profile) HashMap(java.util.HashMap) Profile(com.erudika.scoold.core.Profile) LinkedList(java.util.LinkedList) Pager(com.erudika.para.core.utils.Pager) ParaObject(com.erudika.para.core.ParaObject) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 52 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam 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 53 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project dhis2-core by dhis2.

the class AbstractFullReadOnlyController method getCollectionItem.

@GetMapping("/{uid}/{property}/{itemId}")
@ResponseBody
public RootNode getCollectionItem(@PathVariable("uid") String pvUid, @PathVariable("property") String pvProperty, @PathVariable("itemId") String pvItemId, @RequestParam Map<String, String> parameters, TranslateParams translateParams, HttpServletResponse response, @CurrentUser User currentUser) throws Exception {
    setUserContext(currentUser, translateParams);
    try {
        if (!aclService.canRead(currentUser, getEntityClass())) {
            throw new ReadAccessDeniedException("You don't have the proper permissions to read objects of this type.");
        }
        RootNode rootNode = getObjectInternal(pvUid, parameters, Lists.newArrayList(), Lists.newArrayList(pvProperty + "[:all]"), currentUser);
        // TODO optimize this using field filter (collection filtering)
        if (!rootNode.getChildren().isEmpty() && rootNode.getChildren().get(0).isCollection()) {
            rootNode.getChildren().get(0).getChildren().stream().filter(Node::isComplex).forEach(node -> {
                node.getChildren().stream().filter(child -> child.isSimple() && child.getName().equals("id") && !((SimpleNode) child).getValue().equals(pvItemId)).forEach(child -> rootNode.getChildren().get(0).removeChild(node));
            });
        }
        if (rootNode.getChildren().isEmpty() || rootNode.getChildren().get(0).getChildren().isEmpty()) {
            throw new WebMessageException(notFound(pvProperty + " with ID " + pvItemId + " could not be found."));
        }
        cachePrivate(response);
        return rootNode;
    } finally {
        UserContext.reset();
    }
}
Also used : 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) RootNode(org.hisp.dhis.node.types.RootNode) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) GetMapping(org.springframework.web.bind.annotation.GetMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 54 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project dhis2-core by dhis2.

the class EnrollmentController method postEnrollmentXml.

@PostMapping(value = "", consumes = APPLICATION_XML_VALUE, produces = APPLICATION_XML_VALUE)
@ResponseBody
public WebMessage postEnrollmentXml(@RequestParam(defaultValue = "CREATE_AND_UPDATE") ImportStrategy strategy, ImportOptions importOptions, HttpServletRequest request) throws IOException {
    importOptions.setStrategy(strategy);
    InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat(request.getInputStream());
    if (!importOptions.isAsync()) {
        ImportSummaries importSummaries = enrollmentService.addEnrollmentsXml(inputStream, importOptions);
        importSummaries.setImportOptions(importOptions);
        importSummaries.getImportSummaries().stream().filter(importSummary -> !importOptions.isDryRun() && !importSummary.getStatus().equals(ImportStatus.ERROR) && !importOptions.getImportStrategy().isDelete() && (!importOptions.getImportStrategy().isSync() || importSummary.getImportCount().getDeleted() == 0)).forEach(importSummary -> importSummary.setHref(ContextUtils.getRootPath(request) + RESOURCE_PATH + "/" + importSummary.getReference()));
        if (importSummaries.getImportSummaries().size() == 1) {
            ImportSummary importSummary = importSummaries.getImportSummaries().get(0);
            importSummary.setImportOptions(importOptions);
            if (!importSummary.getStatus().equals(ImportStatus.ERROR)) {
                importSummaries(importSummaries).setHttpStatus(HttpStatus.CREATED).setLocation("/api/" + "enrollments" + "/" + importSummary.getReference());
            }
        }
        return importSummaries(importSummaries).setHttpStatus(HttpStatus.CREATED);
    }
    return startAsyncImport(importOptions, enrollmentService.getEnrollmentsXml(inputStream));
}
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) Autowired(org.springframework.beans.factory.annotation.Autowired) NodeUtils(org.hisp.dhis.node.NodeUtils) Model(org.springframework.ui.Model) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) PutMapping(org.springframework.web.bind.annotation.PutMapping) Map(java.util.Map) PagerUtils(org.hisp.dhis.common.PagerUtils) JobConfiguration(org.hisp.dhis.scheduling.JobConfiguration) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) EnrollmentService(org.hisp.dhis.dxf2.events.enrollment.EnrollmentService) PostMapping(org.springframework.web.bind.annotation.PostMapping) ImportEnrollmentsTask(org.hisp.dhis.dxf2.events.enrollment.ImportEnrollmentsTask) ProgramInstanceQueryParams(org.hisp.dhis.program.ProgramInstanceQueryParams) ContextService(org.hisp.dhis.webapi.service.ContextService) FieldFilterService(org.hisp.dhis.fieldfilter.FieldFilterService) Set(java.util.Set) Collectors(java.util.stream.Collectors) Enrollments(org.hisp.dhis.dxf2.events.enrollment.Enrollments) EnrollmentCriteria(org.hisp.dhis.webapi.controller.event.webrequest.EnrollmentCriteria) List(java.util.List) FieldFilterParams(org.hisp.dhis.fieldfilter.FieldFilterParams) ProgramInstanceService(org.hisp.dhis.program.ProgramInstanceService) AsyncTaskExecutor(org.hisp.dhis.common.AsyncTaskExecutor) Enrollment(org.hisp.dhis.dxf2.events.enrollment.Enrollment) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RootNode(org.hisp.dhis.node.types.RootNode) DhisApiVersion(org.hisp.dhis.common.DhisApiVersion) WebMessageUtils.notFound(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ENROLLMENT_IMPORT(org.hisp.dhis.scheduling.JobType.ENROLLMENT_IMPORT) 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) SlimPager(org.hisp.dhis.common.SlimPager) WebMessageUtils.importSummaries(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.importSummaries) EnrollmentCriteriaMapper(org.hisp.dhis.webapi.controller.event.mapper.EnrollmentCriteriaMapper) WebMessageUtils.importSummary(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.importSummary) GetMapping(org.springframework.web.bind.annotation.GetMapping) WebMessageUtils.jobConfigurationReport(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.jobConfigurationReport) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ImportStatus(org.hisp.dhis.dxf2.importsummary.ImportStatus) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) NotFoundException(org.hisp.dhis.webapi.controller.exception.NotFoundException) IOException(java.io.IOException) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) ImportOptions(org.hisp.dhis.dxf2.common.ImportOptions) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries) HttpStatus(org.springframework.http.HttpStatus) CurrentUserService(org.hisp.dhis.user.CurrentUserService) InputStream(java.io.InputStream) TextUtils(org.hisp.dhis.commons.util.TextUtils) InputStream(java.io.InputStream) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 55 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam 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)

Aggregations

RequestParam (org.springframework.web.bind.annotation.RequestParam)62 List (java.util.List)46 PathVariable (org.springframework.web.bind.annotation.PathVariable)42 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)42 Collectors (java.util.stream.Collectors)37 HttpServletRequest (javax.servlet.http.HttpServletRequest)34 HttpServletResponse (javax.servlet.http.HttpServletResponse)34 IOException (java.io.IOException)32 Autowired (org.springframework.beans.factory.annotation.Autowired)32 Map (java.util.Map)28 Controller (org.springframework.stereotype.Controller)28 GetMapping (org.springframework.web.bind.annotation.GetMapping)27 HttpStatus (org.springframework.http.HttpStatus)25 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)25 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)23 MediaType (org.springframework.http.MediaType)22 Model (org.springframework.ui.Model)20 StringUtils (org.apache.commons.lang3.StringUtils)19 Set (java.util.Set)18 Logger (org.slf4j.Logger)18