Search in sources :

Example 11 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project nakadi by zalando.

the class EventStreamController method streamEvents.

@RequestMapping(value = "/event-types/{name}/events", method = RequestMethod.GET)
public StreamingResponseBody streamEvents(@PathVariable("name") final String eventTypeName, @Nullable @RequestParam(value = "batch_limit", required = false) final Integer batchLimit, @Nullable @RequestParam(value = "stream_limit", required = false) final Integer streamLimit, @Nullable @RequestParam(value = "batch_flush_timeout", required = false) final Integer batchTimeout, @Nullable @RequestParam(value = "stream_timeout", required = false) final Integer streamTimeout, @Nullable @RequestParam(value = "stream_keep_alive_limit", required = false) final Integer streamKeepAliveLimit, @Nullable @RequestHeader(name = "X-nakadi-cursors", required = false) final String cursorsStr, final HttpServletRequest request, final HttpServletResponse response, final Client client) {
    final String flowId = FlowIdUtils.peek();
    return outputStream -> {
        FlowIdUtils.push(flowId);
        if (blacklistService.isConsumptionBlocked(eventTypeName, client.getClientId())) {
            writeProblemResponse(response, outputStream, Problem.valueOf(Response.Status.FORBIDDEN, "Application or event type is blocked"));
            return;
        }
        final AtomicBoolean connectionReady = closedConnectionsCrutch.listenForConnectionClose(request);
        Counter consumerCounter = null;
        EventStream eventStream = null;
        List<ConnectionSlot> connectionSlots = ImmutableList.of();
        final AtomicBoolean needCheckAuthorization = new AtomicBoolean(false);
        LOG.info("[X-NAKADI-CURSORS] \"{}\" {}", eventTypeName, Optional.ofNullable(cursorsStr).orElse("-"));
        try (Closeable ignore = eventTypeChangeListener.registerListener(et -> needCheckAuthorization.set(true), Collections.singletonList(eventTypeName))) {
            final EventType eventType = eventTypeRepository.findByName(eventTypeName);
            authorizeStreamRead(eventTypeName);
            // validate parameters
            final EventStreamConfig streamConfig = EventStreamConfig.builder().withBatchLimit(batchLimit).withStreamLimit(streamLimit).withBatchTimeout(batchTimeout).withStreamTimeout(streamTimeout).withStreamKeepAliveLimit(streamKeepAliveLimit).withEtName(eventTypeName).withConsumingClient(client).withCursors(getStreamingStart(eventType, cursorsStr)).withMaxMemoryUsageBytes(maxMemoryUsageBytes).build();
            // acquire connection slots to limit the number of simultaneous connections from one client
            if (featureToggleService.isFeatureEnabled(LIMIT_CONSUMERS_NUMBER)) {
                final List<String> partitions = streamConfig.getCursors().stream().map(NakadiCursor::getPartition).collect(Collectors.toList());
                connectionSlots = consumerLimitingService.acquireConnectionSlots(client.getClientId(), eventTypeName, partitions);
            }
            consumerCounter = metricRegistry.counter(metricNameFor(eventTypeName, CONSUMERS_COUNT_METRIC_NAME));
            consumerCounter.inc();
            final String kafkaQuotaClientId = getKafkaQuotaClientId(eventTypeName, client);
            response.setStatus(HttpStatus.OK.value());
            response.setHeader("Warning", "299 - nakadi - the Low-level API is deprecated and will " + "be removed from a future release. Please consider migrating to the Subscriptions API.");
            response.setContentType("application/x-json-stream");
            final EventConsumer eventConsumer = timelineService.createEventConsumer(kafkaQuotaClientId, streamConfig.getCursors());
            final String bytesFlushedMetricName = MetricUtils.metricNameForLoLAStream(client.getClientId(), eventTypeName);
            final Meter bytesFlushedMeter = this.streamMetrics.meter(bytesFlushedMetricName);
            eventStream = eventStreamFactory.createEventStream(outputStream, eventConsumer, streamConfig, bytesFlushedMeter);
            // Flush status code to client
            outputStream.flush();
            eventStream.streamEvents(connectionReady, () -> {
                if (needCheckAuthorization.getAndSet(false)) {
                    authorizeStreamRead(eventTypeName);
                }
            });
        } catch (final UnparseableCursorException e) {
            LOG.debug("Incorrect syntax of X-nakadi-cursors header: {}. Respond with BAD_REQUEST.", e.getCursors(), e);
            writeProblemResponse(response, outputStream, BAD_REQUEST, e.getMessage());
        } catch (final NoSuchEventTypeException e) {
            writeProblemResponse(response, outputStream, NOT_FOUND, "topic not found");
        } catch (final NoConnectionSlotsException e) {
            LOG.debug("Connection creation failed due to exceeding max connection count");
            writeProblemResponse(response, outputStream, e.asProblem());
        } catch (final NakadiException e) {
            LOG.error("Error while trying to stream events.", e);
            writeProblemResponse(response, outputStream, e.asProblem());
        } catch (final InvalidCursorException e) {
            writeProblemResponse(response, outputStream, PRECONDITION_FAILED, e.getMessage());
        } catch (final AccessDeniedException e) {
            writeProblemResponse(response, outputStream, FORBIDDEN, e.explain());
        } catch (final Exception e) {
            LOG.error("Error while trying to stream events. Respond with INTERNAL_SERVER_ERROR.", e);
            writeProblemResponse(response, outputStream, INTERNAL_SERVER_ERROR, e.getMessage());
        } finally {
            connectionReady.set(false);
            consumerLimitingService.releaseConnectionSlots(connectionSlots);
            if (consumerCounter != null) {
                consumerCounter.dec();
            }
            if (eventStream != null) {
                eventStream.close();
            }
            try {
                outputStream.flush();
            } finally {
                outputStream.close();
            }
        }
    };
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) FlowIdUtils(org.zalando.nakadi.util.FlowIdUtils) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) NakadiException(org.zalando.nakadi.exceptions.NakadiException) NoSuchEventTypeException(org.zalando.nakadi.exceptions.NoSuchEventTypeException) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) Problem(org.zalando.problem.Problem) Map(java.util.Map) Counter(com.codahale.metrics.Counter) TimelineService(org.zalando.nakadi.service.timeline.TimelineService) TypeReference(com.fasterxml.jackson.core.type.TypeReference) FeatureToggleService(org.zalando.nakadi.service.FeatureToggleService) EventTypeChangeListener(org.zalando.nakadi.service.EventTypeChangeListener) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) ConsumerLimitingService(org.zalando.nakadi.service.ConsumerLimitingService) TopicRepository(org.zalando.nakadi.repository.TopicRepository) ConnectionSlot(org.zalando.nakadi.service.ConnectionSlot) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) PartitionStatistics(org.zalando.nakadi.domain.PartitionStatistics) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) InvalidCursorException(org.zalando.nakadi.exceptions.InvalidCursorException) BlacklistService(org.zalando.nakadi.service.BlacklistService) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) Timeline(org.zalando.nakadi.domain.Timeline) ServiceTemporarilyUnavailableException(org.zalando.nakadi.exceptions.runtime.ServiceTemporarilyUnavailableException) Optional(java.util.Optional) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) UnparseableCursorException(org.zalando.nakadi.exceptions.UnparseableCursorException) Client(org.zalando.nakadi.security.Client) Storage(org.zalando.nakadi.domain.Storage) ClosedConnectionsCrutch(org.zalando.nakadi.service.ClosedConnectionsCrutch) NakadiCursor(org.zalando.nakadi.domain.NakadiCursor) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cursor(org.zalando.nakadi.view.Cursor) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) Meter(com.codahale.metrics.Meter) HttpServletRequest(javax.servlet.http.HttpServletRequest) ImmutableList(com.google.common.collect.ImmutableList) EventStreamFactory(org.zalando.nakadi.service.EventStreamFactory) Qualifier(org.springframework.beans.factory.annotation.Qualifier) PRECONDITION_FAILED(javax.ws.rs.core.Response.Status.PRECONDITION_FAILED) Nullable(javax.annotation.Nullable) OutputStream(java.io.OutputStream) AccessDeniedException(org.zalando.nakadi.exceptions.runtime.AccessDeniedException) EventType(org.zalando.nakadi.domain.EventType) MetricRegistry(com.codahale.metrics.MetricRegistry) Logger(org.slf4j.Logger) INTERNAL_SERVER_ERROR(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) MetricUtils.metricNameFor(org.zalando.nakadi.metrics.MetricUtils.metricNameFor) IOException(java.io.IOException) FORBIDDEN(javax.ws.rs.core.Response.Status.FORBIDDEN) EventStream(org.zalando.nakadi.service.EventStream) AuthorizationValidator(org.zalando.nakadi.service.AuthorizationValidator) HttpStatus(org.springframework.http.HttpStatus) EventConsumer(org.zalando.nakadi.repository.EventConsumer) EventTypeRepository(org.zalando.nakadi.repository.EventTypeRepository) Closeable(java.io.Closeable) NoConnectionSlotsException(org.zalando.nakadi.exceptions.NoConnectionSlotsException) LIMIT_CONSUMERS_NUMBER(org.zalando.nakadi.service.FeatureToggleService.Feature.LIMIT_CONSUMERS_NUMBER) CursorError(org.zalando.nakadi.domain.CursorError) VisibleForTesting(com.google.common.annotations.VisibleForTesting) MetricUtils(org.zalando.nakadi.metrics.MetricUtils) EventStreamConfig(org.zalando.nakadi.service.EventStreamConfig) InternalNakadiException(org.zalando.nakadi.exceptions.InternalNakadiException) Collections(java.util.Collections) CursorConverter(org.zalando.nakadi.service.CursorConverter) AccessDeniedException(org.zalando.nakadi.exceptions.runtime.AccessDeniedException) NakadiCursor(org.zalando.nakadi.domain.NakadiCursor) EventType(org.zalando.nakadi.domain.EventType) Meter(com.codahale.metrics.Meter) Closeable(java.io.Closeable) InvalidCursorException(org.zalando.nakadi.exceptions.InvalidCursorException) UnparseableCursorException(org.zalando.nakadi.exceptions.UnparseableCursorException) NakadiException(org.zalando.nakadi.exceptions.NakadiException) NoSuchEventTypeException(org.zalando.nakadi.exceptions.NoSuchEventTypeException) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) InvalidCursorException(org.zalando.nakadi.exceptions.InvalidCursorException) ServiceTemporarilyUnavailableException(org.zalando.nakadi.exceptions.runtime.ServiceTemporarilyUnavailableException) UnparseableCursorException(org.zalando.nakadi.exceptions.UnparseableCursorException) AccessDeniedException(org.zalando.nakadi.exceptions.runtime.AccessDeniedException) IOException(java.io.IOException) NoConnectionSlotsException(org.zalando.nakadi.exceptions.NoConnectionSlotsException) InternalNakadiException(org.zalando.nakadi.exceptions.InternalNakadiException) NakadiException(org.zalando.nakadi.exceptions.NakadiException) InternalNakadiException(org.zalando.nakadi.exceptions.InternalNakadiException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EventStreamConfig(org.zalando.nakadi.service.EventStreamConfig) EventConsumer(org.zalando.nakadi.repository.EventConsumer) Counter(com.codahale.metrics.Counter) EventStream(org.zalando.nakadi.service.EventStream) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) NoConnectionSlotsException(org.zalando.nakadi.exceptions.NoConnectionSlotsException) NoSuchEventTypeException(org.zalando.nakadi.exceptions.NoSuchEventTypeException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 12 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project rpki-validator-3 by RIPE-NCC.

the class TrustAnchorController method add.

@PostMapping(path = "/upload", consumes = "multipart/form-data")
public ResponseEntity<ApiResponse<TrustAnchorResource>> add(@RequestParam("file") MultipartFile trustAnchorLocator, Locale locale) {
    try {
        TrustAnchorLocator locator = TrustAnchorLocator.fromMultipartFile(trustAnchorLocator);
        AddTrustAnchor command = AddTrustAnchor.builder().type(TrustAnchor.TYPE).name(locator.getCaName()).locations(locator.getCertificateLocations().stream().map(URI::toASCIIString).collect(Collectors.toList())).subjectPublicKeyInfo(locator.getPublicKeyInfo()).rsyncPrefetchUri(locator.getPrefetchUris().stream().filter(uri -> "rsync".equalsIgnoreCase(uri.getScheme())).map(URI::toASCIIString).findFirst().orElse(null)).build();
        long id = trustAnchorService.execute(command);
        TrustAnchor trustAnchor = trustAnchorRepository.get(id);
        Link selfRel = linkTo(methodOn(TrustAnchorController.class).get(id, locale)).withSelfRel();
        return ResponseEntity.created(URI.create(selfRel.getHref())).body(trustAnchorResource(trustAnchor, locale));
    } catch (TrustAnchorExtractorException ex) {
        return ResponseEntity.badRequest().body(ApiResponse.error(ApiError.of(HttpStatus.BAD_REQUEST, "Invalid trust anchor locator: " + ex.getMessage())));
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RpkiRepository(net.ripe.rpki.validator3.domain.RpkiRepository) StringUtils(org.apache.commons.lang.StringUtils) RequestParam(org.springframework.web.bind.annotation.RequestParam) Autowired(org.springframework.beans.factory.annotation.Autowired) Valid(javax.validation.Valid) Paging(net.ripe.rpki.validator3.api.Paging) RpkiRepositories(net.ripe.rpki.validator3.domain.RpkiRepositories) Api(net.ripe.rpki.validator3.api.Api) Locale(java.util.Locale) ValidationRunController(net.ripe.rpki.validator3.api.validationruns.ValidationRunController) TrustAnchorExtractorException(net.ripe.rpki.validator3.util.TrustAnchorExtractorException) URI(java.net.URI) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) TrustAnchorLocator(net.ripe.rpki.validator3.util.TrustAnchorLocator) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) TrustAnchor(net.ripe.rpki.validator3.domain.TrustAnchor) PostMapping(org.springframework.web.bind.annotation.PostMapping) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) Slf4j(lombok.extern.slf4j.Slf4j) ValidationRun(net.ripe.rpki.validator3.domain.ValidationRun) List(java.util.List) Stream(java.util.stream.Stream) Optional(java.util.Optional) ValidationRuns(net.ripe.rpki.validator3.domain.ValidationRuns) Links(org.springframework.hateoas.Links) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ControllerLinkBuilder.methodOn(org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn) Metadata(net.ripe.rpki.validator3.api.Metadata) ArrayList(java.util.ArrayList) Sorting(net.ripe.rpki.validator3.api.Sorting) RequestBody(org.springframework.web.bind.annotation.RequestBody) ControllerLinkBuilder.linkTo(org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo) GetMapping(org.springframework.web.bind.annotation.GetMapping) TrustAnchorValidationRun(net.ripe.rpki.validator3.domain.TrustAnchorValidationRun) MessageSource(org.springframework.context.MessageSource) ValidationCheckResource(net.ripe.rpki.validator3.api.validationruns.ValidationCheckResource) Link(org.springframework.hateoas.Link) ApiError(net.ripe.rpki.validator3.api.ApiError) TrustAnchors(net.ripe.rpki.validator3.domain.TrustAnchors) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HttpStatus(org.springframework.http.HttpStatus) ApiCommand(net.ripe.rpki.validator3.api.ApiCommand) ValidationRunResource(net.ripe.rpki.validator3.api.validationruns.ValidationRunResource) SearchTerm(net.ripe.rpki.validator3.api.SearchTerm) MultipartFile(org.springframework.web.multipart.MultipartFile) ResponseEntity(org.springframework.http.ResponseEntity) ApiResponse(net.ripe.rpki.validator3.api.ApiResponse) TrustAnchorExtractorException(net.ripe.rpki.validator3.util.TrustAnchorExtractorException) TrustAnchor(net.ripe.rpki.validator3.domain.TrustAnchor) TrustAnchorLocator(net.ripe.rpki.validator3.util.TrustAnchorLocator) URI(java.net.URI) Link(org.springframework.hateoas.Link) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 13 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project com.revolsys.open by revolsys.

