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