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() : "");
}
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();
}
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();
}
}
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));
}
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."));
}
}
Aggregations