Search in sources :

Example 6 with RequestBody

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();
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) Lists(org.elasticsearch.common.collect.Lists) Arrays(java.util.Arrays) ApplicationEnvironmentService(alien4cloud.application.ApplicationEnvironmentService) Subject(alien4cloud.security.Subject) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) LocationService(alien4cloud.orchestrators.locations.services.LocationService) ResourcePermissionService(alien4cloud.authorization.ResourcePermissionService) ApplicationEnvironmentAuthorizationDTO(alien4cloud.rest.orchestrator.model.ApplicationEnvironmentAuthorizationDTO) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ArrayUtils(org.apache.commons.lang3.ArrayUtils) LocationSecurityService(alien4cloud.orchestrators.locations.services.LocationSecurityService) AlienUtils.safe(alien4cloud.utils.AlienUtils.safe) Location(alien4cloud.model.orchestrators.locations.Location) RequestBody(org.springframework.web.bind.annotation.RequestBody) ApiOperation(io.swagger.annotations.ApiOperation) Audit(alien4cloud.audit.annotation.Audit) RestResponseBuilder(alien4cloud.rest.model.RestResponseBuilder) RestResponse(alien4cloud.rest.model.RestResponse) Application(alien4cloud.model.application.Application) ILocationResourceService(alien4cloud.orchestrators.locations.services.ILocationResourceService) MapUtils(org.apache.commons.collections4.MapUtils) ApplicationEnvironment(alien4cloud.model.application.ApplicationEnvironment) MediaType(org.springframework.http.MediaType) Resource(javax.annotation.Resource) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Set(java.util.Set) IGenericSearchDAO(alien4cloud.dao.IGenericSearchDAO) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) List(java.util.List) GroupDTO(alien4cloud.rest.orchestrator.model.GroupDTO) UserDTO(alien4cloud.rest.orchestrator.model.UserDTO) AbstractLocationResourceTemplate(alien4cloud.model.orchestrators.locations.AbstractLocationResourceTemplate) ApplicationEnvironmentAuthorizationUpdateRequest(alien4cloud.rest.orchestrator.model.ApplicationEnvironmentAuthorizationUpdateRequest) GroupDTO(alien4cloud.rest.orchestrator.model.GroupDTO) AbstractLocationResourceTemplate(alien4cloud.model.orchestrators.locations.AbstractLocationResourceTemplate) List(java.util.List) Location(alien4cloud.model.orchestrators.locations.Location) Audit(alien4cloud.audit.annotation.Audit) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 7 with RequestBody

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;
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) AnalysisHelper(com.odysseusinc.arachne.portal.util.AnalysisHelper) ResultFile(com.odysseusinc.arachne.portal.model.ResultFile) LoggerFactory(org.slf4j.LoggerFactory) StringUtils(org.apache.commons.lang3.StringUtils) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) PutMapping(org.springframework.web.bind.annotation.PutMapping) Analysis(com.odysseusinc.arachne.portal.model.Analysis) ResultFileSearch(com.odysseusinc.arachne.portal.model.search.ResultFileSearch) SubmissionFile(com.odysseusinc.arachne.portal.model.SubmissionFile) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) Path(java.nio.file.Path) SubmissionStatusHistoryElement(com.odysseusinc.arachne.portal.model.SubmissionStatusHistoryElement) ToPdfConverter(com.odysseusinc.arachne.portal.service.ToPdfConverter) BaseSubmissionService(com.odysseusinc.arachne.portal.service.submission.BaseSubmissionService) PostMapping(org.springframework.web.bind.annotation.PostMapping) BaseAnalysisService(com.odysseusinc.arachne.portal.service.analysis.BaseAnalysisService) ContentStorageService(com.odysseusinc.arachne.storage.service.ContentStorageService) ResultFileDTO(com.odysseusinc.arachne.portal.api.v1.dto.ResultFileDTO) HttpUtils(com.odysseusinc.arachne.portal.util.HttpUtils) MediaType(org.springframework.http.MediaType) ArachneFileMeta(com.odysseusinc.arachne.storage.model.ArachneFileMeta) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) IUser(com.odysseusinc.arachne.portal.model.IUser) FileDTO(com.odysseusinc.arachne.portal.api.v1.dto.FileDTO) IOUtils(org.apache.commons.io.IOUtils) Principal(java.security.Principal) BaseSubmissionDTO(com.odysseusinc.arachne.portal.api.v1.dto.BaseSubmissionDTO) SubmissionStatus(com.odysseusinc.arachne.portal.model.SubmissionStatus) FilenameUtils(org.apache.commons.io.FilenameUtils) java.util(java.util) FileDtoContentHandler(com.odysseusinc.arachne.portal.api.v1.dto.converters.FileDtoContentHandler) ZipInputStream(java.util.zip.ZipInputStream) StringUtils.getFilename(org.springframework.util.StringUtils.getFilename) ArrayUtils(org.apache.commons.lang3.ArrayUtils) Submission(com.odysseusinc.arachne.portal.model.Submission) ValidationException(com.odysseusinc.arachne.portal.exception.ValidationException) JsonResult(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult) RequestBody(org.springframework.web.bind.annotation.RequestBody) NoExecutableFileException(com.odysseusinc.arachne.portal.exception.NoExecutableFileException) ApproveDTO(com.odysseusinc.arachne.portal.api.v1.dto.ApproveDTO) ZipUtil(com.odysseusinc.arachne.portal.util.ZipUtil) Files(com.google.common.io.Files) ObjectUtils(org.apache.commons.lang3.ObjectUtils) SubmissionStatusHistoryElementDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionStatusHistoryElementDTO) NO_ERROR(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult.ErrorCode.NO_ERROR) GetMapping(org.springframework.web.bind.annotation.GetMapping) UploadFileDTO(com.odysseusinc.arachne.portal.api.v1.dto.UploadFileDTO) BaseController(com.odysseusinc.arachne.portal.api.v1.controller.BaseController) Validated(org.springframework.validation.annotation.Validated) Logger(org.slf4j.Logger) HttpServletResponse(javax.servlet.http.HttpServletResponse) FileUtils(org.apache.commons.io.FileUtils) IOException(java.io.IOException) CommonAnalysisExecutionStatusDTO(com.odysseusinc.arachne.commons.api.v1.dto.CommonAnalysisExecutionStatusDTO) CreateSubmissionsDTO(com.odysseusinc.arachne.portal.api.v1.dto.CreateSubmissionsDTO) SubmissionFileDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionFileDTO) File(java.io.File) PermissionDeniedException(com.odysseusinc.arachne.portal.exception.PermissionDeniedException) ContentStorageHelper(com.odysseusinc.arachne.portal.util.ContentStorageHelper) HttpStatus(org.springframework.http.HttpStatus) NotExistException(com.odysseusinc.arachne.portal.exception.NotExistException) MultipartFile(org.springframework.web.multipart.MultipartFile) SubmissionDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionDTO) BaseSubmissionAndAnalysisTypeDTO(com.odysseusinc.arachne.portal.api.v1.dto.BaseSubmissionAndAnalysisTypeDTO) SubmissionInsightService(com.odysseusinc.arachne.portal.service.submission.SubmissionInsightService) Submission(com.odysseusinc.arachne.portal.model.Submission) Analysis(com.odysseusinc.arachne.portal.model.Analysis) IUser(com.odysseusinc.arachne.portal.model.IUser) PermissionDeniedException(com.odysseusinc.arachne.portal.exception.PermissionDeniedException) ResultFileDTO(com.odysseusinc.arachne.portal.api.v1.dto.ResultFileDTO) FileDTO(com.odysseusinc.arachne.portal.api.v1.dto.FileDTO) BaseSubmissionDTO(com.odysseusinc.arachne.portal.api.v1.dto.BaseSubmissionDTO) ApproveDTO(com.odysseusinc.arachne.portal.api.v1.dto.ApproveDTO) SubmissionStatusHistoryElementDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionStatusHistoryElementDTO) UploadFileDTO(com.odysseusinc.arachne.portal.api.v1.dto.UploadFileDTO) CommonAnalysisExecutionStatusDTO(com.odysseusinc.arachne.commons.api.v1.dto.CommonAnalysisExecutionStatusDTO) CreateSubmissionsDTO(com.odysseusinc.arachne.portal.api.v1.dto.CreateSubmissionsDTO) SubmissionFileDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionFileDTO) SubmissionDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionDTO) BaseSubmissionAndAnalysisTypeDTO(com.odysseusinc.arachne.portal.api.v1.dto.BaseSubmissionAndAnalysisTypeDTO) PostMapping(org.springframework.web.bind.annotation.PostMapping) ApiOperation(io.swagger.annotations.ApiOperation)

