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