use of org.springframework.web.bind.annotation.RequestBody in project alien4cloud by alien4cloud.
the class AbstractLocationResourcesSecurityController method grantAccessToGroups.
/**
*****************************************************************************************************************************
*
* SECURITY ON GROUPS
*
******************************************************************************************************************************
*/
/**
* Grant access to the location resource to the groups
*
* @param locationId The location's id.
* @param groupIds The authorized groups.
* @return A {@link Void} {@link RestResponse}.
*/
@ApiOperation(value = "Grant access to the location to the groups", notes = "Only user with ADMIN role can grant access to a group.")
@RequestMapping(value = "/groups", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('ADMIN')")
@Audit
public synchronized RestResponse<List<GroupDTO>> grantAccessToGroups(@PathVariable String orchestratorId, @PathVariable String locationId, @PathVariable String resourceId, @RequestBody String[] groupIds) {
Location location = locationService.getLocation(orchestratorId, locationId);
locationSecurityService.grantAuthorizationOnLocationIfNecessary(location, Subject.GROUP, groupIds);
AbstractLocationResourceTemplate resourceTemplate = locationResourceService.getOrFail(resourceId);
resourcePermissionService.grantPermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.GROUP, groupIds);
List<GroupDTO> groups = GroupDTO.convert(resourcePermissionService.getAuthorizedGroups(resourceTemplate));
return RestResponseBuilder.<List<GroupDTO>>builder().data(groups).build();
}
use of org.springframework.web.bind.annotation.RequestBody in project ArachneCentralAPI by OHDSI.
the class BaseSubmissionController method createSubmission.
@ApiOperation("Create and send submission.")
@PostMapping("/api/v1/analysis-management/{analysisId}/submissions")
public JsonResult<List<DTO>> createSubmission(Principal principal, @RequestBody @Validated CreateSubmissionsDTO createSubmissionsDTO, @PathVariable("analysisId") Long analysisId) throws PermissionDeniedException, NotExistException, IOException, NoExecutableFileException, ValidationException {
final JsonResult<List<DTO>> result;
if (principal == null) {
throw new PermissionDeniedException();
}
IUser user = userService.getByUsername(principal.getName());
if (user == null) {
throw new PermissionDeniedException();
}
Analysis analysis = analysisService.getById(analysisId);
final List<Submission> submissions = AnalysisHelper.createSubmission(submissionService, createSubmissionsDTO.getDataSources(), user, analysis);
final List<DTO> submissionDTOs = submissions.stream().map(s -> conversionService.convert(s, getSubmissionDTOClass())).collect(Collectors.toList());
result = new JsonResult<>(NO_ERROR);
result.setResult(submissionDTOs);
return result;
}
use of org.springframework.web.bind.annotation.RequestBody in project data-prep by Talend.
the class PreparationAPI method addPreparationAction.
// TODO: this API should take a list of AppendStep.
@RequestMapping(value = "/api/preparations/{id}/actions", method = POST, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Adds an action at the end of preparation.", notes = "Does not return any value, client may expect successful operation based on HTTP status code.")
@Timed
public void addPreparationAction(@ApiParam(name = "id", value = "Preparation id.") @PathVariable(value = "id") final String preparationId, @ApiParam("Action to add at end of the preparation.") @RequestBody final AppendStep actionsContainer) {
if (LOG.isDebugEnabled()) {
LOG.debug("Adding action to preparation (pool: {} )...", getConnectionStats());
}
// This trick is to keep the API taking and unrolling ONE AppendStep until the codefreeze but this must not stay
// that way
List<AppendStep> stepsToAppend = actionsContainer.getActions().stream().map(a -> {
AppendStep s = new AppendStep();
s.setActions(singletonList(a));
return s;
}).collect(toList());
getCommand(PreparationAddAction.class, preparationId, stepsToAppend).execute();
if (LOG.isDebugEnabled()) {
LOG.debug("Added action to preparation (pool: {} )...", getConnectionStats());
}
}
use of org.springframework.web.bind.annotation.RequestBody in project com.revolsys.open by revolsys.
the class WebMethodHandler method body.
@SuppressWarnings({ "unchecked", "rawtypes" })
public static WebParameterHandler body(final WebAnnotationMethodHandlerAdapter adapter, final Parameter parameter, final Annotation annotation) {
final boolean required = ((RequestBody) annotation).required();
final String parameterName = parameter.getName();
final Class parameterClass = parameter.getType();
final DataType dataType = DataTypes.getDataType(parameterClass);
return //
WebParameterHandler.function(//
parameterName, (request, response) -> {
try {
final HttpInputMessage inputMessage = new ServletServerHttpRequest(request);
MediaType contentType = MediaTypeUtil.getContentType(request);
if (contentType == null) {
contentType = MediaType.APPLICATION_FORM_URLENCODED;
}
if (!MediaType.APPLICATION_FORM_URLENCODED.includes(contentType) && !MediaType.MULTIPART_FORM_DATA.includes(contentType)) {
contentType = MediaTypeUtil.getRequestMediaType(request, adapter.mediaTypes, adapter.mediaTypeOrder, adapter.urlPathHelper, adapter.parameterName, adapter.defaultMediaType, "");
}
final HttpHeaders headers = inputMessage.getHeaders();
if (contentType == null) {
final StringBuilder builder = new StringBuilder(ClassUtils.getShortName(parameterClass));
final String paramName = parameterName;
if (paramName != null) {
builder.append(' ');
builder.append(paramName);
}
throw new HttpMediaTypeNotSupportedException("Cannot extract @RequestBody parameter (" + builder.toString() + "): no Content-Type found");
} else {
HttpServletUtils.setContentTypeWithCharset(headers, contentType);
}
final List<MediaType> allSupportedMediaTypes = new ArrayList<>();
if (adapter.messageConverters != null) {
for (final HttpMessageConverter<?> messageConverter : adapter.messageConverters) {
allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
if (messageConverter.canRead(parameterClass, contentType)) {
return messageConverter.read(parameterClass, inputMessage);
}
}
String body = null;
if (MediaType.APPLICATION_FORM_URLENCODED.includes(contentType)) {
Charset charset = contentType.getCharSet();
if (charset == null) {
charset = StandardCharsets.UTF_8;
}
final String urlBody = FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));
final String[] pairs = StringUtils.tokenizeToStringArray(urlBody, "&");
final MultiValueMap<String, String> values = new LinkedMultiValueMap<>(pairs.length);
for (final String pair : pairs) {
final int idx = pair.indexOf('=');
if (idx == -1) {
values.add(URLDecoder.decode(pair, charset.name()), null);
} else {
final String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
final String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
values.add(name, value);
}
}
body = values.getFirst("body");
} else if (request instanceof MultipartHttpServletRequest) {
final MultipartHttpServletRequest multiPartRequest = (MultipartHttpServletRequest) request;
final MultipartFile bodyFile = multiPartRequest.getFile("body");
contentType = MediaTypeUtil.getRequestMediaType(request, adapter.mediaTypes, adapter.mediaTypeOrder, adapter.urlPathHelper, adapter.parameterName, adapter.defaultMediaType, bodyFile.getOriginalFilename());
HttpServletUtils.setContentTypeWithCharset(headers, contentType);
final HttpInputMessage newInputMessage = new HttpInputMessage() {
@Override
public InputStream getBody() throws IOException {
return bodyFile.getInputStream();
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
};
for (final HttpMessageConverter<?> messageConverter : adapter.messageConverters) {
if (messageConverter.canRead(parameterClass, contentType)) {
return messageConverter.read(parameterClass, newInputMessage);
}
}
}
if (body == null) {
body = request.getParameter("body");
}
if (body != null) {
contentType = MediaTypeUtil.getRequestMediaType(request, adapter.mediaTypes, adapter.mediaTypeOrder, adapter.urlPathHelper, adapter.parameterName, adapter.defaultMediaType, "");
HttpServletUtils.setContentTypeWithCharset(headers, contentType);
byte[] bytes;
bytes = body.getBytes();
final InputStream bodyIn = new ByteArrayInputStream(bytes);
final HttpInputMessage newInputMessage = new HttpInputMessage() {
@Override
public InputStream getBody() throws IOException {
return bodyIn;
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
};
for (final HttpMessageConverter<?> messageConverter : adapter.messageConverters) {
if (messageConverter.canRead(parameterClass, contentType)) {
return messageConverter.read(parameterClass, newInputMessage);
}
}
}
}
throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes);
} catch (final Exception e) {
return Exceptions.throwUncheckedException(e);
}
}, //
dataType, //
required, //
null);
}
use of org.springframework.web.bind.annotation.RequestBody in project alien4cloud by alien4cloud.
the class AbstractLocationResourcesBatchSecurityController method updateAuthorizedEnvironmentsPerApplication.
/**
*****************************************************************************************************************************
*
* SECURITY ON APPLICATIONS
*
******************************************************************************************************************************
*/
/**
* Update applications, environments and environment types authorized to access the location resource.
*/
@ApiOperation(value = "Update applications, environments and environment type authorized to access the location resource", notes = "Only user with ADMIN role can update authorized applications/environments for the location.")
@RequestMapping(value = "/environmentsPerApplication", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('ADMIN')")
public synchronized RestResponse<Void> updateAuthorizedEnvironmentsPerApplication(@PathVariable String orchestratorId, @PathVariable String locationId, @RequestBody ApplicationEnvironmentAuthorizationUpdateRequest request) {
if (ArrayUtils.isEmpty(request.getResources())) {
return RestResponseBuilder.<Void>builder().build();
}
Location location = locationService.getLocation(orchestratorId, locationId);
locationSecurityService.grantAuthorizationOnLocationIfNecessary(request.getApplicationsToAdd(), request.getEnvironmentsToAdd(), request.getEnvironmentTypesToAdd(), location);
Arrays.stream(request.getResources()).forEach(resourceId -> {
AbstractLocationResourceTemplate resourceTemplate = locationResourceService.getOrFail(resourceId);
if (ArrayUtils.isNotEmpty(request.getApplicationsToDelete())) {
resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.APPLICATION, request.getApplicationsToDelete());
}
if (ArrayUtils.isNotEmpty(request.getEnvironmentsToDelete())) {
resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT, request.getEnvironmentsToDelete());
}
if (ArrayUtils.isNotEmpty(request.getEnvironmentTypesToDelete())) {
resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT_TYPE, request.getEnvironmentTypesToDelete());
}
Set<String> envIds = Sets.newHashSet();
if (ArrayUtils.isNotEmpty(request.getApplicationsToAdd())) {
resourcePermissionService.grantPermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.APPLICATION, request.getApplicationsToAdd());
// when an app is added, all eventual existing env authorizations are removed
for (String applicationToAddId : request.getApplicationsToAdd()) {
ApplicationEnvironment[] aes = applicationEnvironmentService.getByApplicationId(applicationToAddId);
for (ApplicationEnvironment ae : aes) {
envIds.add(ae.getId());
}
}
if (!envIds.isEmpty()) {
resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT, envIds.toArray(new String[envIds.size()]));
}
}
if (ArrayUtils.isNotEmpty(request.getEnvironmentsToAdd())) {
List<String> envToAddSet = Arrays.stream(request.getEnvironmentsToAdd()).filter(env -> !envIds.contains(env)).collect(Collectors.toList());
resourcePermissionService.grantPermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT, envToAddSet.toArray(new String[envToAddSet.size()]));
}
if (ArrayUtils.isNotEmpty(request.getEnvironmentTypesToAdd())) {
List<String> envToAddSet = Arrays.stream(request.getEnvironmentTypesToAdd()).filter(env -> !envIds.contains(env)).collect(Collectors.toList());
resourcePermissionService.grantPermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT_TYPE, envToAddSet.toArray(new String[envToAddSet.size()]));
}
});
return RestResponseBuilder.<Void>builder().build();
}
Aggregations