Example 8 with RequestBody

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());
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) PreparationListItemDTO(org.talend.dataprep.api.preparation.PreparationListItemDTO) RequestParam(org.springframework.web.bind.annotation.RequestParam) PUT(org.springframework.web.bind.annotation.RequestMethod.PUT) Autowired(org.springframework.beans.factory.annotation.Autowired) ApiParam(io.swagger.annotations.ApiParam) CommandHelper.toStream(org.talend.dataprep.command.CommandHelper.toStream) StringUtils(org.apache.commons.lang3.StringUtils) TEXT_PLAIN_VALUE(org.springframework.http.MediaType.TEXT_PLAIN_VALUE) Collections.singletonList(java.util.Collections.singletonList) PreparationDelete(org.talend.dataprep.api.service.command.preparation.PreparationDelete) PreparationLock(org.talend.dataprep.api.service.command.preparation.PreparationLock) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) AppendStep(org.talend.dataprep.api.preparation.AppendStep) PreviewDiff(org.talend.dataprep.api.service.command.preparation.PreviewDiff) DataprepBundle.message(org.talend.dataprep.i18n.DataprepBundle.message) DataSetMetadata(org.talend.dataprep.api.dataset.DataSetMetadata) PreparationDeleteAction(org.talend.dataprep.api.service.command.preparation.PreparationDeleteAction) PreparationSummaryGet(org.talend.dataprep.command.preparation.PreparationSummaryGet) INVALID_HEAD_STEP_USING_DELETED_DATASET(org.talend.dataprep.exception.error.APIErrorCodes.INVALID_HEAD_STEP_USING_DELETED_DATASET) CachePreparationEviction(org.talend.dataprep.api.service.command.preparation.CachePreparationEviction) PreparationDetailsGet(org.talend.dataprep.command.preparation.PreparationDetailsGet) ExportParameters(org.talend.dataprep.api.export.ExportParameters) PreparationUpdate(org.talend.dataprep.command.preparation.PreparationUpdate) Order(org.talend.dataprep.util.SortAndOrderHelper.Order) PublicAPI(org.talend.dataprep.security.PublicAPI) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) DiffMetadata(org.talend.dataprep.api.service.command.preparation.DiffMetadata) PreviewDiffParameters(org.talend.dataprep.api.service.api.PreviewDiffParameters) FindStep(org.talend.dataprep.api.service.command.preparation.FindStep) RestController(org.springframework.web.bind.annotation.RestController) PREPARATION_STEP_DOES_NOT_EXIST(org.talend.dataprep.exception.error.PreparationErrorCodes.PREPARATION_STEP_DOES_NOT_EXIST) APIErrorCodes(org.talend.dataprep.exception.error.APIErrorCodes) List(java.util.List) PreviewAdd(org.talend.dataprep.api.service.command.preparation.PreviewAdd) HystrixCommand(com.netflix.hystrix.HystrixCommand) Stream(java.util.stream.Stream) PreparationGetMetadata(org.talend.dataprep.api.service.command.preparation.PreparationGetMetadata) PreparationGetContent(org.talend.dataprep.api.service.command.preparation.PreparationGetContent) PreparationList(org.talend.dataprep.api.service.command.preparation.PreparationList) PreparationMoveHead(org.talend.dataprep.api.service.command.preparation.PreparationMoveHead) GenericCommand(org.talend.dataprep.command.GenericCommand) TDPException(org.talend.dataprep.exception.TDPException) InjectorUtil(org.talend.dataprep.util.InjectorUtil) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) GET(org.springframework.web.bind.annotation.RequestMethod.GET) DatasetClient(org.talend.dataprep.dataset.adapter.DatasetClient) ArrayList(java.util.ArrayList) RequestBody(org.springframework.web.bind.annotation.RequestBody) PreviewUpdateParameters(org.talend.dataprep.api.service.api.PreviewUpdateParameters) POST(org.springframework.web.bind.annotation.RequestMethod.POST) Action(org.talend.dataprep.api.preparation.Action) PreviewAddParameters(org.talend.dataprep.api.service.api.PreviewAddParameters) PreparationCreate(org.talend.dataprep.api.service.command.preparation.PreparationCreate) Preparation(org.talend.dataprep.api.preparation.Preparation) PreparationUnlock(org.talend.dataprep.api.service.command.preparation.PreparationUnlock) PreparationDetailsDTO(org.talend.dataprep.api.preparation.PreparationDetailsDTO) DELETE(org.springframework.web.bind.annotation.RequestMethod.DELETE) PreviewUpdate(org.talend.dataprep.api.service.command.preparation.PreviewUpdate) ActionRegistry(org.talend.dataprep.transformation.pipeline.ActionRegistry) GetPreparationColumnTypes(org.talend.dataprep.api.service.command.transformation.GetPreparationColumnTypes) HttpResponseContext(org.talend.dataprep.http.HttpResponseContext) PreparationCopyStepsFrom(org.talend.dataprep.api.service.command.preparation.PreparationCopyStepsFrom) Sort(org.talend.dataprep.util.SortAndOrderHelper.Sort) PreparationCopy(org.talend.dataprep.api.service.command.preparation.PreparationCopy) Step(org.talend.dataprep.api.preparation.Step) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) PreparationAddAction(org.talend.dataprep.api.PreparationAddAction) PreparationDTO(org.talend.dataprep.api.preparation.PreparationDTO) PreparationReorderStep(org.talend.dataprep.api.service.command.preparation.PreparationReorderStep) PreparationMove(org.talend.dataprep.api.service.command.preparation.PreparationMove) Collectors.toList(java.util.stream.Collectors.toList) Lookup(org.talend.dataprep.transformation.actions.datablending.Lookup) PreparationGetActions(org.talend.dataprep.command.preparation.PreparationGetActions) ResponseEntity(org.springframework.http.ResponseEntity) CommandHelper(org.talend.dataprep.command.CommandHelper) PreparationUpdateAction(org.talend.dataprep.api.service.command.preparation.PreparationUpdateAction) Timed(org.talend.dataprep.metrics.Timed) InputStream(java.io.InputStream) PreparationAddAction(org.talend.dataprep.api.PreparationAddAction) AppendStep(org.talend.dataprep.api.preparation.AppendStep) Timed(org.talend.dataprep.metrics.Timed) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 9 with RequestBody

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);
}
Also used : ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) HttpHeaders(org.springframework.http.HttpHeaders) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ArrayList(java.util.ArrayList) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) MultipartFile(org.springframework.web.multipart.MultipartFile) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) DataType(com.revolsys.datatype.DataType) MediaType(org.springframework.http.MediaType) RequestBody(org.springframework.web.bind.annotation.RequestBody) HttpInputMessage(org.springframework.http.HttpInputMessage) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) IOException(java.io.IOException) WrappedException(com.revolsys.util.WrappedException) IOException(java.io.IOException) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) ByteArrayInputStream(java.io.ByteArrayInputStream) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest)