the class WebMethodHandler method requestParameter.

public static WebParameterHandler requestParameter(final WebAnnotationMethodHandlerAdapter adapter, final Parameter parameter, final Annotation annotation) {
    final RequestParam requestParam = (RequestParam) annotation;
    final String name = getName(parameter, requestParam.value());
    final boolean required = requestParam.required();
    final String defaultValueString = requestParam.defaultValue();
    final Class<?> parameterClass = parameter.getType();
    final DataType dataType = DataTypes.getDataType(parameterClass);
    BiFunction<HttpServletRequest, HttpServletResponse, Object> function;
    Object defaultValue = null;
    if (List.class.equals(parameterClass)) {
        if (ValueConstants.DEFAULT_NONE.equals(defaultValueString)) {
            final ParameterizedType parameterizedType = (ParameterizedType) parameter.getParameterizedType();
            final Type[] typeParameters = parameterizedType.getActualTypeArguments();
            final Type elementType = typeParameters[0];
            if (MultipartFile.class.equals(elementType)) {
                function = (request, response) -> {
                    if (request instanceof MultipartRequest) {
                        final MultipartRequest multipartRequest = (MultipartRequest) request;
                        return multipartRequest.getFiles(name);
                    } else {
                        return Collections.emptyList();
                    }
                };
            } else {
                final DataType elementDataType = DataTypes.getDataType(elementType);
                function = (request, response) -> {
                    final List<Object> list = new ArrayList<>();
                    final String[] parameterValues = request.getParameterValues(name);
                    if (parameterValues != null) {
                        for (final String stringValue : parameterValues) {
                            final Object value = elementDataType.toObject(stringValue);
                            list.add(value);
                        }
                    }
                    return list;
                };
            }
        } else {
            throw new IllegalArgumentException("RequestParam.defaultValue not allowed for " + name);
        }
    } else if (parameterClass.isArray()) {
        if (ValueConstants.DEFAULT_NONE.equals(defaultValueString)) {
            final Class<?> elementClass = parameterClass.getComponentType();
            if (MultipartFile.class.equals(elementClass)) {
                function = (request, response) -> {
                    if (request instanceof MultipartRequest) {
                        final MultipartRequest multipartRequest = (MultipartRequest) request;
                        final List<MultipartFile> files = multipartRequest.getFiles(name);
                        return files.toArray();
                    } else {
                        return new MultipartFile[0];
                    }
                };
            } else {
                final DataType elementDataType = DataTypes.getDataType(elementClass);
                function = (request, response) -> {
                    final String[] parameterValues = request.getParameterValues(name);
                    int length;
                    if (parameterValues == null) {
                        length = 0;
                    } else {
                        length = parameterValues.length;
                    }
                    final Object array = Array.newInstance(elementClass, length);
                    for (int i = 0; i < length; i++) {
                        final String stringValue = parameterValues[i];
                        final Object value = elementDataType.toObject(stringValue);
                        Array.set(array, i, value);
                    }
                    return array;
                };
            }
        } else {
            throw new IllegalArgumentException("RequestParam.defaultValue not allowed for " + name);
        }
    } else {
        defaultValue = parseDefaultValueAttribute(dataType, defaultValueString);
        if (MultipartFile.class.equals(parameterClass)) {
            function = (request, response) -> {
                if (request instanceof MultipartRequest) {
                    final MultipartRequest multipartRequest = (MultipartRequest) request;
                    return multipartRequest.getFile(name);
                } else {
                    return null;
                }
            };
        } else {
            function = (request, response) -> {
                return request.getParameter(name);
            };
        }
    }
    return // 
    WebParameterHandler.function(// 
    name, // 
    function, // 
    dataType, // 
    required, // 
    defaultValue);
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) WrappedException(com.revolsys.util.WrappedException) RequestParam(org.springframework.web.bind.annotation.RequestParam) Array(java.lang.reflect.Array) URLDecoder(java.net.URLDecoder) BiFunction(java.util.function.BiFunction) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) Property(com.revolsys.util.Property) CookieValue(org.springframework.web.bind.annotation.CookieValue) RequestContextUtils(org.springframework.web.servlet.support.RequestContextUtils) ByteArrayInputStream(java.io.ByteArrayInputStream) Locale(java.util.Locale) Map(java.util.Map) MultipartRequest(org.springframework.web.multipart.MultipartRequest) Method(java.lang.reflect.Method) HttpSession(javax.servlet.http.HttpSession) WebUtils(org.springframework.web.util.WebUtils) ClassUtils(org.springframework.util.ClassUtils) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) StandardCharsets(java.nio.charset.StandardCharsets) Logs(com.revolsys.logging.Logs) List(java.util.List) Principal(java.security.Principal) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) HandlerMapping(org.springframework.web.servlet.HandlerMapping) Type(java.lang.reflect.Type) ServletResponse(javax.servlet.ServletResponse) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) Annotation(java.lang.annotation.Annotation) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) FileCopyUtils(org.springframework.util.FileCopyUtils) Exceptions(com.revolsys.util.Exceptions) HashMap(java.util.HashMap) HttpServletUtils(com.revolsys.ui.web.utils.HttpServletUtils) ArrayList(java.util.ArrayList) RequestBody(org.springframework.web.bind.annotation.RequestBody) HttpServletRequest(javax.servlet.http.HttpServletRequest) Charset(java.nio.charset.Charset) Parameter(java.lang.reflect.Parameter) Cookie(javax.servlet.http.Cookie) OutputStream(java.io.OutputStream) ServletRequest(javax.servlet.ServletRequest) RequestAttribute(com.revolsys.ui.web.annotation.RequestAttribute) HttpServletResponse(javax.servlet.http.HttpServletResponse) MultiValueMap(org.springframework.util.MultiValueMap) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) DataTypes(com.revolsys.datatype.DataTypes) Reader(com.revolsys.io.Reader) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) Function3(com.revolsys.util.function.Function3) HttpInputMessage(org.springframework.http.HttpInputMessage) ParameterizedType(java.lang.reflect.ParameterizedType) MultipartFile(org.springframework.web.multipart.MultipartFile) Writer(com.revolsys.io.Writer) ValueConstants(org.springframework.web.bind.annotation.ValueConstants) DataType(com.revolsys.datatype.DataType) Collections(java.util.Collections) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) InputStream(java.io.InputStream) StringUtils(org.springframework.util.StringUtils) RequestParam(org.springframework.web.bind.annotation.RequestParam) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ParameterizedType(java.lang.reflect.ParameterizedType) MediaType(org.springframework.http.MediaType) Type(java.lang.reflect.Type) ParameterizedType(java.lang.reflect.ParameterizedType) DataType(com.revolsys.datatype.DataType) MultipartFile(org.springframework.web.multipart.MultipartFile) DataType(com.revolsys.datatype.DataType) List(java.util.List) ArrayList(java.util.ArrayList) MultipartRequest(org.springframework.web.multipart.MultipartRequest)

