language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/docs/http/client/bind/type/MetadataClient.java | {
"start": 178,
"end": 283
} | interface ____ {
@Get("/client/bind")
String get(Metadata metadata);
}
//end::clazz[]
| MetadataClient |
java | quarkusio__quarkus | test-framework/junit5-internal/src/main/java/io/quarkus/test/QuarkusProdModeTest.java | {
"start": 34077,
"end": 34219
} | class ____ that we need to be able to copy the BuildStep into a new deployment archive that
// is then added to the build
public static | is |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/metrics/TDigestPercentilesAggregator.java | {
"start": 893,
"end": 2276
} | class ____ extends AbstractTDigestPercentilesAggregator {
TDigestPercentilesAggregator(
String name,
ValuesSourceConfig config,
AggregationContext context,
Aggregator parent,
double[] percents,
double compression,
TDigestExecutionHint executionHint,
boolean keyed,
DocValueFormat formatter,
Map<String, Object> metadata
) throws IOException {
super(name, config, context, parent, percents, compression, executionHint, keyed, formatter, metadata);
}
@Override
public InternalAggregation buildAggregation(long owningBucketOrdinal) {
TDigestState state = getState(owningBucketOrdinal);
if (state == null) {
return buildEmptyAggregation();
} else {
return new InternalTDigestPercentiles(name, keys, state, keyed, formatter, metadata());
}
}
@Override
public double metric(String name, long bucketOrd) {
TDigestState state = getState(bucketOrd);
if (state == null) {
return Double.NaN;
} else {
return state.quantile(Double.parseDouble(name) / 100);
}
}
@Override
public InternalAggregation buildEmptyAggregation() {
return InternalTDigestPercentiles.empty(name, keys, keyed, formatter, metadata());
}
}
| TDigestPercentilesAggregator |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/txn/JtaObtainConnectionExceptionTest.java | {
"start": 1544,
"end": 1947
} | class ____ implements JdbcConnectionAccess {
@Override
public Connection obtainConnection() throws SQLException {
throw new SQLException( "No connection" );
}
@Override
public void releaseConnection(Connection connection) throws SQLException {
}
@Override
public boolean supportsAggressiveRelease() {
return false;
}
}
public static | ObtainConnectionSqlExceptionConnectionAccess |
java | spring-projects__spring-boot | module/spring-boot-webmvc/src/test/java/org/springframework/boot/webmvc/actuate/endpoint/web/ControllerEndpointHandlerMappingTests.java | {
"start": 2133,
"end": 6506
} | class ____ {
private final StaticApplicationContext context = new StaticApplicationContext();
@Test
void mappingWithNoPrefix() throws Exception {
ExposableControllerEndpoint firstEndpoint = firstEndpoint();
ExposableControllerEndpoint secondEndpoint = secondEndpoint();
ControllerEndpointHandlerMapping mapping = createMapping("", firstEndpoint, secondEndpoint);
HandlerExecutionChain firstHandler = mapping.getHandler(request("GET", "/first"));
assertThat(firstHandler).isNotNull();
assertThat(firstHandler.getHandler()).isEqualTo(handlerOf(firstEndpoint.getController(), "get"));
HandlerExecutionChain secondHandler = mapping.getHandler(request("POST", "/second"));
assertThat(secondHandler).isNotNull();
assertThat(secondHandler.getHandler()).isEqualTo(handlerOf(secondEndpoint.getController(), "save"));
HandlerExecutionChain thirdHandler = mapping.getHandler(request("GET", "/third"));
assertThat(thirdHandler).isNull();
}
@Test
void mappingWithPrefix() throws Exception {
ExposableControllerEndpoint firstEndpoint = firstEndpoint();
ExposableControllerEndpoint secondEndpoint = secondEndpoint();
ControllerEndpointHandlerMapping mapping = createMapping("actuator", firstEndpoint, secondEndpoint);
HandlerExecutionChain firstHandler = mapping.getHandler(request("GET", "/actuator/first"));
assertThat(firstHandler).isNotNull();
assertThat(firstHandler.getHandler()).isEqualTo(handlerOf(firstEndpoint.getController(), "get"));
HandlerExecutionChain secondHandler = mapping.getHandler(request("POST", "/actuator/second"));
assertThat(secondHandler).isNotNull();
assertThat(secondHandler.getHandler()).isEqualTo(handlerOf(secondEndpoint.getController(), "save"));
assertThat(mapping.getHandler(request("GET", "/first"))).isNull();
assertThat(mapping.getHandler(request("GET", "/second"))).isNull();
}
@Test
void mappingNarrowedToMethod() {
ExposableControllerEndpoint first = firstEndpoint();
ControllerEndpointHandlerMapping mapping = createMapping("actuator", first);
assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class)
.isThrownBy(() -> mapping.getHandler(request("POST", "/actuator/first")));
}
@Test
void mappingWithNoPath() throws Exception {
ExposableControllerEndpoint pathless = pathlessEndpoint();
ControllerEndpointHandlerMapping mapping = createMapping("actuator", pathless);
HandlerExecutionChain handler = mapping.getHandler(request("GET", "/actuator/pathless"));
assertThat(handler).isNotNull();
assertThat(handler.getHandler()).isEqualTo(handlerOf(pathless.getController(), "get"));
assertThat(mapping.getHandler(request("GET", "/pathless"))).isNull();
assertThat(mapping.getHandler(request("GET", "/"))).isNull();
}
private ControllerEndpointHandlerMapping createMapping(String prefix, ExposableControllerEndpoint... endpoints) {
ControllerEndpointHandlerMapping mapping = new ControllerEndpointHandlerMapping(new EndpointMapping(prefix),
Arrays.asList(endpoints), null, (endpointId, defaultAccess) -> Access.UNRESTRICTED);
mapping.setApplicationContext(this.context);
mapping.afterPropertiesSet();
return mapping;
}
private HandlerMethod handlerOf(Object source, String methodName) {
Method method = ReflectionUtils.findMethod(source.getClass(), methodName);
assertThat(method).isNotNull();
return new HandlerMethod(source, method);
}
private MockHttpServletRequest request(String method, String requestURI) {
return new MockHttpServletRequest(method, requestURI);
}
private ExposableControllerEndpoint firstEndpoint() {
return mockEndpoint(EndpointId.of("first"), new FirstTestMvcEndpoint());
}
private ExposableControllerEndpoint secondEndpoint() {
return mockEndpoint(EndpointId.of("second"), new SecondTestMvcEndpoint());
}
private ExposableControllerEndpoint pathlessEndpoint() {
return mockEndpoint(EndpointId.of("pathless"), new PathlessControllerEndpoint());
}
private ExposableControllerEndpoint mockEndpoint(EndpointId id, Object controller) {
ExposableControllerEndpoint endpoint = mock(ExposableControllerEndpoint.class);
given(endpoint.getEndpointId()).willReturn(id);
given(endpoint.getController()).willReturn(controller);
given(endpoint.getRootPath()).willReturn(id.toString());
return endpoint;
}
@ControllerEndpoint(id = "first")
static | ControllerEndpointHandlerMappingTests |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/junit/jupiter/comics/Character.java | {
"start": 779,
"end": 929
} | class ____ {
private final String name;
Character(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
| Character |
java | quarkusio__quarkus | extensions/reactive-routes/deployment/src/main/java/io/quarkus/vertx/web/deployment/ReactiveRoutesProcessor.java | {
"start": 5412,
"end": 76658
} | class ____ {
private static final Logger LOGGER = Logger.getLogger(ReactiveRoutesProcessor.class.getName());
private static final String HANDLER_SUFFIX = "_RouteHandler";
private static final String VALUE_PATH = "path";
private static final String VALUE_REGEX = "regex";
private static final String VALUE_PRODUCES = "produces";
private static final String VALUE_CONSUMES = "consumes";
private static final String VALUE_METHODS = "methods";
private static final String VALUE_ORDER = "order";
private static final String VALUE_TYPE = "type";
private static final String SLASH = "/";
private static final DotName ROLES_ALLOWED = DotName.createSimple(RolesAllowed.class.getName());
private static final DotName AUTHENTICATED = DotName.createSimple(Authenticated.class.getName());
private static final DotName DENY_ALL = DotName.createSimple(DenyAll.class.getName());
private static final DotName PERMISSIONS_ALLOWED = DotName.createSimple(PermissionsAllowed.class.getName());
private static final List<ParameterInjector> PARAM_INJECTORS = initParamInjectors();
private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("[a-zA-Z_0-9]+");
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(Feature.REACTIVE_ROUTES);
}
@BuildStep
void unremovableBeans(BuildProducer<UnremovableBeanBuildItem> unremovableBeans) {
unremovableBeans.produce(UnremovableBeanBuildItem.beanClassAnnotation(DotNames.ROUTE));
unremovableBeans.produce(UnremovableBeanBuildItem.beanClassAnnotation(DotNames.ROUTES));
unremovableBeans.produce(UnremovableBeanBuildItem.beanClassAnnotation(DotNames.ROUTE_FILTER));
}
@BuildStep
void validateBeanDeployment(
BeanArchiveIndexBuildItem beanArchive,
ValidationPhaseBuildItem validationPhase,
TransformedAnnotationsBuildItem transformedAnnotations,
BuildProducer<AnnotatedRouteHandlerBuildItem> routeHandlerBusinessMethods,
BuildProducer<AnnotatedRouteFilterBuildItem> routeFilterBusinessMethods,
BuildProducer<ValidationErrorBuildItem> errors,
VertxHttpBuildTimeConfig httpBuildTimeConfig) {
// Collect all business methods annotated with @Route and @RouteFilter
AnnotationStore annotationStore = validationPhase.getContext().get(BuildExtension.Key.ANNOTATION_STORE);
for (BeanInfo bean : validationPhase.getContext().beans().classBeans()) {
// NOTE: inherited business methods are not taken into account
ClassInfo beanClass = bean.getTarget().get().asClass();
AnnotationInstance routeBaseAnnotation = beanClass
.declaredAnnotation(DotNames.ROUTE_BASE);
for (MethodInfo method : beanClass.methods()) {
if (method.isSynthetic() || Modifier.isStatic(method.flags()) || method.name().equals("<init>")) {
continue;
}
List<AnnotationInstance> routes = new LinkedList<>();
AnnotationInstance routeAnnotation = annotationStore.getAnnotation(method,
DotNames.ROUTE);
if (routeAnnotation != null) {
validateRouteMethod(bean, method, transformedAnnotations, beanArchive.getIndex(), routeAnnotation);
routes.add(routeAnnotation);
}
if (routes.isEmpty()) {
AnnotationInstance routesAnnotation = annotationStore.getAnnotation(method,
DotNames.ROUTES);
if (routesAnnotation != null) {
for (AnnotationInstance annotation : routesAnnotation.value().asNestedArray()) {
validateRouteMethod(bean, method, transformedAnnotations, beanArchive.getIndex(), annotation);
routes.add(annotation);
}
}
}
if (!routes.isEmpty()) {
LOGGER.debugf("Found route handler business method %s declared on %s", method, bean);
HttpCompression compression = HttpCompression.UNDEFINED;
if (annotationStore.hasAnnotation(method, DotNames.COMPRESSED)) {
compression = HttpCompression.ON;
}
if (annotationStore.hasAnnotation(method, DotNames.UNCOMPRESSED)) {
if (compression == HttpCompression.ON) {
errors.produce(new ValidationErrorBuildItem(new IllegalStateException(
String.format(
"@Compressed and @Uncompressed cannot be both declared on business method %s declared on %s",
method, bean))));
} else {
compression = HttpCompression.OFF;
}
}
// Authenticate user if the proactive authentication is disabled and the route is secured with
// an RBAC annotation that requires authentication as io.quarkus.security.runtime.interceptor.SecurityConstrainer
// access the SecurityIdentity in a synchronous manner
final boolean blocking = annotationStore.hasAnnotation(method, DotNames.BLOCKING);
final boolean alwaysAuthenticateRoute;
if (!httpBuildTimeConfig.auth().proactive() && !blocking) {
final DotName returnTypeName = method.returnType().name();
// method either returns 'something' in a synchronous manner or void (in which case we can't tell)
final boolean possiblySynchronousResponse = !returnTypeName.equals(DotNames.UNI)
&& !returnTypeName.equals(DotNames.MULTI) && !returnTypeName.equals(DotNames.COMPLETION_STAGE);
final boolean hasRbacAnnotationThatRequiresAuth = annotationStore.hasAnnotation(method, ROLES_ALLOWED)
|| annotationStore.hasAnnotation(method, AUTHENTICATED)
|| annotationStore.hasAnnotation(method, PERMISSIONS_ALLOWED)
|| annotationStore.hasAnnotation(method, DENY_ALL);
alwaysAuthenticateRoute = possiblySynchronousResponse && hasRbacAnnotationThatRequiresAuth;
} else {
alwaysAuthenticateRoute = false;
}
routeHandlerBusinessMethods
.produce(new AnnotatedRouteHandlerBuildItem(bean, method, routes, routeBaseAnnotation,
blocking, compression, alwaysAuthenticateRoute));
}
//
AnnotationInstance filterAnnotation = annotationStore.getAnnotation(method,
DotNames.ROUTE_FILTER);
if (filterAnnotation != null) {
if (!routes.isEmpty()) {
errors.produce(new ValidationErrorBuildItem(new IllegalStateException(
String.format(
"@Route and @RouteFilter cannot be declared on business method %s declared on %s",
method, bean))));
} else {
validateRouteFilterMethod(bean, method);
routeFilterBusinessMethods
.produce(new AnnotatedRouteFilterBuildItem(bean, method, filterAnnotation));
LOGGER.debugf("Found route filter business method %s declared on %s", method, bean);
}
}
}
}
}
@BuildStep
@Record(value = ExecutionTime.STATIC_INIT)
public void replaceDefaultAuthFailureHandler(VertxWebRecorder recorder, Capabilities capabilities,
BuildProducer<FilterBuildItem> filterBuildItemBuildProducer) {
if (capabilities.isMissing(Capability.RESTEASY_REACTIVE)) {
// replace default auth failure handler added by vertx-http so that route failure handlers can customize response
filterBuildItemBuildProducer
.produce(new FilterBuildItem(recorder.addAuthFailureHandler(),
SecurityHandlerPriorities.AUTHENTICATION - 1));
}
}
@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
void addAdditionalRoutes(
VertxWebRecorder recorder,
List<AnnotatedRouteHandlerBuildItem> routeHandlerBusinessMethods,
List<AnnotatedRouteFilterBuildItem> routeFilterBusinessMethods,
BuildProducer<GeneratedClassBuildItem> generatedClass,
BuildProducer<GeneratedResourceBuildItem> generatedResource,
BuildProducer<ReflectiveClassBuildItem> reflectiveClasses,
BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy,
io.quarkus.vertx.http.deployment.BodyHandlerBuildItem bodyHandler,
BuildProducer<RouteBuildItem> routeProducer,
BuildProducer<FilterBuildItem> filterProducer,
List<RequireBodyHandlerBuildItem> bodyHandlerRequired,
BeanArchiveIndexBuildItem beanArchive,
TransformedAnnotationsBuildItem transformedAnnotations,
ShutdownContextBuildItem shutdown,
LaunchModeBuildItem launchMode,
BuildProducer<RouteDescriptionBuildItem> descriptions,
Capabilities capabilities,
Optional<BeanValidationAnnotationsBuildItem> beanValidationAnnotations,
List<ApplicationClassPredicateBuildItem> predicates) {
Predicate<String> appClassPredicate = new Predicate<String>() {
@Override
public boolean test(String name) {
int idx = name.lastIndexOf(HANDLER_SUFFIX);
String className = idx != -1 ? name.substring(0, idx) : name;
for (ApplicationClassPredicateBuildItem i : predicates) {
if (i.test(className)) {
return true;
}
}
return GeneratedClassGizmoAdaptor.isApplicationClass(className);
}
};
Gizmo gizmo = Gizmo.create(new GeneratedClassGizmo2Adaptor(generatedClass, generatedResource, appClassPredicate))
.withDebugInfo(false)
.withParameters(false);
IndexView index = beanArchive.getIndex();
Map<RouteMatcher, MethodInfo> matchers = new HashMap<>();
boolean validatorAvailable = capabilities.isPresent(Capability.HIBERNATE_VALIDATOR);
for (AnnotatedRouteHandlerBuildItem businessMethod : routeHandlerBusinessMethods) {
AnnotationInstance routeBaseAnnotation = businessMethod.getRouteBase();
String pathPrefix = null;
String[] baseProduces = null;
String[] baseConsumes = null;
if (routeBaseAnnotation != null) {
AnnotationValue pathPrefixValue = routeBaseAnnotation.value(VALUE_PATH);
if (pathPrefixValue != null) {
pathPrefix = pathPrefixValue.asString();
}
AnnotationValue producesValue = routeBaseAnnotation.value(VALUE_PRODUCES);
if (producesValue != null) {
baseProduces = producesValue.asStringArray();
}
AnnotationValue consumesValue = routeBaseAnnotation.value(VALUE_CONSUMES);
if (consumesValue != null) {
baseConsumes = consumesValue.asStringArray();
}
}
// Route annotations with the same values share a single handler instance
// @Route string value -> handler
Map<String, Handler<RoutingContext>> routeHandlers = new HashMap<>();
for (AnnotationInstance route : businessMethod.getRoutes()) {
String routeString = route.toString(true);
Handler<RoutingContext> routeHandler = routeHandlers.get(routeString);
AnnotationValue regexValue = route.value(VALUE_REGEX);
AnnotationValue pathValue = route.value(VALUE_PATH);
AnnotationValue orderValue = route.valueWithDefault(index, VALUE_ORDER);
AnnotationValue producesValue = route.valueWithDefault(index, VALUE_PRODUCES);
AnnotationValue consumesValue = route.valueWithDefault(index, VALUE_CONSUMES);
AnnotationValue methodsValue = route.valueWithDefault(index, VALUE_METHODS);
String path = null;
String regex = null;
String[] produces = producesValue.asStringArray();
String[] consumes = consumesValue.asStringArray();
AnnotationValue typeValue = route.value(VALUE_TYPE);
Route.HandlerType routeHandlerType = typeValue == null ? Route.HandlerType.NORMAL
: Route.HandlerType.from(typeValue.asEnum());
String[] methods = Arrays.stream(methodsValue.asStringArray())
.map(String::toUpperCase)
.toArray(String[]::new);
int order = orderValue.asInt();
if (regexValue == null) {
if (pathPrefix != null) {
// A path prefix is set
StringBuilder prefixed = new StringBuilder();
prefixed.append(pathPrefix);
if (pathValue == null) {
// No path param set - use the method name for non-failure handlers
if (routeHandlerType != Route.HandlerType.FAILURE) {
prefixed.append(SLASH);
prefixed.append(dashify(businessMethod.getMethod().name()));
}
} else {
// Path param set
String pathValueStr = pathValue.asString();
if (!pathValueStr.isEmpty() && !pathValueStr.startsWith(SLASH)) {
prefixed.append(SLASH);
}
prefixed.append(pathValueStr);
}
path = prefixed.toString();
} else {
if (pathValue == null) {
// No path param set - use the method name for non-failure handlers
if (routeHandlerType != Route.HandlerType.FAILURE) {
path = dashify(businessMethod.getMethod().name());
}
} else {
// Path param set
path = pathValue.asString();
}
}
if (path != null && !path.startsWith(SLASH)) {
path = SLASH + path;
}
} else {
regex = regexValue.asString();
}
if (route.value(VALUE_PRODUCES) == null && baseProduces != null) {
produces = baseProduces;
}
if (route.value(VALUE_CONSUMES) == null && baseConsumes != null) {
consumes = baseConsumes;
}
HandlerType handlerType = HandlerType.NORMAL;
if (routeHandlerType != null) {
handlerType = switch (routeHandlerType) {
case NORMAL -> HandlerType.NORMAL;
case BLOCKING -> HandlerType.BLOCKING;
case FAILURE -> HandlerType.FAILURE;
default -> throw new IllegalStateException("Unknown type " + routeHandlerType);
};
}
if (businessMethod.isBlocking()) {
if (handlerType == HandlerType.NORMAL) {
handlerType = HandlerType.BLOCKING;
} else if (handlerType == HandlerType.FAILURE) {
throw new IllegalStateException(
"Invalid combination - a reactive route cannot use @Blocking and use the type `failure` at the same time: "
+ businessMethod.getMethod().toString());
}
}
if (routeHandler == null) {
String handlerClass = generateHandler(
new HandlerDescriptor(businessMethod.getMethod(), beanValidationAnnotations.orElse(null),
handlerType == HandlerType.FAILURE, produces),
businessMethod.getBean(), businessMethod.getMethod(), gizmo, transformedAnnotations,
route, reflectiveHierarchy, produces.length > 0 ? produces[0] : null,
validatorAvailable, index);
reflectiveClasses
.produce(ReflectiveClassBuildItem.builder(handlerClass).build());
routeHandler = recorder.createHandler(handlerClass);
routeHandlers.put(routeString, routeHandler);
}
// Wrap the route handler if necessary
// Note that route annotations with the same values share a single handler implementation
routeHandler = recorder.compressRouteHandler(routeHandler, businessMethod.getCompression());
if (businessMethod.getMethod().hasDeclaredAnnotation(DotNames.RUN_ON_VIRTUAL_THREAD)) {
LOGGER.debugf("Route %s#%s() will be executed on a virtual thread",
businessMethod.getMethod().declaringClass().name(), businessMethod.getMethod().name());
routeHandler = recorder.runOnVirtualThread(routeHandler);
// The handler must be executed on the event loop
handlerType = HandlerType.NORMAL;
}
RouteMatcher matcher = new RouteMatcher(path, regex, produces, consumes, methods, order);
matchers.put(matcher, businessMethod.getMethod());
Function<Router, io.vertx.ext.web.Route> routeFunction = recorder.createRouteFunction(matcher,
bodyHandler.getHandler(), businessMethod.shouldAlwaysAuthenticateRoute());
//TODO This needs to be refactored to use routeFunction() taking a Consumer<Route> instead
RouteBuildItem.Builder builder = RouteBuildItem.builder()
.routeFunction(routeFunction)
.handlerType(handlerType)
.handler(routeHandler);
routeProducer.produce(builder.build());
if (launchMode.getLaunchMode().equals(LaunchMode.DEVELOPMENT)) {
if (methods.length == 0) {
// No explicit method declared - match all methods
methods = Arrays.stream(HttpMethod.values())
.map(Enum::name)
.toArray(String[]::new);
}
descriptions.produce(new RouteDescriptionBuildItem(
businessMethod.getMethod().declaringClass().name().withoutPackagePrefix() + "#"
+ businessMethod.getMethod().name() + "()",
regex != null ? regex : path,
String.join(", ", methods), produces, consumes));
}
}
}
for (AnnotatedRouteFilterBuildItem filterMethod : routeFilterBusinessMethods) {
String handlerClass = generateHandler(
new HandlerDescriptor(filterMethod.getMethod(), beanValidationAnnotations.orElse(null), false,
new String[0]),
filterMethod.getBean(), filterMethod.getMethod(), gizmo, transformedAnnotations,
filterMethod.getRouteFilter(), reflectiveHierarchy, null, validatorAvailable, index);
reflectiveClasses.produce(ReflectiveClassBuildItem.builder(handlerClass).build());
Handler<RoutingContext> routingHandler = recorder.createHandler(handlerClass);
AnnotationValue priorityValue = filterMethod.getRouteFilter().value();
filterProducer.produce(new FilterBuildItem(routingHandler,
priorityValue != null ? priorityValue.asInt() : RouteFilter.DEFAULT_PRIORITY));
}
detectConflictingRoutes(matchers);
}
@BuildStep
AutoAddScopeBuildItem autoAddScope() {
return AutoAddScopeBuildItem.builder()
.containsAnnotations(DotNames.ROUTE,
DotNames.ROUTES,
DotNames.ROUTE_FILTER)
.defaultScope(BuiltinScope.SINGLETON)
.reason("Found route handler business methods").build();
}
private void validateRouteFilterMethod(BeanInfo bean, MethodInfo method) {
if (!method.returnType().kind().equals(Type.Kind.VOID)) {
throw new IllegalStateException(
String.format("Route filter method must return void [method: %s, bean: %s]", method, bean));
}
List<Type> params = method.parameterTypes();
if (params.size() != 1 || !params.get(0).name()
.equals(DotNames.ROUTING_CONTEXT)) {
throw new IllegalStateException(String.format(
"Route filter method must accept exactly one parameter of type %s: %s [method: %s, bean: %s]",
DotNames.ROUTING_CONTEXT, params, method, bean));
}
}
private void validateRouteMethod(BeanInfo bean, MethodInfo method,
TransformedAnnotationsBuildItem transformedAnnotations, IndexView index, AnnotationInstance routeAnnotation) {
List<Type> params = method.parameterTypes();
if (params.isEmpty()) {
if (method.returnType().kind() == Kind.VOID && params.isEmpty()) {
throw new IllegalStateException(String.format(
"Route method that returns void must accept at least one injectable parameter [method: %s, bean: %s]",
method, bean));
}
} else {
AnnotationValue typeValue = routeAnnotation.value(VALUE_TYPE);
Route.HandlerType handlerType = typeValue == null
? Route.HandlerType.NORMAL
: Route.HandlerType.from(typeValue.asEnum());
DotName returnTypeName = method.returnType().name();
if ((returnTypeName.equals(DotNames.UNI)
|| returnTypeName.equals(DotNames.MULTI)
|| returnTypeName.equals(DotNames.COMPLETION_STAGE))
&& method.returnType().kind() == Kind.CLASS) {
throw new IllegalStateException(String.format(
"Route business method returning a Uni/Multi/CompletionStage must declare a type argument on the return type [method: %s, bean: %s]",
method, bean));
}
boolean canEndResponse = false;
int idx = 0;
int failureParams = 0;
for (Type paramType : params) {
Set<AnnotationInstance> paramAnnotations = Annotations.getParameterAnnotations(transformedAnnotations,
method, idx);
List<ParameterInjector> injectors = getMatchingInjectors(paramType, paramAnnotations, index);
if (injectors.isEmpty()) {
throw new IllegalStateException(String.format(
"No parameter injector found for parameter %s of route method %s declared on %s", idx,
method, bean));
}
if (injectors.size() > 1) {
throw new IllegalStateException(String.format(
"Multiple parameter injectors found for parameter %s of route method %s declared on %s",
idx, method, bean));
}
ParameterInjector injector = injectors.get(0);
if (injector.getTargetHandlerType() != null && !injector.getTargetHandlerType().equals(handlerType)) {
throw new IllegalStateException(String.format(
"HandlerType.%s is not legal for parameter %s of route method %s declared on %s",
injector.getTargetHandlerType(), idx, method, bean));
}
// A param injector may validate the parameter annotations
injector.validate(bean, method, routeAnnotation, paramType, paramAnnotations);
if (injector.canEndResponse) {
canEndResponse = true;
}
if (Route.HandlerType.FAILURE == handlerType && isThrowable(paramType, index)) {
failureParams++;
}
idx++;
}
if (method.returnType().kind() == Kind.VOID && !canEndResponse) {
throw new IllegalStateException(String.format(
"Route method that returns void must accept at least one parameter that can end the response [method: %s, bean: %s]",
method, bean));
}
if (failureParams > 1) {
throw new IllegalStateException(String.format(
"A failure handler may only define one failure parameter - route method %s declared on %s",
method, bean));
}
}
}
private String generateHandler(HandlerDescriptor desc, BeanInfo bean, MethodInfo method, Gizmo gizmo,
TransformedAnnotationsBuildItem transformedAnnotations, AnnotationInstance routeAnnotation,
BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy, String defaultProduces,
boolean validatorAvailable, IndexView index) {
if (desc.requireValidation() && !validatorAvailable) {
throw new IllegalStateException(
"A route requires validation, but the Hibernate Validator extension is not present");
}
StringBuilder signature = new StringBuilder();
signature.append(method.name()).append("_").append(method.returnType().name());
for (Type parameterType : method.parameterTypes()) {
signature.append(parameterType.name());
}
signature.append(routeAnnotation.toString(true));
String generatedName = bean.getImplClazz().name().toString() + HANDLER_SUFFIX + "_" + method.name() + "_"
+ HashUtil.sha1(signature.toString());
gizmo.class_(generatedName, cc -> {
cc.extends_(RouteHandler.class);
FieldDesc beanField = cc.field("bean", fc -> {
fc.private_();
fc.final_();
fc.setType(InjectableBean.class);
});
FieldDesc contextField;
FieldDesc containerField;
if (BuiltinScope.APPLICATION.is(bean.getScope()) || BuiltinScope.SINGLETON.is(bean.getScope())) {
// Singleton and application contexts are always active and unambiguous
contextField = cc.field("context", fc -> {
fc.private_();
fc.final_();
fc.setType(InjectableContext.class);
});
containerField = null;
} else {
contextField = null;
containerField = cc.field("container", fc -> {
fc.private_();
fc.final_();
fc.setType(ArcContainer.class);
});
}
FieldDesc validatorField;
if (desc.isProducedResponseValidated()) {
// If the produced item needs to be validated, we inject the Validator
validatorField = cc.field("validator", fc -> {
fc.public_(); // TODO why???
fc.final_();
fc.setType(Methods.VALIDATION_VALIDATOR);
});
} else {
validatorField = null;
}
generateConstructor(cc, bean, beanField, contextField, containerField, validatorField);
generateInvoke(cc, desc, bean, method, beanField, contextField, containerField, validatorField,
transformedAnnotations, reflectiveHierarchy, defaultProduces, index);
});
return generatedName;
}
void generateConstructor(io.quarkus.gizmo2.creator.ClassCreator cc, BeanInfo btBean, FieldDesc beanField,
FieldDesc contextField, FieldDesc containerField, FieldDesc validatorField) {
cc.constructor(mc -> {
mc.body(bc -> {
bc.invokeSpecial(Methods.ROUTE_HANDLER_CTOR, cc.this_());
LocalVar arc = bc.localVar("arc", bc.invokeStatic(Methods.ARC_CONTAINER));
LocalVar rtBean = bc.localVar("bean",
bc.invokeInterface(Methods.ARC_CONTAINER_BEAN, arc, Const.of(btBean.getIdentifier())));
bc.set(cc.this_().field(beanField), rtBean);
if (contextField != null) {
Expr scope = bc.invokeInterface(Methods.BEAN_GET_SCOPE, rtBean);
Expr context = bc.invokeInterface(Methods.ARC_CONTAINER_GET_ACTIVE_CONTEXT, arc, scope);
bc.set(cc.this_().field(contextField), context);
}
if (containerField != null) {
bc.set(cc.this_().field(containerField), arc);
}
if (validatorField != null) {
bc.set(cc.this_().field(validatorField), bc.invokeStatic(Methods.VALIDATION_GET_VALIDATOR, arc));
}
bc.return_();
});
});
}
void generateInvoke(ClassCreator cc, HandlerDescriptor descriptor, BeanInfo btBean, MethodInfo method,
FieldDesc beanField, FieldDesc contextField, FieldDesc containerField, FieldDesc validatorField,
TransformedAnnotationsBuildItem transformedAnnotations,
BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy, String defaultProduces, IndexView index) {
cc.method("invoke", mc -> {
mc.returning(void.class);
ParamVar routingContext = mc.parameter("routingContext", RoutingContext.class);
mc.body(b0 -> {
// For failure handlers attempt to match the failure type
if (descriptor.isFailureHandler()) {
Type failureType = getFailureType(method.parameterTypes(), index);
if (failureType != null) {
LocalVar failure = b0.localVar("failure", b0.invokeInterface(Methods.FAILURE, routingContext));
b0.ifNull(failure, b1 -> {
b1.invokeInterface(Methods.NEXT, routingContext);
b1.return_();
});
Expr isAssignable = b0.invokeVirtual(Methods.IS_ASSIGNABLE_FROM, Const.of(classDescOf(failureType)),
b0.withObject(failure).getClass_());
b0.ifNot(isAssignable, b1 -> {
b1.invokeInterface(Methods.NEXT, routingContext);
b1.return_();
});
}
}
FieldVar rtBean = cc.this_().field(beanField);
LocalVar creationalContext = BuiltinScope.DEPENDENT.is(btBean.getScope())
? b0.localVar("cc", b0.new_(Methods.CREATIONAL_CONTEXT_IMPL_CTOR, rtBean))
: null;
LocalVar beanInstance = b0.localVar("beanInstance", b0.blockExpr(CD_Object, b1 -> {
if (BuiltinScope.DEPENDENT.is(btBean.getScope())) {
b1.yield(b1.invokeInterface(Methods.INJECTABLE_REF_PROVIDER_GET, rtBean, creationalContext));
} else {
Var context;
if (contextField != null) {
context = cc.this_().field(contextField);
} else {
context = b1.localVar("context", b1.invokeInterface(Methods.ARC_CONTAINER_GET_ACTIVE_CONTEXT,
cc.this_().field(containerField), b1.invokeInterface(Methods.BEAN_GET_SCOPE, rtBean)));
b1.ifNull(context, b2 -> {
b2.throw_(ContextNotActiveException.class, "Context not active: "
+ btBean.getScope().getDotName());
});
}
// First try to obtain the bean via Context.get(bean)
LocalVar tmp = b1.localVar("tmp", b1.invokeInterface(Methods.CONTEXT_GET_IF_PRESENT,
context, rtBean));
// If not present, try Context.get(bean,creationalContext)
b1.ifNull(tmp, b2 -> {
b2.set(tmp, b2.invokeInterface(Methods.CONTEXT_GET, context, rtBean,
b2.new_(Methods.CREATIONAL_CONTEXT_IMPL_CTOR, rtBean)));
});
b1.yield(tmp);
}
}));
ClassDesc[] params = new ClassDesc[method.parametersCount()];
LocalVar[] args = new LocalVar[method.parametersCount()];
int idx = 0;
for (MethodParameterInfo methodParam : method.parameters()) {
Set<AnnotationInstance> paramAnnotations = Annotations.getParameterAnnotations(transformedAnnotations,
method, idx);
// At this point we can be sure that exactly one matching injector exists
args[idx] = getMatchingInjectors(methodParam.type(), paramAnnotations, index).get(0)
.getValue(methodParam, paramAnnotations, routingContext, b0, reflectiveHierarchy);
params[idx] = classDescOf(methodParam.type());
idx++;
}
MethodDesc desc = ClassMethodDesc.of(classDescOf(btBean.getImplClazz()), method.name(),
MethodTypeDesc.of(classDescOf(descriptor.getReturnType()), params));
// If no content-type header is set then try to use the most acceptable content type
// the business method can override this manually if required
b0.invokeStatic(Methods.ROUTE_HANDLERS_SET_CONTENT_TYPE, routingContext,
defaultProduces == null ? Const.ofNull(String.class) : Const.of(defaultProduces));
// Invoke the business method handler
LocalVar result;
if (descriptor.isReturningUni()) {
result = b0.localVar("result", Const.ofDefault(Uni.class));
} else if (descriptor.isReturningMulti()) {
result = b0.localVar("result", Const.ofDefault(Multi.class));
} else if (descriptor.isReturningCompletionStage()) {
result = b0.localVar("result", Const.ofDefault(CompletionStage.class));
} else {
result = b0.localVar("result", Const.ofDefault(Object.class));
}
if (!descriptor.requireValidation()) {
Expr value = b0.invokeVirtual(desc, beanInstance, args);
if (!value.isVoid()) {
b0.set(result, value);
}
} else {
b0.try_(tc -> {
tc.body(b1 -> {
Expr value = b1.invokeVirtual(desc, beanInstance, args);
if (!value.isVoid()) {
b1.set(result, value);
}
});
tc.catch_(Methods.VALIDATION_CONSTRAINT_VIOLATION_EXCEPTION, "e", (b1, e) -> {
boolean forceJsonEncoding = !descriptor.isPayloadString()
&& !descriptor.isPayloadBuffer()
&& !descriptor.isPayloadMutinyBuffer();
b1.invokeStatic(Methods.VALIDATION_HANDLE_VIOLATION, e, routingContext,
Const.of(forceJsonEncoding));
b1.return_();
});
});
}
// Get the response: HttpServerResponse response = rc.response()
MethodDesc end = Methods.getEndMethodForContentType(descriptor);
if (descriptor.isReturningUni()) {
// The method returns a Uni.
// We subscribe to this Uni and write the provided item in the HTTP response
// If the method returned null, we fail
// If the provided item is null and the method does not return a Uni<Void>, we fail
// If the provided item is null, and the method return a Uni<Void>, we reply with a 204 - NO CONTENT
// If the provided item is not null, if it's a string or buffer, the response.end method is used to write the response
// If the provided item is not null, and it's an object, the item is mapped to JSON and written into the response
b0.invokeVirtual(Methods.UNI_SUBSCRIBE_WITH,
b0.invokeInterface(Methods.UNI_SUBSCRIBE, result),
getUniOnItemCallback(descriptor, b0, routingContext, end, cc.this_(), validatorField),
getUniOnFailureCallback(b0, routingContext));
registerForReflection(descriptor.getPayloadType(), reflectiveHierarchy);
} else if (descriptor.isReturningMulti()) {
// 3 cases - regular multi vs. sse multi vs. json array multi, we need to check the type.
// Let's check if we have a content type and use that one to decide which serialization we need to apply.
String contentType = descriptor.getFirstContentType();
if (contentType != null) {
if (contentType.toLowerCase().startsWith(EVENT_STREAM)) {
handleSSEMulti(descriptor, b0, routingContext, result);
} else if (contentType.toLowerCase().startsWith(APPLICATION_JSON)) {
handleJsonArrayMulti(descriptor, b0, routingContext, result);
} else if (contentType.toLowerCase().startsWith(ND_JSON)
|| contentType.toLowerCase().startsWith(JSON_STREAM)) {
handleNdjsonMulti(descriptor, b0, routingContext, result);
} else {
handleRegularMulti(descriptor, b0, routingContext, result);
}
} else {
// No content type, use the Multi Type - this approach does not work when using Quarkus security
// (as it wraps the produced Multi).
b0.ifElse(b0.invokeStatic(Methods.IS_SSE, result), b1 -> {
handleSSEMulti(descriptor, b1, routingContext, result);
}, b1 -> {
b1.ifElse(b1.invokeStatic(Methods.IS_NDJSON, result), b2 -> {
handleNdjsonMulti(descriptor, b2, routingContext, result);
}, b2 -> {
b2.ifElse(b2.invokeStatic(Methods.IS_JSON_ARRAY, result), b3 -> {
handleJsonArrayMulti(descriptor, b3, routingContext, result);
}, b3 -> {
handleRegularMulti(descriptor, b3, routingContext, result);
});
});
});
}
registerForReflection(descriptor.getPayloadType(), reflectiveHierarchy);
} else if (descriptor.isReturningCompletionStage()) {
// The method returns a CompletionStage - we write the provided item in the HTTP response
// If the method returned null, we fail
// If the provided item is null and the method does not return a CompletionStage<Void>, we fail
// If the provided item is null, and the method return a CompletionStage<Void>, we reply with a 204 - NO CONTENT
// If the provided item is not null, if it's a string or buffer, the response.end method is used to write the response
// If the provided item is not null, and it's an object, the item is mapped to JSON and written into the response
Expr consumer = getWhenCompleteCallback(descriptor, b0, routingContext, end, cc.this_(), validatorField);
b0.invokeInterface(Methods.CS_WHEN_COMPLETE, result, consumer);
registerForReflection(descriptor.getPayloadType(), reflectiveHierarchy);
} else if (descriptor.getPayloadType() != null) {
// The method returns "something" in a synchronous manner, write it into the response
LocalVar response = b0.localVar("response", b0.invokeInterface(Methods.RESPONSE, routingContext));
// If the method returned null, we fail
// If the method returns string or buffer, the response.end method is used to write the response
// If the method returns an object, the result is mapped to JSON and written into the response
Expr content = getContentToWrite(descriptor, response, result, b0, cc.this_(), validatorField);
b0.invokeInterface(end, response, content);
registerForReflection(descriptor.getPayloadType(), reflectiveHierarchy);
}
// Destroy dependent instance afterwards
if (BuiltinScope.DEPENDENT.is(btBean.getScope())) {
b0.invokeInterface(Methods.INJECTABLE_BEAN_DESTROY, rtBean, beanInstance, creationalContext);
}
b0.return_();
});
});
}
private Type getFailureType(List<Type> parameters, IndexView index) {
for (Type paramType : parameters) {
if (isThrowable(paramType, index)) {
return paramType;
}
}
return null;
}
private static boolean isThrowable(Type paramType, IndexView index) {
ClassInfo clazz = index.getClassByName(paramType.name());
while (clazz != null) {
if (clazz.superName() == null) {
break;
}
if (DotNames.EXCEPTION.equals(clazz.superName()) || DotNames.THROWABLE.equals(clazz.superName())) {
return true;
}
clazz = index.getClassByName(clazz.superName());
}
return false;
}
private static final List<DotName> TYPES_IGNORED_FOR_REFLECTION = Arrays.asList(
DotName.STRING_NAME, DotNames.BUFFER, DotNames.JSON_ARRAY, DotNames.JSON_OBJECT);
private static void registerForReflection(Type contentType,
BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) {
if (TYPES_IGNORED_FOR_REFLECTION.contains(contentType.name())) {
return;
}
reflectiveHierarchy.produce(ReflectiveHierarchyBuildItem
.builder(contentType)
.ignoreTypePredicate(ReflectiveHierarchyBuildItem.DefaultIgnoreTypePredicate.INSTANCE
.or(TYPES_IGNORED_FOR_REFLECTION::contains))
.source(ReactiveRoutesProcessor.class.getSimpleName() + " > " + contentType)
.build());
}
private void handleRegularMulti(HandlerDescriptor descriptor, BlockCreator bc, Var routingContext,
Expr res) {
// The method returns a Multi.
// We subscribe to this Multi and write the provided items (one by one) in the HTTP response.
// On completion, we "end" the response
// If the method returned null, we fail
// If the provided item is null we fail
// If the multi is empty, and the method return a Multi<Void>, we reply with a 204 - NO CONTENT
// If the produce item is a string or buffer, the response.write method is used to write the response
// If the produce item is an object, the item is mapped to JSON and written into the response. The response is a JSON array.
if (Methods.isNoContent(descriptor)) { // Multi<Void> - so return a 204.
bc.invokeStatic(Methods.MULTI_SUBSCRIBE_VOID, res, routingContext);
} else if (descriptor.isPayloadBuffer()) {
bc.invokeStatic(Methods.MULTI_SUBSCRIBE_BUFFER, res, routingContext);
} else if (descriptor.isPayloadMutinyBuffer()) {
bc.invokeStatic(Methods.MULTI_SUBSCRIBE_MUTINY_BUFFER, res, routingContext);
} else if (descriptor.isPayloadString()) {
bc.invokeStatic(Methods.MULTI_SUBSCRIBE_STRING, res, routingContext);
} else { // Multi<Object> - encode to json.
bc.invokeStatic(Methods.MULTI_SUBSCRIBE_OBJECT, res, routingContext);
}
}
private void handleSSEMulti(HandlerDescriptor descriptor, BlockCreator bc, Var routingContext,
Expr res) {
// The method returns a Multi that needs to be written as server-sent event.
// We subscribe to this Multi and write the provided items (one by one) in the HTTP response.
// On completion, we "end" the response
// If the method returned null, we fail
// If the provided item is null we fail
// If the multi is empty, and the method return a Multi<Void>, we reply with a 204 - NO CONTENT (as regular)
// If the produced item is a string or buffer, the response.write method is used to write the events in the response
// If the produced item is an object, the item is mapped to JSON and included in the `data` section of the event.
if (Methods.isNoContent(descriptor)) { // Multi<Void> - so return a 204.
bc.invokeStatic(Methods.MULTI_SUBSCRIBE_VOID, res, routingContext);
} else if (descriptor.isPayloadBuffer()) {
bc.invokeStatic(Methods.MULTI_SSE_SUBSCRIBE_BUFFER, res, routingContext);
} else if (descriptor.isPayloadMutinyBuffer()) {
bc.invokeStatic(Methods.MULTI_SSE_SUBSCRIBE_MUTINY_BUFFER, res, routingContext);
} else if (descriptor.isPayloadString()) {
bc.invokeStatic(Methods.MULTI_SSE_SUBSCRIBE_STRING, res, routingContext);
} else { // Multi<Object> - encode to json.
bc.invokeStatic(Methods.MULTI_SSE_SUBSCRIBE_OBJECT, res, routingContext);
}
}
private void handleNdjsonMulti(HandlerDescriptor descriptor, BlockCreator bc, Var routingContext,
Expr res) {
// The method returns a Multi that needs to be written as server-sent event.
// We subscribe to this Multi and write the provided items (one by one) in the HTTP response.
// On completion, we "end" the response
// If the method returned null, we fail
// If the provided item is null we fail
// If the multi is empty, and the method return a Multi<Void>, we reply with a 204 - NO CONTENT (as regular)
// If the produced item is a string or buffer, the response.write method is used to write the events in the response
// If the produced item is an object, the item is mapped to JSON and included in the `data` section of the event.
if (Methods.isNoContent(descriptor)) { // Multi<Void> - so return a 204.
bc.invokeStatic(Methods.MULTI_SUBSCRIBE_VOID, res, routingContext);
} else if (descriptor.isPayloadString()) {
bc.invokeStatic(Methods.MULTI_NDJSON_SUBSCRIBE_STRING, res, routingContext);
} else if (descriptor.isPayloadBuffer() || descriptor.isPayloadMutinyBuffer()) {
bc.invokeStatic(Methods.MULTI_JSON_FAIL, routingContext);
} else { // Multi<Object> - encode to json.
bc.invokeStatic(Methods.MULTI_NDJSON_SUBSCRIBE_OBJECT, res, routingContext);
}
}
private void handleJsonArrayMulti(HandlerDescriptor descriptor, BlockCreator bc, Var routingContext,
Expr res) {
// The method returns a Multi that needs to be written as JSON Array.
// We subscribe to this Multi and write the provided items (one by one) in the HTTP response.
// On completion, we "end" the response
// If the method returned null, we fail
// If the provided item is null we fail
// If the multi is empty, we send an empty JSON array
// If the produced item is a string, the response.write method is used to write the events in the response
// If the produced item is an object, the item is mapped to JSON and included in the `data` section of the event.
// If the produced item is a buffer, we fail
if (Methods.isNoContent(descriptor)) { // Multi<Void> - so return a 204.
bc.invokeStatic(Methods.MULTI_JSON_SUBSCRIBE_VOID, res, routingContext);
} else if (descriptor.isPayloadString()) {
bc.invokeStatic(Methods.MULTI_JSON_SUBSCRIBE_STRING, res, routingContext);
} else if (descriptor.isPayloadBuffer() || descriptor.isPayloadMutinyBuffer()) {
bc.invokeStatic(Methods.MULTI_JSON_FAIL, routingContext);
} else { // Multi<Object> - encode to json.
bc.invokeStatic(Methods.MULTI_JSON_SUBSCRIBE_OBJECT, res, routingContext);
}
}
/**
* Generates the following function depending on the payload type
* <p>
* If the method returns a {@code Uni<Void>}
*
* <pre>
* item -> routingContext.response().setStatusCode(204).end();
* </pre>
* <p>
* If the method returns a {@code Uni<Buffer>}:
*
* <pre>
* item -> {
* if (item != null) {
* Buffer buffer = getBuffer(item); // Manage Mutiny buffer
* routingContext.response().end(buffer);
* } else {
* routingContext.fail(new NullPointerException(...);
* }
* }
* </pre>
* <p>
* If the method returns a {@code Uni<String>} :
*
* <pre>
* item -> {
* if (item != null) {
* routingContext.response().end(item);
* } else {
* routingContext.fail(new NullPointerException(...);
* }
* }
* </pre>
* <p>
* If the method returns a {@code Uni<T>} :
*
* <pre>
* item -> {
* if (item != null) {
* String json = Json.encode(item);
* routingContext.response().end(json);
* } else {
* routingContext.fail(new NullPointerException(...);
* }
* }
* </pre>
* <p>
* This last version also set the {@code content-type} header to {@code application/json }if not set.
*
* @param descriptor the method descriptor
* @param bc the main bytecode writer
* @param routingContext the reference to the routing context variable
* @param end the end method to use
* @param validatorField the validator field if validation is enabled
* @return the function creator
*/
private Expr getUniOnItemCallback(HandlerDescriptor descriptor, BlockCreator bc, Var routingContext,
MethodDesc end, This this_, FieldDesc validatorField) {
return bc.lambda(Consumer.class, lc -> {
Var capturedRoutingContext = lc.capture("routingContext", routingContext);
Var capturedThis = lc.capture("this_", this_);
ParamVar item = lc.parameter("item", 0);
lc.body(lb0 -> {
LocalVar response = lb0.localVar("response", lb0.invokeInterface(Methods.RESPONSE, capturedRoutingContext));
if (Methods.isNoContent(descriptor)) { // Uni<Void> - so return a 204.
lb0.invokeInterface(Methods.SET_STATUS, response, Const.of(204));
lb0.invokeInterface(Methods.END, response);
} else {
// Check if the item is null
lb0.ifElse(lb0.isNotNull(item), lb1 -> {
Expr content = getContentToWrite(descriptor, response, item, lb1, capturedThis, validatorField);
lb1.invokeInterface(end, response, content);
}, lb1 -> {
lb1.invokeInterface(Methods.FAIL, capturedRoutingContext, Methods.createNpeItemIsNull(lb1));
});
}
lb0.return_();
});
});
}
private Expr getUniOnFailureCallback(BlockCreator bc, Var routingContext) {
return bc.new_(ConstructorDesc.of(UniFailureCallback.class, RoutingContext.class), routingContext);
}
private Expr getWhenCompleteCallback(HandlerDescriptor descriptor, BlockCreator bc, Var routingContext,
MethodDesc end, This this_, FieldDesc validatorField) {
return bc.lambda(BiConsumer.class, lc -> {
Var capturedThis = lc.capture("this_", this_);
Var capturedRoutingContext = lc.capture("routingContext", routingContext);
ParamVar value = lc.parameter("value", 0);
ParamVar error = lc.parameter("error", 1);
lc.body(lb0 -> {
LocalVar response = lb0.localVar("response", lb0.invokeInterface(Methods.RESPONSE, capturedRoutingContext));
lb0.ifElse(lb0.isNull(error), lb1 -> {
if (Methods.isNoContent(descriptor)) {
// CompletionStage<Void> - so always return a 204
lb1.invokeInterface(Methods.SET_STATUS, response, Const.of(204));
lb1.invokeInterface(Methods.END, response);
} else {
// First check if the item is null
lb1.ifElse(lb1.isNotNull(value), lb2 -> {
Expr content = getContentToWrite(descriptor, response, value, lb2, capturedThis, validatorField);
lb2.invokeInterface(end, response, content);
}, lb2 -> {
Expr npe = lb2.new_(ConstructorDesc.of(NullPointerException.class, String.class),
Const.of("Null is not a valid return value for @Route method with return type: "
+ descriptor.getReturnType()));
lb2.invokeInterface(Methods.FAIL, capturedRoutingContext, npe);
});
}
}, lb1 -> {
lb1.invokeInterface(Methods.FAIL, capturedRoutingContext, error);
});
lb0.return_();
});
});
}
// `this_` is always either `This` or a captured `Var`
private Expr getContentToWrite(HandlerDescriptor descriptor, Var response, Var result,
BlockCreator bc, Expr this_, FieldDesc validatorField) {
if (descriptor.isPayloadString() || descriptor.isPayloadBuffer()) {
return result;
}
if (descriptor.isPayloadMutinyBuffer()) {
return bc.invokeVirtual(Methods.MUTINY_GET_DELEGATE, result);
}
// Encode to Json
Methods.setContentTypeToJson(response, bc);
// Validate result if needed
if (descriptor.isProducedResponseValidated()
&& (descriptor.isReturningUni() || descriptor.isReturningMulti() || descriptor.isReturningCompletionStage())) {
return Methods.validateProducedItem(response, bc, result, this_, validatorField);
} else {
return bc.invokeStatic(Methods.JSON_ENCODE, result);
}
}
// De-camel-case the name and then join the segments with hyphens
private static String dashify(String value) {
StringBuilder ret = new StringBuilder();
char[] chars = value.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (i != 0 && i != (chars.length - 1) && Character.isUpperCase(c)) {
ret.append('-');
}
ret.append(Character.toLowerCase(c));
}
return ret.toString();
}
private void detectConflictingRoutes(Map<RouteMatcher, MethodInfo> matchers) {
if (matchers.isEmpty()) {
return;
}
// First we need to group matchers that could potentially match the same request
Set<LinkedHashSet<RouteMatcher>> groups = new HashSet<>();
for (Iterator<Entry<RouteMatcher, MethodInfo>> iterator = matchers.entrySet().iterator(); iterator
.hasNext();) {
Entry<RouteMatcher, MethodInfo> entry = iterator.next();
LinkedHashSet<RouteMatcher> group = new LinkedHashSet<>();
group.add(entry.getKey());
matchers.entrySet().stream().filter(e -> {
if (e.getKey().equals(entry.getKey())) {
// Skip - the same matcher
return false;
}
if (e.getValue().equals(entry.getValue())) {
// Skip - the same method
return false;
}
if (e.getKey().getOrder() != entry.getKey().getOrder()) {
// Skip - different order set
return false;
}
return canMatchSameRequest(entry.getKey(), e.getKey());
}).map(Entry::getKey).forEach(group::add);
groups.add(group);
}
// Log a warning for any group that contains more than one member
boolean conflictExists = false;
for (Set<RouteMatcher> group : groups) {
if (group.size() > 1) {
Iterator<RouteMatcher> it = group.iterator();
RouteMatcher firstMatcher = it.next();
MethodInfo firstMethod = matchers.get(firstMatcher);
conflictExists = true;
StringBuilder conflictingRoutes = new StringBuilder();
while (it.hasNext()) {
RouteMatcher rm = it.next();
MethodInfo method = matchers.get(rm);
conflictingRoutes.append("\n\t- ").append(method.declaringClass().name().toString()).append("#")
.append(method.name()).append("()");
}
LOGGER.warnf(
"Route %s#%s() can match the same request and has the same order [%s] as:%s",
firstMethod.declaringClass().name(),
firstMethod.name(), firstMatcher.getOrder(), conflictingRoutes);
}
}
if (conflictExists) {
LOGGER.warn("You can use @Route#order() to ensure the routes are not executed in random order");
}
}
static boolean canMatchSameRequest(RouteMatcher m1, RouteMatcher m2) {
// regex not null and other not equal
if (m1.getRegex() != null) {
if (!Objects.equals(m1.getRegex(), m2.getRegex())) {
return false;
}
} else {
// path not null and other not equal
if (m1.getPath() != null && !Objects.equals(m1.getPath(), m2.getPath())) {
return false;
}
}
// methods not matching
if (m1.getMethods().length > 0 && m2.getMethods().length > 0
&& !Arrays.equals(m1.getMethods(), m2.getMethods())) {
return false;
}
// produces not matching
if (m1.getProduces().length > 0 && m2.getProduces().length > 0
&& !Arrays.equals(m1.getProduces(), m2.getProduces())) {
return false;
}
// consumes not matching
if (m1.getConsumes().length > 0 && m2.getConsumes().length > 0
&& !Arrays.equals(m1.getConsumes(), m2.getConsumes())) {
return false;
}
return true;
}
private List<ParameterInjector> getMatchingInjectors(Type paramType, Set<AnnotationInstance> paramAnnotations,
IndexView index) {
List<ParameterInjector> injectors = new ArrayList<>();
for (ParameterInjector injector : PARAM_INJECTORS) {
if (injector.matches(paramType, paramAnnotations, index)) {
injectors.add(injector);
}
}
return injectors;
}
static List<ParameterInjector> initParamInjectors() {
List<ParameterInjector> injectors = new ArrayList<>();
injectors.add(ParameterInjector.builder().canEndResponse().matchType(DotNames.ROUTING_CONTEXT)
.valueProvider(new ValueProvider() {
@Override
public Expr get(MethodParameterInfo methodParam, Set<AnnotationInstance> annotations, Var routingContext,
BlockCreator bc, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) {
return routingContext;
}
}).build());
injectors.add(ParameterInjector.builder().canEndResponse().matchType(DotNames.ROUTING_EXCHANGE)
.valueProvider(new ValueProvider() {
@Override
public Expr get(MethodParameterInfo methodParam, Set<AnnotationInstance> annotations, Var routingContext,
BlockCreator bc, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) {
return bc.new_(ConstructorDesc.of(RoutingExchangeImpl.class, RoutingContext.class), routingContext);
}
}).build());
injectors.add(ParameterInjector.builder().canEndResponse().matchType(DotNames.HTTP_SERVER_REQUEST)
.valueProvider(new ValueProvider() {
@Override
public Expr get(MethodParameterInfo methodParam, Set<AnnotationInstance> annotations, Var routingContext,
BlockCreator bc, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) {
return bc.invokeInterface(Methods.REQUEST, routingContext);
}
}).build());
injectors.add(ParameterInjector.builder().canEndResponse().matchType(DotNames.HTTP_SERVER_RESPONSE)
.valueProvider(new ValueProvider() {
@Override
public Expr get(MethodParameterInfo methodParam, Set<AnnotationInstance> annotations, Var routingContext,
BlockCreator bc, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) {
return bc.invokeInterface(Methods.RESPONSE, routingContext);
}
}).build());
injectors.add(ParameterInjector.builder().canEndResponse().matchType(DotNames.MUTINY_HTTP_SERVER_REQUEST)
.valueProvider(new ValueProvider() {
@Override
public Expr get(MethodParameterInfo methodParam, Set<AnnotationInstance> annotations, Var routingContext,
BlockCreator bc, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) {
return bc.new_(ConstructorDesc.of(io.vertx.mutiny.core.http.HttpServerRequest.class,
HttpServerRequest.class), bc.invokeInterface(Methods.REQUEST, routingContext));
}
}).build());
injectors.add(ParameterInjector.builder().canEndResponse().matchType(DotNames.MUTINY_HTTP_SERVER_RESPONSE)
.valueProvider(new ValueProvider() {
@Override
public Expr get(MethodParameterInfo methodParam, Set<AnnotationInstance> annotations, Var routingContext,
BlockCreator bc, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) {
return bc.new_(ConstructorDesc.of(io.vertx.mutiny.core.http.HttpServerResponse.class,
HttpServerResponse.class), bc.invokeInterface(Methods.RESPONSE, routingContext));
}
}).build());
injectors.add(ParameterInjector.builder()
.matchPrimitiveWrappers()
.matchType(DotName.STRING_NAME)
.matchOptionalOf(DotName.STRING_NAME)
.matchListOf(DotName.STRING_NAME)
.requireAnnotations(DotNames.PARAM)
.valueProvider(new ParamAndHeaderProvider(DotNames.PARAM, Methods.REQUEST_PARAMS, Methods.REQUEST_GET_PARAM))
.validate(new ParamValidator() {
@Override
public void validate(BeanInfo bean, MethodInfo method, AnnotationInstance routeAnnotation, Type paramType,
Set<AnnotationInstance> paramAnnotations) {
AnnotationInstance paramAnnotation = Annotations.find(paramAnnotations, DotNames.PARAM);
AnnotationValue paramNameValue = paramAnnotation.value();
if (paramNameValue != null && !paramNameValue.asString().equals(Param.ELEMENT_NAME)) {
String paramName = paramNameValue.asString();
AnnotationValue regexValue = routeAnnotation.value(VALUE_REGEX);
AnnotationValue pathValue = routeAnnotation.value(VALUE_PATH);
if (regexValue == null && pathValue != null) {
String path = pathValue.asString();
// Validate the name if used as a path parameter
if (path.contains(":" + paramName) && !PATH_PARAM_PATTERN.matcher(paramName).matches()) {
// TODO This requirement should be relaxed in vertx 4.0.3+
// https://github.com/vert-x3/vertx-web/pull/1881
throw new IllegalStateException(String.format(
"A path param name must only contain word characters (a-zA-Z_0-9): %s [route method %s declared on %s]",
paramName, method, bean.getBeanClass()));
}
}
}
}
})
.build());
injectors.add(ParameterInjector.builder()
.matchPrimitiveWrappers()
.matchType(DotName.STRING_NAME)
.matchOptionalOf(DotName.STRING_NAME)
.matchListOf(DotName.STRING_NAME)
.requireAnnotations(DotNames.HEADER)
.valueProvider(new ParamAndHeaderProvider(DotNames.HEADER, Methods.REQUEST_HEADERS, Methods.REQUEST_GET_HEADER))
.build());
injectors.add(ParameterInjector.builder()
.matchType(DotName.STRING_NAME)
.matchType(DotNames.BUFFER)
.matchType(DotNames.JSON_OBJECT)
.matchType(DotNames.JSON_ARRAY)
.requireAnnotations(DotNames.BODY)
.valueProvider(new ValueProvider() {
@Override
public Expr get(MethodParameterInfo methodParam, Set<AnnotationInstance> annotations, Var routingContext,
BlockCreator bc, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) {
Type paramType = methodParam.type();
if (paramType.name().equals(DotName.STRING_NAME)) {
return bc.invokeInterface(Methods.GET_BODY_AS_STRING, routingContext);
} else if (paramType.name().equals(DotNames.BUFFER)) {
return bc.invokeInterface(Methods.GET_BODY, routingContext);
} else if (paramType.name().equals(DotNames.JSON_OBJECT)) {
return bc.invokeInterface(Methods.GET_BODY_AS_JSON, routingContext);
} else if (paramType.name().equals(DotNames.JSON_ARRAY)) {
return bc.invokeInterface(Methods.GET_BODY_AS_JSON_ARRAY, routingContext);
}
// This should never happen
throw new IllegalArgumentException("Unsupported param type: " + paramType);
}
}).build());
injectors.add(ParameterInjector.builder()
.skipType(DotName.STRING_NAME)
.skipType(DotNames.BUFFER)
.skipType(DotNames.JSON_OBJECT)
.skipType(DotNames.JSON_ARRAY)
.requireAnnotations(DotNames.BODY)
.valueProvider(new ValueProvider() {
@Override
public Expr get(MethodParameterInfo methodParam, Set<AnnotationInstance> annotations, Var routingContext,
BlockCreator b0, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) {
Type paramType = methodParam.type();
registerForReflection(paramType, reflectiveHierarchy);
LocalVar bodyAsJson = b0.localVar("bodyAsJson",
b0.invokeInterface(Methods.GET_BODY_AS_JSON, routingContext));
LocalVar result = b0.localVar("result", Const.ofDefault(Object.class));
b0.ifNotNull(bodyAsJson, b1 -> {
// TODO load `paramType` | ReactiveRoutesProcessor |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/GenericToOneAssociationTest.java | {
"start": 4451,
"end": 4690
} | class ____ extends AbstractParent<Child> {
@Id
private Long id;
public Parent() {
}
public Parent(Long id) {
this.id = id;
}
public Long getId() {
return this.id;
}
}
@MappedSuperclass
public abstract static | Parent |
java | apache__maven | compat/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/reflection/MethodMap.java | {
"start": 12448,
"end": 14510
} | class ____ using a
* method invocation conversion, without matching object and primitive
* types. This method is used to determine the more specific type when
* comparing signatures of methods.
*
* @param formal the formal parameter type to which the actual
* parameter type should be convertible
* @param actual the actual parameter type.
* @return true if either formal type is assignable from actual type,
* or formal and actual are both primitive types and actual can be
* subject to widening conversion to formal.
*/
private static boolean isStrictMethodInvocationConvertible(Class<?> formal, Class<?> actual) {
// we shouldn't get a null into, but if so
if (actual == null && !formal.isPrimitive()) {
return true;
}
// Check for identity or widening reference conversion
if (formal.isAssignableFrom(actual)) {
return true;
}
// Check for widening primitive conversion.
if (formal.isPrimitive()) {
if (formal == Short.TYPE && (actual == Byte.TYPE)) {
return true;
}
if (formal == Integer.TYPE && (actual == Short.TYPE || actual == Byte.TYPE)) {
return true;
}
if (formal == Long.TYPE && (actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE)) {
return true;
}
if (formal == Float.TYPE
&& (actual == Long.TYPE || actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE)) {
return true;
}
if (formal == Double.TYPE
&& (actual == Float.TYPE
|| actual == Long.TYPE
|| actual == Integer.TYPE
|| actual == Short.TYPE
|| actual == Byte.TYPE)) {
return true;
}
}
return false;
}
}
| object |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/authentication/ott/RedirectOneTimeTokenGenerationSuccessHandler.java | {
"start": 1216,
"end": 1477
} | class ____ implements OneTimeTokenGenerationSuccessHandler {
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private final String redirectUrl;
/**
* Constructs an instance of this | RedirectOneTimeTokenGenerationSuccessHandler |
java | apache__kafka | connect/mirror/src/main/java/org/apache/kafka/connect/mirror/OffsetSyncWriter.java | {
"start": 6468,
"end": 8784
} | class ____ {
long previousUpstreamOffset = -1L;
long previousDownstreamOffset = -1L;
long lastSyncDownstreamOffset = -1L;
long maxOffsetLag;
boolean shouldSyncOffsets;
PartitionState(long maxOffsetLag) {
this.maxOffsetLag = maxOffsetLag;
}
// true if we should emit an offset sync
boolean update(long upstreamOffset, long downstreamOffset) {
// Emit an offset sync if any of the following conditions are true
boolean noPreviousSyncThisLifetime = lastSyncDownstreamOffset == -1L;
// the OffsetSync::translateDownstream method will translate this offset 1 past the last sync, so add 1.
// TODO: share common implementation to enforce this relationship
boolean translatedOffsetTooStale = downstreamOffset - (lastSyncDownstreamOffset + 1) >= maxOffsetLag;
boolean skippedUpstreamRecord = upstreamOffset - previousUpstreamOffset != 1L;
boolean truncatedDownstreamTopic = downstreamOffset < previousDownstreamOffset;
if (noPreviousSyncThisLifetime || translatedOffsetTooStale || skippedUpstreamRecord || truncatedDownstreamTopic) {
lastSyncDownstreamOffset = downstreamOffset;
shouldSyncOffsets = true;
}
previousUpstreamOffset = upstreamOffset;
previousDownstreamOffset = downstreamOffset;
return shouldSyncOffsets;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PartitionState that)) return false;
return previousUpstreamOffset == that.previousUpstreamOffset &&
previousDownstreamOffset == that.previousDownstreamOffset &&
lastSyncDownstreamOffset == that.lastSyncDownstreamOffset &&
maxOffsetLag == that.maxOffsetLag &&
shouldSyncOffsets == that.shouldSyncOffsets;
}
@Override
public int hashCode() {
return Objects.hash(previousUpstreamOffset, previousDownstreamOffset, lastSyncDownstreamOffset, maxOffsetLag, shouldSyncOffsets);
}
void reset() {
shouldSyncOffsets = false;
}
}
}
| PartitionState |
java | grpc__grpc-java | services/src/main/java/io/grpc/protobuf/services/BinlogHelper.java | {
"start": 20981,
"end": 21083
} | interface ____ {
@Nullable
BinlogHelper getLog(String fullMethodName);
}
static final | Factory |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TestInstanceFactoryTests.java | {
"start": 26090,
"end": 26317
} | class ____ extends AbstractTestInstanceFactory {
@Override
public ExtensionContextScope getTestInstantiationExtensionContextScope(ExtensionContext rootContext) {
return TEST_METHOD;
}
}
private static | FooInstanceFactory |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/cluster/ClusterScanSupport.java | {
"start": 9697,
"end": 10812
} | class ____ extends StreamScanCursor implements ClusterScanCursor {
final List<String> nodeIds;
final String currentNodeId;
final StreamScanCursor cursor;
public ClusterStreamScanCursor(List<String> nodeIds, String currentNodeId, StreamScanCursor cursor) {
super();
this.nodeIds = nodeIds;
this.currentNodeId = currentNodeId;
this.cursor = cursor;
setCursor(cursor.getCursor());
setCount(cursor.getCount());
if (cursor.isFinished()) {
int nodeIndex = nodeIds.indexOf(currentNodeId);
if (nodeIndex == -1 || nodeIndex == nodeIds.size() - 1) {
setFinished(true);
}
}
}
@Override
public List<String> getNodeIds() {
return nodeIds;
}
@Override
public String getCurrentNodeId() {
return currentNodeId;
}
public boolean isScanOnCurrentNodeFinished() {
return cursor.isFinished();
}
}
}
| ClusterStreamScanCursor |
java | micronaut-projects__micronaut-core | context/src/main/java/io/micronaut/runtime/graceful/GracefulShutdownCapable.java | {
"start": 1094,
"end": 3906
} | interface ____ {
/**
* Trigger a graceful shutdown. The returned {@link CompletionStage} will complete when the
* shutdown is complete.
* <p>
* Note that the completion of the returned future may be user-dependent. If a user does not
* close their connection, the future may never terminate. Always add a timeout for a hard
* shutdown.
* <p>
* This method should not throw an exception, nor should the returned stage complete
* exceptionally. Just log an error instead.
*
* @return A future that completes when this bean is fully shut down
*/
@NonNull
CompletionStage<?> shutdownGracefully();
/**
* After a call to {@link #shutdownGracefully()} report the state of the shutdown. If
* {@link #shutdownGracefully()} has not been called the behavior of this method is undefined.
*
* @return The current number of still-active tasks before the shutdown completes, or
* {@link Optional#empty()} if no state can be reported
*/
default OptionalLong reportActiveTasks() {
return OptionalLong.empty();
}
/**
* Combine the given futures.
*
* @param stages The input futures
* @return A future that completes when all inputs have completed
*/
@NonNull
static CompletionStage<?> allOf(@NonNull Stream<CompletionStage<?>> stages) {
return CompletableFuture.allOf(stages.map(CompletionStage::toCompletableFuture).toArray(CompletableFuture[]::new));
}
/**
* Shutdown all the given lifecycles.
*
* @param stages The input lifecycles
* @return A future that completes when all inputs have completed shutdown
*/
@NonNull
static CompletionStage<?> shutdownAll(@NonNull Stream<? extends GracefulShutdownCapable> stages) {
return CompletableFuture.allOf(stages.map(l -> {
CompletionStage<?> s;
try {
s = l.shutdownGracefully();
} catch (Exception e) {
LogHolder.LOG.warn("Exception when attempting graceful shutdown", e);
return CompletableFuture.completedFuture(null);
}
return s.toCompletableFuture();
}).toArray(CompletableFuture[]::new));
}
@NonNull
static OptionalLong combineActiveTasks(@NonNull Iterable<? extends GracefulShutdownCapable> delegates) {
long sum = 0;
boolean anyPresent = false;
for (GracefulShutdownCapable delegate : delegates) {
OptionalLong r = delegate.reportActiveTasks();
if (r.isPresent()) {
anyPresent = true;
sum += r.getAsLong();
}
}
return anyPresent ? OptionalLong.of(sum) : OptionalLong.empty();
}
}
@Internal
final | GracefulShutdownCapable |
java | quarkusio__quarkus | extensions/scheduler/deployment/src/test/java/io/quarkus/scheduler/test/staticmethod/ScheduledStaticMethodTest.java | {
"start": 1372,
"end": 1584
} | class ____ {
static final CountDownLatch LATCH = new CountDownLatch(1);
@Scheduled(every = "1s")
static void everySecond() {
LATCH.countDown();
}
}
| AbstractJobs |
java | junit-team__junit5 | junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/Constants.java | {
"start": 4261,
"end": 4980
} | class ____ matches both an inclusion and exclusion pattern will be excluded.
*
* @see JupiterConfiguration#EXTENSIONS_AUTODETECTION_INCLUDE_PROPERTY_NAME
*/
public static final String EXTENSIONS_AUTODETECTION_INCLUDE_PROPERTY_NAME = JupiterConfiguration.EXTENSIONS_AUTODETECTION_INCLUDE_PROPERTY_NAME;
/**
* Property name used to exclude patterns for auto-detecting extensions: {@value}
*
* <h4>Pattern Matching Syntax</h4>
*
* <p>If the property value consists solely of an asterisk ({@code *}), all
* extensions will be excluded. Otherwise, the property value will be treated
* as a comma-separated list of patterns where each individual pattern will be
* matched against the fully qualified | that |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/api/impl/pb/client/MRClientProtocolPBClientImpl.java | {
"start": 7663,
"end": 14543
} | class ____ implements MRClientProtocol,
Closeable {
protected MRClientProtocolPB proxy;
public MRClientProtocolPBClientImpl() {};
public MRClientProtocolPBClientImpl(long clientVersion,
InetSocketAddress addr, Configuration conf) throws IOException {
RPC.setProtocolEngine(conf, MRClientProtocolPB.class,
ProtobufRpcEngine2.class);
proxy = RPC.getProxy(MRClientProtocolPB.class, clientVersion, addr, conf);
}
@Override
public InetSocketAddress getConnectAddress() {
return RPC.getServerAddress(proxy);
}
@Override
public void close() {
if (this.proxy != null) {
RPC.stopProxy(this.proxy);
}
}
@Override
public GetJobReportResponse getJobReport(GetJobReportRequest request)
throws IOException {
GetJobReportRequestProto requestProto = ((GetJobReportRequestPBImpl)request).getProto();
try {
return new GetJobReportResponsePBImpl(proxy.getJobReport(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public GetTaskReportResponse getTaskReport(GetTaskReportRequest request)
throws IOException {
GetTaskReportRequestProto requestProto = ((GetTaskReportRequestPBImpl)request).getProto();
try {
return new GetTaskReportResponsePBImpl(proxy.getTaskReport(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public GetTaskAttemptReportResponse getTaskAttemptReport(
GetTaskAttemptReportRequest request) throws IOException {
GetTaskAttemptReportRequestProto requestProto = ((GetTaskAttemptReportRequestPBImpl)request).getProto();
try {
return new GetTaskAttemptReportResponsePBImpl(proxy.getTaskAttemptReport(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public GetCountersResponse getCounters(GetCountersRequest request)
throws IOException {
GetCountersRequestProto requestProto = ((GetCountersRequestPBImpl)request).getProto();
try {
return new GetCountersResponsePBImpl(proxy.getCounters(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents(
GetTaskAttemptCompletionEventsRequest request) throws IOException {
GetTaskAttemptCompletionEventsRequestProto requestProto = ((GetTaskAttemptCompletionEventsRequestPBImpl)request).getProto();
try {
return new GetTaskAttemptCompletionEventsResponsePBImpl(proxy.getTaskAttemptCompletionEvents(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request)
throws IOException {
GetTaskReportsRequestProto requestProto = ((GetTaskReportsRequestPBImpl)request).getProto();
try {
return new GetTaskReportsResponsePBImpl(proxy.getTaskReports(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request)
throws IOException {
GetDiagnosticsRequestProto requestProto = ((GetDiagnosticsRequestPBImpl)request).getProto();
try {
return new GetDiagnosticsResponsePBImpl(proxy.getDiagnostics(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public GetDelegationTokenResponse getDelegationToken(
GetDelegationTokenRequest request) throws IOException {
GetDelegationTokenRequestProto requestProto = ((GetDelegationTokenRequestPBImpl)
request).getProto();
try {
return new GetDelegationTokenResponsePBImpl(proxy.getDelegationToken(
null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public KillJobResponse killJob(KillJobRequest request)
throws IOException {
KillJobRequestProto requestProto = ((KillJobRequestPBImpl)request).getProto();
try {
return new KillJobResponsePBImpl(proxy.killJob(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public KillTaskResponse killTask(KillTaskRequest request)
throws IOException {
KillTaskRequestProto requestProto = ((KillTaskRequestPBImpl)request).getProto();
try {
return new KillTaskResponsePBImpl(proxy.killTask(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public KillTaskAttemptResponse killTaskAttempt(KillTaskAttemptRequest request)
throws IOException {
KillTaskAttemptRequestProto requestProto = ((KillTaskAttemptRequestPBImpl)request).getProto();
try {
return new KillTaskAttemptResponsePBImpl(proxy.killTaskAttempt(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public FailTaskAttemptResponse failTaskAttempt(FailTaskAttemptRequest request)
throws IOException {
FailTaskAttemptRequestProto requestProto = ((FailTaskAttemptRequestPBImpl)request).getProto();
try {
return new FailTaskAttemptResponsePBImpl(proxy.failTaskAttempt(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public RenewDelegationTokenResponse renewDelegationToken(
RenewDelegationTokenRequest request) throws IOException {
RenewDelegationTokenRequestProto requestProto =
((RenewDelegationTokenRequestPBImpl) request).getProto();
try {
return new RenewDelegationTokenResponsePBImpl(proxy.renewDelegationToken(
null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
@Override
public CancelDelegationTokenResponse cancelDelegationToken(
CancelDelegationTokenRequest request) throws IOException {
CancelDelegationTokenRequestProto requestProto =
((CancelDelegationTokenRequestPBImpl) request).getProto();
try {
return new CancelDelegationTokenResponsePBImpl(
proxy.cancelDelegationToken(null, requestProto));
} catch (ServiceException e) {
throw unwrapAndThrowException(e);
}
}
private IOException unwrapAndThrowException(ServiceException se) {
if (se.getCause() instanceof RemoteException) {
return ((RemoteException) se.getCause()).unwrapRemoteException();
} else if (se.getCause() instanceof IOException) {
return (IOException)se.getCause();
} else {
throw new UndeclaredThrowableException(se.getCause());
}
}
}
| MRClientProtocolPBClientImpl |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_xujin_int.java | {
"start": 582,
"end": 2195
} | class ____<T extends Serializable> implements Serializable {
private static final long serialVersionUID = 3682481175041925854L;
private static final String DEFAULT_ERR_CODE = "xin.unknown.error";
private String errorMsg;
private String errorCode;
private int success;
private T module;
public ResultDTO() {
buildSuccessResult();
}
public ResultDTO(T obj) {
this.success = 1;
this.module = obj;
}
public static <T extends Serializable> ResultDTO<T> buildSuccessResult() {
return new ResultDTO((Serializable)null);
}
public static <T extends Serializable> ResultDTO<T> buildSuccessResult(T obj) {
return new ResultDTO(obj);
}
public String getErrorMsg() {
return this.errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getErrorCode() {
return this.errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public int isSuccess() {
return this.success;
}
public void setSuccess(int success) {
this.success = success;
}
public T getModule() {
return this.module;
}
public void setModule(T module) {
this.module = module;
}
public String toJsonString() {
return JSON.toJSONString(this);
}
}
}
| ResultDTO |
java | resilience4j__resilience4j | resilience4j-spring-boot2/src/main/java/io/github/resilience4j/circuitbreaker/autoconfigure/CircuitBreakerProperties.java | {
"start": 906,
"end": 988
} | class ____ extends CircuitBreakerConfigurationProperties {
}
| CircuitBreakerProperties |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java | {
"start": 1541,
"end": 16828
} | class ____ extends AbstractMBeanServerTests {
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
void testRegisterNotificationListenerForMBean() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
JmxTestBean bean = new JmxTestBean();
Map<String, Object> beans = new HashMap<>();
beans.put(objectName.getCanonicalName(), bean);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
Map notificationListeners = new HashMap();
notificationListeners.put(objectName, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(notificationListeners);
start(exporter);
// update the attribute
String attributeName = "Name";
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
void testRegisterNotificationListenerWithWildcard() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
JmxTestBean bean = new JmxTestBean();
Map<String, Object> beans = new HashMap<>();
beans.put(objectName.getCanonicalName(), bean);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
Map notificationListeners = new HashMap();
notificationListeners.put("*", listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(notificationListeners);
start(exporter);
// update the attribute
String attributeName = "Name";
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1);
}
@Test
void testRegisterNotificationListenerWithHandback() throws Exception {
String objectName = "spring:name=Test";
JmxTestBean bean = new JmxTestBean();
Map<String, Object> beans = new HashMap<>();
beans.put(objectName, bean);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
Object handback = new Object();
NotificationListenerBean listenerBean = new NotificationListenerBean();
listenerBean.setNotificationListener(listener);
listenerBean.setMappedObjectName("spring:name=Test");
listenerBean.setHandback(handback);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(listenerBean);
start(exporter);
// update the attribute
String attributeName = "Name";
server.setAttribute(ObjectNameManager.getInstance("spring:name=Test"), new Attribute(attributeName,
"Rob Harrop"));
assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1);
assertThat(listener.getLastHandback(attributeName)).as("Handback object not transmitted correctly").isEqualTo(handback);
}
@Test
void testRegisterNotificationListenerForAllMBeans() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
JmxTestBean bean = new JmxTestBean();
Map<String, Object> beans = new HashMap<>();
beans.put(objectName.getCanonicalName(), bean);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
NotificationListenerBean listenerBean = new NotificationListenerBean();
listenerBean.setNotificationListener(listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(listenerBean);
start(exporter);
// update the attribute
String attributeName = "Name";
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1);
}
@SuppressWarnings("serial")
@Test
void testRegisterNotificationListenerWithFilter() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
JmxTestBean bean = new JmxTestBean();
Map<String, Object> beans = new HashMap<>();
beans.put(objectName.getCanonicalName(), bean);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
NotificationListenerBean listenerBean = new NotificationListenerBean();
listenerBean.setNotificationListener(listener);
listenerBean.setNotificationFilter(notification -> {
if (notification instanceof AttributeChangeNotification changeNotification) {
return "Name".equals(changeNotification.getAttributeName());
}
else {
return false;
}
});
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(listenerBean);
start(exporter);
// update the attributes
String nameAttribute = "Name";
String ageAttribute = "Age";
server.setAttribute(objectName, new Attribute(nameAttribute, "Rob Harrop"));
server.setAttribute(objectName, new Attribute(ageAttribute, 90));
assertThat(listener.getCount(nameAttribute)).as("Listener not notified for Name").isEqualTo(1);
assertThat(listener.getCount(ageAttribute)).as("Listener incorrectly notified for Age").isEqualTo(0);
}
@Test
void testCreationWithNoNotificationListenerSet() {
assertThatIllegalArgumentException().as("no NotificationListener supplied").isThrownBy(
new NotificationListenerBean()::afterPropertiesSet);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
void testRegisterNotificationListenerWithBeanNameAndBeanNameInBeansMap() throws Exception {
String beanName = "testBean";
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
SelfNamingTestBean testBean = new SelfNamingTestBean();
testBean.setObjectName(objectName);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerSingleton(beanName, testBean);
Map<String, Object> beans = new HashMap<>();
beans.put(beanName, beanName);
Map listenerMappings = new HashMap();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
listenerMappings.put(beanName, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(listenerMappings);
exporter.setBeanFactory(factory);
start(exporter);
assertIsRegistered("Should have registered MBean", objectName);
server.setAttribute(objectName, new Attribute("Age", 77));
assertThat(listener.getCount("Age")).as("Listener not notified").isEqualTo(1);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
void testRegisterNotificationListenerWithBeanNameAndBeanInstanceInBeansMap() throws Exception {
String beanName = "testBean";
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
SelfNamingTestBean testBean = new SelfNamingTestBean();
testBean.setObjectName(objectName);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerSingleton(beanName, testBean);
Map<String, Object> beans = new HashMap<>();
beans.put(beanName, testBean);
Map listenerMappings = new HashMap();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
listenerMappings.put(beanName, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(listenerMappings);
exporter.setBeanFactory(factory);
start(exporter);
assertIsRegistered("Should have registered MBean", objectName);
server.setAttribute(objectName, new Attribute("Age", 77));
assertThat(listener.getCount("Age")).as("Listener not notified").isEqualTo(1);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
void testRegisterNotificationListenerWithBeanNameBeforeObjectNameMappedToSameBeanInstance() throws Exception {
String beanName = "testBean";
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
SelfNamingTestBean testBean = new SelfNamingTestBean();
testBean.setObjectName(objectName);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerSingleton(beanName, testBean);
Map<String, Object> beans = new HashMap<>();
beans.put(beanName, testBean);
Map listenerMappings = new HashMap();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
listenerMappings.put(beanName, listener);
listenerMappings.put(objectName, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(listenerMappings);
exporter.setBeanFactory(factory);
start(exporter);
assertIsRegistered("Should have registered MBean", objectName);
server.setAttribute(objectName, new Attribute("Age", 77));
assertThat(listener.getCount("Age")).as("Listener should have been notified exactly once").isEqualTo(1);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
void testRegisterNotificationListenerWithObjectNameBeforeBeanNameMappedToSameBeanInstance() throws Exception {
String beanName = "testBean";
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
SelfNamingTestBean testBean = new SelfNamingTestBean();
testBean.setObjectName(objectName);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerSingleton(beanName, testBean);
Map<String, Object> beans = new HashMap<>();
beans.put(beanName, testBean);
Map listenerMappings = new HashMap();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
listenerMappings.put(objectName, listener);
listenerMappings.put(beanName, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(listenerMappings);
exporter.setBeanFactory(factory);
start(exporter);
assertIsRegistered("Should have registered MBean", objectName);
server.setAttribute(objectName, new Attribute("Age", 77));
assertThat(listener.getCount("Age")).as("Listener should have been notified exactly once").isEqualTo(1);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
void testRegisterNotificationListenerWithTwoBeanNamesMappedToDifferentBeanInstances() throws Exception {
String beanName1 = "testBean1";
String beanName2 = "testBean2";
ObjectName objectName1 = ObjectName.getInstance("spring:name=Test1");
ObjectName objectName2 = ObjectName.getInstance("spring:name=Test2");
SelfNamingTestBean testBean1 = new SelfNamingTestBean();
testBean1.setObjectName(objectName1);
SelfNamingTestBean testBean2 = new SelfNamingTestBean();
testBean2.setObjectName(objectName2);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerSingleton(beanName1, testBean1);
factory.registerSingleton(beanName2, testBean2);
Map<String, Object> beans = new HashMap<>();
beans.put(beanName1, testBean1);
beans.put(beanName2, testBean2);
Map listenerMappings = new HashMap();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
listenerMappings.put(beanName1, listener);
listenerMappings.put(beanName2, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(listenerMappings);
exporter.setBeanFactory(factory);
start(exporter);
assertIsRegistered("Should have registered MBean", objectName1);
assertIsRegistered("Should have registered MBean", objectName2);
server.setAttribute(ObjectNameManager.getInstance(objectName1), new Attribute("Age", 77));
assertThat(listener.getCount("Age")).as("Listener not notified for testBean1").isEqualTo(1);
server.setAttribute(ObjectNameManager.getInstance(objectName2), new Attribute("Age", 33));
assertThat(listener.getCount("Age")).as("Listener not notified for testBean2").isEqualTo(2);
}
@Test
void testNotificationListenerRegistrar() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
JmxTestBean bean = new JmxTestBean();
Map<String, Object> beans = new HashMap<>();
beans.put(objectName.getCanonicalName(), bean);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
start(exporter);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
NotificationListenerRegistrar registrar = new NotificationListenerRegistrar();
registrar.setServer(server);
registrar.setNotificationListener(listener);
registrar.setMappedObjectName(objectName);
registrar.afterPropertiesSet();
// update the attribute
String attributeName = "Name";
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1);
registrar.destroy();
// try to update the attribute again
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertThat(listener.getCount(attributeName)).as("Listener notified after destruction").isEqualTo(1);
}
@Test
void testNotificationListenerRegistrarWithMultipleNames() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
ObjectName objectName2 = ObjectName.getInstance("spring:name=Test2");
JmxTestBean bean = new JmxTestBean();
JmxTestBean bean2 = new JmxTestBean();
Map<String, Object> beans = new HashMap<>();
beans.put(objectName.getCanonicalName(), bean);
beans.put(objectName2.getCanonicalName(), bean2);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
start(exporter);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
NotificationListenerRegistrar registrar = new NotificationListenerRegistrar();
registrar.setServer(server);
registrar.setNotificationListener(listener);
//registrar.setMappedObjectNames(new Object[] {objectName, objectName2});
registrar.setMappedObjectNames("spring:name=Test", "spring:name=Test2");
registrar.afterPropertiesSet();
// update the attribute
String attributeName = "Name";
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1);
registrar.destroy();
// try to update the attribute again
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertThat(listener.getCount(attributeName)).as("Listener notified after destruction").isEqualTo(1);
}
@SuppressWarnings({"rawtypes", "unchecked"})
private static | NotificationListenerTests |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/util/Closer.java | {
"start": 944,
"end": 2143
} | class ____ {
private Closer() {
// empty
}
/**
* Closes an AutoCloseable or ignores if {@code null}.
*
* @param closeable the resource to close; may be null
* @return Whether the resource was closed.
* @throws Exception if the resource cannot be closed
* @since 2.8
* @since 2.11.2 returns a boolean instead of being a void return type.
*/
public static boolean close(final AutoCloseable closeable) throws Exception {
if (closeable != null) {
StatusLogger.getLogger().debug("Closing {} {}", closeable.getClass().getSimpleName(), closeable);
closeable.close();
return true;
}
return false;
}
/**
* Closes an AutoCloseable and returns {@code true} if it closed without exception.
*
* @param closeable the resource to close; may be null
* @return true if resource was closed successfully, or false if an exception was thrown
*/
public static boolean closeSilently(final AutoCloseable closeable) {
try {
return close(closeable);
} catch (final Exception ignored) {
return false;
}
}
}
| Closer |
java | netty__netty | common/src/main/java/io/netty/util/ResourceLeakHint.java | {
"start": 765,
"end": 935
} | interface ____ {
/**
* Returns a human-readable message that potentially enables easier resource leak tracking.
*/
String toHintString();
}
| ResourceLeakHint |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/array/BytePrimitiveArrayComparatorTest.java | {
"start": 993,
"end": 1658
} | class ____ extends PrimitiveArrayComparatorTestBase<byte[]> {
public BytePrimitiveArrayComparatorTest() {
super(PrimitiveArrayTypeInfo.BYTE_PRIMITIVE_ARRAY_TYPE_INFO);
}
@Override
protected void deepEquals(String message, byte[] should, byte[] is) {
assertThat(is).as(message).containsExactly(should);
}
@Override
protected byte[][] getSortedTestData() {
return new byte[][] {
new byte[] {-1, 0},
new byte[] {0, -1},
new byte[] {0, 0},
new byte[] {0, 1},
new byte[] {0, 1, 2},
new byte[] {2}
};
}
}
| BytePrimitiveArrayComparatorTest |
java | apache__kafka | server-common/src/main/java/org/apache/kafka/server/share/persister/DefaultStatePersister.java | {
"start": 1561,
"end": 1851
} | interface ____ is used by the
* group coordinator and share-partition leaders to manage the durable share-partition state.
* This implementation uses inter-broker RPCs to make requests to the share coordinator
* which is responsible for persisting the share-partition state.
*/
public | which |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/DefaultScheduledPollConsumerBridgeErrorHandlerTest.java | {
"start": 2813,
"end": 3064
} | class ____ extends DefaultComponent {
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) {
return new MyEndpoint(uri, this);
}
}
public static | MyComponent |
java | spring-projects__spring-boot | module/spring-boot-http-converter/src/main/java/org/springframework/boot/http/converter/autoconfigure/DefaultClientHttpMessageConvertersCustomizer.java | {
"start": 1145,
"end": 2719
} | class ____ implements ClientHttpMessageConvertersCustomizer {
private final @Nullable HttpMessageConverters legacyConverters;
private final Collection<HttpMessageConverter<?>> converters;
DefaultClientHttpMessageConvertersCustomizer(@Nullable HttpMessageConverters legacyConverters,
Collection<HttpMessageConverter<?>> converters) {
this.legacyConverters = legacyConverters;
this.converters = converters;
}
@Override
public void customize(ClientBuilder builder) {
if (this.legacyConverters != null) {
this.legacyConverters.forEach(builder::addCustomConverter);
}
else {
builder.registerDefaults();
this.converters.forEach((converter) -> {
if (converter instanceof StringHttpMessageConverter) {
builder.withStringConverter(converter);
}
else if (converter instanceof KotlinSerializationJsonHttpMessageConverter) {
builder.withKotlinSerializationJsonConverter(converter);
}
else if (supportsMediaType(converter, MediaType.APPLICATION_JSON)) {
builder.withJsonConverter(converter);
}
else if (supportsMediaType(converter, MediaType.APPLICATION_XML)) {
builder.withXmlConverter(converter);
}
else {
builder.addCustomConverter(converter);
}
});
}
}
private static boolean supportsMediaType(HttpMessageConverter<?> converter, MediaType mediaType) {
for (MediaType supportedMediaType : converter.getSupportedMediaTypes()) {
if (supportedMediaType.equalsTypeAndSubtype(mediaType)) {
return true;
}
}
return false;
}
}
| DefaultClientHttpMessageConvertersCustomizer |
java | quarkusio__quarkus | integration-tests/vertx-http/src/main/java/io/quarkus/it/vertx/SimpleResource.java | {
"start": 185,
"end": 486
} | class ____ {
@GET
@Path("/access-log-test-endpoint")
public String accessLogTest() {
return "passed";
}
@OPTIONS
@Path("/options")
public Response optionsHandler() {
return Response.ok("options").header("X-Custom-Header", "abc").build();
}
}
| SimpleResource |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/util/URLs_contentOf_Test.java | {
"start": 1242,
"end": 2145
} | class ____ {
private final URL sampleResourceURL = resourceURL("utf8.txt");
private final String expectedContent = "A text file encoded in UTF-8, with diacritics:\né à";
@Test
void should_throw_exception_if_url_not_found() {
File missingFile = new File("missing.txt");
assertThat(missingFile.exists()).isFalse();
assertThatExceptionOfType(UncheckedIOException.class).isThrownBy(() -> URLs.contentOf(missingFile.toURI().toURL(),
Charset.defaultCharset()));
}
@Test
void should_load_resource_from_url_using_charset() {
assertThat(URLs.contentOf(sampleResourceURL, UTF_8)).isEqualTo(expectedContent);
}
@Test
void should_load_resource_from_url_using_charset_name() {
assertThat(URLs.contentOf(sampleResourceURL, "UTF-8")).isEqualTo(expectedContent);
}
}
| URLs_contentOf_Test |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cache/CollectionCacheEvictionWithoutMappedByTest.java | {
"start": 4807,
"end": 4901
} | class ____ {
@Id
@GeneratedValue
private Integer id;
protected Person() {
}
}
}
| Person |
java | apache__dubbo | dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java | {
"start": 1471,
"end": 2100
} | class ____ {
private Invoker<?> invoker = mock(Invoker.class);
private Validation validation = mock(Validation.class);
private Validator validator = mock(Validator.class);
private RpcInvocation invocation = mock(RpcInvocation.class);
private ValidationFilter validationFilter;
@BeforeEach
public void setUp() {
this.validationFilter = new ValidationFilter();
}
@Test
void testItWithNotExistClass() {
URL url = URL.valueOf("test://test:11/test?validation=true");
given(validation.getValidator(url)).willThrow(new IllegalStateException("Not found | ValidationFilterTest |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/ser/PropertyWriter.java | {
"start": 1556,
"end": 5546
} | class ____ making that apply to all properties
* unless overridden by per-property annotations.
*<p>
* This method is functionally equivalent to:
*<pre>
* MyAnnotation ann = propWriter.getAnnotation(MyAnnotation.class);
* if (ann == null) {
* ann = propWriter.getContextAnnotation(MyAnnotation.class);
* }
*</pre>
* that is, tries to find a property annotation first, but if one is not
* found, tries to find context-annotation (from enclosing class) of
* same type.
*
* @since 2.5
*/
public <A extends Annotation> A findAnnotation(Class<A> acls) {
A ann = getAnnotation(acls);
if (ann == null) {
ann = getContextAnnotation(acls);
}
return ann;
}
/**
* Method for accessing annotations directly declared for property that this
* writer is associated with.
*
* @since 2.5
*/
@Override
public abstract <A extends Annotation> A getAnnotation(Class<A> acls);
/**
* Method for accessing annotations declared in context of the property that this
* writer is associated with; usually this means annotations on enclosing class
* for property.
*/
@Override
public abstract <A extends Annotation> A getContextAnnotation(Class<A> acls);
/*
/**********************************************************************
/* Serialization methods, regular output
/**********************************************************************
*/
/**
* The main serialization method called by filter when property is to be written
* as an Object property.
*/
public abstract void serializeAsProperty(Object value, JsonGenerator g, SerializationContext provider)
throws Exception;
/**
* Serialization method that filter needs to call in cases where a property value
* (key, value) is to be
* filtered, but the underlying data format requires a placeholder of some kind.
* This is usually the case for tabular (positional) data formats such as CSV.
*/
public abstract void serializeAsOmittedProperty(Object value, JsonGenerator g, SerializationContext provider)
throws Exception;
/*
/**********************************************************************
/* Serialization methods, explicit positional/tabular formats
/**********************************************************************
*/
/**
* Serialization method called when output is to be done as an array,
* that is, not using property names. This is needed when serializing
* container ({@link java.util.Collection}, array) types,
* or POJOs using <code>tabular</code> ("as array") output format.
*<p>
* Note that this mode of operation is independent of underlying
* data format; so it is typically NOT called for fully tabular formats such as CSV,
* where logical output is still as form of POJOs.
*/
public abstract void serializeAsElement(Object value, JsonGenerator g, SerializationContext provider)
throws Exception;
/**
* Serialization method called when doing tabular (positional) output from databind,
* but then value is to be omitted. This requires output of a placeholder value
* of some sort; often similar to {@link #serializeAsOmittedProperty}.
*/
public abstract void serializeAsOmittedElement(Object value, JsonGenerator g, SerializationContext provider)
throws Exception;
/*
/**********************************************************************
/* Schema-related
/**********************************************************************
*/
/**
* Traversal method used for things like JSON Schema generation, or
* POJO introspection.
*/
@Override
public abstract void depositSchemaProperty(JsonObjectFormatVisitor objectVisitor,
SerializationContext provider);
}
| and |
java | google__guava | android/guava-tests/test/com/google/common/reflect/ClassPathTest.java | {
"start": 18279,
"end": 23595
} | class ____ {}
public void testNulls() throws IOException {
new NullPointerTester().testAllPublicStaticMethods(ClassPath.class);
new NullPointerTester()
.testAllPublicInstanceMethods(ClassPath.from(getClass().getClassLoader()));
}
@AndroidIncompatible // ClassPath is documented as not supporting Android
public void testLocationsFrom_idempotentScan() throws IOException {
ImmutableSet<ClassPath.LocationInfo> locations =
ClassPath.locationsFrom(getClass().getClassLoader());
assertThat(locations).isNotEmpty();
for (ClassPath.LocationInfo location : locations) {
ImmutableSet<ResourceInfo> resources = location.scanResources();
assertThat(location.scanResources()).containsExactlyElementsIn(resources);
}
}
public void testLocationsFrom_idempotentLocations() {
ImmutableSet<ClassPath.LocationInfo> locations =
ClassPath.locationsFrom(getClass().getClassLoader());
assertThat(ClassPath.locationsFrom(getClass().getClassLoader()))
.containsExactlyElementsIn(locations);
}
public void testLocationEquals() {
ClassLoader child = getClass().getClassLoader();
ClassLoader parent = child.getParent();
new EqualsTester()
.addEqualityGroup(
new ClassPath.LocationInfo(new File("foo.jar"), child),
new ClassPath.LocationInfo(new File("foo.jar"), child))
.addEqualityGroup(new ClassPath.LocationInfo(new File("foo.jar"), parent))
.addEqualityGroup(new ClassPath.LocationInfo(new File("foo"), child))
.testEquals();
}
@AndroidIncompatible // ClassPath is documented as not supporting Android
public void testScanAllResources() throws IOException {
assertThat(scanResourceNames(ClassLoader.getSystemClassLoader()))
.contains("com/google/common/reflect/ClassPathTest.class");
}
private static ClassPath.ClassInfo findClass(
Iterable<ClassPath.ClassInfo> classes, Class<?> cls) {
for (ClassPath.ClassInfo classInfo : classes) {
if (classInfo.getName().equals(cls.getName())) {
return classInfo;
}
}
throw new AssertionError("failed to find " + cls);
}
private static ResourceInfo resourceInfo(Class<?> cls) {
String resource = cls.getName().replace('.', '/') + ".class";
ClassLoader loader = cls.getClassLoader();
return ResourceInfo.of(FILE, resource, loader);
}
private static ClassInfo classInfo(Class<?> cls) {
return classInfo(cls, cls.getClassLoader());
}
private static ClassInfo classInfo(Class<?> cls, ClassLoader classLoader) {
String resource = cls.getName().replace('.', '/') + ".class";
return new ClassInfo(FILE, resource, classLoader);
}
private static Manifest manifestClasspath(String classpath) throws IOException {
return manifest("Class-Path: " + classpath + "\n");
}
private static void writeSelfReferencingJarFile(File jarFile, String... entries)
throws IOException {
Manifest manifest = new Manifest();
// Without version, the manifest is silently ignored. Ugh!
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, jarFile.getName());
Closer closer = Closer.create();
try {
FileOutputStream fileOut = closer.register(new FileOutputStream(jarFile));
JarOutputStream jarOut = closer.register(new JarOutputStream(fileOut, manifest));
for (String entry : entries) {
jarOut.putNextEntry(new ZipEntry(entry));
Resources.copy(ClassPathTest.class.getResource(entry), jarOut);
jarOut.closeEntry();
}
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
private static Manifest manifest(String content) throws IOException {
InputStream in = new ByteArrayInputStream(content.getBytes(US_ASCII));
Manifest manifest = new Manifest();
manifest.read(in);
return manifest;
}
private static File fullpath(String path) {
return new File(new File(path).toURI());
}
private static URL makeJarUrlWithName(String name) throws IOException {
/*
* TODO: cpovirk - Use java.nio.file.Files.createTempDirectory instead of
* c.g.c.io.Files.createTempDir?
*/
File fullPath = new File(Files.createTempDir(), name);
File jarFile = pickAnyJarFile();
Files.copy(jarFile, fullPath);
return fullPath.toURI().toURL();
}
private static File pickAnyJarFile() throws IOException {
for (ClassPath.LocationInfo location :
ClassPath.locationsFrom(ClassPathTest.class.getClassLoader())) {
if (!location.file().isDirectory() && location.file().exists()) {
return location.file();
}
}
throw new AssertionError("Failed to find a jar file");
}
private static ImmutableSet<String> scanResourceNames(ClassLoader loader) throws IOException {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
for (ClassPath.LocationInfo location : ClassPath.locationsFrom(loader)) {
for (ResourceInfo resource : location.scanResources()) {
builder.add(resource.getResourceName());
}
}
return builder.build();
}
private static boolean isWindows() {
return OS_NAME.value().startsWith("Windows");
}
}
| Nested |
java | google__guava | android/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java | {
"start": 5369,
"end": 5720
} | class ____ {}
TesterRequirements requirements = buildTesterRequirements(Tester.class);
assertThat(requirements.getPresentFeatures()).isEmpty();
assertThat(requirements.getAbsentFeatures()).isEmpty();
}
public void testBuildTesterRequirements_class_present() throws Exception {
@Require({IMPLIES_IMPLIES_FOO, IMPLIES_BAR})
| Tester |
java | hibernate__hibernate-orm | local-build-plugins/src/main/java/org/hibernate/orm/properties/SettingDescriptorComparator.java | {
"start": 518,
"end": 1622
} | class ____ implements Comparator<SettingDescriptor> {
public static final SettingDescriptorComparator INSTANCE = new SettingDescriptorComparator();
public static final String JPA_PREFIX = "jakarta.persistence.";
public static final String HIBERNATE_PREFIX = "hibernate.";
public static final String LEGACY_JPA_PREFIX = "javax.persistence.";
@Override
public int compare(SettingDescriptor o1, SettingDescriptor o2) {
if ( o1.getName().startsWith( JPA_PREFIX ) ) {
if ( o2.getName().startsWith( JPA_PREFIX ) ) {
return o1.getName().compareTo( o2.getName() );
}
return -1;
}
if ( o1.getName().startsWith( HIBERNATE_PREFIX ) ) {
if ( o2.getName().startsWith( JPA_PREFIX ) ) {
return 1;
}
if ( o2.getName().startsWith( HIBERNATE_PREFIX ) ) {
return o1.getName().compareTo( o2.getName() );
}
return -1;
}
assert o1.getName().startsWith( LEGACY_JPA_PREFIX );
if ( o2.getName().startsWith( JPA_PREFIX )
|| o2.getName().startsWith( HIBERNATE_PREFIX ) ) {
return 1;
}
return o1.getName().compareTo( o2.getName() );
}
}
| SettingDescriptorComparator |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/language/LanguageAnnotation.java | {
"start": 1188,
"end": 1290
} | interface ____ {
String language();
Class<?> factory() default Object.class;
}
| LanguageAnnotation |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/metadata/TotalFeatureImportance.java | {
"start": 8301,
"end": 11746
} | class ____ implements ToXContentObject, Writeable {
private static final String NAME = "total_class_importance";
public static final ParseField CLASS_NAME = new ParseField("class_name");
public static final ParseField IMPORTANCE = new ParseField("importance");
// These parsers follow the pattern that metadata is parsed leniently (to allow for enhancements), whilst config is parsed strictly
public static final ConstructingObjectParser<ClassImportance, Void> LENIENT_PARSER = createParser(true);
public static final ConstructingObjectParser<ClassImportance, Void> STRICT_PARSER = createParser(false);
private static ConstructingObjectParser<ClassImportance, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<ClassImportance, Void> parser = new ConstructingObjectParser<>(
NAME,
ignoreUnknownFields,
a -> new ClassImportance(a[0], (Importance) a[1])
);
parser.declareField(ConstructingObjectParser.constructorArg(), (p, c) -> {
if (p.currentToken() == XContentParser.Token.VALUE_STRING) {
return p.text();
} else if (p.currentToken() == XContentParser.Token.VALUE_NUMBER) {
return p.numberValue();
} else if (p.currentToken() == XContentParser.Token.VALUE_BOOLEAN) {
return p.booleanValue();
}
throw new XContentParseException("Unsupported token [" + p.currentToken() + "]");
}, CLASS_NAME, ObjectParser.ValueType.VALUE);
parser.declareObject(
ConstructingObjectParser.constructorArg(),
ignoreUnknownFields ? Importance.LENIENT_PARSER : Importance.STRICT_PARSER,
IMPORTANCE
);
return parser;
}
public final Object className;
public final Importance importance;
public ClassImportance(StreamInput in) throws IOException {
this.className = in.readGenericValue();
this.importance = new Importance(in);
}
ClassImportance(Object className, Importance importance) {
this.className = className;
this.importance = importance;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeGenericValue(className);
importance.writeTo(out);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.map(asMap());
}
private Map<String, Object> asMap() {
Map<String, Object> map = new LinkedHashMap<>();
map.put(CLASS_NAME.getPreferredName(), className);
map.put(IMPORTANCE.getPreferredName(), importance.asMap());
return map;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClassImportance that = (ClassImportance) o;
return Objects.equals(that.importance, importance) && Objects.equals(className, that.className);
}
@Override
public int hashCode() {
return Objects.hash(className, importance);
}
}
}
| ClassImportance |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/nestedfetch/NestedFetchTest.java | {
"start": 1521,
"end": 3515
} | class ____ {
@BeforeAll
public void createTestData(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final Product sprocket = new Product( 1, "Sprocket" );
final Product thingamajig = new Product( 2, "Thingamajig" );
session.persist( sprocket );
session.persist( thingamajig );
final Customer ibm = new Customer( 1, "IBM" );
session.persist( ibm );
final Order order = new Order( 1, "ibm-1", ibm );
order.addOrderLine( sprocket, 20 );
order.addOrderLine( thingamajig, 1500 );
session.persist( order );
} );
}
@AfterAll
public void tearDown(SessionFactoryScope scope) {
scope.dropData();
}
@Test
public void testNestedFetch(SessionFactoryScope scope) {
final SQLStatementInspector sqlCollector = scope.getCollectingStatementInspector();
sqlCollector.clear();
final Customer customer = scope.fromTransaction( (session) -> {
final CriteriaBuilder cb = session.getCriteriaBuilder();
final CriteriaQuery<Customer> criteria = cb.createQuery( Customer.class );
final Root<Customer> fromRoot = criteria.from( Customer.class );
final Fetch<Customer, Order> ordersFetch = fromRoot.fetch( "orders", JoinType.LEFT );
final Fetch<Order, OrderLine> linesFetch = ordersFetch.fetch( "lines", JoinType.LEFT );
final Fetch<OrderLine, Product> productFetch = linesFetch.fetch( "product", JoinType.LEFT );
return session.createQuery( criteria.select( fromRoot ) ).getSingleResult();
} );
// make sure that the fetches really got fetched...
assertThat( customer.orders ).hasSize( 1 );
final Order order = customer.orders.iterator().next();
assertThat( order.lines ).hasSize( 2 );
assertThat( order.lines.stream().map( orderLine -> orderLine.product.name ) )
.contains( "Sprocket", "Thingamajig" );
// should have happened by joins
assertThat( sqlCollector.getSqlQueries() ).hasSize( 1 );
}
@Entity
@Table(name="products")
@SuppressWarnings({"FieldCanBeLocal", "unused"})
public static | NestedFetchTest |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/StandardFunctionReturnTypeResolvers.java | {
"start": 1001,
"end": 9507
} | class ____ {
/**
* Disallow instantiation
*/
private StandardFunctionReturnTypeResolvers() {
}
/**
* A resolver that defines an invariant result type. E.g. `substring` always
* returns a String. Note however that to account for attribute converters and
* such, this resolver allows the context-implied expression type to be the
* return type so long as the Java types are compatible.
*/
public static FunctionReturnTypeResolver invariant(BasicType<?> invariantType) {
if ( invariantType == null ) {
throw new IllegalArgumentException( "Passed `invariantType` for function return cannot be null" );
}
return new FunctionReturnTypeResolver() {
@Override
public ReturnableType<?> resolveFunctionReturnType(
ReturnableType<?> impliedType,
@Nullable SqmToSqlAstConverter converter,
List<? extends SqmTypedNode<?>> arguments,
TypeConfiguration typeConfiguration) {
return isAssignableTo( invariantType, impliedType ) ? impliedType : invariantType;
}
@Override
public BasicValuedMapping resolveFunctionReturnType(
Supplier<BasicValuedMapping> impliedTypeAccess,
List<? extends SqlAstNode> arguments) {
return useImpliedTypeIfPossible( invariantType, impliedTypeAccess.get() );
}
@Override
public String getReturnType() {
return invariantType.getJavaType().getSimpleName();
}
};
}
public static FunctionReturnTypeResolver useArgType(int argPosition) {
return new FunctionReturnTypeResolver() {
@Override
public ReturnableType<?> resolveFunctionReturnType(
ReturnableType<?> impliedType,
@Nullable SqmToSqlAstConverter converter,
List<? extends SqmTypedNode<?>> arguments,
TypeConfiguration typeConfiguration) {
final var argType = extractArgumentType( arguments, argPosition );
return isAssignableTo( argType, impliedType ) ? impliedType : argType;
}
@Override
public BasicValuedMapping resolveFunctionReturnType(
Supplier<BasicValuedMapping> impliedTypeAccess,
List<? extends SqlAstNode> arguments) {
final var specifiedArgType = extractArgumentValuedMapping( arguments, argPosition );
return useImpliedTypeIfPossible( specifiedArgType, impliedTypeAccess.get() );
}
};
}
public static FunctionReturnTypeResolver useFirstNonNull() {
return new FunctionReturnTypeResolver() {
@Override
public BasicValuedMapping resolveFunctionReturnType(
Supplier<BasicValuedMapping> impliedTypeAccess,
List<? extends SqlAstNode> arguments) {
for ( SqlAstNode arg: arguments ) {
if ( arg instanceof Expression expression
&& expression.getExpressionType() instanceof BasicValuedMapping argType ) {
return useImpliedTypeIfPossible( argType, impliedTypeAccess.get() );
}
}
return impliedTypeAccess.get();
}
@Override
public ReturnableType<?> resolveFunctionReturnType(
ReturnableType<?> impliedType,
@Nullable SqmToSqlAstConverter converter,
List<? extends SqmTypedNode<?>> arguments,
TypeConfiguration typeConfiguration) {
for ( int i = 0; i < arguments.size(); i++ ) {
if ( arguments.get( i ) != null ) {
final var argType = extractArgumentType( arguments, i + 1 );
if ( argType != null ) {
return isAssignableTo( argType, impliedType ) ? impliedType : argType;
}
}
}
return impliedType;
}
};
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Internal helpers
@Internal
public static boolean isAssignableTo(ReturnableType<?> defined, ReturnableType<?> implied) {
if ( implied == null ) {
return false;
}
else if ( defined == null ) {
return true;
}
else {
return implied instanceof BasicType<?> impliedType
&& defined instanceof BasicType<?> definedType
&& isAssignableTo( definedType.getJdbcMapping(), impliedType.getJdbcMapping() );
}
}
@Internal
public static boolean isAssignableTo(JdbcMapping defined, JdbcMapping implied) {
//This list of cases defines legal promotions from a SQL function return
//type specified in the function template (i.e. in the Dialect) and a type
//that is determined by how the function is used in the HQL query. In essence
//the types are compatible if the map to the same JDBC type, of if they are
//both numeric types.
final int impliedTypeCode = implied.getJdbcType().getDefaultSqlTypeCode();
final int definedTypeCode = defined.getJdbcType().getDefaultSqlTypeCode();
return impliedTypeCode == definedTypeCode
|| isNumericType( impliedTypeCode ) && isNumericType( definedTypeCode )
|| isCharacterOrClobType( impliedTypeCode ) && isCharacterOrClobType( definedTypeCode );
}
@Internal
public static BasicValuedMapping useImpliedTypeIfPossible(BasicValuedMapping defined, BasicValuedMapping implied) {
if ( defined == null ) {
return implied;
}
else if ( implied == null ) {
return defined;
}
else {
return areCompatible( defined, implied ) ? implied : defined;
}
}
private static boolean areCompatible(BasicValuedMapping defined, BasicValuedMapping implied) {
if ( defined == null || implied == null) {
return true;
}
else if ( defined.getJdbcMapping() == null ) {
return true;
}
else if ( implied.getJdbcMapping() == null ) {
return true;
}
else {
//This list of cases defines legal promotions from a SQL function return
//type specified in the function template (i.e. in the Dialect) and a type
//that is determined by how the function is used in the HQL query. In essence
//the types are compatible if the map to the same JDBC type, of if they are
//both numeric types.
return isAssignableTo( defined.getJdbcMapping(), implied.getJdbcMapping() );
}
}
public static ReturnableType<?> extractArgumentType(List<? extends SqmTypedNode<?>> arguments, int position) {
final SqmTypedNode<?> specifiedArgument = arguments.get( position - 1 );
final SqmExpressible<?> specifiedArgType = getArgumentExpressible( specifiedArgument );
if ( specifiedArgType == null ) {
return null;
}
else if ( specifiedArgType instanceof ReturnableType<?> returnableType ) {
return returnableType;
}
else {
throw new FunctionArgumentException(
String.format(
Locale.ROOT,
"Function argument [%s] of type [%s] at specified position [%d] in call arguments was not typed as an allowable function return type",
specifiedArgument,
specifiedArgType,
position
)
);
}
}
private static SqmExpressible<?> getArgumentExpressible(SqmTypedNode<?> specifiedArgument) {
final SqmExpressible<?> expressible = specifiedArgument.getExpressible();
return expressible != null ? expressible.getSqmType() : null;
}
// public static JdbcMapping extractArgumentJdbcMapping(
// TypeConfiguration typeConfiguration,
// List<? extends SqmTypedNode<?>> arguments,
// int position) {
// final SqmTypedNode<?> specifiedArgument = arguments.get( position - 1 );
// final SqmExpressible<?> specifiedArgType = specifiedArgument.getNodeType();
// if ( specifiedArgType instanceof BasicType<?> ) {
// return ( (BasicType<?>) specifiedArgType ).getJdbcMapping();
// }
// else {
// final BasicType<?> basicType = typeConfiguration.getBasicTypeForJavaType(
// specifiedArgType.getExpressibleJavaType().getJavaTypeClass()
// );
// if ( basicType == null ) {
// throw new FunctionArgumentException(
// String.format(
// Locale.ROOT,
// "Function argument [%s] of type [%s] at specified position [%d] in call arguments was not typed as basic type",
// specifiedArgument,
// specifiedArgType,
// position
// )
// );
// }
//
// return basicType.getJdbcMapping();
// }
// }
public static BasicValuedMapping extractArgumentValuedMapping(List<? extends SqlAstNode> arguments, int position) {
final SqlAstNode specifiedArgument = arguments.get( position-1 );
final var specifiedArgType =
specifiedArgument instanceof Expression expression
? expression.getExpressionType()
: null;
if ( specifiedArgType instanceof BasicValuedMapping basicValuedMapping ) {
return basicValuedMapping;
}
else {
throw new FunctionArgumentException(
String.format(
Locale.ROOT,
"Function argument [%s] at specified position [%d] in call arguments was not typed as an allowable function return type",
specifiedArgument,
position
)
);
}
}
}
| StandardFunctionReturnTypeResolvers |
java | netty__netty | common/src/main/java/io/netty/util/DomainWildcardMappingBuilder.java | {
"start": 997,
"end": 3937
} | class ____<V> {
private final V defaultValue;
private final Map<String, V> map;
/**
* Constructor with default initial capacity of the map holding the mappings
*
* @param defaultValue the default value for {@link Mapping#map(Object)} )} to return
* when nothing matches the input
*/
public DomainWildcardMappingBuilder(V defaultValue) {
this(4, defaultValue);
}
/**
* Constructor with initial capacity of the map holding the mappings
*
* @param initialCapacity initial capacity for the internal map
* @param defaultValue the default value for {@link Mapping#map(Object)} to return
* when nothing matches the input
*/
public DomainWildcardMappingBuilder(int initialCapacity, V defaultValue) {
this.defaultValue = checkNotNull(defaultValue, "defaultValue");
map = new LinkedHashMap<String, V>(initialCapacity);
}
/**
* Adds a mapping that maps the specified (optionally wildcard) host name to the specified output value.
* {@code null} values are forbidden for both hostnames and values.
* <p>
* <a href="https://tools.ietf.org/search/rfc6125#section-6.4">DNS wildcard</a> is supported as hostname. The
* wildcard will only match one sub-domain deep and only when wildcard is used as the most-left label.
*
* For example:
*
* <p>
* *.netty.io will match xyz.netty.io but NOT abc.xyz.netty.io
* </p>
*
* @param hostname the host name (optionally wildcard)
* @param output the output value that will be returned by {@link Mapping#map(Object)}
* when the specified host name matches the specified input host name
*/
public DomainWildcardMappingBuilder<V> add(String hostname, V output) {
map.put(normalizeHostName(hostname),
checkNotNull(output, "output"));
return this;
}
private String normalizeHostName(String hostname) {
checkNotNull(hostname, "hostname");
if (hostname.isEmpty() || hostname.charAt(0) == '.') {
throw new IllegalArgumentException("Hostname '" + hostname + "' not valid");
}
hostname = ImmutableDomainWildcardMapping.normalize(checkNotNull(hostname, "hostname"));
if (hostname.charAt(0) == '*') {
if (hostname.length() < 3 || hostname.charAt(1) != '.') {
throw new IllegalArgumentException("Wildcard Hostname '" + hostname + "'not valid");
}
return hostname.substring(1);
}
return hostname;
}
/**
* Creates a new instance of an immutable {@link Mapping}.
*
* @return new {@link Mapping} instance
*/
public Mapping<String, V> build() {
return new ImmutableDomainWildcardMapping<V>(defaultValue, map);
}
private static final | DomainWildcardMappingBuilder |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java | {
"start": 2869,
"end": 3759
} | class ____ {
private AroundAdviceBindingCollaborator collaborator = null;
public void setCollaborator(AroundAdviceBindingCollaborator aCollaborator) {
this.collaborator = aCollaborator;
}
// "advice" methods
public void oneIntArg(ProceedingJoinPoint pjp, int age) throws Throwable {
this.collaborator.oneIntArg(age);
pjp.proceed();
}
public int oneObjectArg(ProceedingJoinPoint pjp, Object bean) throws Throwable {
this.collaborator.oneObjectArg(bean);
return (Integer) pjp.proceed();
}
public void oneIntAndOneObject(ProceedingJoinPoint pjp, int x , Object o) throws Throwable {
this.collaborator.oneIntAndOneObject(x,o);
pjp.proceed();
}
public int justJoinPoint(ProceedingJoinPoint pjp) throws Throwable {
this.collaborator.justJoinPoint(pjp.getSignature().getName());
return (Integer) pjp.proceed();
}
/**
* Collaborator | AroundAdviceBindingTestAspect |
java | netty__netty | example/src/main/java/io/netty/example/discard/DiscardServerHandler.java | {
"start": 821,
"end": 1237
} | class ____ extends SimpleChannelInboundHandler<Object> {
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
// discard
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
| DiscardServerHandler |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/typeutils/SortedMapSerializer.java | {
"start": 1649,
"end": 4240
} | class ____<K, V> extends AbstractMapSerializer<K, V, SortedMap<K, V>> {
private static final long serialVersionUID = 1L;
/** The comparator for the keys in the map. */
private final Comparator<K> comparator;
/**
* Constructor with given comparator, and the serializers for the keys and values in the map.
*
* @param comparator The comparator for the keys in the map.
* @param keySerializer The serializer for the keys in the map.
* @param valueSerializer The serializer for the values in the map.
*/
public SortedMapSerializer(
Comparator<K> comparator,
TypeSerializer<K> keySerializer,
TypeSerializer<V> valueSerializer) {
super(keySerializer, valueSerializer);
this.comparator = comparator;
}
/**
* Returns the comparator for the keys in the map.
*
* @return The comparator for the keys in the map.
*/
public Comparator<K> getComparator() {
return comparator;
}
@Override
public TypeSerializer<SortedMap<K, V>> duplicate() {
TypeSerializer<K> keySerializer = getKeySerializer().duplicate();
TypeSerializer<V> valueSerializer = getValueSerializer().duplicate();
return new SortedMapSerializer<>(comparator, keySerializer, valueSerializer);
}
@Override
public SortedMap<K, V> createInstance() {
return new TreeMap<>(comparator);
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) {
return false;
}
SortedMapSerializer<?, ?> that = (SortedMapSerializer<?, ?>) o;
return comparator.equals(that.comparator);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = result * 31 + comparator.hashCode();
return result;
}
@Override
public String toString() {
return "SortedMapSerializer{"
+ "comparator = "
+ comparator
+ ", keySerializer = "
+ keySerializer
+ ", valueSerializer = "
+ valueSerializer
+ "}";
}
// --------------------------------------------------------------------------------------------
// Serializer configuration snapshot
// --------------------------------------------------------------------------------------------
@Override
public TypeSerializerSnapshot<SortedMap<K, V>> snapshotConfiguration() {
return new SortedMapSerializerSnapshot<>(this);
}
}
| SortedMapSerializer |
java | quarkusio__quarkus | extensions/infinispan-cache/runtime/src/main/java/io/quarkus/cache/infinispan/runtime/InfinispanCacheBuildRecorder.java | {
"start": 484,
"end": 3057
} | class ____ {
private static final Logger LOGGER = Logger.getLogger(InfinispanCacheBuildRecorder.class);
private final InfinispanCachesBuildTimeConfig buildConfig;
private final RuntimeValue<InfinispanCachesConfig> infinispanCacheConfigRV;
public InfinispanCacheBuildRecorder(InfinispanCachesBuildTimeConfig buildConfig,
RuntimeValue<InfinispanCachesConfig> infinispanCacheConfigRV) {
this.buildConfig = buildConfig;
this.infinispanCacheConfigRV = infinispanCacheConfigRV;
}
public CacheManagerInfo getCacheManagerSupplier() {
return new CacheManagerInfo() {
@Override
public boolean supports(Context context) {
return context.cacheEnabled() && "infinispan".equals(context.cacheType());
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Supplier<CacheManager> get(Context context) {
return new Supplier<CacheManager>() {
@Override
public CacheManager get() {
Set<InfinispanCacheInfo> cacheInfos = InfinispanCacheInfoBuilder.build(context.cacheNames(),
buildConfig,
infinispanCacheConfigRV.getValue());
if (cacheInfos.isEmpty()) {
return new CacheManagerImpl(Collections.emptyMap());
} else {
// The number of caches is known at build time so we can use fixed initialCapacity and loadFactor for the caches map.
Map<String, Cache> caches = new HashMap<>(cacheInfos.size() + 1, 1.0F);
for (InfinispanCacheInfo cacheInfo : cacheInfos) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debugf(
"Building Infinispan cache [%s] with [lifespan=%s], [maxIdle=%s]",
cacheInfo.name, cacheInfo.lifespan, cacheInfo.maxIdle);
}
InfinispanCacheImpl cache = new InfinispanCacheImpl(cacheInfo, buildConfig.clientName());
caches.put(cacheInfo.name, cache);
}
return new CacheManagerImpl(caches);
}
}
};
}
};
}
}
| InfinispanCacheBuildRecorder |
java | apache__flink | flink-connectors/flink-hadoop-compatibility/src/test/java/org/apache/flink/test/hadoopcompatibility/mapred/HadoopIOFormatsITCase.java | {
"start": 3057,
"end": 7120
} | class ____ extends JavaProgramTestBase {
private static final int NUM_PROGRAMS = 2;
@Parameter private int curProgId;
private String[] resultPath;
private String[] expectedResult;
private String sequenceFileInPath;
private String sequenceFileInPathNull;
@BeforeEach
void checkOperatingSystem() {
// FLINK-5164 - see https://wiki.apache.org/hadoop/WindowsProblems
assumeThat(OperatingSystem.isWindows())
.as("This test can't run successfully on Windows.")
.isFalse();
}
@Override
@TestTemplate
public void testJobWithObjectReuse() throws Exception {
super.testJobWithoutObjectReuse();
}
@Override
@TestTemplate
public void testJobWithoutObjectReuse() throws Exception {
super.testJobWithoutObjectReuse();
}
@Override
protected void preSubmit() throws Exception {
resultPath = new String[] {getTempDirPath("result0"), getTempDirPath("result1")};
File sequenceFile = createAndRegisterTempFile("seqFile");
sequenceFileInPath = sequenceFile.toURI().toString();
// Create a sequence file
org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
FileSystem fs = FileSystem.get(URI.create(sequenceFile.getAbsolutePath()), conf);
Path path = new Path(sequenceFile.getAbsolutePath());
// ------------------ Long / Text Key Value pair: ------------
int kvCount = 4;
LongWritable key = new LongWritable();
Text value = new Text();
SequenceFile.Writer writer = null;
try {
writer = SequenceFile.createWriter(fs, conf, path, key.getClass(), value.getClass());
for (int i = 0; i < kvCount; i++) {
if (i == 1) {
// write key = 0 a bit more often.
for (int a = 0; a < 15; a++) {
key.set(i);
value.set(i + " - somestring");
writer.append(key, value);
}
}
key.set(i);
value.set(i + " - somestring");
writer.append(key, value);
}
} finally {
IOUtils.closeStream(writer);
}
// ------------------ Long / Text Key Value pair: ------------
File sequenceFileNull = createAndRegisterTempFile("seqFileNullKey");
sequenceFileInPathNull = sequenceFileNull.toURI().toString();
path = new Path(sequenceFileInPathNull);
LongWritable value1 = new LongWritable();
SequenceFile.Writer writer1 = null;
try {
writer1 =
SequenceFile.createWriter(
fs, conf, path, NullWritable.class, value1.getClass());
for (int i = 0; i < kvCount; i++) {
value1.set(i);
writer1.append(NullWritable.get(), value1);
}
} finally {
IOUtils.closeStream(writer1);
}
}
@Override
protected JobExecutionResult testProgram() throws Exception {
Tuple2<String[], JobExecutionResult> expectedResultAndJobExecutionResult =
HadoopIOFormatPrograms.runProgram(
curProgId, resultPath, sequenceFileInPath, sequenceFileInPathNull);
expectedResult = expectedResultAndJobExecutionResult.f0;
return expectedResultAndJobExecutionResult.f1;
}
@Override
protected void postSubmit() throws Exception {
for (int i = 0; i < resultPath.length; i++) {
compareResultsByLinesInMemory(expectedResult[i], resultPath[i]);
}
}
@Parameters(name = "curProgId = {0}")
public static Collection<Integer> getConfigurations() {
Collection<Integer> programIds = new ArrayList<>(NUM_PROGRAMS);
for (int i = 1; i <= NUM_PROGRAMS; i++) {
programIds.add(i);
}
return programIds;
}
private static | HadoopIOFormatsITCase |
java | quarkusio__quarkus | extensions/oidc-db-token-state-manager/deployment/src/test/java/io/quarkus/oidc/db/token/state/manager/OidcDbTokenStateManagerEntity.java | {
"start": 245,
"end": 745
} | class ____ {
@Id
String id;
@Column(name = "id_token", length = 4000)
String idToken;
@Column(name = "refresh_token", length = 4000)
String refreshToken;
@Column(name = "access_token", length = 4000)
String accessToken;
@Column(name = "access_token_expires_in")
Long accessTokenExpiresIn;
@Column(name = "access_token_scope", length = 100)
String accessTokenScope;
@Column(name = "expires_in")
Long expiresIn;
}
| OidcDbTokenStateManagerEntity |
java | apache__camel | core/camel-management/src/test/java/org/apache/camel/management/BigRouteTest.java | {
"start": 1139,
"end": 1921
} | class ____ extends ContextTestSupport {
@Override
protected boolean useJmx() {
return true;
}
@Test
public void testBigRoute() throws Exception {
for (int i = 0; i < 1000; i++) {
getMockEndpoint("mock:" + i).expectedMessageCount(1);
}
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
RouteDefinition route = from("direct:start");
for (int i = 0; i < 1000; i++) {
route = route.to("mock:" + i);
}
}
};
}
}
| BigRouteTest |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java | {
"start": 1488,
"end": 3340
} | class ____ extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, @Nullable Object> attributes = metadata
.getAnnotationAttributes(ConditionalOnExpression.class.getName());
Assert.state(attributes != null, "'attributes' must not be null");
String expression = (String) attributes.get("value");
Assert.state(expression != null, "'expression' must not be null");
expression = wrapIfNecessary(expression);
ConditionMessage.Builder messageBuilder = ConditionMessage.forCondition(ConditionalOnExpression.class,
"(" + expression + ")");
expression = context.getEnvironment().resolvePlaceholders(expression);
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
if (beanFactory != null) {
boolean result = evaluateExpression(beanFactory, expression);
return new ConditionOutcome(result, messageBuilder.resultedIn(result));
}
return ConditionOutcome.noMatch(messageBuilder.because("no BeanFactory available."));
}
private boolean evaluateExpression(ConfigurableListableBeanFactory beanFactory, String expression) {
BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver();
if (resolver == null) {
resolver = new StandardBeanExpressionResolver();
}
BeanExpressionContext expressionContext = new BeanExpressionContext(beanFactory, null);
Object result = resolver.evaluate(expression, expressionContext);
return (result != null && (boolean) result);
}
/**
* Allow user to provide bare expression with no '#{}' wrapper.
* @param expression source expression
* @return wrapped expression
*/
private String wrapIfNecessary(String expression) {
if (!expression.startsWith("#{")) {
return "#{" + expression + "}";
}
return expression;
}
}
| OnExpressionCondition |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/InferenceConfigItemTestCase.java | {
"start": 2716,
"end": 5852
} | class ____<T extends VersionedNamedWriteable & ToXContent> extends AbstractBWCSerializationTestCase<
T> {
static InferenceConfig mutateForVersion(NlpConfig inferenceConfig, TransportVersion version) {
if (inferenceConfig instanceof TextClassificationConfig textClassificationConfig) {
return TextClassificationConfigTests.mutateForVersion(textClassificationConfig, version);
} else if (inferenceConfig instanceof FillMaskConfig fillMaskConfig) {
return FillMaskConfigTests.mutateForVersion(fillMaskConfig, version);
} else if (inferenceConfig instanceof QuestionAnsweringConfig questionAnsweringConfig) {
return QuestionAnsweringConfigTests.mutateForVersion(questionAnsweringConfig, version);
} else if (inferenceConfig instanceof NerConfig nerConfig) {
return NerConfigTests.mutateForVersion(nerConfig, version);
} else if (inferenceConfig instanceof PassThroughConfig passThroughConfig) {
return PassThroughConfigTests.mutateForVersion(passThroughConfig, version);
} else if (inferenceConfig instanceof TextEmbeddingConfig textEmbeddingConfig) {
return TextEmbeddingConfigTests.mutateForVersion(textEmbeddingConfig, version);
} else if (inferenceConfig instanceof TextSimilarityConfig textSimilarityConfig) {
return TextSimilarityConfigTests.mutateForVersion(textSimilarityConfig, version);
} else if (inferenceConfig instanceof ZeroShotClassificationConfig zeroShotClassificationConfig) {
return ZeroShotClassificationConfigTests.mutateForVersion(zeroShotClassificationConfig, version);
} else if (inferenceConfig instanceof TextExpansionConfig textExpansionConfig) {
return TextExpansionConfigTests.mutateForVersion(textExpansionConfig, version);
} else {
throw new IllegalArgumentException("unknown inference config [" + inferenceConfig.getName() + "]");
}
}
@Override
protected NamedXContentRegistry xContentRegistry() {
List<NamedXContentRegistry.Entry> namedXContent = new ArrayList<>();
namedXContent.addAll(new MlInferenceNamedXContentProvider().getNamedXContentParsers());
namedXContent.addAll(new MlLTRNamedXContentProvider().getNamedXContentParsers());
namedXContent.addAll(new SearchModule(Settings.EMPTY, Collections.emptyList()).getNamedXContents());
return new NamedXContentRegistry(namedXContent);
}
@Override
protected NamedWriteableRegistry getNamedWriteableRegistry() {
List<NamedWriteableRegistry.Entry> namedWriteables = new ArrayList<>(new MlInferenceNamedXContentProvider().getNamedWriteables());
namedWriteables.addAll(new MlLTRNamedXContentProvider().getNamedWriteables());
return new NamedWriteableRegistry(namedWriteables);
}
@Override
protected List<TransportVersion> bwcVersions() {
T obj = createTestInstance();
return getAllBWCVersions().stream().filter(v -> v.onOrAfter(obj.getMinimalSupportedVersion())).collect(Collectors.toList());
}
}
| InferenceConfigItemTestCase |
java | apache__maven | impl/maven-testing/src/test/java/org/apache/maven/api/plugin/testing/ExpressionEvaluatorTest.java | {
"start": 9055,
"end": 10118
} | class ____ implements org.apache.maven.api.plugin.Mojo {
private Path basedir;
private Path workdir;
private String param;
private String param2;
private List<String> strings;
private String[] stringArray;
private Map<String, String> mapParam;
private Properties propertiesParam;
private TestBean beanParam;
private int intValue;
private boolean boolValue;
/** {@inheritDoc} */
@Override
public void execute() throws MojoException {
if (basedir == null) {
throw new MojoException("basedir was not injected.");
}
if (workdir == null) {
throw new MojoException("workdir was not injected.");
} else if (!workdir.startsWith(basedir)) {
throw new MojoException("workdir does not start with basedir.");
}
}
}
/**
* A simple bean for testing complex parameter injection.
*/
public static | ExpressionEvaluatorMojo |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java | {
"start": 12613,
"end": 13011
} | class ____ by this TypeToken using getRawType")
.put(
/*
* A call to super.run() from a direct subclass of Thread is a no-op. That could be
* worth telling the user about, but it's not as big a deal as "You meant to call
* start()," so we ignore it here.
*
* (And if someone defines a MyThread | described |
java | apache__camel | components/camel-master/src/test/java/org/apache/camel/component/file/cluster/FileLockClusterServiceBasicFailoverTest.java | {
"start": 1655,
"end": 10561
} | class ____ extends FileLockClusterServiceTestBase {
@Test
void singleClusterMemberLeaderElection() throws Exception {
try (CamelContext clusterLeader = createCamelContext()) {
MockEndpoint mockEndpoint = clusterLeader.getEndpoint("mock:result", MockEndpoint.class);
mockEndpoint.expectedMessageCount(5);
clusterLeader.start();
mockEndpoint.assertIsSatisfied();
Awaitility.await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
assertTrue(Files.exists(lockFile));
assertTrue(Files.exists(dataFile));
FileLockClusterLeaderInfo clusterLeaderInfo = FileLockClusterUtils.readClusterLeaderInfo(dataFile);
assertNotNull(clusterLeaderInfo);
String leaderId = clusterLeaderInfo.getId();
assertNotNull(leaderId);
assertDoesNotThrow(() -> UUID.fromString(leaderId));
});
}
assertEquals(0, Files.size(dataFile));
}
@Test
void multiClusterMemberLeaderElection() throws Exception {
CamelContext clusterLeader = createCamelContext();
ClusterConfig followerConfig = new ClusterConfig();
followerConfig.setAcquireLockDelay(2);
CamelContext clusterFollower = createCamelContext(followerConfig);
try {
MockEndpoint mockEndpointClustered = clusterLeader.getEndpoint("mock:result", MockEndpoint.class);
mockEndpointClustered.expectedMessageCount(5);
clusterLeader.start();
clusterFollower.start();
mockEndpointClustered.assertIsSatisfied();
Awaitility.await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
assertTrue(Files.exists(lockFile));
assertTrue(Files.exists(dataFile));
assertTrue(getClusterMember(clusterLeader).isLeader());
FileLockClusterLeaderInfo clusterLeaderInfo = FileLockClusterUtils.readClusterLeaderInfo(dataFile);
assertNotNull(clusterLeaderInfo);
String leaderId = clusterLeaderInfo.getId();
assertNotNull(leaderId);
assertDoesNotThrow(() -> UUID.fromString(leaderId));
});
// Wait enough time for the follower to have run its lock acquisition scheduled task
Thread.sleep(followerConfig.getStartupDelayWithOffsetMillis());
// The follower should not have produced any messages
MockEndpoint mockEndpointFollower = clusterFollower.getEndpoint("mock:result", MockEndpoint.class);
assertTrue(mockEndpointFollower.getExchanges().isEmpty());
} finally {
clusterFollower.stop();
clusterLeader.stop();
}
assertEquals(0, Files.size(dataFile));
}
@Test
void clusterFailoverWhenLeaderCamelContextStopped() throws Exception {
CamelContext clusterLeader = createCamelContext();
ClusterConfig followerConfig = new ClusterConfig();
followerConfig.setAcquireLockDelay(2);
CamelContext clusterFollower = createCamelContext(followerConfig);
try {
MockEndpoint mockEndpointClustered = clusterLeader.getEndpoint("mock:result", MockEndpoint.class);
mockEndpointClustered.expectedMessageCount(5);
clusterLeader.start();
clusterFollower.start();
mockEndpointClustered.assertIsSatisfied();
AtomicReference<String> leaderId = new AtomicReference<>();
Awaitility.await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
assertTrue(Files.exists(lockFile));
assertTrue(Files.exists(dataFile));
assertTrue(getClusterMember(clusterLeader).isLeader());
FileLockClusterLeaderInfo clusterLeaderInfo = FileLockClusterUtils.readClusterLeaderInfo(dataFile);
assertNotNull(clusterLeaderInfo);
assertNotNull(clusterLeaderInfo.getId());
assertDoesNotThrow(() -> UUID.fromString(clusterLeaderInfo.getId()));
leaderId.set(clusterLeaderInfo.getId());
});
// Wait enough time for the follower to have run its lock acquisition scheduled task
Thread.sleep(followerConfig.getStartupDelayWithOffsetMillis());
// The follower should not have produced any messages
MockEndpoint mockEndpointFollower = clusterFollower.getEndpoint("mock:result", MockEndpoint.class);
assertTrue(mockEndpointFollower.getExchanges().isEmpty());
// Stop the cluster leader
clusterLeader.stop();
// Verify the follower was elected as the new cluster leader
Awaitility.await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
assertTrue(getClusterMember(clusterFollower).isLeader());
FileLockClusterLeaderInfo updatedClusterLeaderInfo = FileLockClusterUtils.readClusterLeaderInfo(dataFile);
assertNotNull(updatedClusterLeaderInfo);
String newLeaderId = updatedClusterLeaderInfo.getId();
assertNotNull(newLeaderId);
assertDoesNotThrow(() -> UUID.fromString(newLeaderId));
assertNotEquals(leaderId.get(), newLeaderId);
assertEquals(5, mockEndpointFollower.getExchanges().size());
});
} finally {
clusterFollower.stop();
}
assertEquals(0, Files.size(dataFile));
}
@Test
void singleClusterMemberRecoversLeadershipIfUUIDRemovedFromLockFile() throws Exception {
try (CamelContext clusterLeader = createCamelContext()) {
MockEndpoint mockEndpoint = clusterLeader.getEndpoint("mock:result", MockEndpoint.class);
mockEndpoint.expectedMinimumMessageCount(1);
clusterLeader.start();
mockEndpoint.assertIsSatisfied();
AtomicReference<String> leaderId = new AtomicReference<>();
Awaitility.await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
assertTrue(Files.exists(lockFile));
assertTrue(Files.exists(dataFile));
assertTrue(getClusterMember(clusterLeader).isLeader());
FileLockClusterLeaderInfo clusterLeaderInfo = FileLockClusterUtils.readClusterLeaderInfo(dataFile);
assertNotNull(clusterLeaderInfo);
assertNotNull(clusterLeaderInfo.getId());
assertDoesNotThrow(() -> UUID.fromString(clusterLeaderInfo.getId()));
leaderId.set(clusterLeaderInfo.getId());
});
// Truncate the lock file
Files.write(dataFile, new byte[0]);
Awaitility.await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
// Leadership should be lost
assertFalse(getClusterMember(clusterLeader).isLeader());
});
mockEndpoint.reset();
mockEndpoint.expectedMinimumMessageCount(1);
// Await recovery
Awaitility.await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
assertTrue(getClusterMember(clusterLeader).isLeader());
FileLockClusterLeaderInfo recoveredClusterLeaderInfo = FileLockClusterUtils.readClusterLeaderInfo(dataFile);
assertNotNull(recoveredClusterLeaderInfo);
String recoveredLeaderId = recoveredClusterLeaderInfo.getId();
assertNotNull(recoveredLeaderId);
assertDoesNotThrow(() -> UUID.fromString(recoveredLeaderId));
assertEquals(leaderId.get(), recoveredLeaderId);
mockEndpoint.assertIsSatisfied();
});
}
assertEquals(0, Files.size(dataFile));
}
@Test
void negativeHeartbeatTimeoutMultiplierThrowsException() throws Exception {
ClusterConfig config = new ClusterConfig();
config.setHeartbeatTimeoutMultiplier(-1);
Exception exception = assertThrows(Exception.class, () -> {
try (CamelContext camelContext = createCamelContext(config)) {
camelContext.start();
}
});
assertIsInstanceOf(IllegalArgumentException.class, exception.getCause());
}
@Test
void zeroHeartbeatTimeoutMultiplierThrowsException() throws Exception {
ClusterConfig config = new ClusterConfig();
config.setHeartbeatTimeoutMultiplier(0);
Exception exception = assertThrows(Exception.class, () -> {
try (CamelContext camelContext = createCamelContext(config)) {
camelContext.start();
}
});
assertIsInstanceOf(IllegalArgumentException.class, exception.getCause());
}
}
| FileLockClusterServiceBasicFailoverTest |
java | junit-team__junit5 | documentation/src/test/java/example/TestTemplateDemo.java | {
"start": 939,
"end": 1291
} | class ____ {
// tag::user_guide[]
final List<String> fruits = Arrays.asList("apple", "banana", "lemon");
@TestTemplate
@ExtendWith(MyTestTemplateInvocationContextProvider.class)
void testTemplate(String fruit) {
assertTrue(fruits.contains(fruit));
}
// end::user_guide[]
static
// @formatter:off
// tag::user_guide[]
public | TestTemplateDemo |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/impl/ITestS3APutIfMatchAndIfNoneMatch.java | {
"start": 3720,
"end": 27931
} | class ____ extends AbstractS3ATestBase {
private static final int UPDATED_MULTIPART_THRESHOLD = 100 * _1KB;
private static final byte[] SMALL_FILE_BYTES = dataset(TEST_FILE_LEN, 0, 255);
private static final byte[] MULTIPART_FILE_BYTES = dataset(UPDATED_MULTIPART_THRESHOLD * 5, 'a', 'z' - 'a');
public static final String PRECONDITION_FAILED = "PreconditionFailed";
private BlockOutputStreamStatistics statistics;
@Override
public Configuration createConfiguration() {
Configuration conf = super.createConfiguration();
S3ATestUtils.disableFilesystemCaching(conf);
removeBaseAndBucketOverrides(
conf,
FS_S3A_CREATE_PERFORMANCE,
FS_S3A_PERFORMANCE_FLAGS,
MULTIPART_SIZE,
MIN_MULTIPART_THRESHOLD,
UPLOAD_PART_COUNT_LIMIT
);
conf.setLong(UPLOAD_PART_COUNT_LIMIT, 2);
conf.setLong(MIN_MULTIPART_THRESHOLD, UPDATED_MULTIPART_THRESHOLD);
conf.setInt(MULTIPART_SIZE, UPDATED_MULTIPART_THRESHOLD);
return conf;
}
@Override
@BeforeEach
public void setup() throws Exception {
super.setup();
Configuration conf = getFileSystem().getConf();
assumeConditionalCreateEnabled(conf);
}
/**
* Asserts that an S3Exception has the expected HTTP status code.
* @param code Expected HTTP status code.
* @param ex Exception to validate.
* @return the inner exception
* @throws AssertionError if the status code doesn't match.
*/
private static S3Exception verifyS3ExceptionStatusCode(int code, Exception ex) {
final Throwable cause = ex.getCause();
if (cause == null) {
throw new AssertionError("No inner exception of" + ex, ex);
}
if (!(cause instanceof S3Exception)) {
throw new AssertionError("Inner exception is not S3Exception under " + ex, ex);
}
S3Exception s3Exception = (S3Exception) cause;
if (s3Exception.statusCode() != code) {
throw new AssertionError("Expected status code " + code + " from " + ex, ex);
}
return s3Exception;
}
/**
* Asserts that the FSDataOutputStream has the conditional create capability enabled.
*
* @param stream The output stream to check.
*/
private static void assertHasCapabilityConditionalCreate(FSDataOutputStream stream) {
Assertions.assertThat(stream.hasCapability(FS_OPTION_CREATE_CONDITIONAL_OVERWRITE))
.as("Conditional create capability should be enabled")
.isTrue();
}
/**
* Asserts that the FSDataOutputStream has the ETag-based conditional create capability enabled.
*
* @param stream The output stream to check.
*/
private static void assertHasCapabilityEtagWrite(FSDataOutputStream stream) {
Assertions.assertThat(stream.hasCapability(FS_OPTION_CREATE_CONDITIONAL_OVERWRITE_ETAG))
.as("ETag-based conditional create capability should be enabled")
.isTrue();
}
protected String getBlockOutputBufferName() {
return FAST_UPLOAD_BUFFER_ARRAY;
}
/**
* Creates a file with specified flags and writes data to it.
*
* @param fs The FileSystem instance.
* @param path Path of the file to create.
* @param data Byte data to write into the file.
* @param ifNoneMatchFlag If true, enforces conditional creation.
* @param etag The ETag for conditional writes.
* @param forceMultipart If true, forces multipart upload.
* @return The FileStatus of the created file.
* @throws Exception If an error occurs during file creation.
*/
private static FileStatus createFileWithFlags(
FileSystem fs,
Path path,
byte[] data,
boolean ifNoneMatchFlag,
String etag,
boolean forceMultipart) throws Exception {
try (FSDataOutputStream stream = getStreamWithFlags(fs, path, ifNoneMatchFlag, etag,
forceMultipart)) {
if (ifNoneMatchFlag) {
assertHasCapabilityConditionalCreate(stream);
}
if (etag != null) {
assertHasCapabilityEtagWrite(stream);
}
if (data != null && data.length > 0) {
stream.write(data);
}
}
return fs.getFileStatus(path);
}
/**
* Overloaded method to create a file without forcing multipart upload.
*
* @param fs The FileSystem instance.
* @param path Path of the file to create.
* @param data Byte data to write into the file.
* @param ifNoneMatchFlag If true, enforces conditional creation.
* @param etag The ETag for conditional writes.
* @return The FileStatus of the created file.
* @throws Exception If an error occurs during file creation.
*/
private static FileStatus createFileWithFlags(
FileSystem fs,
Path path,
byte[] data,
boolean ifNoneMatchFlag,
String etag) throws Exception {
return createFileWithFlags(fs, path, data, ifNoneMatchFlag, etag, false);
}
/**
* Opens a file for writing with specific conditional write flags.
*
* @param fs The FileSystem instance.
* @param path Path of the file to open.
* @param ifNoneMatchFlag If true, enables conditional overwrites.
* @param etag The ETag for conditional writes.
* @param forceMultipart If true, forces multipart upload.
* @return The FSDataOutputStream for writing.
* @throws Exception If an error occurs while opening the file.
*/
private static FSDataOutputStream getStreamWithFlags(
FileSystem fs,
Path path,
boolean ifNoneMatchFlag,
String etag,
boolean forceMultipart) throws Exception {
FSDataOutputStreamBuilder builder = fs.createFile(path);
if (ifNoneMatchFlag) {
builder.must(FS_OPTION_CREATE_CONDITIONAL_OVERWRITE, true);
}
if (etag != null) {
builder.must(FS_OPTION_CREATE_CONDITIONAL_OVERWRITE_ETAG, etag);
}
if (forceMultipart) {
builder.opt(FS_S3A_CREATE_MULTIPART, true);
}
return builder.create().build();
}
/**
* Opens a file for writing with specific conditional write flags and without forcing multipart upload.
*
* @param fs The FileSystem instance.
* @param path Path of the file to open.
* @param ifNoneMatchFlag If true, enables conditional overwrites.
* @param etag The ETag for conditional writes.
* @return The FSDataOutputStream for writing.
* @throws Exception If an error occurs while opening the file.
*/
private static FSDataOutputStream getStreamWithFlags(
FileSystem fs,
Path path,
boolean ifNoneMatchFlag,
String etag) throws Exception {
return getStreamWithFlags(fs, path, ifNoneMatchFlag, etag, false);
}
/**
* Reads the content of a file as a string.
*
* @param fs The FileSystem instance.
* @param path The file path to read.
* @return The content of the file as a string.
* @throws Throwable If an error occurs while reading the file.
*/
private static String readFileContent(FileSystem fs, Path path) throws Throwable {
try (FSDataInputStream inputStream = fs.open(path)) {
return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
}
}
/**
* Updates the statistics of the output stream.
*
* @param stream The FSDataOutputStream whose statistics should be updated.
*/
private void updateStatistics(FSDataOutputStream stream) {
statistics = S3ATestUtils.getOutputStreamStatistics(stream);
}
/**
* Retrieves the ETag of a file.
*
* @param fs The FileSystem instance.
* @param path The path of the file.
* @return The ETag associated with the file.
* @throws IOException If an error occurs while fetching the file status.
*/
private static String getEtag(FileSystem fs, Path path) throws IOException {
String etag = ((S3AFileStatus) fs.getFileStatus(path)).getETag();
return etag;
}
@Test
public void testIfNoneMatchConflictOnOverwrite() throws Throwable {
describe("generate conflict on overwrites");
FileSystem fs = getFileSystem();
Path testFile = methodPath();
fs.mkdirs(testFile.getParent());
// create a file over an empty path: all good
createFileWithFlags(fs, testFile, SMALL_FILE_BYTES, true, null);
// attempted overwrite fails
RemoteFileChangedException firstException = intercept(RemoteFileChangedException.class,
() -> createFileWithFlags(fs, testFile, SMALL_FILE_BYTES, true, null));
verifyS3ExceptionStatusCode(SC_412_PRECONDITION_FAILED, firstException);
// second attempt also fails
RemoteFileChangedException secondException = intercept(RemoteFileChangedException.class,
() -> createFileWithFlags(fs, testFile, SMALL_FILE_BYTES, true, null));
verifyS3ExceptionStatusCode(SC_412_PRECONDITION_FAILED, secondException);
// Delete file and verify an overwrite works again
fs.delete(testFile, false);
createFileWithFlags(fs, testFile, SMALL_FILE_BYTES, true, null);
}
@Test
public void testIfNoneMatchConflictOnMultipartUpload() throws Throwable {
FileSystem fs = getFileSystem();
Path testFile = methodPath();
// Skip if multipart upload not supported
assumeThat(fs.hasPathCapability(testFile, STORE_CAPABILITY_MULTIPART_UPLOAD_ENABLED))
.as("Skipping as multipart upload not supported")
.isTrue();
createFileWithFlags(fs, testFile, MULTIPART_FILE_BYTES, true, null, true);
expectPreconditionFailure(() ->
createFileWithFlags(fs, testFile, MULTIPART_FILE_BYTES, true, null, true));
expectPreconditionFailure(() ->
createFileWithFlags(fs, testFile, MULTIPART_FILE_BYTES, true, null, true));
}
@Test
public void testIfNoneMatchMultipartUploadWithRaceCondition() throws Throwable {
FileSystem fs = getFileSystem();
Path testFile = methodPath();
// Skip test if multipart uploads are not supported
assumeThat(fs.hasPathCapability(testFile, STORE_CAPABILITY_MULTIPART_UPLOAD_ENABLED))
.as("Skipping as multipart upload not supported")
.isTrue();
// Create a file with multipart upload but do not close the stream
FSDataOutputStream stream = getStreamWithFlags(fs, testFile, true, null, true);
assertHasCapabilityConditionalCreate(stream);
stream.write(MULTIPART_FILE_BYTES);
// create and close another small file in parallel
createFileWithFlags(fs, testFile, SMALL_FILE_BYTES, true, null);
// Closing the first stream should throw RemoteFileChangedException
expectPreconditionFailure(stream::close);
}
@Test
public void testIfNoneMatchTwoConcurrentMultipartUploads() throws Throwable {
FileSystem fs = getFileSystem();
Path testFile = methodPath();
// Skip test if multipart uploads are not supported
assumeThat(fs.hasPathCapability(testFile, STORE_CAPABILITY_MULTIPART_UPLOAD_ENABLED))
.as("Skipping as multipart upload not supported")
.isTrue();
// Create a file with multipart upload but do not close the stream
FSDataOutputStream stream = getStreamWithFlags(fs, testFile, true, null, true);
assertHasCapabilityConditionalCreate(stream);
stream.write(MULTIPART_FILE_BYTES);
// create and close another multipart file in parallel
createFileWithFlags(fs, testFile, MULTIPART_FILE_BYTES, true, null, true);
// Closing the first stream should throw RemoteFileChangedException
// or or the S3 Express equivalent.
expectPreconditionFailure(stream::close);
}
/**
* Expect an operation to fail with an S3 classic or S3 Express precondition failure.
* @param eval closure to eval
* @throws Exception any other failure.
*/
private static void expectPreconditionFailure(final LambdaTestUtils.VoidCallable eval)
throws Exception {
RemoteFileChangedException exception = intercept(RemoteFileChangedException.class, eval);
S3Exception s3Exception = (S3Exception) exception.getCause();
if (!(s3Exception.statusCode() == SC_412_PRECONDITION_FAILED
|| (s3Exception.statusCode() == SC_200_OK)
&& PRECONDITION_FAILED.equals(s3Exception.awsErrorDetails().errorCode()))) {
throw exception;
}
}
@Test
public void testIfNoneMatchOverwriteWithEmptyFile() throws Throwable {
FileSystem fs = getFileSystem();
Path testFile = methodPath();
fs.mkdirs(testFile.getParent());
// create a non-empty file
createFileWithFlags(fs, testFile, SMALL_FILE_BYTES, true, null);
// overwrite with zero-byte file (no write)
FSDataOutputStream stream = getStreamWithFlags(fs, testFile, true, null);
assertHasCapabilityConditionalCreate(stream);
// close the stream, should throw RemoteFileChangedException
RemoteFileChangedException exception = intercept(RemoteFileChangedException.class, stream::close);
verifyS3ExceptionStatusCode(SC_412_PRECONDITION_FAILED, exception);
}
@Test
public void testIfNoneMatchOverwriteEmptyFileWithFile() throws Throwable {
FileSystem fs = getFileSystem();
Path testFile = methodPath();
fs.mkdirs(testFile.getParent());
// create an empty file (no write)
FSDataOutputStream stream = getStreamWithFlags(fs, testFile, true, null);
assertHasCapabilityConditionalCreate(stream);
stream.close();
// overwrite with non-empty file, should throw RemoteFileChangedException
RemoteFileChangedException exception = intercept(RemoteFileChangedException.class,
() -> createFileWithFlags(fs, testFile, SMALL_FILE_BYTES, true, null));
verifyS3ExceptionStatusCode(SC_412_PRECONDITION_FAILED, exception);
}
@Test
public void testIfNoneMatchOverwriteEmptyWithEmptyFile() throws Throwable {
FileSystem fs = getFileSystem();
Path testFile = methodPath();
fs.mkdirs(testFile.getParent());
// create an empty file (no write)
FSDataOutputStream stream1 = getStreamWithFlags(fs, testFile, true, null);
assertHasCapabilityConditionalCreate(stream1);
stream1.close();
// overwrite with another empty file, should throw RemoteFileChangedException
FSDataOutputStream stream2 = getStreamWithFlags(fs, testFile, true, null);
assertHasCapabilityConditionalCreate(stream2);
RemoteFileChangedException exception = intercept(RemoteFileChangedException.class, stream2::close);
verifyS3ExceptionStatusCode(SC_412_PRECONDITION_FAILED, exception);
}
@Test
public void testIfMatchOverwriteWithCorrectEtag() throws Throwable {
FileSystem fs = getFileSystem();
Path path = methodPath();
fs.mkdirs(path.getParent());
// Create a file
createFileWithFlags(fs, path, SMALL_FILE_BYTES, false, null);
// Retrieve the etag from the created file
String etag = getEtag(fs, path);
Assertions.assertThat(etag)
.as("ETag should not be null after file creation")
.isNotNull();
String updatedFileContent = "Updated content";
byte[] updatedData = updatedFileContent.getBytes(StandardCharsets.UTF_8);
// overwrite file with etag
createFileWithFlags(fs, path, updatedData, false, etag);
// read file and verify overwritten content
String fileContent = readFileContent(fs, path);
Assertions.assertThat(fileContent)
.as("File content should be correctly updated after overwriting with the correct ETag")
.isEqualTo(updatedFileContent);
}
@Test
public void testIfMatchOverwriteWithOutdatedEtag() throws Throwable {
FileSystem fs = getFileSystem();
Path path = methodPath();
fs.mkdirs(path.getParent());
// Create a file
createFileWithFlags(fs, path, SMALL_FILE_BYTES, true, null);
// Retrieve the etag from the created file
String etag = getEtag(fs, path);
Assertions.assertThat(etag)
.as("ETag should not be null after file creation")
.isNotNull();
String updatedFileContent = "Updated content";
byte[] updatedData = updatedFileContent.getBytes(StandardCharsets.UTF_8);
// Overwrite the file. Will update the etag, making the previously fetched etag outdated.
createFileWithFlags(fs, path, updatedData, false, null);
// overwrite file with outdated etag. Should throw RemoteFileChangedException
RemoteFileChangedException exception = intercept(RemoteFileChangedException.class,
() -> createFileWithFlags(fs, path, SMALL_FILE_BYTES, false, etag));
verifyS3ExceptionStatusCode(SC_412_PRECONDITION_FAILED, exception);
}
@Test
public void testIfMatchOverwriteDeletedFileWithEtag() throws Throwable {
FileSystem fs = getFileSystem();
Path path = methodPath();
fs.mkdirs(path.getParent());
// Create a file
createFileWithFlags(fs, path, SMALL_FILE_BYTES, false, null);
// Retrieve the etag from the created file
String etag = getEtag(fs, path);
Assertions.assertThat(etag)
.as("ETag should not be null after file creation")
.isNotNull();
// delete the file
fs.delete(path);
// overwrite file with etag. Should throw FileNotFoundException
FileNotFoundException exception = intercept(FileNotFoundException.class,
() -> createFileWithFlags(fs, path, SMALL_FILE_BYTES, false, etag));
verifyS3ExceptionStatusCode(SC_404_NOT_FOUND, exception);
}
@Test
public void testIfMatchOverwriteFileWithEmptyEtag() throws Throwable {
FileSystem fs = getFileSystem();
Path path = methodPath();
fs.mkdirs(path.getParent());
// Create a file
createFileWithFlags(fs, path, SMALL_FILE_BYTES, false, null);
// overwrite file with empty etag. Should throw IllegalArgumentException
intercept(IllegalArgumentException.class,
() -> createFileWithFlags(fs, path, SMALL_FILE_BYTES, false, ""));
}
@Test
public void testIfMatchTwoMultipartUploadsRaceConditionOneClosesFirst() throws Throwable {
FileSystem fs = getFileSystem();
Path testFile = methodPath();
// Skip test if multipart uploads are not supported
assumeThat(fs.hasPathCapability(testFile, STORE_CAPABILITY_MULTIPART_UPLOAD_ENABLED))
.as("Skipping as multipart upload not supported")
.isTrue();
// Create a file and retrieve its etag
createFileWithFlags(fs, testFile, SMALL_FILE_BYTES, false, null);
String etag = getEtag(fs, testFile);
Assertions.assertThat(etag)
.as("ETag should not be null after file creation")
.isNotNull();
// Start two multipart uploads with the same etag
FSDataOutputStream stream1 = getStreamWithFlags(fs, testFile, false, etag, true);
assertHasCapabilityEtagWrite(stream1);
FSDataOutputStream stream2 = getStreamWithFlags(fs, testFile, false, etag, true);
assertHasCapabilityEtagWrite(stream2);
// Write data to both streams
stream1.write(MULTIPART_FILE_BYTES);
stream2.write(MULTIPART_FILE_BYTES);
// Close the first stream successfully. Will update the etag
stream1.close();
// Close second stream, should fail due to etag mismatch
expectPreconditionFailure(stream2::close);
}
@Disabled("conditional_write statistics not yet fully implemented")
@Test
public void testConditionalWriteStatisticsWithoutIfNoneMatch() throws Throwable {
FileSystem fs = getFileSystem();
Path testFile = methodPath();
// write without an If-None-Match
// conditional_write, conditional_write_statistics should remain 0
FSDataOutputStream stream = getStreamWithFlags(fs, testFile, false, null, false);
updateStatistics(stream);
stream.write(SMALL_FILE_BYTES);
stream.close();
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE.getSymbol(), 0);
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE_FAILED.getSymbol(), 0);
// write with overwrite = true
// conditional_write, conditional_write_statistics should remain 0
try (FSDataOutputStream outputStream = fs.create(testFile, true)) {
outputStream.write(SMALL_FILE_BYTES);
updateStatistics(outputStream);
}
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE.getSymbol(), 0);
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE_FAILED.getSymbol(), 0);
// write in path where file already exists with overwrite = false
// conditional_write, conditional_write_statistics should remain 0
try (FSDataOutputStream outputStream = fs.create(testFile, false)) {
outputStream.write(SMALL_FILE_BYTES);
updateStatistics(outputStream);
} catch (FileAlreadyExistsException e) {}
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE.getSymbol(), 0);
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE_FAILED.getSymbol(), 0);
// delete the file
fs.delete(testFile, false);
// write in path where file doesn't exist with overwrite = false
// conditional_write, conditional_write_statistics should remain 0
try (FSDataOutputStream outputStream = fs.create(testFile, false)) {
outputStream.write(SMALL_FILE_BYTES);
updateStatistics(outputStream);
}
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE.getSymbol(), 0);
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE_FAILED.getSymbol(), 0);
}
@Disabled("conditional_write statistics not yet fully implemented")
@Test
public void testConditionalWriteStatisticsWithIfNoneMatch() throws Throwable {
FileSystem fs = getFileSystem();
Path testFile = methodPath();
FSDataOutputStream stream = getStreamWithFlags(fs, testFile, true, null, false);
updateStatistics(stream);
stream.write(SMALL_FILE_BYTES);
stream.close();
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE.getSymbol(), 1);
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE_FAILED.getSymbol(), 0);
intercept(RemoteFileChangedException.class,
() -> {
// try again with If-None-Match. should fail
FSDataOutputStream s = getStreamWithFlags(fs, testFile, true, null, false);
updateStatistics(s);
s.write(SMALL_FILE_BYTES);
s.close();
return "Second write using If-None-Match should have failed due to existing file." + s;
}
);
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE.getSymbol(), 1);
verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE_FAILED.getSymbol(), 1);
}
/**
* Tests that a conditional create operation is triggered when the performance flag is enabled
* and the overwrite option is set to false.
*/
@Test
public void testConditionalCreateWhenPerformanceFlagEnabledAndOverwriteDisabled() throws Throwable {
FileSystem fs = getFileSystem();
Path testFile = methodPath();
fs.mkdirs(testFile.getParent());
// Create a file
createFileWithFlags(fs, testFile, SMALL_FILE_BYTES, false, null);
// Attempt to override the file without overwrite and performance flag.
// Should throw RemoteFileChangedException (due to conditional write operation)
intercept(RemoteFileChangedException.class, () -> {
FSDataOutputStreamBuilder cf = fs.createFile(testFile);
cf.overwrite(false);
cf.must(FS_S3A_CREATE_PERFORMANCE, true);
try (FSDataOutputStream stream = cf.build()) {
assertHasCapabilityConditionalCreate(stream);
stream.write(SMALL_FILE_BYTES);
updateStatistics(stream);
}
});
// TODO: uncomment when statistics are getting initialised
// verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE.getSymbol(), 0);
// verifyStatisticCounterValue(statistics.getIOStatistics(), Statistic.CONDITIONAL_CREATE_FAILED.getSymbol(), 1);
}
}
| ITestS3APutIfMatchAndIfNoneMatch |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/creation/internal/SessionBuilderImpl.java | {
"start": 901,
"end": 6278
} | class ____
extends AbstractCommonBuilder<SessionBuilderImplementor>
implements SessionBuilderImplementor, SessionCreationOptions {
private boolean autoJoinTransactions = true;
private boolean autoClose;
private boolean autoClear;
private boolean identifierRollback;
private FlushMode flushMode;
private int defaultBatchFetchSize;
private boolean subselectFetchEnabled;
// Lazy: defaults can be built by invoking the builder in fastSessionServices.defaultSessionEventListeners
// (Need a fresh build for each Session as the listener instances can't be reused across sessions)
// Only initialize of the builder is overriding the default.
private List<SessionEventListener> listeners;
public SessionBuilderImpl(SessionFactoryImplementor sessionFactory) {
super( sessionFactory );
// set up default builder values
final var options = sessionFactory.getSessionFactoryOptions();
autoClose = options.isAutoCloseSessionEnabled();
identifierRollback = options.isIdentifierRollbackEnabled();
defaultBatchFetchSize = options.getDefaultBatchFetchSize();
subselectFetchEnabled = options.isSubselectFetchEnabled();
}
@Override
protected SessionBuilderImplementor getThis() {
return this;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SessionCreationOptions
@Override
public boolean shouldAutoJoinTransactions() {
return autoJoinTransactions;
}
@Override
public FlushMode getInitialSessionFlushMode() {
return flushMode;
}
@Override
public boolean isSubselectFetchEnabled() {
return subselectFetchEnabled;
}
@Override
public int getDefaultBatchFetchSize() {
return defaultBatchFetchSize;
}
@Override
public boolean shouldAutoClose() {
return autoClose;
}
@Override
public boolean shouldAutoClear() {
return autoClear;
}
@Override
public Connection getConnection() {
return connection;
}
@Override
public Interceptor getInterceptor() {
return configuredInterceptor();
}
@Override
public StatementInspector getStatementInspector() {
return statementInspector;
}
@Override
public PhysicalConnectionHandlingMode getPhysicalConnectionHandlingMode() {
return connectionHandlingMode;
}
@Override
public Object getTenantIdentifierValue() {
return tenantIdentifier;
}
@Override
public boolean isReadOnly() {
return readOnly;
}
@Override
public CacheMode getInitialCacheMode() {
return cacheMode;
}
@Override
public boolean isIdentifierRollbackEnabled() {
return identifierRollback;
}
@Override
public TimeZone getJdbcTimeZone() {
return jdbcTimeZone;
}
@Override
public List<SessionEventListener> getCustomSessionEventListeners() {
return listeners;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SessionBuilder
@Override
public SessionImplementor openSession() {
CORE_LOGGER.openingSession( tenantIdentifier );
return createSession();
}
protected abstract SessionImplementor createSession();
@Override
@Deprecated
public SessionBuilderImplementor statementInspector(StatementInspector statementInspector) {
this.statementInspector = statementInspector;
return this;
}
@Override
@Deprecated
public SessionBuilderImplementor connectionHandlingMode(PhysicalConnectionHandlingMode connectionHandlingMode) {
this.connectionHandlingMode = connectionHandlingMode;
return this;
}
@Override
public SessionBuilderImplementor autoJoinTransactions(boolean autoJoinTransactions) {
this.autoJoinTransactions = autoJoinTransactions;
return this;
}
@Override
public SessionBuilderImplementor autoClose(boolean autoClose) {
this.autoClose = autoClose;
return this;
}
@Override
public SessionBuilderImplementor autoClear(boolean autoClear) {
this.autoClear = autoClear;
return this;
}
@Override
public SessionBuilderImplementor flushMode(FlushMode flushMode) {
this.flushMode = flushMode;
return this;
}
@Override
@Deprecated(forRemoval = true)
public SessionBuilderImplementor tenantIdentifier(String tenantIdentifier) {
this.tenantIdentifier = tenantIdentifier;
return this;
}
@Override
public SessionBuilderImplementor identifierRollback(boolean identifierRollback) {
this.identifierRollback = identifierRollback;
return this;
}
@Override
public SessionBuilderImplementor eventListeners(SessionEventListener... listeners) {
if ( this.listeners == null ) {
final var baselineListeners =
sessionFactory.getSessionFactoryOptions().buildSessionEventListeners();
this.listeners = new ArrayList<>( baselineListeners.length + listeners.length );
addAll( this.listeners, baselineListeners );
}
addAll( this.listeners, listeners );
return this;
}
@Override
public SessionBuilderImplementor clearEventListeners() {
if ( listeners == null ) {
//Needs to initialize explicitly to an empty list as otherwise "null" implies the default listeners will be applied
listeners = new ArrayList<>( 3 );
}
else {
listeners.clear();
}
return this;
}
@Override
public SessionBuilderImplementor defaultBatchFetchSize(int defaultBatchFetchSize) {
this.defaultBatchFetchSize = defaultBatchFetchSize;
return this;
}
@Override
public SessionBuilderImplementor subselectFetchEnabled(boolean subselectFetchEnabled) {
this.subselectFetchEnabled = subselectFetchEnabled;
return this;
}
}
| SessionBuilderImpl |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/config/FluentProducerTemplateAutoRegisterTest.java | {
"start": 1240,
"end": 1797
} | class ____ extends SpringRunWithTestSupport {
@Autowired
private FluentProducerTemplate template;
@Autowired
private CamelContext context;
@Test
public void testHasFluentTemplate() {
assertNotNull(template, "Should have injected a fluent producer template");
FluentProducerTemplate lookup
= context.getRegistry().lookupByNameAndType("fluentTemplate", FluentProducerTemplate.class);
assertNotNull(lookup, "Should lookup fluent producer template");
}
}
| FluentProducerTemplateAutoRegisterTest |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/accesscontrol/wrapper/DlsFlsFeatureTrackingIndicesAccessControlWrapper.java | {
"start": 909,
"end": 2021
} | class ____ {
private final XPackLicenseState licenseState;
private final boolean isDlsFlsEnabled;
public DlsFlsFeatureTrackingIndicesAccessControlWrapper(Settings settings, XPackLicenseState licenseState) {
this.licenseState = licenseState;
this.isDlsFlsEnabled = XPackSettings.DLS_FLS_ENABLED.get(settings);
}
public IndicesAccessControl wrap(IndicesAccessControl indicesAccessControl) {
if (isDlsFlsEnabled == false
|| indicesAccessControl == null
|| indicesAccessControl == IndicesAccessControl.ALLOW_NO_INDICES
|| indicesAccessControl == IndicesAccessControl.DENIED
|| indicesAccessControl == IndicesAccessControl.allowAll()
|| indicesAccessControl instanceof DlsFlsFeatureUsageTracker) {
// Wrap only if it's not one of the statically defined nor already wrapped.
return indicesAccessControl;
} else {
return new DlsFlsFeatureUsageTracker(indicesAccessControl, licenseState);
}
}
private static | DlsFlsFeatureTrackingIndicesAccessControlWrapper |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/headers/OptionalHeaderTest.java | {
"start": 2027,
"end": 2213
} | interface ____ {
@GET
String send(@RestHeader Optional<String> header2, @RestHeader Optional<Integer> header3);
}
@Path("resource")
public static | OtherSubClient |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/annotation/JsonSeeAlsoTest.java | {
"start": 2009,
"end": 2136
} | class ____ extends Dog {
public String tidySpecific;
}
@JSONType(typeName = "labrador")
public static | Tidy |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/CaseLeastGreatestEmulation.java | {
"start": 1054,
"end": 2637
} | class ____
extends AbstractSqmSelfRenderingFunctionDescriptor {
private final String operator;
public CaseLeastGreatestEmulation(boolean least) {
super(
least ? "least" : "greatest",
new ArgumentTypesValidator( StandardArgumentsValidators.min( 2 ), COMPARABLE, COMPARABLE ),
StandardFunctionReturnTypeResolvers.useFirstNonNull(),
StandardFunctionArgumentTypeResolvers.ARGUMENT_OR_IMPLIED_RESULT_TYPE
);
this.operator = least ? "<=" : ">=";
}
@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> arguments,
ReturnableType<?> returnType,
SqlAstTranslator<?> walker) {
final int numberOfArguments = arguments.size();
if ( numberOfArguments > 1 ) {
final int lastArgument = numberOfArguments - 1;
sqlAppender.appendSql( "case" );
for ( int i = 0; i < lastArgument; i++ ) {
sqlAppender.appendSql( " when " );
String separator = "";
for ( int j = i + 1; j < numberOfArguments; j++ ) {
sqlAppender.appendSql( separator );
arguments.get( i ).accept( walker );
sqlAppender.appendSql( operator );
arguments.get( j ).accept( walker );
separator = " and ";
}
sqlAppender.appendSql( " then " );
arguments.get( i ).accept( walker );
}
sqlAppender.appendSql( " else " );
arguments.get( lastArgument ).accept( walker );
sqlAppender.appendSql( " end" );
}
else {
arguments.get( 0 ).accept( walker );
}
}
@Override
public String getArgumentListSignature() {
return "(COMPARABLE arg0[, COMPARABLE arg1[, ...]])";
}
}
| CaseLeastGreatestEmulation |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestLocalFsFCStatistics.java | {
"start": 1154,
"end": 2066
} | class ____ extends FCStatisticsBaseTest {
static final String LOCAL_FS_ROOT_URI = "file:///tmp/test";
@BeforeEach
public void setUp() throws Exception {
fc = FileContext.getLocalFSFileContext();
fc.mkdir(fileContextTestHelper.getTestRootPath(fc, "test"), FileContext.DEFAULT_PERM, true);
}
@AfterEach
public void tearDown() throws Exception {
fc.delete(fileContextTestHelper.getTestRootPath(fc, "test"), true);
}
@Override
protected void verifyReadBytes(Statistics stats) {
// one blockSize for read, one for pread
assertEquals(2*blockSize, stats.getBytesRead());
}
@Override
protected void verifyWrittenBytes(Statistics stats) {
//Extra 12 bytes are written apart from the block.
assertEquals(blockSize + 12, stats.getBytesWritten());
}
@Override
protected URI getFsUri() {
return URI.create(LOCAL_FS_ROOT_URI);
}
}
| TestLocalFsFCStatistics |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/event/EventPublishingTestExecutionListener.java | {
"start": 5654,
"end": 8166
} | class ____ extends AbstractTestExecutionListener {
/**
* The {@link #getOrder() order} value for this listener: {@value}.
* @since 6.2.3
*/
public static final int ORDER = 10_000;
/**
* Returns {@value #ORDER}, which ensures that the {@code EventPublishingTestExecutionListener}
* is ordered after the
* {@link org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener
* SqlScriptsTestExecutionListener} and before the
* {@link org.springframework.test.context.bean.override.mockito.MockitoResetTestExecutionListener
* MockitoResetTestExecutionListener}.
*/
@Override
public final int getOrder() {
return ORDER;
}
/**
* Publish a {@link BeforeTestClassEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void beforeTestClass(TestContext testContext) {
testContext.publishEvent(BeforeTestClassEvent::new);
}
/**
* Publish a {@link PrepareTestInstanceEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void prepareTestInstance(TestContext testContext) {
testContext.publishEvent(PrepareTestInstanceEvent::new);
}
/**
* Publish a {@link BeforeTestMethodEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void beforeTestMethod(TestContext testContext) {
testContext.publishEvent(BeforeTestMethodEvent::new);
}
/**
* Publish a {@link BeforeTestExecutionEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void beforeTestExecution(TestContext testContext) {
testContext.publishEvent(BeforeTestExecutionEvent::new);
}
/**
* Publish an {@link AfterTestExecutionEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void afterTestExecution(TestContext testContext) {
testContext.publishEvent(AfterTestExecutionEvent::new);
}
/**
* Publish an {@link AfterTestMethodEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void afterTestMethod(TestContext testContext) {
testContext.publishEvent(AfterTestMethodEvent::new);
}
/**
* Publish an {@link AfterTestClassEvent} to the {@code ApplicationContext}
* for the supplied {@link TestContext}.
*/
@Override
public void afterTestClass(TestContext testContext) {
testContext.publishEvent(AfterTestClassEvent::new);
}
}
| EventPublishingTestExecutionListener |
java | apache__flink | flink-core/src/test/java/org/apache/flink/configuration/FilesystemSchemeConfigTest.java | {
"start": 1373,
"end": 3601
} | class ____ {
@TempDir private File tempFolder;
@AfterEach
void clearFsSettings() {
FileSystem.initialize(new Configuration());
}
// ------------------------------------------------------------------------
@Test
void testDefaultsToLocal() throws Exception {
URI justPath = new URI(File.createTempFile("junit", null, tempFolder).toURI().getPath());
assertThat(justPath.getScheme()).isNull();
FileSystem fs = FileSystem.get(justPath);
assertThat(fs.getUri().getScheme()).isEqualTo("file");
}
@Test
void testExplicitlySetToLocal() throws Exception {
final Configuration conf = new Configuration();
conf.set(CoreOptions.DEFAULT_FILESYSTEM_SCHEME, LocalFileSystem.getLocalFsURI().toString());
FileSystem.initialize(conf);
URI justPath = new URI(File.createTempFile("junit", null, tempFolder).toURI().getPath());
assertThat(justPath.getScheme()).isNull();
FileSystem fs = FileSystem.get(justPath);
assertThat(fs.getUri().getScheme()).isEqualTo("file");
}
@Test
void testExplicitlySetToOther() throws Exception {
final Configuration conf = new Configuration();
conf.set(CoreOptions.DEFAULT_FILESYSTEM_SCHEME, "otherFS://localhost:1234/");
FileSystem.initialize(conf);
URI justPath = new URI(File.createTempFile("junit", null, tempFolder).toURI().getPath());
assertThat(justPath.getScheme()).isNull();
assertThatThrownBy(() -> FileSystem.get(justPath))
.isInstanceOf(UnsupportedFileSystemSchemeException.class)
.hasMessageContaining("otherFS");
}
@Test
void testExplicitlyPathTakesPrecedence() throws Exception {
final Configuration conf = new Configuration();
conf.set(CoreOptions.DEFAULT_FILESYSTEM_SCHEME, "otherFS://localhost:1234/");
FileSystem.initialize(conf);
URI pathAndScheme = File.createTempFile("junit", null, tempFolder).toURI();
assertThat(pathAndScheme.getScheme()).isNotNull();
FileSystem fs = FileSystem.get(pathAndScheme);
assertThat(fs.getUri().getScheme()).isEqualTo("file");
}
}
| FilesystemSchemeConfigTest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/retry/RetryPolicies.java | {
"start": 22298,
"end": 28110
} | class ____ implements RetryPolicy {
private RetryPolicy fallbackPolicy;
private int maxFailovers;
private int maxRetries;
private long delayMillis;
private long maxDelayBase;
public FailoverOnNetworkExceptionRetry(RetryPolicy fallbackPolicy,
int maxFailovers) {
this(fallbackPolicy, maxFailovers, 0, 0, 0);
}
public FailoverOnNetworkExceptionRetry(RetryPolicy fallbackPolicy,
int maxFailovers, long delayMillis, long maxDelayBase) {
this(fallbackPolicy, maxFailovers, 0, delayMillis, maxDelayBase);
}
public FailoverOnNetworkExceptionRetry(RetryPolicy fallbackPolicy,
int maxFailovers, int maxRetries, long delayMillis, long maxDelayBase) {
this.fallbackPolicy = fallbackPolicy;
this.maxFailovers = maxFailovers;
this.maxRetries = maxRetries;
this.delayMillis = delayMillis;
this.maxDelayBase = maxDelayBase;
}
/**
* @return 0 if this is our first failover/retry (i.e., retry immediately),
* sleep exponentially otherwise
*/
private long getFailoverOrRetrySleepTime(int times) {
return times == 0 ? 0 :
calculateExponentialTime(delayMillis, times, maxDelayBase);
}
@Override
public RetryAction shouldRetry(Exception e, int retries,
int failovers, boolean isIdempotentOrAtMostOnce) throws Exception {
if (failovers >= maxFailovers) {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0,
"failovers (" + failovers + ") exceeded maximum allowed ("
+ maxFailovers + ")");
}
if (retries - failovers > maxRetries) {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0, "retries ("
+ retries + ") exceeded maximum allowed (" + maxRetries + ")");
}
if (isSaslFailure(e)) {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0,
"SASL failure");
}
if (e instanceof ConnectException ||
e instanceof EOFException ||
e instanceof NoRouteToHostException ||
e instanceof UnknownHostException ||
e instanceof StandbyException ||
e instanceof ConnectTimeoutException ||
shouldFailoverOnException(e)) {
return new RetryAction(RetryAction.RetryDecision.FAILOVER_AND_RETRY,
getFailoverOrRetrySleepTime(failovers));
} else if (e instanceof RetriableException
|| getWrappedRetriableException(e) != null) {
// RetriableException or RetriableException wrapped
return new RetryAction(RetryAction.RetryDecision.RETRY,
getFailoverOrRetrySleepTime(retries));
} else if (e instanceof InvalidToken) {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0,
"Invalid or Cancelled Token");
} else if (e instanceof AccessControlException ||
hasWrappedAccessControlException(e)) {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0,
"Access denied");
} else if (e instanceof SocketException
|| (e instanceof IOException && !(e instanceof RemoteException))) {
if (isIdempotentOrAtMostOnce) {
return new RetryAction(RetryAction.RetryDecision.FAILOVER_AND_RETRY,
getFailoverOrRetrySleepTime(retries));
} else {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0,
"the invoked method is not idempotent, and unable to determine "
+ "whether it was invoked");
}
} else {
return fallbackPolicy.shouldRetry(e, retries, failovers,
isIdempotentOrAtMostOnce);
}
}
}
/**
* Return a value which is <code>time</code> increasing exponentially as a
* function of <code>retries</code>, +/- 0%-50% of that value, chosen
* randomly.
*
* @param time the base amount of time to work with
* @param retries the number of retries that have so occurred so far
* @param cap value at which to cap the base sleep time
* @return an amount of time to sleep
*/
private static long calculateExponentialTime(long time, int retries,
long cap) {
long baseTime = Math.min(time * (1L << retries), cap);
return (long) (baseTime * (ThreadLocalRandom.current().nextDouble() + 0.5));
}
private static long calculateExponentialTime(long time, int retries) {
return calculateExponentialTime(time, retries, Long.MAX_VALUE);
}
private static boolean shouldFailoverOnException(Exception e) {
if (!(e instanceof RemoteException)) {
return false;
}
Exception unwrapped = ((RemoteException)e).unwrapRemoteException(
StandbyException.class,
ObserverRetryOnActiveException.class);
return unwrapped instanceof StandbyException;
}
private static boolean isSaslFailure(Exception e) {
Throwable current = e;
do {
if (current instanceof SaslException) {
return true;
}
current = current.getCause();
} while (current != null);
return false;
}
static RetriableException getWrappedRetriableException(Exception e) {
if (!(e instanceof RemoteException)) {
return null;
}
Exception unwrapped = ((RemoteException)e).unwrapRemoteException(
RetriableException.class);
return unwrapped instanceof RetriableException ?
(RetriableException) unwrapped : null;
}
private static boolean hasWrappedAccessControlException(Exception e) {
Throwable throwable = e;
while (!(throwable instanceof AccessControlException) &&
throwable.getCause() != null) {
throwable = throwable.getCause();
}
return throwable instanceof AccessControlException;
}
}
| FailoverOnNetworkExceptionRetry |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/support/replication/TransportReplicationAction.java | {
"start": 4228,
"end": 4717
} | class ____ requests that should be executed on a primary copy followed by replica copies.
* Subclasses can resolve the target shard and provide implementation for primary and replica operations.
* <p>
* The action samples cluster state on the receiving node to reroute to node with primary copy and on the
* primary node to validate request before primary operation followed by sampling state again for resolving
* nodes with replica copies to perform replication.
*/
public abstract | for |
java | apache__camel | components/camel-ai/camel-weaviate/src/main/java/org/apache/camel/component/weaviate/WeaviateVectorDbProducer.java | {
"start": 1758,
"end": 11656
} | class ____ extends DefaultProducer {
private WeaviateClient client;
private ExecutorService executor;
public WeaviateVectorDbProducer(WeaviateVectorDbEndpoint endpoint) {
super(endpoint);
}
@Override
public WeaviateVectorDbEndpoint getEndpoint() {
return (WeaviateVectorDbEndpoint) super.getEndpoint();
}
@Override
public void doStart() throws Exception {
super.doStart();
this.client = getEndpoint().getClient();
}
@Override
public void process(Exchange exchange) {
final Message in = exchange.getMessage();
final WeaviateVectorDbAction action = in.getHeader(WeaviateVectorDbHeaders.ACTION, WeaviateVectorDbAction.class);
try {
if (action == null) {
throw new NoSuchHeaderException("The action is a required header", exchange, WeaviateVectorDbHeaders.ACTION);
}
switch (action) {
case CREATE_COLLECTION:
createCollection(exchange);
break;
case CREATE:
create(exchange);
break;
case UPDATE_BY_ID:
updateById(exchange);
break;
case DELETE_BY_ID:
deleteById(exchange);
break;
case DELETE_COLLECTION:
deleteCollection(exchange);
break;
case QUERY:
query(exchange);
break;
case QUERY_BY_ID:
queryById(exchange);
break;
default:
throw new UnsupportedOperationException("Unsupported action: " + action.name());
}
} catch (Exception e) {
exchange.setException(e);
}
}
// ***************************************
//
// Actions
//
// ***************************************
private void createCollection(Exchange exchange) throws Exception {
final Message in = exchange.getMessage();
String collectionName;
if (in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class) != null) {
collectionName = in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class);
} else {
collectionName = getEndpoint().getCollection();
}
WeaviateClass collection = WeaviateClass.builder().className(collectionName).build();
Result<Boolean> res = client.misc().readyChecker().run();
Result<Boolean> result = client.schema().classCreator().withClass(collection).run();
populateResponse(result, exchange);
}
private void create(Exchange exchange) throws Exception {
final Message in = exchange.getMessage();
List elements = in.getMandatoryBody(List.class);
// Check the headers for a collection name. Use the endpoint's
// collection name by default
String collectionName;
if (in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class) != null) {
collectionName = in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class);
} else {
collectionName = getEndpoint().getCollection();
}
HashMap<String, Object> props = in.getHeader(WeaviateVectorDbHeaders.PROPERTIES, HashMap.class);
Float[] vectors = (Float[]) elements.toArray(new Float[0]);
Result<WeaviateObject> result = client.data().creator()
.withClassName(collectionName)
.withVector(vectors)
.withProperties(props)
.run();
populateResponse(result, exchange);
}
private void updateById(Exchange exchange) throws Exception {
final Message in = exchange.getMessage();
List elements = in.getMandatoryBody(List.class);
String indexId = ExchangeHelper.getMandatoryHeader(exchange, WeaviateVectorDbHeaders.INDEX_ID, String.class);
// Check the headers for a collection name. Use the endpoint's
// collection name by default
String collectionName;
if (in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class) != null) {
collectionName = in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class);
} else {
collectionName = getEndpoint().getCollection();
}
Float[] vectors = (Float[]) elements.toArray(new Float[0]);
HashMap<String, Object> props = in.getHeader(WeaviateVectorDbHeaders.PROPERTIES, HashMap.class);
ObjectUpdater ou = client.data().updater();
boolean updateWithMerge = in.getHeader(WeaviateVectorDbHeaders.UPDATE_WITH_MERGE, true, Boolean.class);
if (updateWithMerge) {
ou.withMerge();
}
Result<Boolean> result = ou
.withID(indexId)
.withClassName(collectionName)
.withVector(vectors)
.withProperties(props)
.run();
populateResponse(result, exchange);
}
private void deleteById(Exchange exchange) throws Exception {
final Message in = exchange.getMessage();
String indexId = ExchangeHelper.getMandatoryHeader(exchange, WeaviateVectorDbHeaders.INDEX_ID, String.class);
// Check the headers for a collection name. Use the endpoint's
// collection name by default
String collectionName;
if (in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class) != null) {
collectionName = in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class);
} else {
collectionName = getEndpoint().getCollection();
}
Result<Boolean> result = this.client.data().deleter()
.withClassName(collectionName)
.withID(indexId)
.run();
populateResponse(result, exchange);
}
private void deleteCollection(Exchange exchange) throws Exception {
final Message in = exchange.getMessage();
String collectionName;
if (in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class) != null) {
collectionName = in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class);
} else {
collectionName = getEndpoint().getCollection();
}
Result<Boolean> result = this.client.schema().classDeleter()
.withClassName(collectionName)
.run();
populateResponse(result, exchange);
}
private void query(Exchange exchange) throws Exception {
final Message in = exchange.getMessage();
List elements = in.getMandatoryBody(List.class);
// topK default of 10
int topK = 10;
if (in.getHeader(WeaviateVectorDbHeaders.QUERY_TOP_K, Integer.class) != null) {
topK = in.getHeader(WeaviateVectorDbHeaders.QUERY_TOP_K, Integer.class);
}
// Check the headers for a collection name. Use the endpoint's
// collection name by default
String collectionName;
if (in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class) != null) {
collectionName = in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class);
} else {
collectionName = getEndpoint().getCollection();
}
Float[] vectors = (Float[]) elements.toArray(new Float[0]);
NearVectorArgument nearVectorArg = NearVectorArgument.builder()
.vector(vectors)
.build();
Fields fields;
if (in.getHeader(WeaviateVectorDbHeaders.FIELDS, HashMap.class) != null) {
HashMap<String, Object> fieldToSearch = in.getHeader(WeaviateVectorDbHeaders.FIELDS, HashMap.class);
Field[] fieldArray
= fieldToSearch.keySet().stream().map(k -> Field.builder().name(k).build()).toArray(Field[]::new);
fields = Fields.builder().fields(fieldArray).build();
} else {
fields = Fields.builder().fields(new Field[0]).build();
}
String query = GetBuilder.builder()
.className(collectionName)
.fields(fields)
.withNearVectorFilter(nearVectorArg)
.limit(topK)
.build()
.buildQuery();
Result<GraphQLResponse> result = client.graphQL().raw().withQuery(query).run();
populateResponse(result, exchange);
}
private void queryById(Exchange exchange) throws Exception {
final Message in = exchange.getMessage();
String indexId = ExchangeHelper.getMandatoryHeader(exchange, WeaviateVectorDbHeaders.INDEX_ID, String.class);
// Check the headers for a collection name. Use the endpoint's
// collection name by default
String collectionName;
if (in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class) != null) {
collectionName = in.getHeader(WeaviateVectorDbHeaders.COLLECTION_NAME, String.class);
} else {
collectionName = getEndpoint().getCollection();
}
Result<List<WeaviateObject>> result = client.data().objectsGetter()
.withClassName(collectionName)
.withID(indexId)
.run();
populateResponse(result, exchange);
}
// ***************************************
//
// Helpers
//
// ***************************************
private CamelContext getCamelContext() {
return getEndpoint().getCamelContext();
}
private void populateResponse(Result<?> r, Exchange exchange) {
Message out = exchange.getMessage();
out.setBody(r);
}
}
| WeaviateVectorDbProducer |
java | apache__rocketmq | remoting/src/main/java/org/apache/rocketmq/remoting/protocol/body/QueryConsumeTimeSpanBody.java | {
"start": 982,
"end": 1350
} | class ____ extends RemotingSerializable {
List<QueueTimeSpan> consumeTimeSpanSet = new ArrayList<>();
public List<QueueTimeSpan> getConsumeTimeSpanSet() {
return consumeTimeSpanSet;
}
public void setConsumeTimeSpanSet(List<QueueTimeSpan> consumeTimeSpanSet) {
this.consumeTimeSpanSet = consumeTimeSpanSet;
}
}
| QueryConsumeTimeSpanBody |
java | elastic__elasticsearch | x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/secrets/action/RestDeleteConnectorSecretAction.java | {
"start": 711,
"end": 1404
} | class ____ extends BaseRestHandler {
@Override
public String getName() {
return "connector_delete_secret";
}
@Override
public List<Route> routes() {
return List.of(new Route(RestRequest.Method.DELETE, "/_connector/_secret/{id}"));
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
final String id = request.param("id");
return restChannel -> client.execute(
DeleteConnectorSecretAction.INSTANCE,
new DeleteConnectorSecretRequest(id),
new RestToXContentListener<>(restChannel)
);
}
}
| RestDeleteConnectorSecretAction |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/web/servlet/result/PrintingResultHandlerTests.java | {
"start": 12212,
"end": 12844
} | class ____ implements ResultValuePrinter {
private String printedHeading;
private final Map<String, Map<String, Object>> printedValues = new HashMap<>();
@Override
public void printHeading(String heading) {
this.printedHeading = heading;
this.printedValues.put(heading, new HashMap<>());
}
@Override
public void printValue(String label, Object value) {
Assert.notNull(this.printedHeading,
"Heading not printed before label " + label + " with value " + value);
this.printedValues.get(this.printedHeading).put(label, value);
}
}
}
public void handle() {
}
}
| TestResultValuePrinter |
java | spring-projects__spring-framework | spring-core-test/src/test/java/org/springframework/core/test/tools/SourceFileAssertTests.java | {
"start": 1053,
"end": 2021
} | class ____ implements Runnable {
void run() {
run("Hello World!");
}
void run(String message) {
System.out.println(message);
}
public static void main(String[] args) {
new Sample().run();
}
}
""";
private final SourceFile sourceFile = SourceFile.of(SAMPLE);
@Test
void containsWhenContainsAll() {
assertThat(this.sourceFile).contains("Sample", "main");
}
@Test
void containsWhenMissingOneThrowsException() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> assertThat(this.sourceFile).contains("Sample",
"missing")).withMessageContaining("to contain");
}
@Test
void isEqualToWhenEqual() {
assertThat(this.sourceFile).hasContent(SAMPLE);
}
@Test
void isEqualToWhenNotEqualThrowsException() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> assertThat(this.sourceFile).hasContent("no")).withMessageContaining(
"expected", "but was");
}
}
| Sample |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/TreatKeywordTest.java | {
"start": 14749,
"end": 14961
} | class ____ extends Animal {
private boolean fast;
protected Dog(boolean fast) {
this.fast = fast;
}
public final boolean isFast() {
return fast;
}
}
@Entity(name = "Dachshund")
public static | Dog |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/type/EsqlDataTypeRegistry.java | {
"start": 418,
"end": 1121
} | class ____ {
public static final EsqlDataTypeRegistry INSTANCE = new EsqlDataTypeRegistry();
private EsqlDataTypeRegistry() {}
public DataType fromEs(String typeName, TimeSeriesParams.MetricType metricType) {
DataType type = DataType.fromEs(typeName);
/*
* If we're handling a time series COUNTER type field then convert it
* into it's counter. But *first* we have to widen it because we only
* have time series counters for `double`, `long` and `int`, not `float`
* and `half_float`, etc.
*/
return metricType == TimeSeriesParams.MetricType.COUNTER ? type.widenSmallNumeric().counter() : type;
}
}
| EsqlDataTypeRegistry |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/inotify/Event.java | {
"start": 15220,
"end": 15326
} | class ____ extends Event {
private String path;
private long timestamp;
public static | UnlinkEvent |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/util/ResourceUtilsTests.java | {
"start": 4459,
"end": 4514
} | class ____ parsing "rmi:..." URLs.
*/
private static | for |
java | apache__avro | lang/java/mapred/src/main/java/org/apache/avro/hadoop/file/SortedKeyValueFile.java | {
"start": 10568,
"end": 11489
} | class ____ does
// not
// mandate the implementation of Comparable, we need to specify a special
// CharSequence comparator if the key type is a string. This hack only fixes the
// problem for primitive string types. If, for example, you tried to use a
// record
// type as the key, any string fields inside of it would not be compared
// correctly
// against java.lang.Strings.
index = new TreeMap<>(new AvroCharSequenceComparator<>());
}
for (GenericRecord genericRecord : fileReader) {
AvroKeyValue<K, Long> indexRecord = new AvroKeyValue<>(genericRecord);
index.put(indexRecord.getKey(), indexRecord.getValue());
}
}
return index;
}
}
/**
* Writes a SortedKeyValueFile.
*
* @param <K> The key type.
* @param <V> The value type.
*/
public static | that |
java | google__guice | core/test/com/google/inject/ProvisionListenerTest.java | {
"start": 28475,
"end": 28553
} | class ____ implements B {
@Inject
void inject(C c) {}
}
private | BImpl |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/sql/SqlJsonQueryFunctionWrapper.java | {
"start": 1851,
"end": 5590
} | class ____ extends SqlJsonQueryFunction {
private final SqlReturnTypeInference returnTypeInference;
SqlJsonQueryFunctionWrapper() {
this.returnTypeInference =
ReturnTypes.cascade(
SqlJsonQueryFunctionWrapper::explicitTypeSpec,
SqlTypeTransforms.FORCE_NULLABLE)
.orElse(VARCHAR_FORCE_NULLABLE);
}
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
RelDataType returnType = returnTypeInference.inferReturnType(opBinding);
if (returnType == null) {
throw new IllegalArgumentException(
"Cannot infer return type for "
+ opBinding.getOperator()
+ "; operand types: "
+ opBinding.collectOperandTypes());
}
return returnType;
}
@Override
public SqlReturnTypeInference getReturnTypeInference() {
return returnTypeInference;
}
@Override
public boolean checkOperandTypes(SqlCallBinding callBinding, boolean throwOnFailure) {
if (!super.checkOperandTypes(callBinding, throwOnFailure)) {
return false;
}
if (callBinding.getOperandCount() >= 6) {
final RelDataType type = SqlTypeUtil.deriveType(callBinding, callBinding.operand(5));
if (SqlTypeUtil.isArray(type)) {
return checkOperandsForArrayReturnType(throwOnFailure, type, callBinding);
}
}
return true;
}
private static boolean checkOperandsForArrayReturnType(
boolean throwOnFailure, RelDataType type, SqlCallBinding callBinding) {
if (!SqlTypeUtil.isCharacter(type.getComponentType())) {
if (throwOnFailure) {
throw new ValidationException(
String.format(
"Unsupported array element type '%s' for RETURNING ARRAY in JSON_QUERY().",
type.getComponentType()));
} else {
return false;
}
}
if (SqlJsonQueryEmptyOrErrorBehavior.EMPTY_OBJECT.equals(
getEnumValue(callBinding.operand(4)))) {
if (throwOnFailure) {
throw new ValidationException(
String.format(
"Illegal on error behavior 'EMPTY OBJECT' for return type: %s",
type));
} else {
return false;
}
}
if (SqlJsonQueryEmptyOrErrorBehavior.EMPTY_OBJECT.equals(
getEnumValue(callBinding.operand(3)))) {
if (throwOnFailure) {
throw new ValidationException(
String.format(
"Illegal on empty behavior 'EMPTY OBJECT' for return type: %s",
type));
} else {
return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
private static <E extends Enum<E>> E getEnumValue(SqlNode operand) {
return (E) requireNonNull(((SqlLiteral) operand).getValue(), "operand.value");
}
/**
* Copied and modified from the original {@link SqlJsonValueFunction}.
*
* <p>Changes: Instead of returning {@link Optional} this method returns null directly.
*/
private static RelDataType explicitTypeSpec(SqlOperatorBinding opBinding) {
if (opBinding.getOperandCount() >= 6) {
return opBinding.getOperandType(5);
}
return null;
}
}
| SqlJsonQueryFunctionWrapper |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/OpenFilesIterator.java | {
"start": 1444,
"end": 1692
} | class ____ extends
BatchedRemoteIterator<Long, OpenFileEntry> {
/** No path to be filtered by default. */
public static final String FILTER_PATH_DEFAULT = "/";
/**
* Open file types to filter the results.
*/
public | OpenFilesIterator |
java | google__guava | android/guava-tests/test/com/google/common/primitives/FloatArrayAsListTest.java | {
"start": 5595,
"end": 5729
} | class ____ extends SampleElements<Float> {
public SampleFloats() {
super(0.0f, 1.0f, 2.0f, 3.0f, 4.0f);
}
}
}
| SampleFloats |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng0496IgnoreUnknownPluginParametersTest.java | {
"start": 1034,
"end": 1859
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test that unused configuration parameters from the POM don't cause the
* mojo to fail...they will show up as warnings in the -X output instead.
*
* @throws Exception in case of failure
*/
@Test
public void testitMNG496() throws Exception {
File testDir = extractResources("/mng-0496");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("org.apache.maven.its.plugins:maven-it-plugin-log-file:2.1-SNAPSHOT:reset");
verifier.execute();
verifier.verifyFilePresent("target/file.txt");
verifier.verifyErrorFreeLog();
}
}
| MavenITmng0496IgnoreUnknownPluginParametersTest |
java | spring-projects__spring-framework | spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/AbstractJCacheOperation.java | {
"start": 6377,
"end": 7040
} | class ____ implements CacheInvocationParameter {
private final CacheParameterDetail detail;
private final @Nullable Object value;
public CacheInvocationParameterImpl(CacheParameterDetail detail, @Nullable Object value) {
this.detail = detail;
this.value = value;
}
@Override
public Class<?> getRawType() {
return this.detail.rawType;
}
@Override
public @Nullable Object getValue() {
return this.value;
}
@Override
public Set<Annotation> getAnnotations() {
return this.detail.annotations;
}
@Override
public int getParameterPosition() {
return this.detail.parameterPosition;
}
}
}
| CacheInvocationParameterImpl |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/cache/LazyInCacheTest.java | {
"start": 2792,
"end": 2953
} | class ____ {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
Long id;
String name;
}
@Entity(name = "Tag")
@Table( name = "TAG" )
static | Product |
java | redisson__redisson | redisson/src/main/java/org/redisson/client/protocol/decoder/TimeLongObjectDecoder.java | {
"start": 812,
"end": 1367
} | class ____ implements MultiDecoder<Long> {
private final TimeUnit timeUnit;
public TimeLongObjectDecoder() {
this(null);
}
public TimeLongObjectDecoder(TimeUnit timeUnit) {
this.timeUnit = timeUnit;
}
@Override
public Long decode(List<Object> parts, State state) {
long time = ((Long) parts.get(0)) * 1000L + ((Long) parts.get(1)) / 1000L;
if (timeUnit != null) {
return timeUnit.convert(time, TimeUnit.MILLISECONDS);
}
return time;
}
}
| TimeLongObjectDecoder |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/IdentityHashMapUsage.java | {
"start": 2031,
"end": 4723
} | class ____ extends BugChecker
implements MethodInvocationTreeMatcher,
AssignmentTreeMatcher,
VariableTreeMatcher,
NewClassTreeMatcher {
private static final String IDENTITY_HASH_MAP = "java.util.IdentityHashMap";
private static final Matcher<ExpressionTree> IHM_ONE_ARG_METHODS =
instanceMethod().onExactClass(IDENTITY_HASH_MAP).namedAnyOf("equals", "putAll");
private static final Matcher<ExpressionTree> IHM_CTOR_MAP_ARG =
constructor().forClass(IDENTITY_HASH_MAP).withParameters("java.util.Map");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (IHM_ONE_ARG_METHODS.matches(tree, state)
&& !ASTHelpers.isSameType(
ASTHelpers.getType(tree.getArguments().getFirst()),
JAVA_UTIL_IDENTITYHASHMAP.get(state),
state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
@Override
public Description matchAssignment(AssignmentTree tree, VisitorState state) {
Type ihmType = JAVA_UTIL_IDENTITYHASHMAP.get(state);
if (!ASTHelpers.isSameType(ASTHelpers.getType(tree.getExpression()), ihmType, state)) {
return Description.NO_MATCH;
}
if (!ASTHelpers.isSameType(ASTHelpers.getType(tree.getVariable()), ihmType, state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
if (tree.getInitializer() == null) {
// method params don't have initializers.
return Description.NO_MATCH;
}
Type ihmType = JAVA_UTIL_IDENTITYHASHMAP.get(state);
if (ASTHelpers.isSameType(ASTHelpers.getType(tree.getType()), ihmType, state)) {
return Description.NO_MATCH;
}
Type type = ASTHelpers.getType(tree.getInitializer());
if (ASTHelpers.isSameType(type, ihmType, state)) {
SuggestedFix.Builder fix = SuggestedFix.builder();
fix.replace(tree.getType(), SuggestedFixes.qualifyType(state, fix, type));
return describeMatch(tree, fix.build());
}
return Description.NO_MATCH;
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (IHM_CTOR_MAP_ARG.matches(tree, state)
&& !ASTHelpers.isSameType(
ASTHelpers.getType(tree.getArguments().getFirst()),
JAVA_UTIL_IDENTITYHASHMAP.get(state),
state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
private static final Supplier<Type> JAVA_UTIL_IDENTITYHASHMAP =
VisitorState.memoize(state -> state.getTypeFromString(IDENTITY_HASH_MAP));
}
| IdentityHashMapUsage |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/DuplicateDateFormatFieldTest.java | {
"start": 4936,
"end": 5366
} | class ____ {
// BUG: Diagnostic contains: uses the field 'm' more than once
SimpleDateFormat format = new SimpleDateFormat("hh:mm[:ss[.SSS]] yyyy/mm/dd");
}
""")
.doTest();
}
@Test
public void noDupliatedFields() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import java.text.SimpleDateFormat;
| Test |
java | apache__camel | components/camel-asterisk/src/generated/java/org/apache/camel/component/asterisk/AsteriskEndpointConfigurer.java | {
"start": 735,
"end": 4062
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
AsteriskEndpoint target = (AsteriskEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "action": target.setAction(property(camelContext, org.apache.camel.component.asterisk.AsteriskAction.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "exceptionhandler":
case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
case "exchangepattern":
case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
case "hostname": target.setHostname(property(camelContext, java.lang.String.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "password": target.setPassword(property(camelContext, java.lang.String.class, value)); return true;
case "username": target.setUsername(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "action": return org.apache.camel.component.asterisk.AsteriskAction.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "exceptionhandler":
case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class;
case "exchangepattern":
case "exchangePattern": return org.apache.camel.ExchangePattern.class;
case "hostname": return java.lang.String.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "password": return java.lang.String.class;
case "username": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
AsteriskEndpoint target = (AsteriskEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "action": return target.getAction();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "exceptionhandler":
case "exceptionHandler": return target.getExceptionHandler();
case "exchangepattern":
case "exchangePattern": return target.getExchangePattern();
case "hostname": return target.getHostname();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "password": return target.getPassword();
case "username": return target.getUsername();
default: return null;
}
}
}
| AsteriskEndpointConfigurer |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/bugs/CompareMatcherTest.java | {
"start": 3171,
"end": 3556
} | class ____ extends GenericMatcher<Integer> {
@Override
public boolean matches(Integer argument) {
return false;
}
}
when(mock.forObject(argThat(new TestMatcher()))).thenReturn("x");
assertThat(mock.forObject(123)).isNull();
}
@Test
public void matchesWithSubTypeGenericMethod() {
| TestMatcher |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/config/ConsumerTemplateAutoRegisterTest.java | {
"start": 1295,
"end": 1916
} | class ____ extends SpringRunWithTestSupport {
@Autowired
private ConsumerTemplate template;
@Autowired
private CamelContext context;
@Test
public void testHasTemplate() {
assertNotNull(template, "Should have injected a consumer template");
assertNotNull(((DefaultConsumerTemplate) template).getCamelContext(), "The template context should not be null");
ConsumerTemplate lookup = context.getRegistry().lookupByNameAndType("consumerTemplate", ConsumerTemplate.class);
assertNotNull(lookup, "Should lookup consumer template");
}
}
| ConsumerTemplateAutoRegisterTest |
java | google__guava | android/guava/src/com/google/common/collect/ConsumingQueueIterator.java | {
"start": 939,
"end": 990
} | class ____ not thread safe.
*/
@GwtCompatible
final | is |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/physical/stream/DuplicateChangesInferRule.java | {
"start": 10342,
"end": 10870
} | interface ____ extends RelRule.Config {
Config DEFAULT =
ImmutableDuplicateChangesInferRule.Config.builder()
.build()
.withOperandSupplier(b0 -> b0.operand(StreamPhysicalRel.class).anyInputs())
.withDescription("DuplicateChangesInferRule")
.as(Config.class);
@Override
default DuplicateChangesInferRule toRule() {
return new DuplicateChangesInferRule(this);
}
}
}
| Config |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/placement/PlacementRule.java | {
"start": 1760,
"end": 4176
} | class ____.
*/
public String getName() {
return this.getClass().getName();
}
/**
* Initialize the rule with the scheduler.
* @param scheduler the scheduler using the rule
* @return <code>true</code> or <code>false</code> The outcome of the
* initialisation, rule dependent response which might not be persisted in
* the rule.
* @throws IOException for any errors
*/
public abstract boolean initialize(ResourceScheduler scheduler)
throws IOException;
/**
* Return the scheduler queue name the application should be placed in
* wrapped in an {@link ApplicationPlacementContext} object.
*
* A non <code>null</code> return value places the application in a queue,
* a <code>null</code> value means the queue is not yet determined. The
* next {@link PlacementRule} in the list maintained in the
* {@link PlacementManager} will be executed.
*
* @param asc The context of the application created on submission
* @param user The name of the user submitting the application
*
* @throws YarnException for any error while executing the rule
*
* @return The queue name wrapped in {@link ApplicationPlacementContext} or
* <code>null</code> if no queue was resolved
*/
public abstract ApplicationPlacementContext getPlacementForApp(
ApplicationSubmissionContext asc, String user) throws YarnException;
/**
* Return the scheduler queue name the application should be placed in
* wrapped in an {@link ApplicationPlacementContext} object.
*
* A non <code>null</code> return value places the application in a queue,
* a <code>null</code> value means the queue is not yet determined. The
* next {@link PlacementRule} in the list maintained in the
* {@link PlacementManager} will be executed.
*
* @param asc The context of the application created on submission
* @param user The name of the user submitting the application
* @param recovery Indicates if the submission is a recovery
*
* @throws YarnException for any error while executing the rule
*
* @return The queue name wrapped in {@link ApplicationPlacementContext} or
* <code>null</code> if no queue was resolved
*/
public ApplicationPlacementContext getPlacementForApp(
ApplicationSubmissionContext asc, String user, boolean recovery)
throws YarnException {
return getPlacementForApp(asc, user);
}
} | name |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/mysql/parser/MySqlSelectParser.java | {
"start": 4043,
"end": 31920
} | class ____ implements Lexer.CommentHandler {
private MySqlSelectQueryBlock queryBlock;
private Lexer lexer;
QueryHintHandler(MySqlSelectQueryBlock queryBlock, Lexer lexer) {
this.queryBlock = queryBlock;
this.lexer = lexer;
}
@Override
public boolean handle(Token lastToken, String comment) {
if (lexer.isEnabled(SQLParserFeature.TDDLHint)
&& (comment.startsWith("+ TDDL")
|| comment.startsWith("+TDDL")
|| comment.startsWith("!TDDL")
|| comment.startsWith("TDDL"))) {
SQLCommentHint hint = new TDDLHint(comment);
if (lexer.getCommentCount() > 0) {
hint.addBeforeComment(lexer.getComments());
}
queryBlock.getHints().add(hint);
lexer.nextToken();
}
return false;
}
}
this.lexer.setCommentHandler(new QueryHintHandler(queryBlock, this.lexer));
if (lexer.hasComment() && lexer.isKeepComments()) {
queryBlock.addBeforeComment(lexer.readAndResetComments());
}
if (lexer.token() == Token.SELECT) {
if (selectListCache != null) {
selectListCache.match(lexer, queryBlock);
}
}
if (lexer.token() == Token.SELECT) {
lexer.nextTokenValue();
for (; ; ) {
if (lexer.token() == Token.HINT) {
this.exprParser.parseHints(queryBlock.getHints());
} else {
break;
}
}
while (true) {
Token token = lexer.token();
if (token == (Token.DISTINCT)) {
queryBlock.setDistionOption(SQLSetQuantifier.DISTINCT);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.DISTINCTROW)) {
queryBlock.setDistionOption(SQLSetQuantifier.DISTINCTROW);
lexer.nextToken();
} else if (token == (Token.ALL)) {
queryBlock.setDistionOption(SQLSetQuantifier.ALL);
lexer.nextToken();
} else if (token == (Token.UNIQUE)) {
queryBlock.setDistionOption(SQLSetQuantifier.UNIQUE);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.HIGH_PRIORITY)) {
queryBlock.setHignPriority(true);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.STRAIGHT_JOIN)) {
queryBlock.setStraightJoin(true);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.SQL_SMALL_RESULT)) {
queryBlock.setSmallResult(true);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.SQL_BIG_RESULT)) {
queryBlock.setBigResult(true);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.SQL_BUFFER_RESULT)) {
queryBlock.setBufferResult(true);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.SQL_CACHE)) {
queryBlock.setCache(true);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.SQL_NO_CACHE)) {
queryBlock.setCache(false);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.SQL_CALC_FOUND_ROWS)) {
queryBlock.setCalcFoundRows(true);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.TOP)) {
Lexer.SavePoint mark = lexer.mark();
lexer.nextToken();
if (lexer.token() == Token.LITERAL_INT) {
SQLLimit limit = new SQLLimit(lexer.integerValue().intValue());
queryBlock.setLimit(limit);
lexer.nextToken();
} else if (lexer.token() == Token.DOT) {
lexer.reset(mark);
break;
}
} else {
break;
}
}
parseSelectList(queryBlock);
if (lexer.identifierEquals(FnvHash.Constants.FORCE)) {
lexer.nextToken();
accept(Token.PARTITION);
SQLName partition = this.exprParser.name();
queryBlock.setForcePartition(partition);
}
parseInto(queryBlock);
}
parseFrom(queryBlock);
parseWhere(queryBlock);
parseHierachical(queryBlock);
if (lexer.token() == Token.GROUP || lexer.token() == Token.HAVING) {
parseGroupBy(queryBlock);
}
if (lexer.identifierEquals(FnvHash.Constants.WINDOW)) {
parseWindow(queryBlock);
}
if (lexer.token() == Token.ORDER) {
queryBlock.setOrderBy(this.exprParser.parseOrderBy());
}
if (lexer.token() == Token.LIMIT) {
queryBlock.setLimit(this.exprParser.parseLimit());
}
if (lexer.token() == Token.FETCH) {
final Lexer.SavePoint mark = lexer.mark();
lexer.nextToken();
if (lexer.identifierEquals(FnvHash.Constants.NEXT)) {
lexer.nextToken();
SQLExpr rows = this.exprParser.primary();
queryBlock.setLimit(
new SQLLimit(rows));
acceptIdentifier("ROWS");
acceptIdentifier("ONLY");
} else {
lexer.reset(mark);
}
}
if (lexer.token() == Token.PROCEDURE) {
lexer.nextToken();
throw new ParserException("TODO. " + lexer.info());
}
if (lexer.token() == Token.INTO) {
parseInto(queryBlock);
}
if (lexer.token() == Token.FOR) {
lexer.nextToken();
if (lexer.token() == Token.UPDATE) {
lexer.nextToken();
queryBlock.setForUpdate(true);
if (lexer.identifierEquals(FnvHash.Constants.NO_WAIT)
|| lexer.identifierEquals(FnvHash.Constants.NOWAIT)) {
lexer.nextToken();
queryBlock.setNoWait(true);
} else if (lexer.identifierEquals(FnvHash.Constants.WAIT)) {
lexer.nextToken();
SQLExpr waitTime = this.exprParser.primary();
queryBlock.setWaitTime(waitTime);
}
if (lexer.identifierEquals(FnvHash.Constants.SKIP)) {
lexer.nextToken();
acceptIdentifier("LOCKED");
queryBlock.setSkipLocked(true);
}
} else {
acceptIdentifier("SHARE");
queryBlock.setForShare(true);
}
}
if (lexer.token() == Token.LOCK) {
lexer.nextToken();
accept(Token.IN);
acceptIdentifier("SHARE");
acceptIdentifier("MODE");
queryBlock.setLockInShareMode(true);
}
if (hints != null) {
queryBlock.setHints(hints);
}
if (lexer.hasComment() && lexer.isKeepComments()) {
queryBlock.addAfterComment(lexer.readAndResetComments());
}
return queryRest(queryBlock, acceptUnion);
}
public SQLTableSource parseTableSource() {
return parseTableSource(null);
}
public SQLTableSource parseTableSource(SQLObject parent) {
if (lexer.token() == Token.LPAREN) {
lexer.nextToken();
List hints = null;
if (lexer.token() == Token.HINT) {
hints = new ArrayList();
this.exprParser.parseHints(hints);
}
SQLTableSource tableSource;
if (lexer.token() == Token.SELECT || lexer.token() == Token.WITH) {
SQLSelect select = select();
accept(Token.RPAREN);
SQLSelectQueryBlock innerQuery = select.getQueryBlock();
boolean noOrderByAndLimit = innerQuery instanceof SQLSelectQueryBlock
&& ((SQLSelectQueryBlock) innerQuery).getOrderBy() == null
&& ((SQLSelectQueryBlock) select.getQuery()).getLimit() == null;
if (lexer.token() == Token.LIMIT) {
SQLLimit limit = this.exprParser.parseLimit();
if (parent != null && parent instanceof SQLSelectQueryBlock) {
((SQLSelectQueryBlock) parent).setLimit(limit);
}
if (parent == null && noOrderByAndLimit) {
innerQuery.setLimit(limit);
}
} else if (lexer.token() == Token.ORDER) {
SQLOrderBy orderBy = this.exprParser.parseOrderBy();
if (parent != null && parent instanceof SQLSelectQueryBlock) {
((SQLSelectQueryBlock) parent).setOrderBy(orderBy);
}
if (parent == null && noOrderByAndLimit) {
innerQuery.setOrderBy(orderBy);
}
}
SQLSelectQuery query = queryRest(select.getQuery(), false);
if (query instanceof SQLUnionQuery && select.getWithSubQuery() == null) {
select.getQuery().setParenthesized(true);
tableSource = new SQLUnionQueryTableSource((SQLUnionQuery) query);
} else {
tableSource = SQLSubqueryTableSource.fixParenthesized(new SQLSubqueryTableSource(select));
}
if (hints != null) {
tableSource.getHints().addAll(hints);
}
} else if (lexer.token() == Token.LPAREN) {
tableSource = parseTableSource();
if (lexer.token() != Token.RPAREN && tableSource instanceof SQLSubqueryTableSource) {
SQLSubqueryTableSource sqlSubqueryTableSource = (SQLSubqueryTableSource) tableSource;
SQLSelect select = sqlSubqueryTableSource.getSelect();
SQLSelectQuery query = queryRest(select.getQuery(), true);
if (query instanceof SQLUnionQuery && select.getWithSubQuery() == null) {
select.getQuery().setParenthesized(true);
tableSource = new SQLUnionQueryTableSource((SQLUnionQuery) query);
} else {
tableSource = SQLSubqueryTableSource.fixParenthesized(new SQLSubqueryTableSource(select));
}
if (hints != null) {
tableSource.getHints().addAll(hints);
}
} else if (lexer.token() != Token.RPAREN && tableSource instanceof SQLUnionQueryTableSource) {
SQLUnionQueryTableSource unionQueryTableSource = (SQLUnionQueryTableSource) tableSource;
SQLUnionQuery unionQuery = unionQueryTableSource.getUnion();
SQLSelectQuery query = queryRest(unionQuery, true);
if (query instanceof SQLUnionQuery) {
unionQuery.setParenthesized(true);
tableSource = new SQLUnionQueryTableSource((SQLUnionQuery) query);
} else {
tableSource = SQLSubqueryTableSource.fixParenthesized(new SQLSubqueryTableSource(unionQuery));
}
if (hints != null) {
tableSource.getHints().addAll(hints);
}
}
accept(Token.RPAREN);
} else {
tableSource = parseTableSource();
accept(Token.RPAREN);
if (lexer.token() == Token.AS
&& tableSource instanceof SQLValuesTableSource) {
lexer.nextToken();
String alias = lexer.stringVal();
lexer.nextToken();
tableSource.setAlias(alias);
accept(Token.LPAREN);
SQLValuesTableSource values = (SQLValuesTableSource) tableSource;
this.exprParser.names(values.getColumns(), tableSource);
accept(Token.RPAREN);
}
}
return parseTableSourceRest(tableSource);
} else if (lexer.token() == Token.LBRACE) {
accept(Token.LBRACE);
acceptIdentifier("OJ");
SQLTableSource tableSrc = parseTableSource();
accept(Token.RBRACE);
tableSrc = parseTableSourceRest(tableSrc);
if (lexer.hasComment() && lexer.isKeepComments()) {
tableSrc.addAfterComment(lexer.readAndResetComments());
}
return tableSrc;
}
if (lexer.token() == Token.VALUES) {
return parseValues();
}
if (lexer.token() == Token.UPDATE) {
SQLTableSource tableSource = new MySqlUpdateTableSource(parseUpdateStatment());
return parseTableSourceRest(tableSource);
}
if (lexer.token() == Token.SELECT) {
throw new ParserException("TODO. " + lexer.info());
}
SQLTableSource unnestTableSource = parseUnnestTableSource();
if (unnestTableSource != null) {
SQLTableSource tableSrc = parseTableSourceRest(unnestTableSource);
return tableSrc;
}
SQLExprTableSource tableReference = new SQLExprTableSource();
parseTableSourceQueryTableExpr(tableReference);
SQLTableSource tableSrc = parseTableSourceRest(tableReference);
if (lexer.hasComment() && lexer.isKeepComments()) {
tableSrc.addAfterComment(lexer.readAndResetComments());
}
return tableSrc;
}
protected MySqlUpdateStatement parseUpdateStatment() {
MySqlUpdateStatement update = new MySqlUpdateStatement();
lexer.nextToken();
if (lexer.identifierEquals(FnvHash.Constants.LOW_PRIORITY)) {
lexer.nextToken();
update.setLowPriority(true);
}
if (lexer.identifierEquals(FnvHash.Constants.IGNORE)) {
lexer.nextToken();
update.setIgnore(true);
}
if (lexer.identifierEquals(FnvHash.Constants.COMMIT_ON_SUCCESS)) {
lexer.nextToken();
update.setCommitOnSuccess(true);
}
if (lexer.identifierEquals(FnvHash.Constants.ROLLBACK_ON_FAIL)) {
lexer.nextToken();
update.setRollBackOnFail(true);
}
if (lexer.identifierEquals(FnvHash.Constants.QUEUE_ON_PK)) {
lexer.nextToken();
update.setQueryOnPk(true);
}
if (lexer.identifierEquals(FnvHash.Constants.TARGET_AFFECT_ROW)) {
lexer.nextToken();
SQLExpr targetAffectRow = this.exprParser.expr();
update.setTargetAffectRow(targetAffectRow);
}
if (lexer.identifierEquals(FnvHash.Constants.FORCE)) {
lexer.nextToken();
if (lexer.token() == Token.ALL) {
lexer.nextToken();
acceptIdentifier("PARTITIONS");
update.setForceAllPartitions(true);
} else if (lexer.identifierEquals(FnvHash.Constants.PARTITIONS)) {
lexer.nextToken();
update.setForceAllPartitions(true);
} else if (lexer.token() == Token.PARTITION) {
lexer.nextToken();
SQLName partition = this.exprParser.name();
update.setForcePartition(partition);
} else {
throw new ParserException("TODO. " + lexer.info());
}
}
while (lexer.token() == Token.HINT) {
this.exprParser.parseHints(update.getHints());
}
SQLSelectParser selectParser = this.exprParser.createSelectParser();
SQLTableSource updateTableSource = selectParser.parseTableSource();
update.setTableSource(updateTableSource);
accept(Token.SET);
for (; ; ) {
SQLUpdateSetItem item = this.exprParser.parseUpdateSetItem();
update.addItem(item);
if (lexer.token() != Token.COMMA) {
break;
}
lexer.nextToken();
}
if (lexer.token() == (Token.WHERE)) {
lexer.nextToken();
update.setWhere(this.exprParser.expr());
}
update.setOrderBy(this.exprParser.parseOrderBy());
update.setLimit(this.exprParser.parseLimit());
return update;
}
protected void parseInto(SQLSelectQueryBlock queryBlock) {
if (lexer.token() != Token.INTO) {
return;
}
lexer.nextToken();
if (lexer.identifierEquals(FnvHash.Constants.OUTFILE)) {
lexer.nextToken();
MySqlOutFileExpr outFile = new MySqlOutFileExpr();
outFile.setFile(expr());
queryBlock.setInto(outFile);
if (lexer.identifierEquals(FnvHash.Constants.FIELDS) || lexer.identifierEquals(FnvHash.Constants.COLUMNS)) {
lexer.nextToken();
if (lexer.identifierEquals(FnvHash.Constants.TERMINATED)) {
lexer.nextToken();
accept(Token.BY);
}
outFile.setColumnsTerminatedBy(expr());
if (lexer.identifierEquals(FnvHash.Constants.OPTIONALLY)) {
lexer.nextToken();
outFile.setColumnsEnclosedOptionally(true);
}
if (lexer.identifierEquals(FnvHash.Constants.ENCLOSED)) {
lexer.nextToken();
accept(Token.BY);
outFile.setColumnsEnclosedBy((SQLLiteralExpr) expr());
}
if (lexer.identifierEquals(FnvHash.Constants.ESCAPED)) {
lexer.nextToken();
accept(Token.BY);
outFile.setColumnsEscaped((SQLLiteralExpr) expr());
}
}
if (lexer.identifierEquals(FnvHash.Constants.LINES)) {
lexer.nextToken();
if (lexer.identifierEquals(FnvHash.Constants.STARTING)) {
lexer.nextToken();
accept(Token.BY);
outFile.setLinesStartingBy((SQLLiteralExpr) expr());
} else {
if (lexer.identifierEquals(FnvHash.Constants.TERMINATED)) {
lexer.nextToken();
}
accept(Token.BY);
outFile.setLinesTerminatedBy((SQLLiteralExpr) expr());
}
}
} else {
SQLExpr expr = this.expr();
if (lexer.token() != Token.COMMA) {
queryBlock.setInto(expr);
return;
}
SQLListExpr list = new SQLListExpr();
list.addItem(expr);
while (lexer.token() == Token.COMMA) {
lexer.nextToken();
list.addItem(expr());
}
queryBlock.setInto(list);
}
}
protected SQLTableSource primaryTableSourceRest(SQLTableSource tableSource) {
if (lexer.token() == Token.USE) {
lexer.nextToken();
MySqlUseIndexHint hint = new MySqlUseIndexHint();
parseIndexHint(hint);
tableSource.getHints().add(hint);
}
if (lexer.identifierEquals(FnvHash.Constants.IGNORE)) {
lexer.nextToken();
MySqlIgnoreIndexHint hint = new MySqlIgnoreIndexHint();
parseIndexHint(hint);
tableSource.getHints().add(hint);
}
if (lexer.identifierEquals(FnvHash.Constants.FORCE)) {
lexer.nextToken();
MySqlForceIndexHint hint = new MySqlForceIndexHint();
parseIndexHint(hint);
tableSource.getHints().add(hint);
}
if (lexer.token() == Token.PARTITION) {
lexer.nextToken();
// 兼容jsqlparser 和presto
if (lexer.token() == Token.ON) {
tableSource.setAlias("partition");
} else {
accept(Token.LPAREN);
this.exprParser.names(((SQLExprTableSource) tableSource).getPartitions(), tableSource);
accept(Token.RPAREN);
}
}
return tableSource;
}
public SQLTableSource parseTableSourceRest(SQLTableSource tableSource) {
if (lexer.identifierEquals(FnvHash.Constants.TABLESAMPLE) && tableSource instanceof SQLExprTableSource) {
Lexer.SavePoint mark = lexer.mark();
lexer.nextToken();
SQLTableSampling sampling = new SQLTableSampling();
if (lexer.identifierEquals(FnvHash.Constants.BERNOULLI)) {
lexer.nextToken();
sampling.setBernoulli(true);
} else if (lexer.identifierEquals(FnvHash.Constants.SYSTEM)) {
lexer.nextToken();
sampling.setSystem(true);
}
if (lexer.token() == Token.LPAREN) {
lexer.nextToken();
if (lexer.identifierEquals(FnvHash.Constants.BUCKET)) {
lexer.nextToken();
SQLExpr bucket = this.exprParser.primary();
sampling.setBucket(bucket);
if (lexer.token() == Token.OUT) {
lexer.nextToken();
accept(Token.OF);
SQLExpr outOf = this.exprParser.primary();
sampling.setOutOf(outOf);
}
if (lexer.token() == Token.ON) {
lexer.nextToken();
SQLExpr on = this.exprParser.expr();
sampling.setOn(on);
}
}
if (lexer.token() == Token.LITERAL_INT || lexer.token() == Token.LITERAL_FLOAT) {
SQLExpr val = this.exprParser.primary();
if (lexer.identifierEquals(FnvHash.Constants.ROWS)) {
lexer.nextToken();
sampling.setRows(val);
} else if (lexer.token() == Token.RPAREN) {
sampling.setRows(val);
} else {
acceptIdentifier("PERCENT");
sampling.setPercent(val);
}
}
if (lexer.token() == Token.IDENTIFIER) {
String strVal = lexer.stringVal();
char first = strVal.charAt(0);
char last = strVal.charAt(strVal.length() - 1);
if (last >= 'a' && last <= 'z') {
last -= 32; // to upper
}
boolean match = false;
if ((first == '.' || (first >= '0' && first <= '9'))) {
switch (last) {
case 'B':
case 'K':
case 'M':
case 'G':
case 'T':
case 'P':
match = true;
break;
default:
break;
}
}
SQLSizeExpr size = new SQLSizeExpr(strVal.substring(0, strVal.length() - 2), last);
sampling.setByteLength(size);
lexer.nextToken();
}
final SQLExprTableSource table = (SQLExprTableSource) tableSource;
table.setSampling(sampling);
accept(Token.RPAREN);
} else {
lexer.reset(mark);
}
}
if (lexer.identifierEquals(FnvHash.Constants.USING)) {
return tableSource;
}
parseIndexHintList(tableSource);
if (lexer.token() == Token.PARTITION) {
lexer.nextToken();
accept(Token.LPAREN);
this.exprParser.names(((SQLExprTableSource) tableSource).getPartitions(), tableSource);
accept(Token.RPAREN);
}
return super.parseTableSourceRest(tableSource);
}
private void parseIndexHintList(SQLTableSource tableSource) {
if (lexer.token() == Token.USE) {
lexer.nextToken();
MySqlUseIndexHint hint = new MySqlUseIndexHint();
parseIndexHint(hint);
tableSource.getHints().add(hint);
parseIndexHintList(tableSource);
}
if (lexer.identifierEquals(FnvHash.Constants.IGNORE)) {
lexer.nextToken();
MySqlIgnoreIndexHint hint = new MySqlIgnoreIndexHint();
parseIndexHint(hint);
tableSource.getHints().add(hint);
parseIndexHintList(tableSource);
}
if (lexer.identifierEquals(FnvHash.Constants.FORCE)) {
lexer.nextToken();
MySqlForceIndexHint hint = new MySqlForceIndexHint();
parseIndexHint(hint);
tableSource.getHints().add(hint);
parseIndexHintList(tableSource);
}
}
private void parseIndexHint(MySqlIndexHintImpl hint) {
if (lexer.token() == Token.INDEX) {
lexer.nextToken();
} else {
accept(Token.KEY);
}
if (lexer.token() == Token.FOR) {
lexer.nextToken();
if (lexer.token() == Token.JOIN) {
lexer.nextToken();
hint.setOption(MySqlIndexHint.Option.JOIN);
} else if (lexer.token() == Token.ORDER) {
lexer.nextToken();
accept(Token.BY);
hint.setOption(MySqlIndexHint.Option.ORDER_BY);
} else {
accept(Token.GROUP);
accept(Token.BY);
hint.setOption(MySqlIndexHint.Option.GROUP_BY);
}
}
accept(Token.LPAREN);
while (lexer.token() != Token.RPAREN && lexer.token() != Token.EOF) {
if (lexer.token() == Token.PRIMARY) {
lexer.nextToken();
hint.getIndexList().add(new SQLIdentifierExpr("PRIMARY"));
} else {
SQLName name = this.exprParser.name();
name.setParent(hint);
hint.getIndexList().add(name);
}
if (lexer.token() == Token.COMMA) {
lexer.nextToken();
} else {
break;
}
}
accept(Token.RPAREN);
}
public SQLUnionQuery unionRest(SQLUnionQuery union) {
if (lexer.token() == Token.LIMIT) {
union.setLimit(this.exprParser.parseLimit());
}
return super.unionRest(union);
}
public MySqlExprParser getExprParser() {
return (MySqlExprParser) exprParser;
}
}
| QueryHintHandler |
java | google__guice | core/test/com/google/inject/example/ClientServiceWithDependencyInjection.java | {
"start": 860,
"end": 1013
} | class ____ implements ClientServiceWithDependencyInjection.Service {
@Override
public void go() {
// ...
}
}
public static | ServiceImpl |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/scan/valid/b/BScanConfiguration.java | {
"start": 873,
"end": 954
} | interface ____ {
}
@ConfigurationProperties("b.first")
public static | BProperties |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/defaultbean/DefaultProducerMethodTest.java | {
"start": 1794,
"end": 2022
} | class ____ {
private final String message;
GreetingBean(String message) {
this.message = message;
}
String greet() {
return message;
}
}
static | GreetingBean |
java | grpc__grpc-java | api/src/test/java/io/grpc/ClientStreamTracerTest.java | {
"start": 987,
"end": 2076
} | class ____ {
private final CallOptions callOptions = CallOptions.DEFAULT.withDeadlineAfter(1, MINUTES);
@Test
public void streamInfo_empty() {
StreamInfo info = StreamInfo.newBuilder().build();
assertThat(info.getCallOptions()).isSameInstanceAs(CallOptions.DEFAULT);
}
@Test
public void streamInfo_withInfo() {
StreamInfo info = StreamInfo.newBuilder().setCallOptions(callOptions).build();
assertThat(info.getCallOptions()).isSameInstanceAs(callOptions);
}
@Test
public void streamInfo_noEquality() {
StreamInfo info1 = StreamInfo.newBuilder().setCallOptions(callOptions).build();
StreamInfo info2 = StreamInfo.newBuilder().setCallOptions(callOptions).build();
assertThat(info1).isNotSameInstanceAs(info2);
assertThat(info1).isNotEqualTo(info2);
}
@Test
public void streamInfo_toBuilder() {
StreamInfo info1 = StreamInfo.newBuilder()
.setCallOptions(callOptions).build();
StreamInfo info2 = info1.toBuilder().build();
assertThat(info2.getCallOptions()).isSameInstanceAs(callOptions);
}
}
| ClientStreamTracerTest |
java | redisson__redisson | redisson/src/main/java/org/redisson/connection/NodeSource.java | {
"start": 827,
"end": 3089
} | enum ____ {MOVED, ASK}
private Integer slot;
private RedisURI addr;
private RedisClient redisClient;
private Redirect redirect;
private MasterSlaveEntry entry;
public NodeSource(NodeSource nodeSource, RedisClient redisClient) {
this.slot = nodeSource.slot;
this.addr = nodeSource.addr;
this.redisClient = redisClient;
this.redirect = nodeSource.getRedirect();
this.entry = nodeSource.getEntry();
}
public NodeSource(MasterSlaveEntry entry) {
this.entry = entry;
}
public NodeSource(Integer slot) {
this.slot = slot;
}
public NodeSource(MasterSlaveEntry entry, RedisClient redisClient) {
this.entry = entry;
this.redisClient = redisClient;
}
public NodeSource(RedisClient redisClient) {
this.redisClient = redisClient;
}
public NodeSource(Integer slot, RedisClient redisClient) {
this.slot = slot;
this.redisClient = redisClient;
}
public NodeSource(Integer slot, RedisURI addr, Redirect redirect) {
this.slot = slot;
this.addr = addr;
this.redirect = redirect;
}
public MasterSlaveEntry getEntry() {
return entry;
}
public Redirect getRedirect() {
return redirect;
}
public Integer getSlot() {
return slot;
}
public RedisClient getRedisClient() {
return redisClient;
}
public RedisURI getAddr() {
return addr;
}
@Override
public String toString() {
return "NodeSource [slot=" + slot + ", addr=" + addr + ", redisClient=" + redisClient + ", redirect=" + redirect
+ ", entry=" + entry + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeSource that = (NodeSource) o;
return Objects.equals(slot, that.slot) && Objects.equals(addr, that.addr) && Objects.equals(redisClient, that.redisClient) && redirect == that.redirect && Objects.equals(entry, that.entry);
}
@Override
public int hashCode() {
return Objects.hash(slot, addr, redisClient, redirect, entry);
}
}
| Redirect |
java | quarkusio__quarkus | integration-tests/smallrye-jwt-oidc-webapp/src/test/java/io/quarkus/it/keycloak/SmallRyeJwtOidcWebAppTest.java | {
"start": 615,
"end": 3254
} | class ____ {
final KeycloakTestClient client = new KeycloakTestClient();
@Test
public void testGetUserNameWithBearerToken() {
RestAssured.given().auth().oauth2(client.getAccessToken("alice"))
.when().get("/protected")
.then()
.statusCode(200)
.body(equalTo("alice"));
}
@Test
public void testGetUserNameWithWrongBearerToken() {
RestAssured.given().auth().oauth2("123")
.when().get("/protected")
.then()
.statusCode(401);
}
@Test
public void testGetUserNameWithCookieToken() {
RestAssured.given().header("Cookie", "Bearer=" + client.getAccessToken("alice"))
.when().get("/protected")
.then()
.statusCode(200)
.body(equalTo("alice"));
}
@Test
public void testGetUserNameWithWrongCookieToken() {
RestAssured.given().header("Cookie", "Bearer=123")
.when().get("/protected")
.then()
.statusCode(401);
}
@Test
public void testNoToken() {
// OIDC has a higher priority than JWT
RestAssured.given().when().redirects().follow(false)
.get("/protected")
.then()
.statusCode(302);
}
@Test
public void testGetUserNameWithCodeFlow() throws Exception {
try (final WebClient webClient = createWebClient()) {
assertTokenStateCount(0);
HtmlPage page = webClient.getPage("http://localhost:8081/protected");
assertEquals("Sign in to quarkus", page.getTitleText());
HtmlForm loginForm = page.getForms().get(0);
loginForm.getInputByName("username").setValueAttribute("alice");
loginForm.getInputByName("password").setValueAttribute("alice");
page = loginForm.getButtonByName("login").click();
assertEquals("alice", page.getBody().asNormalizedText());
webClient.getCookieManager().clearCookies();
assertTokenStateCount(1);
}
}
private WebClient createWebClient() {
WebClient webClient = new WebClient();
webClient.setCssErrorHandler(new SilentCssErrorHandler());
return webClient;
}
private static void assertTokenStateCount(Integer expectedNumOfTokens) {
RestAssured
.get("/public/token-state-count")
.then()
.statusCode(200)
.body(Matchers.is(expectedNumOfTokens.toString()));
}
}
| SmallRyeJwtOidcWebAppTest |
java | quarkusio__quarkus | extensions/smallrye-metrics/runtime/src/main/java/io/quarkus/smallrye/metrics/runtime/SmallRyeMetricsFactory.java | {
"start": 679,
"end": 1015
} | class ____ implements MetricsFactory {
public boolean metricsSystemSupported(String name) {
return MetricsFactory.MP_METRICS.equals(name);
}
@Override
public MetricBuilder builder(String name, MetricsFactory.Type type) {
return new SmallRyeMetricBuilder(name, type);
}
static | SmallRyeMetricsFactory |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/codec/AbstractSingleValueEncoder.java | {
"start": 1093,
"end": 1294
} | class ____ {@link org.springframework.core.codec.Encoder}
* classes that can only deal with a single value.
*
* @author Arjen Poutsma
* @since 5.0
* @param <T> the element type
*/
public abstract | for |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.