use of org.springframework.web.bind.annotation.RequestBody in project dhis2-core by dhis2.
the class SystemSettingController method setSystemSettingV29.
@PostMapping(consumes = ContextUtils.CONTENT_TYPE_JSON)
@PreAuthorize("hasRole('ALL') or hasRole('F_SYSTEM_SETTING')")
@ResponseBody
public WebMessage setSystemSettingV29(@RequestBody Map<String, Object> settings) {
List<String> invalidKeys = settings.keySet().stream().filter((key) -> !SettingKey.getByName(key).isPresent()).collect(Collectors.toList());
if (!invalidKeys.isEmpty()) {
return conflict("Key(s) is not supported: " + StringUtils.join(invalidKeys, ", "));
}
for (Entry<String, Object> entry : settings.entrySet()) {
String key = entry.getKey();
Serializable valueObject = SettingKey.getAsRealClass(key, entry.getValue().toString());
systemSettingManager.saveSystemSetting(SettingKey.getByName(key).get(), valueObject);
}
return ok("System settings imported");
}
use of org.springframework.web.bind.annotation.RequestBody in project dhis2-core by dhis2.
the class DataValueController method setDataValuesFollowUp.
@PutMapping(value = "/followups")
@ResponseStatus(value = HttpStatus.OK)
public void setDataValuesFollowUp(@RequestBody DataValuesFollowUpRequest request) {
List<DataValueFollowUpRequest> values = request == null ? null : request.getValues();
if (values == null || values.isEmpty() || values.stream().anyMatch(e -> e.getFollowup() == null)) {
throw new IllegalQueryException(ErrorCode.E2033);
}
List<DataValue> dataValues = new ArrayList<>();
for (DataValueFollowUpRequest e : values) {
DataValue dataValue = dataValueValidation.getAndValidateDataValue(e);
dataValue.setFollowup(e.getFollowup());
}
dataValueService.updateDataValues(dataValues);
}
use of org.springframework.web.bind.annotation.RequestBody in project vorto by eclipse.
the class NamespaceController method requestAccessToNamespace.
@PostMapping("/requestAccess")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<OperationResult> requestAccessToNamespace(@RequestBody @ApiParam(value = "The request body specifying who initiates the request, the namespace, whom the request is intended for, and an optional collection of suggested roles", required = true) NamespaceAccessRequestDTO request) {
Optional<OperationResult> validationError = NamespaceValidator.validateAccessRequest(request);
if (validationError.isPresent()) {
return new ResponseEntity<>(validationError.get(), HttpStatus.BAD_REQUEST);
}
// checks namespace exists
// should only occur if namespace was deleted after user search, but before sending request
Namespace target;
try {
target = namespaceService.getByName(request.getNamespaceName());
} catch (DoesNotExistException dnee) {
return new ResponseEntity<>(OperationResult.failure("Namespace not found."), HttpStatus.NOT_FOUND);
}
// checks any admin with an e-mail address set
Set<User> adminsWithEmail = userNamespaceRoleRepository.findAllByNamespace(target).stream().map(UserNamespaceRoles::getUser).filter(u -> !Strings.nullToEmpty(u.getEmailAddress()).trim().isEmpty()).collect(Collectors.toSet());
if (adminsWithEmail.isEmpty()) {
return new ResponseEntity<>(OperationResult.failure(String.format("None of the users administrating namespace %s has set their own e-mail. Please contact them directly. ", request.getNamespaceName())), HttpStatus.PRECONDITION_FAILED);
}
int successCount = adminsWithEmail.size();
// attempts to send the e-mails
// ugly exception handling here, due to the way this was designed in the service
Collection<IMessage> messages = adminsWithEmail.stream().map(u -> new RequestAccessToNamespaceMessage(request, u, host)).collect(Collectors.toList());
for (IMessage message : messages) {
try {
emailNotificationService.sendNotification(message);
} catch (NotificationProblem np) {
successCount--;
}
}
// worked for all recipients
if (successCount == adminsWithEmail.size()) {
return new ResponseEntity<>(OperationResult.success(), HttpStatus.OK);
} else // worked for some recipients
if (successCount > 0) {
return new ResponseEntity<>(OperationResult.success("The message could not be sent to all administrators."), HttpStatus.OK);
} else // did not work for any recipient
{
return new ResponseEntity<>(OperationResult.failure("The message could not be sent to any administrator."), HttpStatus.SERVICE_UNAVAILABLE);
}
}
use of org.springframework.web.bind.annotation.RequestBody in project data-prep by Talend.
the class DataSetService method updateDataSet.
/**
* Updates a data set metadata. If no data set exists for given id, a {@link TDPException} is thrown.
*
* @param dataSetId The id of data set to be updated.
* @param dataSetMetadata The new content for the data set. If empty, existing content will <b>not</b> be replaced.
* For delete operation, look at {@link #delete(String)}.
*/
@RequestMapping(value = "/datasets/{id}", method = PUT)
@ApiOperation(value = "Update a data set metadata by id", notes = "Update a data set metadata according to the content of the PUT body. Id should be a UUID returned by the list operation. Not valid or non existing data set id return an error response.")
@Timed
public void updateDataSet(@PathVariable(value = "id") @ApiParam(name = "id", value = "Id of the data set to update") String dataSetId, @RequestBody DataSetMetadata dataSetMetadata) {
if (dataSetMetadata != null && dataSetMetadata.getName() != null) {
checkDataSetName(dataSetMetadata.getName());
}
final DistributedLock lock = dataSetMetadataRepository.createDatasetMetadataLock(dataSetId);
lock.lock();
try {
DataSetMetadata metadataForUpdate = dataSetMetadataRepository.get(dataSetId);
if (metadataForUpdate == null) {
// No need to silently create the data set metadata: associated content will most likely not exist.
throw new TDPException(DataSetErrorCodes.DATASET_DOES_NOT_EXIST, build().put("id", dataSetId));
}
LOG.debug("updateDataSet: {}", dataSetMetadata);
//
// Only part of the metadata can be updated, so the original dataset metadata is loaded and updated
//
DataSetMetadata original = metadataBuilder.metadata().copy(metadataForUpdate).build();
try {
// update the name
metadataForUpdate.setName(dataSetMetadata.getName());
// update the sheet content (in case of a multi-sheet excel file)
if (metadataForUpdate.getSchemaParserResult() != null) {
Optional<Schema.SheetContent> sheetContentFound = metadataForUpdate.getSchemaParserResult().getSheetContents().stream().filter(sheetContent -> dataSetMetadata.getSheetName().equals(//
sheetContent.getName())).findFirst();
if (sheetContentFound.isPresent()) {
List<ColumnMetadata> columnMetadatas = sheetContentFound.get().getColumnMetadatas();
if (metadataForUpdate.getRowMetadata() == null) {
metadataForUpdate.setRowMetadata(new RowMetadata(emptyList()));
}
metadataForUpdate.getRowMetadata().setColumns(columnMetadatas);
}
metadataForUpdate.setSheetName(dataSetMetadata.getSheetName());
metadataForUpdate.setSchemaParserResult(null);
}
// Location updates
if (dataSetMetadata.getLocation() != null) {
metadataForUpdate.setLocation(dataSetMetadata.getLocation());
}
// update parameters & encoding (so that user can change import parameters for CSV)
metadataForUpdate.getContent().setParameters(dataSetMetadata.getContent().getParameters());
metadataForUpdate.setEncoding(dataSetMetadata.getEncoding());
// update limit
final Optional<Long> newLimit = dataSetMetadata.getContent().getLimit();
newLimit.ifPresent(limit -> metadataForUpdate.getContent().setLimit(limit));
// Validate that the new data set metadata and removes the draft status
final String formatFamilyId = dataSetMetadata.getContent().getFormatFamilyId();
if (formatFamilyFactory.hasFormatFamily(formatFamilyId)) {
FormatFamily format = formatFamilyFactory.getFormatFamily(formatFamilyId);
try {
DraftValidator draftValidator = format.getDraftValidator();
DraftValidator.Result result = draftValidator.validate(dataSetMetadata);
if (result.isDraft()) {
// This is not an exception case: data set may remain a draft after update (although rather
// unusual)
LOG.warn("Data set #{} is still a draft after update.", dataSetId);
return;
}
// Data set metadata to update is no longer a draft
metadataForUpdate.setDraft(false);
} catch (UnsupportedOperationException e) {
// no need to validate draft here
}
}
// update schema
formatAnalyzer.update(original, metadataForUpdate);
// save the result
metadataForUpdate.getLifecycle().setInProgress(true);
metadataForUpdate.getContent().setNbRecords(0);
dataSetMetadataRepository.save(metadataForUpdate);
// Asks for a in depth schema analysis (for column type information).
analyzeDataSet(dataSetId, singletonList(FormatAnalysis.class));
} catch (TDPException e) {
throw e;
} catch (Exception e) {
throw new TDPException(UNABLE_TO_CREATE_OR_UPDATE_DATASET, e);
}
} finally {
lock.unlock();
}
publisher.publishEvent(new DatasetUpdatedEvent(dataSetMetadata));
}
Aggregations