Example 14 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project spring-framework by spring-projects.

the class RequestParamMethodArgumentResolver method contributeMethodArgument.

@Override
public void contributeMethodArgument(MethodParameter parameter, @Nullable Object value, UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {
    Class<?> paramType = parameter.getNestedParameterType();
    if (Map.class.isAssignableFrom(paramType) || MultipartFile.class == paramType || Part.class == paramType) {
        return;
    }
    RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class);
    String name = (requestParam != null && StringUtils.hasLength(requestParam.name()) ? requestParam.name() : parameter.getParameterName());
    Assert.state(name != null, "Unresolvable parameter name");
    parameter = parameter.nestedIfOptional();
    if (value instanceof Optional) {
        value = ((Optional<?>) value).orElse(null);
    }
    if (value == null) {
        if (requestParam != null && (!requestParam.required() || !requestParam.defaultValue().equals(ValueConstants.DEFAULT_NONE))) {
            return;
        }
        builder.queryParam(name);
    } else if (value instanceof Collection) {
        for (Object element : (Collection<?>) value) {
            element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element);
            builder.queryParam(name, element);
        }
    } else {
        builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(parameter), value));
    }
}
Also used : RequestParam(org.springframework.web.bind.annotation.RequestParam) Optional(java.util.Optional) TypeDescriptor(org.springframework.core.convert.TypeDescriptor) RequestPart(org.springframework.web.bind.annotation.RequestPart) Part(jakarta.servlet.http.Part) Collection(java.util.Collection)