Example 10 with RequestBody

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();
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) Arrays(java.util.Arrays) ApplicationEnvironmentService(alien4cloud.application.ApplicationEnvironmentService) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) Subject(alien4cloud.security.Subject) LocationService(alien4cloud.orchestrators.locations.services.LocationService) ResourcePermissionService(alien4cloud.authorization.ResourcePermissionService) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ArrayUtils(org.apache.commons.lang3.ArrayUtils) LocationSecurityService(alien4cloud.orchestrators.locations.services.LocationSecurityService) Location(alien4cloud.model.orchestrators.locations.Location) RequestBody(org.springframework.web.bind.annotation.RequestBody) ApiOperation(io.swagger.annotations.ApiOperation) Audit(alien4cloud.audit.annotation.Audit) RestResponseBuilder(alien4cloud.rest.model.RestResponseBuilder) RestResponse(alien4cloud.rest.model.RestResponse) ILocationResourceService(alien4cloud.orchestrators.locations.services.ILocationResourceService) ApplicationEnvironment(alien4cloud.model.application.ApplicationEnvironment) MediaType(org.springframework.http.MediaType) Resource(javax.annotation.Resource) Set(java.util.Set) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) SubjectsAuthorizationRequest(alien4cloud.rest.orchestrator.model.SubjectsAuthorizationRequest) List(java.util.List) AbstractLocationResourceTemplate(alien4cloud.model.orchestrators.locations.AbstractLocationResourceTemplate) ApplicationEnvironmentAuthorizationUpdateRequest(alien4cloud.rest.orchestrator.model.ApplicationEnvironmentAuthorizationUpdateRequest) AbstractLocationResourceTemplate(alien4cloud.model.orchestrators.locations.AbstractLocationResourceTemplate) ApplicationEnvironment(alien4cloud.model.application.ApplicationEnvironment) Location(alien4cloud.model.orchestrators.locations.Location) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

RequestBody (org.springframework.web.bind.annotation.RequestBody)19 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)14 List (java.util.List)13 Collectors (java.util.stream.Collectors)13 PathVariable (org.springframework.web.bind.annotation.PathVariable)10 HttpStatus (org.springframework.http.HttpStatus)9 MediaType (org.springframework.http.MediaType)9 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)9 Set (java.util.Set)8 RequestParam (org.springframework.web.bind.annotation.RequestParam)8 ApiOperation (io.swagger.annotations.ApiOperation)7 Arrays (java.util.Arrays)7 Map (java.util.Map)7 ResponseEntity (org.springframework.http.ResponseEntity)7 RestController (org.springframework.web.bind.annotation.RestController)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)5 HashSet (java.util.HashSet)5 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)5 ApplicationEnvironmentService (alien4cloud.application.ApplicationEnvironmentService)4