use of org.springframework.web.bind.annotation.RequestHeader 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.RequestHeader in project com.revolsys.open by revolsys.
the class WebMethodHandler method requestHeader.
public static WebParameterHandler requestHeader(final WebAnnotationMethodHandlerAdapter adapter, final Parameter parameter, final Annotation annotation) {
final Class<?> parameterClass = parameter.getType();
final DataType dataType = DataTypes.getDataType(parameterClass);
final RequestHeader requestHeader = (RequestHeader) annotation;
final String name = getName(parameter, requestHeader.value());
final boolean required = requestHeader.required();
final Object defaultValue = parseDefaultValueAttribute(dataType, requestHeader.defaultValue());
return //
WebParameterHandler.function(//
name, (request, response) -> {
return request.getHeader(name);
}, //
dataType, //
required, //
defaultValue);
}
use of org.springframework.web.bind.annotation.RequestHeader in project spring-framework by spring-projects.
the class RequestHeaderMethodArgumentResolver method createNamedValueInfo.
@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
RequestHeader ann = parameter.getParameterAnnotation(RequestHeader.class);
Assert.state(ann != null, "No RequestHeader annotation");
return new RequestHeaderNamedValueInfo(ann);
}
use of org.springframework.web.bind.annotation.RequestHeader in project java-chassis by ServiceComb.
the class RequestHeaderAnnotationProcessor method fillParameter.
@Override
protected void fillParameter(Object annotation, OperationGenerator operationGenerator, int paramIdx, HeaderParameter parameter) {
super.fillParameter(annotation, operationGenerator, paramIdx, parameter);
RequestHeader requestHeader = (RequestHeader) annotation;
parameter.setRequired(requestHeader.required());
}
use of org.springframework.web.bind.annotation.RequestHeader in project judge by zjnu-acm.
the class MockGenerator method generate.
private void generate(Class<?> key, RequestMappingInfo requestMappingInfo, HandlerMethod handlerMethod, String url, TestClass testClass, String lowerMethod) {
Method method = handlerMethod.getMethod();
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
out.println("/**");
out.println(" * Test of " + method.getName() + " method, of class " + key.getSimpleName() + ".");
for (Class<?> type : method.getParameterTypes()) {
testClass.addImport(type);
}
out.println(" *");
out.println(" * @see " + key.getSimpleName() + "#" + method.getName() + Arrays.stream(method.getParameterTypes()).map(Class::getSimpleName).collect(Collectors.joining(", ", "(", ")")));
out.println(" */");
testClass.addImport(Test.class);
out.println("@Test");
out.println("public void test" + f(method.getName()) + "() throws Exception {");
out.println("\tlog.info(\"" + method.getName() + "\");");
List<String> variableDeclares = new ArrayList<>(4);
Map<String, Class<?>> params = new LinkedHashMap<>(4);
String body = null;
Class<?> bodyType = null;
MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
Parameter[] parameters = method.getParameters();
List<String> files = new ArrayList<>(4);
List<String> pathVariables = new ArrayList<>(4);
List<String> headers = new ArrayList<>(4);
String locale = null;
for (MethodParameter methodParameter : methodParameters) {
Class<?> type = methodParameter.getParameterType();
String typeName = type.getSimpleName();
String name = "";
testClass.addImport(type);
boolean unknown = false;
if (methodParameter.hasParameterAnnotation(RequestParam.class)) {
RequestParam requestParam = methodParameter.getParameterAnnotation(RequestParam.class);
name = requestParam.value();
if (name.isEmpty()) {
name = requestParam.name();
}
} else if (methodParameter.hasParameterAnnotation(PathVariable.class)) {
PathVariable pathVariable = methodParameter.getParameterAnnotation(PathVariable.class);
name = pathVariable.value();
if (name.isEmpty()) {
name = pathVariable.name();
}
if (name.isEmpty()) {
name = parameters[methodParameter.getParameterIndex()].getName();
}
pathVariables.add(name);
variableDeclares.add("\t" + typeName + " " + name + " = " + getDefaultValue(type) + ";");
continue;
} else if (methodParameter.hasParameterAnnotation(RequestBody.class)) {
body = "request";
bodyType = type;
variableDeclares.add("\t" + typeName + " request = " + getDefaultValue(type) + ";");
continue;
} else if (methodParameter.hasParameterAnnotation(RequestHeader.class)) {
RequestHeader requestHeader = methodParameter.getParameterAnnotation(RequestHeader.class);
name = requestHeader.value();
if (name.isEmpty()) {
name = requestHeader.name();
}
if (name.isEmpty()) {
name = parameters[methodParameter.getParameterIndex()].getName();
}
headers.add(name);
variableDeclares.add("\t" + typeName + " " + name + " = " + getDefaultValue(type) + ";");
continue;
} else if (HttpServletResponse.class == type || HttpServletRequest.class == type) {
continue;
} else if (Locale.class == type) {
locale = "locale";
variableDeclares.add("\t" + typeName + " " + locale + " = Locale.getDefault();");
continue;
} else {
unknown = true;
}
if (name.isEmpty()) {
name = parameters[methodParameter.getParameterIndex()].getName();
}
if (unknown && type.getClassLoader() != null && type != MultipartFile.class) {
ReflectionUtils.doWithFields(type, field -> process(field.getName(), field.getType(), params, files, variableDeclares, testClass, method, lowerMethod), field -> !Modifier.isStatic(field.getModifiers()));
continue;
} else if (unknown) {
System.err.println("param " + methodParameter.getParameterIndex() + " with type " + typeName + " in " + method + " has no annotation");
}
process(name, type, params, files, variableDeclares, testClass, method, lowerMethod);
}
for (String variableDeclare : variableDeclares) {
out.println(variableDeclare);
}
testClass.addImport(MvcResult.class);
if (files.isEmpty()) {
testClass.addStaticImport("org.springframework.test.web.servlet.request.MockMvcRequestBuilders." + lowerMethod);
out.print("\tMvcResult result = mvc.perform(" + lowerMethod + "(" + url);
for (String pathVariable : pathVariables) {
out.print(", " + pathVariable);
}
out.print(")");
} else {
testClass.addStaticImport("org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload");
out.print("\tMvcResult result = mvc.perform(fileUpload(" + url);
for (String pathVariable : pathVariables) {
out.print(", " + pathVariable);
}
out.print(")");
for (String file : files) {
out.print(".file(" + file + ")");
}
}
boolean newLine = params.size() >= 2;
for (Map.Entry<String, Class<?>> entry : params.entrySet()) {
String param = entry.getKey();
Class<? extends Object> paramType = entry.getValue();
String value;
if (paramType.isPrimitive()) {
value = com.google.common.primitives.Primitives.wrap(paramType).getSimpleName() + ".toString(" + param + ")";
} else if (paramType == String.class) {
value = param;
} else {
testClass.addImport(Objects.class);
value = "Objects.toString(" + param + ", \"\")";
}
if (newLine) {
out.println();
out.print("\t\t\t");
}
out.print(".param(\"" + param + "\", " + value + ")");
}
for (String header : headers) {
out.println();
out.print("\t\t\t.header(\"" + header + "\", " + header + ")");
}
if (locale != null) {
out.println();
out.print("\t\t\t.locale(" + locale + ")");
}
switch(lowerMethod) {
case "get":
case "delete":
if (body != null) {
System.err.println("RequestBody annotation found on " + method + " with request method " + lowerMethod);
}
if (!requestMappingInfo.getConsumesCondition().isEmpty()) {
System.err.println("request consumes " + requestMappingInfo.getConsumesCondition() + " found on " + method);
}
}
if (body != null) {
out.println();
if (bodyType == String.class || bodyType == byte[].class) {
out.print("\t\t\t.content(" + body + ")");
} else {
testClass.addField(ObjectMapper.class, "objectMapper", "@Autowired");
out.print("\t\t\t.content(objectMapper.writeValueAsString(" + body + "))");
}
testClass.addImport(MediaType.class);
out.print(".contentType(MediaType.APPLICATION_JSON)");
}
testClass.addStaticImport("org.springframework.test.web.servlet.result.MockMvcResultMatchers.status");
out.println(")");
out.println("\t\t\t.andExpect(status().isOk())");
out.println("\t\t\t.andReturn();");
out.println("}");
testClass.addMethod(sw.toString());
}
Aggregations