Example 15 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project goci by EBISPOT.

the class AssociationController method addMultiSnps.

@RequestMapping(value = "/studies/{studyId}/associations/add_multi", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String addMultiSnps(@ModelAttribute("form") @Valid SnpAssociationStandardMultiForm snpAssociationStandardMultiForm, BindingResult bindingResult, @PathVariable Long studyId, Model model, @RequestParam(required = true) String measurementType, HttpServletRequest request) throws EnsemblMappingException {
    Study study = studyRepository.findOne(studyId);
    model.addAttribute("study", study);
    model.addAttribute("measurementType", measurementType);
    // Binding vs Validator issue. File: messages.properties
    if (bindingResult.hasErrors()) {
        model.addAttribute("form", snpAssociationStandardMultiForm);
        return "add_multi_snp_association";
    }
    // Check for errors in form that would prevent saving an association
    List<AssociationValidationView> rowErrors = associationOperationsService.checkSnpAssociationFormErrors(snpAssociationStandardMultiForm, measurementType);
    if (!rowErrors.isEmpty()) {
        model.addAttribute("errors", rowErrors);
        model.addAttribute("form", snpAssociationStandardMultiForm);
        model.addAttribute("criticalErrorsFound", true);
        return "add_multi_snp_association";
    } else {
        // Create an association object from details in returned form
        Association newAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationStandardMultiForm);
        // Save and validate form
        String eRelease = ensemblRestTemplateService.getRelease();
        Collection<AssociationValidationView> errors = associationOperationsService.saveAssociationCreatedFromForm(study, newAssociation, currentUserDetailsService.getUserFromRequest(request), eRelease);
        // Determine if we have any errors rather than warnings
        long errorCount = errors.stream().filter(validationError -> !validationError.getWarning()).count();
        if (errorCount > 0) {
            model.addAttribute("errors", errors);
            model.addAttribute("form", snpAssociationStandardMultiForm);
            model.addAttribute("criticalErrorsFound", true);
            return "add_multi_snp_association";
        } else {
            return "redirect:/associations/" + newAssociation.getId();
        }
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) CheckMappingService(uk.ac.ebi.spot.goci.curation.service.CheckMappingService) LoggerFactory(org.slf4j.LoggerFactory) SnpAssociationInteractionForm(uk.ac.ebi.spot.goci.curation.model.SnpAssociationInteractionForm) Autowired(org.springframework.beans.factory.annotation.Autowired) Valid(javax.validation.Valid) AssociationOperationsService(uk.ac.ebi.spot.goci.curation.service.AssociationOperationsService) PreDestroy(javax.annotation.PreDestroy) Model(org.springframework.ui.Model) Future(java.util.concurrent.Future) AssociationDeletionService(uk.ac.ebi.spot.goci.curation.service.AssociationDeletionService) uk.ac.ebi.spot.goci.model(uk.ac.ebi.spot.goci.model) StudyRepository(uk.ac.ebi.spot.goci.repository.StudyRepository) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) EnsemblRestTemplateService(uk.ac.ebi.spot.goci.service.EnsemblRestTemplateService) DateFormat(java.text.DateFormat) RedirectAttributes(org.springframework.web.servlet.mvc.support.RedirectAttributes) HttpSession(javax.servlet.http.HttpSession) MediaType(org.springframework.http.MediaType) EventsViewService(uk.ac.ebi.spot.goci.curation.service.EventsViewService) PageRequest(org.springframework.data.domain.PageRequest) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Page(org.springframework.data.domain.Page) SnpFormColumn(uk.ac.ebi.spot.goci.curation.model.SnpFormColumn) AssociationUploadErrorView(uk.ac.ebi.spot.goci.curation.model.AssociationUploadErrorView) FileNotFoundException(java.io.FileNotFoundException) Executors(java.util.concurrent.Executors) SingleSnpMultiSnpAssociationService(uk.ac.ebi.spot.goci.curation.service.SingleSnpMultiSnpAssociationService) SnpAssociationTableViewService(uk.ac.ebi.spot.goci.curation.service.SnpAssociationTableViewService) LastViewedAssociation(uk.ac.ebi.spot.goci.curation.model.LastViewedAssociation) SnpInteractionAssociationService(uk.ac.ebi.spot.goci.curation.service.SnpInteractionAssociationService) InitBinder(org.springframework.web.bind.annotation.InitBinder) CurrentUserDetailsService(uk.ac.ebi.spot.goci.curation.service.CurrentUserDetailsService) FileUploadException(uk.ac.ebi.spot.goci.curation.exception.FileUploadException) Async(org.springframework.scheduling.annotation.Async) java.util(java.util) SnpAssociationTableView(uk.ac.ebi.spot.goci.curation.model.SnpAssociationTableView) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) SimpleDateFormat(java.text.SimpleDateFormat) BindingResult(org.springframework.validation.BindingResult) Callable(java.util.concurrent.Callable) Controller(org.springframework.stereotype.Controller) SnpAssociationStandardMultiForm(uk.ac.ebi.spot.goci.curation.model.SnpAssociationStandardMultiForm) EfoTraitRepository(uk.ac.ebi.spot.goci.repository.EfoTraitRepository) AssociationService(uk.ac.ebi.spot.goci.service.AssociationService) Value(org.springframework.beans.factory.annotation.Value) AssociationValidationReportService(uk.ac.ebi.spot.goci.curation.service.AssociationValidationReportService) HttpServletRequest(javax.servlet.http.HttpServletRequest) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) Qualifier(org.springframework.beans.factory.annotation.Qualifier) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ExecutorService(java.util.concurrent.ExecutorService) DataIntegrityException(uk.ac.ebi.spot.goci.curation.exception.DataIntegrityException) Logger(org.slf4j.Logger) AssociationUploadService(uk.ac.ebi.spot.goci.curation.service.AssociationUploadService) AssociationRepository(uk.ac.ebi.spot.goci.repository.AssociationRepository) HttpServletResponse(javax.servlet.http.HttpServletResponse) SnpAssociationForm(uk.ac.ebi.spot.goci.curation.model.SnpAssociationForm) EnsemblMappingException(uk.ac.ebi.spot.goci.exception.EnsemblMappingException) SheetProcessingException(uk.ac.ebi.spot.goci.exception.SheetProcessingException) IOException(java.io.IOException) CheckEfoTermAssignmentService(uk.ac.ebi.spot.goci.curation.service.CheckEfoTermAssignmentService) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) StudyAssociationBatchDeletionEventService(uk.ac.ebi.spot.goci.curation.service.StudyAssociationBatchDeletionEventService) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) MapCatalogService(uk.ac.ebi.spot.goci.service.MapCatalogService) SnpFormRow(uk.ac.ebi.spot.goci.curation.model.SnpFormRow) WebDataBinder(org.springframework.web.bind.WebDataBinder) MultipartFile(org.springframework.web.multipart.MultipartFile) AssociationDownloadService(uk.ac.ebi.spot.goci.curation.service.AssociationDownloadService) AssociationValidationView(uk.ac.ebi.spot.goci.curation.model.AssociationValidationView) MappingDetails(uk.ac.ebi.spot.goci.curation.model.MappingDetails) LastViewedAssociation(uk.ac.ebi.spot.goci.curation.model.LastViewedAssociation) AssociationValidationView(uk.ac.ebi.spot.goci.curation.model.AssociationValidationView) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

RequestParam (org.springframework.web.bind.annotation.RequestParam)72 List (java.util.List)56 PathVariable (org.springframework.web.bind.annotation.PathVariable)52 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)49 Collectors (java.util.stream.Collectors)47 IOException (java.io.IOException)37 HttpServletRequest (javax.servlet.http.HttpServletRequest)35 HttpServletResponse (javax.servlet.http.HttpServletResponse)35 Autowired (org.springframework.beans.factory.annotation.Autowired)34 HttpStatus (org.springframework.http.HttpStatus)31 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)31 Map (java.util.Map)30 GetMapping (org.springframework.web.bind.annotation.GetMapping)30 MediaType (org.springframework.http.MediaType)28 Controller (org.springframework.stereotype.Controller)28 RestController (org.springframework.web.bind.annotation.RestController)28 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)27 Set (java.util.Set)21 RequestBody (org.springframework.web.bind.annotation.RequestBody)21 ArrayList (java.util.ArrayList)20