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
spring-projects__spring-boot
module/spring-boot-neo4j/src/dockerTest/java/org/springframework/boot/neo4j/health/Neo4jReactiveHealthIndicatorIntegrationTests.java
{ "start": 1810, "end": 2789 }
class ____ { // gh-33428 @Container private static final Neo4jContainer neo4jServer = TestImage.container(Neo4jContainer.class); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { registry.add("spring.neo4j.uri", neo4jServer::getBoltUrl); registry.add("spring.neo4j.authentication.username", () -> "neo4j"); registry.add("spring.neo4j.authentication.password", neo4jServer::getAdminPassword); } @Autowired private Neo4jReactiveHealthIndicator healthIndicator; @Test void health() { Health health = this.healthIndicator.health(true).block(Duration.ofSeconds(20)); assertThat(health).isNotNull(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsEntry("edition", "community"); } @Configuration(proxyBeanMethods = false) @ImportAutoConfiguration(Neo4jAutoConfiguration.class) @Import(Neo4jReactiveHealthIndicator.class) static
Neo4jReactiveHealthIndicatorIntegrationTests
java
redisson__redisson
redisson-spring-data/redisson-spring-data-31/src/test/java/org/redisson/spring/data/connection/RedissonConnectionTest.java
{ "start": 1085, "end": 14421 }
class ____ extends BaseConnectionTest { @Test public void testZRandMemberScore() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate.boundZSetOps("test").add("2", 20); redisTemplate.boundZSetOps("test").add("3", 30); RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson); ReactiveRedisConnection cc = factory.getReactiveConnection(); Tuple b = cc.zSetCommands().zRandMemberWithScore(ByteBuffer.wrap("test".getBytes())).block(); assertThat(b.getScore()).isNotNaN(); assertThat(new String(b.getValue())).isIn("1", "2", "3"); } @Test public void testBZPop() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate.boundZSetOps("test").add("2", 20); redisTemplate.boundZSetOps("test").add("3", 30); ZSetOperations.TypedTuple<String> r = redisTemplate.boundZSetOps("test").popMin(Duration.ofSeconds(1)); assertThat(r.getValue()).isEqualTo("1"); assertThat(r.getScore()).isEqualTo(10); RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson); ReactiveRedisConnection cc = factory.getReactiveConnection(); Tuple r2 = cc.zSetCommands().bZPopMin(ByteBuffer.wrap("test".getBytes()), Duration.ofSeconds(1)).block(); assertThat(r2.getValue()).isEqualTo("2".getBytes()); assertThat(r2.getScore()).isEqualTo(20); } @Test public void testZPop() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate.boundZSetOps("test").add("2", 20); redisTemplate.boundZSetOps("test").add("3", 30); ZSetOperations.TypedTuple<String> r = redisTemplate.boundZSetOps("test").popMin(); assertThat(r.getValue()).isEqualTo("1"); assertThat(r.getScore()).isEqualTo(10); RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson); ReactiveRedisConnection cc = factory.getReactiveConnection(); Tuple r2 = cc.zSetCommands().zPopMin(ByteBuffer.wrap("test".getBytes())).block(); assertThat(r2.getValue()).isEqualTo("2".getBytes()); assertThat(r2.getScore()).isEqualTo(20); } @Test public void testZRangeWithScores() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate.boundZSetOps("test").add("2", 20); redisTemplate.boundZSetOps("test").add("3", 30); Set<ZSetOperations.TypedTuple<String>> objs = redisTemplate.boundZSetOps("test").rangeWithScores(0, 100); assertThat(objs).hasSize(3); assertThat(objs).containsExactlyInAnyOrder(ZSetOperations.TypedTuple.of("1", 10D), ZSetOperations.TypedTuple.of("2", 20D), ZSetOperations.TypedTuple.of("3", 30D)); } @Test public void testZDiff() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate.boundZSetOps("test").add("2", 20); redisTemplate.boundZSetOps("test").add("3", 30); redisTemplate.boundZSetOps("test").add("4", 30); redisTemplate.boundZSetOps("test2").add("5", 50); redisTemplate.boundZSetOps("test2").add("2", 20); redisTemplate.boundZSetOps("test2").add("3", 30); redisTemplate.boundZSetOps("test2").add("6", 60); Set<String> objs = redisTemplate.boundZSetOps("test").difference("test2"); assertThat(objs).hasSize(2); } @Test public void testZLexCount() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate.boundZSetOps("test").add("2", 20); redisTemplate.boundZSetOps("test").add("3", 30); Long size = redisTemplate.boundZSetOps("test").lexCount(Range.closed("1", "2")); assertThat(size).isEqualTo(2); } @Test public void testZRemLexByRange() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate.boundZSetOps("test").add("2", 20); redisTemplate.boundZSetOps("test").add("3", 30); Long size = redisTemplate.boundZSetOps("test") .removeRangeByLex(Range.closed("1", "2")); assertThat(size).isEqualTo(2); } @Test public void testReverseRangeByLex() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate.boundZSetOps("test").add("2", 20); Set<String> ops = redisTemplate.boundZSetOps("test") .reverseRangeByLex(Range.closed("1", "2") , Limit.limit().count(10)); assertThat(ops.size()).isEqualTo(2); } @Test public void testExecute() { Long s = (Long) connection.execute("ttl", "key".getBytes()); assertThat(s).isEqualTo(-2); connection.execute("flushDb"); } @Test public void testRandomMembers() { RedisTemplate<String, Integer> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); SetOperations<String, Integer> ops = redisTemplate.opsForSet(); ops.add("val", 1, 2, 3, 4); Set<Integer> values = redisTemplate.opsForSet().distinctRandomMembers("val", 1L); assertThat(values).containsAnyOf(1, 2, 3, 4); Integer v = redisTemplate.opsForSet().randomMember("val"); assertThat(v).isNotNull(); } @Test public void testRangeByLex() { RedisTemplate<String, String> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); RedisZSetCommands.Range range = new RedisZSetCommands.Range(); range.lt("c"); Set<String> zSetValue = redisTemplate.opsForZSet().rangeByLex("val", range); assertThat(zSetValue).isEmpty(); } @Test public void testGeo() { RedisTemplate<String, String> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); String key = "test_geo_key"; Point point = new Point(116.401001, 40.119499); redisTemplate.opsForGeo().add(key, point, "a"); point = new Point(111.545998, 36.133499); redisTemplate.opsForGeo().add(key, point, "b"); point = new Point(111.483002, 36.030998); redisTemplate.opsForGeo().add(key, point, "c"); Circle within = new Circle(116.401001, 40.119499, 80000); RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeCoordinates(); GeoResults<RedisGeoCommands.GeoLocation<String>> res = redisTemplate.opsForGeo().radius(key, within, args); assertThat(res.getContent().get(0).getContent().getName()).isEqualTo("a"); } @Test public void testZSet() { connection.zAdd(new byte[] {1}, -1, new byte[] {1}); connection.zAdd(new byte[] {1}, 2, new byte[] {2}); connection.zAdd(new byte[] {1}, 10, new byte[] {3}); assertThat(connection.zRangeByScore(new byte[] {1}, Double.NEGATIVE_INFINITY, 5)) .containsOnly(new byte[] {1}, new byte[] {2}); } @Test public void testEcho() { assertThat(connection.echo("test".getBytes())).isEqualTo("test".getBytes()); } @Test public void testSetGet() { connection.set("key".getBytes(), "value".getBytes()); assertThat(connection.get("key".getBytes())).isEqualTo("value".getBytes()); } @Test public void testSetExpiration() { assertThat(connection.set("key".getBytes(), "value".getBytes(), Expiration.milliseconds(111122), SetOption.SET_IF_ABSENT)).isTrue(); assertThat(connection.get("key".getBytes())).isEqualTo("value".getBytes()); } @Test public void testHSetGet() { assertThat(connection.hSet("key".getBytes(), "field".getBytes(), "value".getBytes())).isTrue(); assertThat(connection.hGet("key".getBytes(), "field".getBytes())).isEqualTo("value".getBytes()); } @Test public void testZScan() { connection.zAdd("key".getBytes(), 1, "value1".getBytes()); connection.zAdd("key".getBytes(), 2, "value2".getBytes()); Cursor<Tuple> t = connection.zScan("key".getBytes(), ScanOptions.scanOptions().build()); assertThat(t.hasNext()).isTrue(); assertThat(t.next().getValue()).isEqualTo("value1".getBytes()); assertThat(t.hasNext()).isTrue(); assertThat(t.next().getValue()).isEqualTo("value2".getBytes()); } @Test public void testRandFieldWithValues() { connection.hSet("map".getBytes(), "key1".getBytes(), "value1".getBytes()); connection.hSet("map".getBytes(), "key2".getBytes(), "value2".getBytes()); connection.hSet("map".getBytes(), "key3".getBytes(), "value3".getBytes()); List<Map.Entry<byte[], byte[]>> s = connection.hRandFieldWithValues("map".getBytes(), 2); assertThat(s).hasSize(2); Map.Entry<byte[], byte[]> s2 = connection.hRandFieldWithValues("map".getBytes()); assertThat(s2).isNotNull(); byte[] f = connection.hRandField("map".getBytes()); assertThat((Object) f).isIn("key1".getBytes(), "key2".getBytes(), "key3".getBytes()); } @Test public void testGetClientList() { List<RedisClientInfo> info = connection.getClientList(); assertThat(info.size()).isGreaterThan(10); } @Test public void testFilterOkResponsesInTransaction() { // Test with filterOkResponses = false (default behavior) RedisTemplate<String, String> redisTemplate = new RedisTemplate<>(); RedissonConnectionFactory connectionFactory = new RedissonConnectionFactory(redisson); // connectionFactory.setFilterOkResponses(false); redisTemplate.setConnectionFactory(connectionFactory); redisTemplate.afterPropertiesSet(); List<Object> results = (List<Object>) redisTemplate.executePipelined((RedisCallback<Object>) connection -> { connection.multi(); connection.set("test:key1".getBytes(), "value1".getBytes()); connection.set("test:key2".getBytes(), "value2".getBytes()); connection.get("test:key1".getBytes()); connection.get("test:key2".getBytes()); return connection.exec(); }, RedisSerializer.string()).get(0); // With filterOkResponses=false, all responses including "OK" should be preserved assertThat(results).hasSize(4); assertThat(results.get(0)).isEqualTo(true); assertThat(results.get(1)).isEqualTo(true); assertThat(results.get(2)).isEqualTo("value1"); assertThat(results.get(3)).isEqualTo("value2"); // Test with filterOkResponses = true connectionFactory.setFilterOkResponses(true); redisTemplate.afterPropertiesSet(); List<Object> filteredResults = (List<Object>) redisTemplate.executePipelined((RedisCallback<Object>) connection -> { connection.multi(); connection.set("test:key3".getBytes(), "value3".getBytes()); connection.set("test:key4".getBytes(), "value4".getBytes()); connection.get("test:key3".getBytes()); connection.get("test:key4".getBytes()); return connection.exec(); }, RedisSerializer.string()).get(0); // With filterOkResponses=true, "OK" responses should be filtered out assertThat(filteredResults).hasSize(2); assertThat(filteredResults.get(0)).isEqualTo("value3"); assertThat(filteredResults.get(1)).isEqualTo("value4"); } }
RedissonConnectionTest
java
apache__rocketmq
client/src/main/java/org/apache/rocketmq/client/consumer/PullTaskCallback.java
{ "start": 912, "end": 1018 }
interface ____ { void doPullTask(final MessageQueue mq, final PullTaskContext context); }
PullTaskCallback
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionBuilderTests.java
{ "start": 1768, "end": 10286 }
class ____ { @Test void route() { RouterFunction<ServerResponse> route = RouterFunctions.route() .GET("/foo", request -> ServerResponse.ok().build()) .POST("/", RequestPredicates.contentType(MediaType.TEXT_PLAIN), request -> ServerResponse.noContent().build()) .route(HEAD("/foo"), request -> ServerResponse.accepted().build()) .build(); ServerRequest getFooRequest = initRequest("GET", "/foo"); Optional<HttpStatusCode> responseStatus = route.route(getFooRequest) .map(handlerFunction -> handle(handlerFunction, getFooRequest)) .map(ServerResponse::statusCode); assertThat(responseStatus).contains(HttpStatus.OK); ServerRequest headFooRequest = initRequest("HEAD", "/foo"); responseStatus = route.route(headFooRequest) .map(handlerFunction -> handle(handlerFunction, getFooRequest)) .map(ServerResponse::statusCode); assertThat(responseStatus).contains(HttpStatus.ACCEPTED); ServerRequest barRequest = initRequest("POST", "/", req -> req.setContentType("text/plain")); responseStatus = route.route(barRequest) .map(handlerFunction -> handle(handlerFunction, barRequest)) .map(ServerResponse::statusCode); assertThat(responseStatus).contains(HttpStatus.NO_CONTENT); ServerRequest invalidRequest = initRequest("POST", "/"); responseStatus = route.route(invalidRequest) .map(handlerFunction -> handle(handlerFunction, invalidRequest)) .map(ServerResponse::statusCode); assertThat(responseStatus).isEmpty(); } private static ServerResponse handle(HandlerFunction<ServerResponse> handlerFunction, ServerRequest request) { try { return handlerFunction.handle(request); } catch (Exception ex) { throw new AssertionError(ex.getMessage(), ex); } } @Test void resource() { Resource resource = new ClassPathResource("/org/springframework/web/servlet/function/response.txt"); assertThat(resource.exists()).isTrue(); RouterFunction<ServerResponse> route = RouterFunctions.route() .resource(path("/test"), resource) .build(); ServerRequest resourceRequest = initRequest("GET", "/test"); Optional<HttpStatusCode> responseStatus = route.route(resourceRequest) .map(handlerFunction -> handle(handlerFunction, resourceRequest)) .map(ServerResponse::statusCode); assertThat(responseStatus).contains(HttpStatus.OK); } @Test void resources() { Resource resource = new ClassPathResource("/org/springframework/web/servlet/function/"); assertThat(resource.exists()).isTrue(); RouterFunction<ServerResponse> route = RouterFunctions.route() .resources("/resources/**", resource) .build(); ServerRequest resourceRequest = initRequest("GET", "/resources/response.txt"); Optional<HttpStatusCode> responseStatus = route.route(resourceRequest) .map(handlerFunction -> handle(handlerFunction, resourceRequest)) .map(ServerResponse::statusCode); assertThat(responseStatus).contains(HttpStatus.OK); ServerRequest invalidRequest = initRequest("POST", "/resources/foo.txt"); responseStatus = route.route(invalidRequest) .map(handlerFunction -> handle(handlerFunction, invalidRequest)) .map(ServerResponse::statusCode); assertThat(responseStatus).isEmpty(); } @Test void resourcesCaching() { Resource resource = new ClassPathResource("/org/springframework/web/servlet/function/"); assertThat(resource.exists()).isTrue(); RouterFunction<ServerResponse> route = RouterFunctions.route() .resources("/resources/**", resource, (r, headers) -> headers.setCacheControl(CacheControl.maxAge(Duration.ofSeconds(60)))) .build(); ServerRequest resourceRequest = initRequest("GET", "/resources/response.txt"); Optional<String> responseCacheControl = route.route(resourceRequest) .map(handlerFunction -> handle(handlerFunction, resourceRequest)) .map(response -> response.headers().getCacheControl()); assertThat(responseCacheControl).contains("max-age=60"); } @Test void nest() { RouterFunction<ServerResponse> route = RouterFunctions.route() .path("/foo", builder -> builder.path("/bar", () -> RouterFunctions.route() .GET("/baz", request -> ServerResponse.ok().build()) .build())) .build(); ServerRequest fooRequest = initRequest("GET", "/foo/bar/baz"); Optional<HttpStatusCode> responseStatus = route.route(fooRequest) .map(handlerFunction -> handle(handlerFunction, fooRequest)) .map(ServerResponse::statusCode); assertThat(responseStatus).contains(HttpStatus.OK); } @Test void filters() { AtomicInteger filterCount = new AtomicInteger(); RouterFunction<ServerResponse> route = RouterFunctions.route() .GET("/foo", request -> ServerResponse.ok().build()) .GET("/bar", request -> { throw new IllegalStateException(); }) .before(request -> { int count = filterCount.getAndIncrement(); assertThat(count).isEqualTo(0); return request; }) .after((request, response) -> { int count = filterCount.getAndIncrement(); assertThat(count).isEqualTo(3); return response; }) .filter((request, next) -> { int count = filterCount.getAndIncrement(); assertThat(count).isEqualTo(1); ServerResponse responseMono = next.handle(request); count = filterCount.getAndIncrement(); assertThat(count).isEqualTo(2); return responseMono; }) .onError(IllegalStateException.class, (e, request) -> ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR) .build()) .build(); ServerRequest fooRequest = initRequest("GET", "/foo"); route.route(fooRequest) .map(handlerFunction -> handle(handlerFunction, fooRequest)); assertThat(filterCount.get()).isEqualTo(4); filterCount.set(0); ServerRequest barRequest = initRequest("GET", "/bar"); Optional<HttpStatusCode> responseStatus = route.route(barRequest) .map(handlerFunction -> handle(handlerFunction, barRequest)) .map(ServerResponse::statusCode); assertThat(responseStatus).contains(HttpStatus.INTERNAL_SERVER_ERROR); } @Test void multipleOnErrors() { RouterFunction<ServerResponse> route = RouterFunctions.route() .GET("/error", request -> { throw new IOException(); }) .onError(IOException.class, (t, r) -> ServerResponse.status(200).build()) .onError(Exception.class, (t, r) -> ServerResponse.status(201).build()) .build(); MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/error"); ServerRequest serverRequest = new DefaultServerRequest(servletRequest, emptyList()); Optional<HttpStatusCode> responseStatus = route.route(serverRequest) .map(handlerFunction -> handle(handlerFunction, serverRequest)) .map(ServerResponse::statusCode); assertThat(responseStatus).contains(HttpStatus.OK); } private ServerRequest initRequest(String httpMethod, String requestUri) { return initRequest(httpMethod, requestUri, null); } private ServerRequest initRequest( String httpMethod, String requestUri, @Nullable Consumer<MockHttpServletRequest> consumer) { return new DefaultServerRequest( PathPatternsTestUtils.initRequest(httpMethod, null, requestUri, true, consumer), emptyList()); } @Test void attributes() { RouterFunction<ServerResponse> route = RouterFunctions.route() .GET("/atts/1", request -> ServerResponse.ok().build()) .withAttribute("foo", "bar") .withAttribute("baz", "qux") .GET("/atts/2", request -> ServerResponse.ok().build()) .withAttributes(atts -> { atts.put("foo", "bar"); atts.put("baz", "qux"); }) .path("/atts", b1 -> b1 .GET("/3", request -> ServerResponse.ok().build()) .withAttribute("foo", "bar") .GET("/4", request -> ServerResponse.ok().build()) .withAttribute("baz", "qux") .path("/5", b2 -> b2 .GET(request -> ServerResponse.ok().build()) .withAttribute("foo", "n3")) .withAttribute("foo", "n2") ) .withAttribute("foo", "n1") .build(); AttributesTestVisitor visitor = new AttributesTestVisitor(); route.accept(visitor); assertThat(visitor.routerFunctionsAttributes()).containsExactly( List.of(Map.of("foo", "bar", "baz", "qux")), List.of(Map.of("foo", "bar", "baz", "qux")), List.of(Map.of("foo", "bar"), Map.of("foo", "n1")), List.of(Map.of("baz", "qux"), Map.of("foo", "n1")), List.of(Map.of("foo", "n3"), Map.of("foo", "n2"), Map.of("foo", "n1")) ); assertThat(visitor.visitCount()).isEqualTo(7); } }
RouterFunctionBuilderTests
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/TestContextConcurrencyTests.java
{ "start": 3035, "end": 3322 }
class ____ { void test_001() { } void test_002() { } void test_003() { } void test_004() { } void test_005() { } void test_006() { } void test_007() { } void test_008() { } void test_009() { } void test_010() { } } private static
TestCase
java
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/ProduceMessageConverterTest.java
{ "start": 3203, "end": 3693 }
class ____ implements MessageConverter { @Override public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { TextMessage txt = session.createTextMessage(); txt.setText("Hello " + object); return txt; } @Override public Object fromMessage(Message message) throws JMSException, MessageConversionException { return null; } } }
MyMessageConverter
java
elastic__elasticsearch
libs/entitlement/asm-provider/src/main/java/org/elasticsearch/entitlement/instrumentation/impl/InstrumentationServiceImpl.java
{ "start": 1782, "end": 8530 }
interface ____ { void visit(Class<?> currentClass, int access, String checkerMethodName, String checkerMethodDescriptor); } private void visitClassAndSupers(Class<?> checkerClass, CheckerMethodVisitor checkerMethodVisitor) throws ClassNotFoundException { Set<Class<?>> visitedClasses = new HashSet<>(); ArrayDeque<Class<?>> classesToVisit = new ArrayDeque<>(Collections.singleton(checkerClass)); while (classesToVisit.isEmpty() == false) { var currentClass = classesToVisit.remove(); if (visitedClasses.contains(currentClass)) { continue; } visitedClasses.add(currentClass); try { var classFileInfo = InstrumenterImpl.getClassFileInfo(currentClass); ClassReader reader = new ClassReader(classFileInfo.bytecodes()); ClassVisitor visitor = new ClassVisitor(Opcodes.ASM9) { @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, name, signature, superName, interfaces); try { if (OBJECT_INTERNAL_NAME.equals(superName) == false) { classesToVisit.add(Class.forName(Type.getObjectType(superName).getClassName())); } for (var interfaceName : interfaces) { classesToVisit.add(Class.forName(Type.getObjectType(interfaceName).getClassName())); } } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Cannot inspect checker class " + currentClass.getName(), e); } } @Override public MethodVisitor visitMethod( int access, String checkerMethodName, String checkerMethodDescriptor, String signature, String[] exceptions ) { var mv = super.visitMethod(access, checkerMethodName, checkerMethodDescriptor, signature, exceptions); checkerMethodVisitor.visit(currentClass, access, checkerMethodName, checkerMethodDescriptor); return mv; } }; reader.accept(visitor, 0); } catch (IOException e) { throw new ClassNotFoundException("Cannot find a definition for class [" + checkerClass.getName() + "]", e); } } } @Override public Map<MethodKey, CheckMethod> lookupMethods(Class<?> checkerClass) throws ClassNotFoundException { Map<MethodKey, CheckMethod> methodsToInstrument = new HashMap<>(); visitClassAndSupers(checkerClass, (currentClass, access, checkerMethodName, checkerMethodDescriptor) -> { if (checkerMethodName.startsWith(InstrumentationService.CHECK_METHOD_PREFIX)) { var checkerMethodArgumentTypes = Type.getArgumentTypes(checkerMethodDescriptor); var methodToInstrument = parseCheckerMethodSignature(checkerMethodName, checkerMethodArgumentTypes); var checkerParameterDescriptors = Arrays.stream(checkerMethodArgumentTypes).map(Type::getDescriptor).toList(); var checkMethod = new CheckMethod(Type.getInternalName(currentClass), checkerMethodName, checkerParameterDescriptors); methodsToInstrument.putIfAbsent(methodToInstrument, checkMethod); } }); return methodsToInstrument; } @SuppressForbidden(reason = "Need access to abstract methods (protected/package internal) in base class") @Override public InstrumentationInfo lookupImplementationMethod( Class<?> targetSuperclass, String targetMethodName, Class<?> implementationClass, Class<?> checkerClass, String checkMethodName, Class<?>... parameterTypes ) throws NoSuchMethodException, ClassNotFoundException { var targetMethod = targetSuperclass.getDeclaredMethod(targetMethodName, parameterTypes); var implementationMethod = implementationClass.getMethod(targetMethod.getName(), targetMethod.getParameterTypes()); validateTargetMethod(implementationClass, targetMethod, implementationMethod); var checkerAdditionalArguments = Stream.of(Class.class, targetSuperclass); var checkMethodArgumentTypes = Stream.concat(checkerAdditionalArguments, Arrays.stream(parameterTypes)) .map(Type::getType) .toArray(Type[]::new); CheckMethod[] checkMethod = new CheckMethod[1]; visitClassAndSupers(checkerClass, (currentClass, access, methodName, methodDescriptor) -> { if (methodName.equals(checkMethodName)) { var methodArgumentTypes = Type.getArgumentTypes(methodDescriptor); if (Arrays.equals(methodArgumentTypes, checkMethodArgumentTypes)) { var checkerParameterDescriptors = Arrays.stream(methodArgumentTypes).map(Type::getDescriptor).toList(); checkMethod[0] = new CheckMethod(Type.getInternalName(currentClass), methodName, checkerParameterDescriptors); } } }); if (checkMethod[0] == null) { throw new NoSuchMethodException( String.format( Locale.ROOT, "Cannot find a method with name [%s] and arguments [%s] in class [%s]", checkMethodName, Arrays.stream(checkMethodArgumentTypes).map(Type::toString).collect(Collectors.joining()), checkerClass.getName() ) ); } return new InstrumentationInfo( new MethodKey( Type.getInternalName(implementationMethod.getDeclaringClass()), implementationMethod.getName(), Arrays.stream(parameterTypes).map(c -> Type.getType(c).getInternalName()).toList() ), checkMethod[0] ); } private static void validateTargetMethod(Class<?> implementationClass, Method targetMethod, Method implementationMethod) { if (targetMethod.getDeclaringClass().isAssignableFrom(implementationClass) == false) { throw new IllegalArgumentException( String.format( Locale.ROOT, "Not an implementation
CheckerMethodVisitor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/querycache/HqlQueryCacheIgnoreResultTransformerTest.java
{ "start": 361, "end": 1822 }
class ____ extends AbstractQueryCacheResultTransformerTest { @Override protected CacheMode getQueryCacheMode() { return CacheMode.IGNORE; } @Override protected void runTest( HqlExecutor hqlExecutor, CriteriaExecutor criteriaExecutor, ResultChecker checker, boolean isSingleResult, SessionFactoryScope scope) throws Exception { createData( scope ); if ( hqlExecutor != null ) { runTest( hqlExecutor, checker, isSingleResult, scope ); } deleteData( scope ); } @Test @Override @FailureExpected(jiraKey = "N/A", reason = "HQL query using Transformers.ALIAS_TO_ENTITY_MAP with no projection") public void testAliasToEntityMapNoProjectionList(SessionFactoryScope scope) throws Exception { super.testAliasToEntityMapNoProjectionList( scope ); } @Test @Override @FailureExpected(jiraKey = "N/A", reason = "HQL query using Transformers.ALIAS_TO_ENTITY_MAP with no projection") public void testAliasToEntityMapNoProjectionMultiAndNullList(SessionFactoryScope scope) throws Exception { super.testAliasToEntityMapNoProjectionMultiAndNullList( scope ); } @Test @Override @FailureExpected(jiraKey = "N/A", reason = "HQL query using Transformers.ALIAS_TO_ENTITY_MAP with no projection") public void testAliasToEntityMapNoProjectionNullAndNonNullAliasList(SessionFactoryScope scope) throws Exception { super.testAliasToEntityMapNoProjectionNullAndNonNullAliasList( scope ); } }
HqlQueryCacheIgnoreResultTransformerTest
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/reverse/SourceTargetMapper.java
{ "start": 415, "end": 1373 }
interface ____ { SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class ); @Mappings({ @Mapping(target = "stringPropY", source = "stringPropX"), @Mapping(target = "integerPropY", source = "integerPropX"), @Mapping(target = "propertyNotToIgnoreUpstream", source = "propertyToIgnoreDownstream") }) Target forward(Source source); @Mappings({ @Mapping(target = "stringPropY", source = "stringPropX"), @Mapping(target = "integerPropY", source = "integerPropX"), @Mapping(target = "propertyNotToIgnoreUpstream", source = "propertyToIgnoreDownstream") }) Target forwardNotToReverse(Source source); @InheritInverseConfiguration(name = "forward") @Mappings({ @Mapping(target = "someConstantDownstream", constant = "test"), @Mapping(target = "propertyToIgnoreDownstream", ignore = true) }) Source reverse(Target target); }
SourceTargetMapper
java
apache__logging-log4j2
log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/ThreadsafeDateFormatBenchmark.java
{ "start": 2938, "end": 3242 }
class ____ { private final long timestamp; private final String formatted; public CachedTimeFixedFmt(final long timestamp) { this.timestamp = timestamp; this.formatted = fixedDateFormat.format(timestamp); } } private static
CachedTimeFixedFmt
java
apache__kafka
metadata/src/main/java/org/apache/kafka/image/node/printer/MetadataNodeRedactionCriteria.java
{ "start": 961, "end": 1560 }
interface ____ { /** * Returns true if SCRAM data should be redacted. */ boolean shouldRedactScram(); /** * Returns true if DelegationToken data should be redacted. */ boolean shouldRedactDelegationToken(); /** * Returns true if a configuration should be redacted. * * @param type The configuration type. * @param key The configuration key. * * @return True if the configuration should be redacted. */ boolean shouldRedactConfig(ConfigResource.Type type, String key);
MetadataNodeRedactionCriteria
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/groupwindow/internal/GeneralWindowProcessFunction.java
{ "start": 1555, "end": 3324 }
class ____<K, W extends Window> extends InternalWindowProcessFunction<K, W> { private static final long serialVersionUID = 5992545519395844485L; private List<W> reuseAffectedWindows; public GeneralWindowProcessFunction( GroupWindowAssigner<W> windowAssigner, NamespaceAggsHandleFunctionBase<W> windowAggregator, long allowedLateness) { super(windowAssigner, windowAggregator, allowedLateness); } @Override public Collection<W> assignStateNamespace(RowData inputRow, long timestamp) throws Exception { Collection<W> elementWindows = windowAssigner.assignWindows(inputRow, timestamp); reuseAffectedWindows = new ArrayList<>(elementWindows.size()); for (W window : elementWindows) { if (!isWindowLate(window)) { reuseAffectedWindows.add(window); } } return reuseAffectedWindows; } @Override public Collection<W> assignActualWindows(RowData inputRow, long timestamp) throws Exception { // actual windows is equal to affected window, reuse it return reuseAffectedWindows; } @Override public void prepareAggregateAccumulatorForEmit(W window) throws Exception { RowData acc = ctx.getWindowAccumulators(window); if (acc == null) { acc = windowAggregator.createAccumulators(); } windowAggregator.setAccumulators(window, acc); } @Override public void cleanWindowIfNeeded(W window, long time) throws Exception { if (isCleanupTime(window, time)) { ctx.clearWindowState(window); ctx.clearPreviousState(window); ctx.clearTrigger(window); } } }
GeneralWindowProcessFunction
java
hibernate__hibernate-orm
hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/CockroachLegacyDialect.java
{ "start": 7548, "end": 41854 }
class ____ extends Dialect { // KNOWN LIMITATIONS: // * no support for java.sql.Clob // Pre-compile and reuse pattern private static final Pattern CRDB_VERSION_PATTERN = Pattern.compile( "v[\\d]+(\\.[\\d]+)?(\\.[\\d]+)?" ); protected static final DatabaseVersion DEFAULT_VERSION = DatabaseVersion.make( 19, 2 ); protected final PostgreSQLDriverKind driverKind; public CockroachLegacyDialect() { this( DEFAULT_VERSION ); } public CockroachLegacyDialect(DialectResolutionInfo info) { this( fetchDataBaseVersion( info ), PostgreSQLDriverKind.determineKind( info ) ); registerKeywords( info ); } public CockroachLegacyDialect(DatabaseVersion version) { super(version); driverKind = PostgreSQLDriverKind.PG_JDBC; } public CockroachLegacyDialect(DatabaseVersion version, PostgreSQLDriverKind driverKind) { super(version); this.driverKind = driverKind; } @Override public DatabaseVersion determineDatabaseVersion(DialectResolutionInfo info) { return fetchDataBaseVersion( info ); } protected static DatabaseVersion fetchDataBaseVersion(DialectResolutionInfo info ) { String versionString = null; if ( info.getDatabaseMetadata() != null ) { try (java.sql.Statement s = info.getDatabaseMetadata().getConnection().createStatement() ) { final ResultSet rs = s.executeQuery( "SELECT version()" ); if ( rs.next() ) { versionString = rs.getString( 1 ); } } catch (SQLException ex) { // Ignore } } return parseVersion( versionString ); } protected static DatabaseVersion parseVersion(String versionString ) { DatabaseVersion databaseVersion = null; // What the DB select returns is similar to "CockroachDB CCL v21.2.10 (x86_64-unknown-linux-gnu, built 2022/05/02 17:38:58, go1.16.6)" Matcher m = CRDB_VERSION_PATTERN.matcher( versionString == null ? "" : versionString ); if ( m.find() ) { String[] versionParts = StringHelper.split( ".", m.group().substring( 1 ) ); // if we got to this point, there is at least a major version, so no need to check [].length > 0 int majorVersion = Integer.parseInt( versionParts[0] ); int minorVersion = versionParts.length > 1 ? Integer.parseInt( versionParts[1] ) : 0; int microVersion = versionParts.length > 2 ? Integer.parseInt( versionParts[2] ) : 0; databaseVersion= new SimpleDatabaseVersion( majorVersion, minorVersion, microVersion); } if ( databaseVersion == null ) { // Recur to the default version of the no-args constructor databaseVersion = DEFAULT_VERSION; } return databaseVersion; } @Override protected String columnType(int sqlTypeCode) { return switch ( sqlTypeCode ) { case TINYINT -> "smallint"; //no tinyint case INTEGER -> "int4"; case NCHAR -> columnType( CHAR ); case NVARCHAR -> columnType( VARCHAR ); case NCLOB, CLOB -> "string"; case BINARY, VARBINARY, BLOB -> "bytes"; // We do not use the time with timezone type because PG deprecated it and it lacks certain operations like subtraction // case TIME_UTC: // return columnType( TIME_WITH_TIMEZONE ); case TIMESTAMP_UTC -> columnType( TIMESTAMP_WITH_TIMEZONE ); default -> super.columnType( sqlTypeCode ); }; } @Override protected String castType(int sqlTypeCode) { return switch ( sqlTypeCode ) { case CHAR, NCHAR, VARCHAR, NVARCHAR, LONG32VARCHAR, LONG32NVARCHAR -> "string"; case BINARY, VARBINARY, LONG32VARBINARY -> "bytes"; default -> super.castType( sqlTypeCode ); }; } @Override protected void registerColumnTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { super.registerColumnTypes( typeContributions, serviceRegistry ); final DdlTypeRegistry ddlTypeRegistry = typeContributions.getTypeConfiguration().getDdlTypeRegistry(); ddlTypeRegistry.addDescriptor( new DdlTypeImpl( UUID, "uuid", this ) ); ddlTypeRegistry.addDescriptor( new DdlTypeImpl( GEOMETRY, "geometry", this ) ); ddlTypeRegistry.addDescriptor( new DdlTypeImpl( GEOGRAPHY, "geography", this ) ); ddlTypeRegistry.addDescriptor( new Scale6IntervalSecondDdlType( this ) ); // Prefer jsonb if possible if ( getVersion().isSameOrAfter( 20 ) ) { ddlTypeRegistry.addDescriptor( new DdlTypeImpl( INET, "inet", this ) ); ddlTypeRegistry.addDescriptor( new DdlTypeImpl( JSON, "jsonb", this ) ); } else { ddlTypeRegistry.addDescriptor( new DdlTypeImpl( JSON, "json", this ) ); } ddlTypeRegistry.addDescriptor( new NamedNativeEnumDdlTypeImpl( this ) ); ddlTypeRegistry.addDescriptor( new NamedNativeOrdinalEnumDdlTypeImpl( this ) ); } @Override public JdbcType resolveSqlTypeDescriptor( String columnTypeName, int jdbcTypeCode, int precision, int scale, JdbcTypeRegistry jdbcTypeRegistry) { switch ( jdbcTypeCode ) { case OTHER: switch ( columnTypeName ) { case "uuid": jdbcTypeCode = UUID; break; case "json": case "jsonb": jdbcTypeCode = JSON; break; case "inet": jdbcTypeCode = INET; break; case "geometry": jdbcTypeCode = GEOMETRY; break; case "geography": jdbcTypeCode = GEOGRAPHY; break; } break; case TIME: // The PostgreSQL JDBC driver reports TIME for timetz, but we use it only for mapping OffsetTime to UTC if ( "timetz".equals( columnTypeName ) ) { jdbcTypeCode = TIME_UTC; } break; case TIMESTAMP: // The PostgreSQL JDBC driver reports TIMESTAMP for timestamptz, but we use it only for mapping Instant if ( "timestamptz".equals( columnTypeName ) ) { jdbcTypeCode = TIMESTAMP_UTC; } break; case ARRAY: // PostgreSQL names array types by prepending an underscore to the base name if ( columnTypeName.charAt( 0 ) == '_' ) { final String componentTypeName = columnTypeName.substring( 1 ); final Integer sqlTypeCode = resolveSqlTypeCode( componentTypeName, jdbcTypeRegistry.getTypeConfiguration() ); if ( sqlTypeCode != null ) { return jdbcTypeRegistry.resolveTypeConstructorDescriptor( jdbcTypeCode, jdbcTypeRegistry.getDescriptor( sqlTypeCode ), ColumnTypeInformation.EMPTY ); } } break; } return jdbcTypeRegistry.getDescriptor( jdbcTypeCode ); } @Override protected Integer resolveSqlTypeCode(String columnTypeName, TypeConfiguration typeConfiguration) { return switch ( columnTypeName ) { case "bool" -> Types.BOOLEAN; // Use REAL instead of FLOAT to get Float as recommended Java type case "float4" -> Types.REAL; case "float8" -> Types.DOUBLE; case "int2" -> Types.SMALLINT; case "int4" -> Types.INTEGER; case "int8" -> Types.BIGINT; default -> super.resolveSqlTypeCode( columnTypeName, typeConfiguration ); }; } @Override public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { super.contributeTypes( typeContributions, serviceRegistry ); contributeCockroachTypes( typeContributions, serviceRegistry ); } protected void contributeCockroachTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { final JdbcTypeRegistry jdbcTypeRegistry = typeContributions.getTypeConfiguration() .getJdbcTypeRegistry(); // Don't use this type due to https://github.com/pgjdbc/pgjdbc/issues/2862 //jdbcTypeRegistry.addDescriptor( TimestampUtcAsOffsetDateTimeJdbcType.INSTANCE ); if ( driverKind == PostgreSQLDriverKind.PG_JDBC ) { jdbcTypeRegistry.addDescriptor( PostgreSQLEnumJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptor( PostgreSQLOrdinalEnumJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLUUIDJdbcType.INSTANCE ); if ( PgJdbcHelper.isUsable( serviceRegistry ) ) { jdbcTypeRegistry.addDescriptorIfAbsent( PgJdbcHelper.getIntervalJdbcType( serviceRegistry ) ); if ( getVersion().isSameOrAfter( 20, 0 ) ) { jdbcTypeRegistry.addDescriptorIfAbsent( PgJdbcHelper.getInetJdbcType( serviceRegistry ) ); jdbcTypeRegistry.addDescriptorIfAbsent( PgJdbcHelper.getJsonbJdbcType( serviceRegistry ) ); jdbcTypeRegistry.addTypeConstructorIfAbsent( PgJdbcHelper.getJsonbArrayJdbcType( serviceRegistry ) ); } else { jdbcTypeRegistry.addDescriptorIfAbsent( PgJdbcHelper.getJsonJdbcType( serviceRegistry ) ); jdbcTypeRegistry.addTypeConstructorIfAbsent( PgJdbcHelper.getJsonArrayJdbcType( serviceRegistry ) ); } } else { jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingIntervalSecondJdbcType.INSTANCE ); if ( getVersion().isSameOrAfter( 20, 0 ) ) { jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingInetJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingJsonJdbcType.JSONB_INSTANCE ); jdbcTypeRegistry.addTypeConstructorIfAbsent( PostgreSQLCastingJsonArrayJdbcTypeConstructor.JSONB_INSTANCE ); } else { jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingJsonJdbcType.JSON_INSTANCE ); jdbcTypeRegistry.addTypeConstructorIfAbsent( PostgreSQLCastingJsonArrayJdbcTypeConstructor.JSON_INSTANCE ); } } } else { jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLUUIDJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingIntervalSecondJdbcType.INSTANCE ); if ( getVersion().isSameOrAfter( 20, 0 ) ) { jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingInetJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingJsonJdbcType.JSONB_INSTANCE ); jdbcTypeRegistry.addTypeConstructorIfAbsent( PostgreSQLCastingJsonArrayJdbcTypeConstructor.JSONB_INSTANCE ); } else { jdbcTypeRegistry.addDescriptorIfAbsent( PostgreSQLCastingJsonJdbcType.JSON_INSTANCE ); jdbcTypeRegistry.addTypeConstructorIfAbsent( PostgreSQLCastingJsonArrayJdbcTypeConstructor.JSON_INSTANCE ); } } // Force Blob binding to byte[] for CockroachDB jdbcTypeRegistry.addDescriptor( Types.BLOB, BlobJdbcType.MATERIALIZED ); jdbcTypeRegistry.addDescriptor( Types.CLOB, ClobJdbcType.MATERIALIZED ); jdbcTypeRegistry.addDescriptor( Types.NCLOB, ClobJdbcType.MATERIALIZED ); // The next two contributions are the same as for Postgresql typeContributions.contributeJdbcType( ObjectNullAsBinaryTypeJdbcType.INSTANCE ); // Until we remove StandardBasicTypes, we have to keep this typeContributions.contributeType( new JavaObjectType( ObjectNullAsBinaryTypeJdbcType.INSTANCE, typeContributions.getTypeConfiguration() .getJavaTypeRegistry() .getDescriptor( Object.class ) ) ); // Replace the standard array constructor jdbcTypeRegistry.addTypeConstructor( PostgreSQLArrayJdbcTypeConstructor.INSTANCE ); } @Override public void initializeFunctionRegistry(FunctionContributions functionContributions) { super.initializeFunctionRegistry(functionContributions); final CommonFunctionFactory functionFactory = new CommonFunctionFactory(functionContributions); functionFactory.ascii(); functionFactory.char_chr(); functionFactory.overlay(); functionFactory.position(); functionFactory.substringFromFor(); functionFactory.locate_positionSubstring(); functionFactory.concat_pipeOperator(); functionFactory.trim2(); functionFactory.substr(); functionFactory.reverse(); functionFactory.repeat(); functionFactory.md5(); functionFactory.sha1(); functionFactory.octetLength(); functionFactory.bitLength(); functionFactory.cbrt(); functionFactory.cot(); functionFactory.degrees(); functionFactory.radians(); functionFactory.pi(); functionFactory.log(); functionFactory.log10_log(); functionFactory.round(); functionFactory.bitandorxornot_operator(); functionFactory.bitAndOr(); functionFactory.everyAny_boolAndOr(); functionFactory.median_percentileCont_castDouble(); functionFactory.stddev(); functionFactory.stddevPopSamp(); functionFactory.variance(); functionFactory.varPopSamp(); functionFactory.covarPopSamp(); functionFactory.corr(); functionFactory.regrLinearRegressionAggregates(); functionContributions.getFunctionRegistry().register( "format", new FormatFunction( "experimental_strftime", false, true, false, functionContributions.getTypeConfiguration() ) ); functionFactory.windowFunctions(); functionFactory.listagg_stringAgg( "string" ); functionFactory.inverseDistributionOrderedSetAggregates(); functionFactory.hypotheticalOrderedSetAggregates_windowEmulation(); functionFactory.array_postgresql(); functionFactory.arrayAggregate(); functionFactory.arrayPosition_postgresql(); functionFactory.arrayPositions_postgresql(); functionFactory.arrayLength_cardinality(); functionFactory.arrayConcat_postgresql(); functionFactory.arrayPrepend_postgresql(); functionFactory.arrayAppend_postgresql(); functionFactory.arrayContains_postgresql(); functionFactory.arrayIntersects_postgresql(); functionFactory.arrayGet_bracket(); functionFactory.arraySet_unnest(); functionFactory.arrayRemove(); functionFactory.arrayRemoveIndex_unnest( true ); functionFactory.arraySlice_operator(); functionFactory.arrayReplace(); functionFactory.arrayTrim_unnest(); functionFactory.arrayFill_cockroachdb(); functionFactory.arrayToString_postgresql(); functionFactory.jsonValue_cockroachdb(); functionFactory.jsonQuery_cockroachdb(); functionFactory.jsonExists_cockroachdb(); functionFactory.jsonObject_postgresql(); functionFactory.jsonArray_postgresql(); functionFactory.jsonArrayAgg_postgresql( false ); functionFactory.jsonObjectAgg_postgresql( false ); functionFactory.jsonSet_postgresql(); functionFactory.jsonRemove_cockroachdb(); functionFactory.jsonReplace_postgresql(); functionFactory.jsonInsert_postgresql(); // No support for WITH clause in subquery: https://github.com/cockroachdb/cockroach/issues/131011 // functionFactory.jsonMergepatch_postgresql(); functionFactory.jsonArrayAppend_postgresql( false ); functionFactory.jsonArrayInsert_postgresql(); functionFactory.unnest_postgresql( false ); functionFactory.generateSeries( null, "ordinality", true ); functionFactory.jsonTable_cockroachdb(); // Postgres uses # instead of ^ for XOR functionContributions.getFunctionRegistry().patternDescriptorBuilder( "bitxor", "(?1#?2)" ) .setExactArgumentCount( 2 ) .setArgumentTypeResolver( StandardFunctionArgumentTypeResolvers.ARGUMENT_OR_IMPLIED_RESULT_TYPE ) .register(); functionContributions.getFunctionRegistry().register( "trunc", new PostgreSQLTruncFunction( getVersion().isSameOrAfter( 22, 2 ), functionContributions.getTypeConfiguration() ) ); functionContributions.getFunctionRegistry().registerAlternateKey( "truncate", "trunc" ); functionFactory.regexpLike_postgresql( false ); } @Override public @Nullable String getDefaultOrdinalityColumnName() { return "ordinality"; } @Override public TimeZoneSupport getTimeZoneSupport() { return TimeZoneSupport.NORMALIZE; } @Override public void appendBooleanValueString(SqlAppender appender, boolean bool) { appender.appendSql( bool ); } @Override public String getCascadeConstraintsString() { return " cascade"; } @Override public boolean supportsCurrentTimestampSelection() { return true; } @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } @Override public String getCurrentTimestampSelectString() { return "select now()"; } @Override public boolean supportsDistinctFromPredicate() { return true; } @Override public boolean supportsIfExistsBeforeTableName() { return true; } @Override public boolean supportsIfExistsBeforeConstraintName() { return true; } @Override public boolean supportsIfExistsAfterAlterTable() { return true; } @Override public boolean qualifyIndexName() { return false; } @Override public IdentityColumnSupport getIdentityColumnSupport() { return CockroachDBIdentityColumnSupport.INSTANCE; } @Override public boolean supportsValuesList() { return true; } @Override public boolean supportsPartitionBy() { return true; } @Override public boolean supportsNonQueryWithCTE() { return true; } @Override public boolean supportsRecursiveCTE() { return getVersion().isSameOrAfter( 20, 1 ); } @Override public boolean supportsConflictClauseForInsertCTE() { return true; } @Override public String getNoColumnsInsertString() { return "default values"; } @Override public String getCaseInsensitiveLike(){ return "ilike"; } @Override public boolean supportsCaseInsensitiveLike() { return true; } @Override public boolean supportsNullPrecedence() { // Not yet implemented: https://www.cockroachlabs.com/docs/v20.2/null-handling.html#nulls-and-sorting return false; } @Override public NullOrdering getNullOrdering() { return NullOrdering.SMALLEST; } @Override public boolean supportsTupleCounts() { return true; } @Override public boolean requiresParensForTupleDistinctCounts() { return true; } @Override public GenerationType getNativeValueGenerationStrategy() { return GenerationType.SEQUENCE; } @Override public SequenceSupport getSequenceSupport() { return PostgreSQLSequenceSupport.INSTANCE; } @Override public String getQuerySequencesString() { return "select sequence_name,sequence_schema,sequence_catalog,start_value,minimum_value,maximum_value,increment from information_schema.sequences"; } @Override public boolean supportsLobValueChangePropagation() { return false; } @Override public SqlAstTranslatorFactory getSqlAstTranslatorFactory() { return new StandardSqlAstTranslatorFactory() { @Override protected <T extends JdbcOperation> SqlAstTranslator<T> buildTranslator( SessionFactoryImplementor sessionFactory, Statement statement) { return new CockroachLegacySqlAstTranslator<>( sessionFactory, statement ); } }; } @Override public NationalizationSupport getNationalizationSupport() { // TEXT / STRING inherently support nationalized data return NationalizationSupport.IMPLICIT; } @Override public AggregateSupport getAggregateSupport() { return CockroachDBAggregateSupport.valueOf( this ); } @Override public int getMaxIdentifierLength() { return 63; } @Override public boolean supportsStandardArrays() { return true; } @Override public boolean supportsTemporalLiteralOffset() { return true; } @Override public void appendDateTimeLiteral( SqlAppender appender, TemporalAccessor temporalAccessor, TemporalType precision, TimeZone jdbcTimeZone) { switch ( precision ) { case DATE: appender.appendSql( "date '" ); appendAsDate( appender, temporalAccessor ); appender.appendSql( '\'' ); break; case TIME: if ( supportsTemporalLiteralOffset() && temporalAccessor.isSupported( ChronoField.OFFSET_SECONDS ) ) { appender.appendSql( "time with time zone '" ); appendAsTime( appender, temporalAccessor, true, jdbcTimeZone ); } else { appender.appendSql( "time '" ); appendAsLocalTime( appender, temporalAccessor ); } appender.appendSql( '\'' ); break; case TIMESTAMP: if ( supportsTemporalLiteralOffset() && temporalAccessor.isSupported( ChronoField.OFFSET_SECONDS ) ) { appender.appendSql( "timestamp with time zone '" ); appendAsTimestampWithMicros( appender, temporalAccessor, true, jdbcTimeZone ); appender.appendSql( '\'' ); } else { appender.appendSql( "timestamp '" ); appendAsTimestampWithMicros( appender, temporalAccessor, false, jdbcTimeZone ); appender.appendSql( '\'' ); } break; default: throw new IllegalArgumentException(); } } @Override public void appendDateTimeLiteral(SqlAppender appender, Date date, TemporalType precision, TimeZone jdbcTimeZone) { switch ( precision ) { case DATE: appender.appendSql( "date '" ); appendAsDate( appender, date ); appender.appendSql( '\'' ); break; case TIME: appender.appendSql( "time with time zone '" ); appendAsTime( appender, date, jdbcTimeZone ); appender.appendSql( '\'' ); break; case TIMESTAMP: appender.appendSql( "timestamp with time zone '" ); appendAsTimestampWithMicros( appender,date, jdbcTimeZone ); appender.appendSql( '\'' ); break; default: throw new IllegalArgumentException(); } } @Override public void appendDateTimeLiteral( SqlAppender appender, Calendar calendar, TemporalType precision, TimeZone jdbcTimeZone) { switch ( precision ) { case DATE: appender.appendSql( "date '" ); appendAsDate( appender, calendar ); appender.appendSql( '\'' ); break; case TIME: appender.appendSql( "time with time zone '" ); appendAsTime( appender, calendar, jdbcTimeZone ); appender.appendSql( '\'' ); break; case TIMESTAMP: appender.appendSql( "timestamp with time zone '" ); appendAsTimestampWithMillis( appender, calendar, jdbcTimeZone ); appender.appendSql( '\'' ); break; default: throw new IllegalArgumentException(); } } /** * The {@code extract()} function returns {@link TemporalUnit#DAY_OF_WEEK} * numbered from 0 to 6. This isn't consistent with what most other * databases do, so here we adjust the result by generating * {@code (extract(dayofweek,arg)+1))}. */ @Override public String extractPattern(TemporalUnit unit) { switch ( unit ) { case DAY_OF_WEEK: return "(" + super.extractPattern(unit) + "+1)"; default: return super.extractPattern(unit); } } @Override public String translateExtractField(TemporalUnit unit) { switch ( unit ) { case DAY_OF_MONTH: return "day"; case DAY_OF_YEAR: return "dayofyear"; case DAY_OF_WEEK: return "dayofweek"; default: return super.translateExtractField( unit ); } } /** * {@code microsecond} is the smallest unit for an {@code interval}, * and the highest precision for a {@code timestamp}. */ @Override public long getFractionalSecondPrecisionInNanos() { return 1_000; //microseconds } @Override public String timestampaddPattern(TemporalUnit unit, TemporalType temporalType, IntervalType intervalType) { return intervalType != null ? "(?2+?3)" : "cast(?3+" + intervalPattern( unit ) + " as " + temporalType.name().toLowerCase() + ")"; } private static String intervalPattern(TemporalUnit unit) { switch (unit) { case NATIVE: return "(?2)*interval '1 microsecond'"; case NANOSECOND: return "(?2)/1e3*interval '1 microsecond'"; case QUARTER: //quarter is not supported in interval literals return "(?2)*interval '3 month'"; case WEEK: //week is not supported in interval literals return "(?2)*interval '7 day'"; default: return "(?2)*interval '1 " + unit + "'"; } } @Override public String timestampdiffPattern(TemporalUnit unit, TemporalType fromTemporalType, TemporalType toTemporalType) { if ( unit == null ) { return "(?3-?2)"; } if ( toTemporalType == TemporalType.DATE && fromTemporalType == TemporalType.DATE ) { // special case: subtraction of two dates // results in an integer number of days // instead of an INTERVAL switch ( unit ) { case YEAR: case MONTH: case QUARTER: // age only supports timestamptz, so we have to cast the date expressions return "extract(" + translateDurationField( unit ) + " from age(cast(?3 as timestamptz),cast(?2 as timestamptz)))"; default: return "(?3-?2)" + DAY.conversionFactor( unit, this ); } } else { if (getVersion().isSameOrAfter( 20, 1 )) { switch (unit) { case YEAR: return "extract(year from ?3-?2)"; case QUARTER: return "(extract(year from ?3-?2)*4+extract(month from ?3-?2)//3)"; case MONTH: return "(extract(year from ?3-?2)*12+extract(month from ?3-?2))"; case WEEK: //week is not supported by extract() when the argument is a duration return "(extract(day from ?3-?2)/7)"; case DAY: return "extract(day from ?3-?2)"; //in order to avoid multiple calls to extract(), //we use extract(epoch from x - y) * factor for //all the following units: // Note that CockroachDB also has an extract_duration function which returns an int, // but we don't use that here because it is deprecated since v20. // We need to use round() instead of cast(... as int) because extract epoch returns // float8 which can cause loss-of-precision in some cases // https://github.com/cockroachdb/cockroach/issues/72523 case HOUR: case MINUTE: case SECOND: case NANOSECOND: case NATIVE: return "round(extract(epoch from ?3-?2)" + EPOCH.conversionFactor( unit, this ) + ")::int"; default: throw new SemanticException( "unrecognized field: " + unit ); } } else { switch (unit) { case YEAR: return "extract(year from ?3-?2)"; case QUARTER: return "(extract(year from ?3-?2)*4+extract(month from ?3-?2)//3)"; case MONTH: return "(extract(year from ?3-?2)*12+extract(month from ?3-?2))"; // Prior to v20, Cockroach didn't support extracting from an interval/duration, // so we use the extract_duration function case WEEK: return "extract_duration(hour from ?3-?2)/168"; case DAY: return "extract_duration(hour from ?3-?2)/24"; case NANOSECOND: return "extract_duration(microsecond from ?3-?2)*1e3"; default: return "extract_duration(?1 from ?3-?2)"; } } } } @Override public String translateDurationField(TemporalUnit unit) { return unit==NATIVE ? "microsecond" : super.translateDurationField(unit); } @Override public void appendDatetimeFormat(SqlAppender appender, String format) { appender.appendSql( SpannerDialect.datetimeFormat( format ).result() ); } @Override public LimitHandler getLimitHandler() { return OffsetFetchLimitHandler.INSTANCE; } @Override public String getForUpdateString(String aliases) { return getForUpdateString() + " of " + aliases; } @Override public String getForUpdateString(LockOptions lockOptions) { // Support was added in 20.1: https://www.cockroachlabs.com/docs/v20.1/select-for-update.html if ( getVersion().isBefore( 20, 1 ) ) { return ""; } return super.getForUpdateString( lockOptions ); } @Override public String getForUpdateString() { return getVersion().isBefore( 20, 1 ) ? "" : " for update"; } @Override public String getForUpdateString(String aliases, LockOptions lockOptions) { // Support was added in 20.1: https://www.cockroachlabs.com/docs/v20.1/select-for-update.html if ( getVersion().isBefore( 20, 1 ) ) { return ""; } final LockMode lockMode = lockOptions.getLockMode(); return switch ( lockMode ) { case PESSIMISTIC_READ -> getReadLockString( aliases, lockOptions.getTimeout() ); case PESSIMISTIC_WRITE -> getWriteLockString( aliases, lockOptions.getTimeout() ); case UPGRADE_NOWAIT, PESSIMISTIC_FORCE_INCREMENT -> getForUpdateNowaitString( aliases ); case UPGRADE_SKIPLOCKED -> getForUpdateSkipLockedString( aliases ); default -> ""; }; } private String withTimeout(String lockString, Timeout timeout) { return withTimeout( lockString, timeout.milliseconds() ); } private String withTimeout(String lockString, int timeout) { return switch ( timeout ) { case Timeouts.NO_WAIT_MILLI -> supportsNoWait() ? lockString + " nowait" : lockString; case Timeouts.SKIP_LOCKED_MILLI -> supportsSkipLocked() ? lockString + " skip locked" : lockString; default -> lockString; }; } @Override public String getWriteLockString(Timeout timeout) { return withTimeout( getForUpdateString(), timeout ); } @Override public String getWriteLockString(String aliases, Timeout timeout) { return withTimeout( getForUpdateString( aliases ), timeout ); } @Override public String getReadLockString(Timeout timeout) { return withTimeout(" for share", timeout ); } @Override public String getReadLockString(String aliases, Timeout timeout) { return withTimeout(" for share of " + aliases, timeout ); } @Override public String getWriteLockString(int timeout) { return withTimeout( getForUpdateString(), timeout ); } @Override public String getWriteLockString(String aliases, int timeout) { return withTimeout( getForUpdateString( aliases ), timeout ); } @Override public String getReadLockString(int timeout) { return withTimeout(" for share", timeout ); } @Override public String getReadLockString(String aliases, int timeout) { return withTimeout(" for share of " + aliases, timeout ); } @Override public String getForUpdateNowaitString() { return supportsNoWait() ? getForUpdateString() + " nowait" : getForUpdateString(); } @Override public String getForUpdateNowaitString(String aliases) { return supportsNoWait() ? getForUpdateString( aliases ) + " nowait" : getForUpdateString( aliases ); } @Override public String getForUpdateSkipLockedString() { return supportsSkipLocked() ? getForUpdateString() + " skip locked" : getForUpdateString(); } @Override public String getForUpdateSkipLockedString(String aliases) { return supportsSkipLocked() ? getForUpdateString( aliases ) + " skip locked" : getForUpdateString( aliases ); } @Override public LockingSupport getLockingSupport() { return getVersion().isSameOrAfter( 20, 1 ) ? COCKROACH_LOCKING_SUPPORT : LEGACY_COCKROACH_LOCKING_SUPPORT; } @Override public boolean useInputStreamToInsertBlob() { // PG-JDBC treats setBinaryStream()/setCharacterStream() calls like bytea/varchar, which are not LOBs, // so disable stream bindings for this dialect completely return false; } @Override public boolean useConnectionToCreateLob() { return false; } @Override public boolean supportsOffsetInSubquery() { return true; } @Override public boolean supportsWindowFunctions() { return true; } @Override public boolean supportsLateral() { return getVersion().isSameOrAfter( 20, 1 ); } @Override public FunctionalDependencyAnalysisSupport getFunctionalDependencyAnalysisSupport() { return FunctionalDependencyAnalysisSupportImpl.TABLE_REFERENCE; } @Override public NameQualifierSupport getNameQualifierSupport() { // This method is overridden so the correct value will be returned when // DatabaseMetaData is not available. return NameQualifierSupport.SCHEMA; } @Override public IdentifierHelper buildIdentifierHelper(IdentifierHelperBuilder builder, DatabaseMetaData metadata) throws SQLException { if ( metadata == null ) { builder.setUnquotedCaseStrategy( IdentifierCaseStrategy.LOWER ); builder.setQuotedCaseStrategy( IdentifierCaseStrategy.MIXED ); } return super.buildIdentifierHelper( builder, metadata ); } @Override public ViolatedConstraintNameExtractor getViolatedConstraintNameExtractor() { return EXTRACTOR; } /** * Constraint-name extractor for Postgres constraint violation exceptions. * Originally contributed by Denny Bartelt. */ private static final ViolatedConstraintNameExtractor EXTRACTOR = new TemplatedViolatedConstraintNameExtractor( sqle -> { final String sqlState = JdbcExceptionHelper.extractSqlState( sqle ); if ( sqlState == null ) { return null; } switch ( Integer.parseInt( sqlState ) ) { // CHECK VIOLATION case 23514: return extractUsingTemplate( "violates check constraint \"","\"", sqle.getMessage() ); // UNIQUE VIOLATION case 23505: return extractUsingTemplate( "violates unique constraint \"","\"", sqle.getMessage() ); // FOREIGN KEY VIOLATION case 23503: return extractUsingTemplate( "violates foreign key constraint \"","\"", sqle.getMessage() ); // NOT NULL VIOLATION case 23502: return extractUsingTemplate( "null value in column \"","\" violates not-null constraint", sqle.getMessage() ); // TODO: RESTRICT VIOLATION case 23001: return null; // ALL OTHER default: return null; } } ); @Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return (sqlException, message, sql) -> { final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException ); if ( sqlState == null ) { return null; } return switch ( sqlState ) { // DEADLOCK DETECTED case "40P01" -> new LockAcquisitionException( message, sqlException, sql); // LOCK NOT AVAILABLE case "55P03" -> new PessimisticLockException( message, sqlException, sql); case "57014" -> new QueryTimeoutException( message, sqlException, sql ); // returning null allows other delegates to operate default -> null; }; }; } @Override public int getDefaultIntervalSecondScale() { // The maximum scale for `interval second` is 6 unfortunately return 6; } // CockroachDB doesn't support this by default. See sql.multiple_modifications_of_table.enabled // // @Override // public SqmMultiTableMutationStrategy getFallbackSqmMutationStrategy( // EntityMappingType rootEntityDescriptor, // RuntimeModelCreationContext runtimeModelCreationContext) { // return new CteMutationStrategy( rootEntityDescriptor, runtimeModelCreationContext ); // } // // @Override // public SqmMultiTableInsertStrategy getFallbackSqmInsertStrategy( // EntityMappingType rootEntityDescriptor, // RuntimeModelCreationContext runtimeModelCreationContext) { // return new CteInsertStrategy( rootEntityDescriptor, runtimeModelCreationContext ); // } @Override public DmlTargetColumnQualifierSupport getDmlTargetColumnQualifierSupport() { return DmlTargetColumnQualifierSupport.TABLE_ALIAS; } @Override public boolean supportsFromClauseInUpdate() { return true; } @Override public boolean supportsRowConstructor() { return true; } @Override public boolean supportsArrayConstructor() { return true; } @Override public boolean supportsRowValueConstructorSyntaxInQuantifiedPredicates() { return false; } @Override public InformationExtractor getInformationExtractor(ExtractionContext extractionContext) { return new InformationExtractorPostgreSQLImpl( extractionContext ); } }
CockroachLegacyDialect
java
quarkusio__quarkus
independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/common/util/ParameterParser.java
{ "start": 574, "end": 10101 }
class ____ { /** * String to be parsed. */ private char[] chars = null; /** * Current position in the string. */ private int pos = 0; /** * Maximum position in the string. */ private int len = 0; /** * Start of a token. */ private int i1 = 0; /** * End of a token. */ private int i2 = 0; /** * Whether names stored in the map should be converted to lower case. */ private boolean lowerCaseNames = false; /** * Default ParameterParser constructor. */ public ParameterParser() { super(); } /** * Are there any characters left to parse? * * @return <code>true</code> if there are unparsed characters, * <code>false</code> otherwise. */ private boolean hasChar() { return this.pos < this.len; } /** * A helper method to process the parsed token. This method removes * leading and trailing blanks as well as enclosing quotation marks, * when necessary. * * @param quoted <code>true</code> if quotation marks are expected, * <code>false</code> otherwise. * @return the token */ private String getToken(boolean quoted) { // Trim leading white spaces while ((i1 < i2) && (Character.isWhitespace(chars[i1]))) { i1++; } // Trim trailing white spaces while ((i2 > i1) && (Character.isWhitespace(chars[i2 - 1]))) { i2--; } // Strip away quotation marks if necessary if (quoted) { if (((i2 - i1) >= 2) && (chars[i1] == '"') && (chars[i2 - 1] == '"')) { i1++; i2--; } } String result = null; if (i2 > i1) { result = new String(chars, i1, i2 - i1); } return result; } /** * Tests if the given character is present in the array of characters. * * @param ch the character to test for presense in the array of characters * @param charray the array of characters to test against * @return <code>true</code> if the character is present in the array of * characters, <code>false</code> otherwise. */ private boolean isOneOf(char ch, final char[] charray) { boolean result = false; for (int i = 0; i < charray.length; i++) { if (ch == charray[i]) { result = true; break; } } return result; } /** * Parses out a token until any of the given terminators * is encountered. * * @param terminators the array of terminating characters. Any of these * characters when encountered signify the end of the token * @return the token */ private String parseToken(final char[] terminators) { char ch; i1 = pos; i2 = pos; while (hasChar()) { ch = chars[pos]; if (isOneOf(ch, terminators)) { break; } i2++; pos++; } return getToken(false); } /** * Parses out a token until any of the given terminators * is encountered outside the quotation marks. * * @param terminators the array of terminating characters. Any of these * characters when encountered outside the quotation marks signify the end * of the token * @return the token */ private String parseQuotedToken(final char[] terminators) { char ch; i1 = pos; i2 = pos; boolean quoted = false; boolean charEscaped = false; while (hasChar()) { ch = chars[pos]; if (!quoted && isOneOf(ch, terminators)) { break; } if (!charEscaped && ch == '"') { quoted = !quoted; } charEscaped = (!charEscaped && ch == '\\'); i2++; pos++; } return getToken(true); } /** * Returns <code>true</code> if parameter names are to be converted to lower * case when name/value pairs are parsed. * * @return <code>true</code> if parameter names are to be * converted to lower case when name/value pairs are parsed. * Otherwise returns <code>false</code> */ public boolean isLowerCaseNames() { return this.lowerCaseNames; } /** * Sets the flag if parameter names are to be converted to lower case when * name/value pairs are parsed. * * @param b <code>true</code> if parameter names are to be * converted to lower case when name/value pairs are parsed. * <code>false</code> otherwise. */ public void setLowerCaseNames(boolean b) { this.lowerCaseNames = b; } /** * Extracts a map of name/value pairs from the given string. Names are * expected to be unique. * * @param str the string that contains a sequence of name/value pairs * @param separator the name/value pairs separator * @return a map of name/value pairs */ public Map<String, String> parse(final String str, char separator) { if (str == null) { return emptyMap(); } return parse(str.toCharArray(), separator); } /** * Extracts a map of name/value pairs from the given array of * characters. Names are expected to be unique. * * @param chars the array of characters that contains a sequence of * name/value pairs * @param separator the name/value pairs separator * @return a map of name/value pairs */ public Map<String, String> parse(final char[] chars, char separator) { if (chars == null) { return emptyMap(); } return parse(chars, 0, chars.length, separator); } /** * Extracts a map of name/value pairs from the given array of * characters. Names are expected to be unique. * * @param chars the array of characters that contains a sequence of * name/value pairs * @param offset - the initial offset. * @param length - the length. * @param separator the name/value pairs separator * @return a map of name/value pairs */ public Map<String, String> parse( final char[] chars, int offset, int length, char separator) { if (chars == null) { return emptyMap(); } Map<String, String> params = newMap(); this.chars = chars; this.pos = offset; this.len = length; String paramName = null; String paramValue = null; while (hasChar()) { paramName = parseToken(new char[] { '=', separator }); paramValue = null; if (hasChar() && (chars[pos] == '=')) { pos++; // skip '=' paramValue = parseQuotedToken(new char[] { separator }); } if (hasChar() && (chars[pos] == separator)) { pos++; // skip separator } if ((paramName != null) && (paramName.length() > 0)) { if (this.lowerCaseNames) { paramName = paramName.toLowerCase(); } params.put(paramName, paramValue); } } return params; } /** * Takes string as-is and only changes the value of a specific attribute. * * @param chars the array of characters that contains a sequence of * name/value pairs * @param offset - the initial offset. * @param length - the length. * @param separator the name/value pairs separator * @param name attribute name * @param value new value * @return updated parameters string */ public String setAttribute( final char[] chars, int offset, int length, char separator, String name, String value) { this.chars = chars; this.pos = offset; this.len = length; String paramName = null; String paramValue = null; int start = offset; StringBuilder newChars = new StringBuilder(); while (hasChar()) { paramName = parseToken(new char[] { '=', separator }); paramValue = null; int index = -1; if (paramName.equals(name)) { newChars.append(new String(chars, start, pos - start)); } if (hasChar() && (chars[pos] == '=')) { pos++; // skip '=' paramValue = parseQuotedToken(new char[] { separator }); } if (paramName.equals(name)) { newChars.append("=").append(value); start = pos; } else { newChars.append(new String(chars, start, pos - start)); start = pos; } if (hasChar() && (chars[pos] == separator)) { pos++; // skip separator } } return newChars.toString(); } protected <K, V> Map<K, V> emptyMap() { return new HashMap<>(); } protected <K, V> Map<K, V> newMap() { return new HashMap<>(); } }
ParameterParser
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/frommap/MapToBeanFromMapAndNestedMap.java
{ "start": 1268, "end": 1586 }
class ____ { private String stringFromNestedMap; public String getStringFromNestedMap() { return stringFromNestedMap; } public void setStringFromNestedMap(String stringFromNestedMap) { this.stringFromNestedMap = stringFromNestedMap; } } }
NestedTarget
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/SHOW_STATUS_Syntax_Test.java
{ "start": 969, "end": 3329 }
class ____ extends TestCase { public void test_0() throws Exception { String sql = "SHOW STATUS LIKE 'Key%'"; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); String text = output(stmtList); assertEquals("SHOW STATUS LIKE 'Key%';", text); } public void test_where() throws Exception { String sql = "SHOW STATUS WHERE X LIKE 'Key%'"; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); String text = output(stmtList); assertEquals("SHOW STATUS WHERE X LIKE 'Key%';", text); } public void test_corba() throws Exception { String sql = "SHOW COBAR_STATUS"; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); String text = output(stmtList); assertEquals("SHOW COBAR_STATUS;", text); } public void test_1() throws Exception { String sql = "SHOW GLOBAL STATUS LIKE 'Key%'"; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); String text = output(stmtList); assertEquals("SHOW GLOBAL STATUS LIKE 'Key%';", text); } public void test_2() throws Exception { String sql = "SHOW SESSION STATUS LIKE 'Key%'"; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); String text = output(stmtList); assertEquals("SHOW SESSION STATUS LIKE 'Key%';", text); } public void test_3() throws Exception { String sql = "SHOW SESSION STATUS"; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); String text = output(stmtList); assertEquals("SHOW SESSION STATUS;", text); } private String output(List<SQLStatement> stmtList) { StringBuilder out = new StringBuilder(); for (SQLStatement stmt : stmtList) { stmt.accept(new MySqlOutputVisitor(out)); out.append(";"); } return out.toString(); } }
SHOW_STATUS_Syntax_Test
java
netty__netty
transport-udt/src/main/java/io/netty/channel/udt/nio/NioUdtMessageAcceptorChannel.java
{ "start": 944, "end": 1262 }
class ____ extends NioUdtAcceptorChannel { public NioUdtMessageAcceptorChannel() { super(TypeUDT.DATAGRAM); } @Override protected UdtChannel newConnectorChannel(SocketChannelUDT channelUDT) { return new NioUdtMessageConnectorChannel(this, channelUDT); } }
NioUdtMessageAcceptorChannel
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/WriteLoadConstraintDeciderTests.java
{ "start": 2397, "end": 28390 }
class ____ extends ESAllocationTestCase { public void testCanAlwaysAllocateDuringReplace() { var wld = new WriteLoadConstraintDecider(ClusterSettings.createBuiltInClusterSettings()); assertEquals(Decision.YES, wld.canForceAllocateDuringReplace(any(), any(), any())); } /** * Test the write load decider behavior when disabled */ public void testWriteLoadDeciderDisabled() { String indexName = "test-index"; var testHarness = createClusterStateAndRoutingAllocation(indexName); var writeLoadDecider = createWriteLoadConstraintDecider( Settings.builder() .put( WriteLoadConstraintSettings.WRITE_LOAD_DECIDER_ENABLED_SETTING.getKey(), WriteLoadConstraintSettings.WriteLoadDeciderStatus.DISABLED ) .build() ); assertEquals( Decision.Type.YES, writeLoadDecider.canAllocate( testHarness.shardRoutingOnNodeBelowUtilThreshold, testHarness.exceedingThresholdRoutingNode, testHarness.routingAllocation ).type() ); assertEquals( Decision.Type.YES, writeLoadDecider.canAllocate( testHarness.shardRoutingOnNodeExceedingUtilThreshold, testHarness.belowThresholdRoutingNode, testHarness.routingAllocation ).type() ); assertEquals( Decision.Type.YES, writeLoadDecider.canAllocate( testHarness.shardRoutingOnNodeExceedingUtilThreshold, testHarness.nearThresholdRoutingNode, testHarness.routingAllocation ).type() ); assertEquals( Decision.Type.YES, writeLoadDecider.canAllocate( testHarness.shardRoutingNoWriteLoad, testHarness.exceedingThresholdRoutingNode, testHarness.routingAllocation ).type() ); assertEquals( Decision.Type.YES, writeLoadDecider.canRemain( testHarness.clusterState.metadata().getProject().index(indexName), testHarness.shardRoutingOnNodeExceedingUtilThreshold, testHarness.exceedingThresholdRoutingNode, testHarness.routingAllocation ).type() ); } /** * Test the {@link WriteLoadConstraintDecider#canAllocate} implementation. */ public void testWriteLoadDeciderCanAllocate() { String indexName = "test-index"; var testHarness = createClusterStateAndRoutingAllocation(indexName); testHarness.routingAllocation.debugDecision(true); var writeLoadDecider = createWriteLoadConstraintDecider( Settings.builder() .put( WriteLoadConstraintSettings.WRITE_LOAD_DECIDER_ENABLED_SETTING.getKey(), randomBoolean() ? WriteLoadConstraintSettings.WriteLoadDeciderStatus.ENABLED : WriteLoadConstraintSettings.WriteLoadDeciderStatus.LOW_THRESHOLD_ONLY ) .build() ); assertDecisionMatches( "Assigning a new shard to a node that is above the threshold should fail", writeLoadDecider.canAllocate( testHarness.shardRoutingOnNodeBelowUtilThreshold, testHarness.exceedingThresholdRoutingNode, testHarness.routingAllocation ), Decision.Type.NOT_PREFERRED, "Node [*] with write thread pool utilization [0.99] already exceeds the high utilization threshold of [0.900000]. " + "Cannot allocate shard [[test-index][1]] to node without risking increased write latencies." ); assertDecisionMatches( "Unassigned shard should always be accepted", writeLoadDecider.canAllocate( testHarness.unassignedShardRouting, randomFrom(testHarness.exceedingThresholdRoutingNode, testHarness.belowThresholdRoutingNode), testHarness.routingAllocation ), Decision.Type.YES, "Shard is unassigned. Decider takes no action." ); assertDecisionMatches( "Assigning a new shard to a node that has capacity should succeed", writeLoadDecider.canAllocate( testHarness.shardRoutingOnNodeExceedingUtilThreshold, testHarness.belowThresholdRoutingNode, testHarness.routingAllocation ), Decision.Type.YES, "Shard [[test-index][0]] in index [[test-index]] can be assigned to node [*]. The node's utilization would become [*]" ); assertDecisionMatches( "Assigning a new shard without a write load estimate to an over-threshold node should be blocked", writeLoadDecider.canAllocate( testHarness.shardRoutingNoWriteLoad, testHarness.exceedingThresholdRoutingNode, testHarness.routingAllocation ), Decision.Type.NOT_PREFERRED, "Node [*] with write thread pool utilization [0.99] already exceeds the high utilization threshold of " + "[0.900000]. Cannot allocate shard [[test-index][2]] to node without risking increased write latencies." ); assertDecisionMatches( "Assigning a new shard without a write load estimate to an under-threshold node should be allowed", writeLoadDecider.canAllocate( testHarness.shardRoutingNoWriteLoad, testHarness.belowThresholdRoutingNode, testHarness.routingAllocation ), Decision.Type.YES, "Shard [[test-index][2]] in index [[test-index]] can be assigned to node [*]. The node's utilization would become [*]" ); assertDecisionMatches( "Assigning a new shard that would cause the node to exceed capacity should fail", writeLoadDecider.canAllocate( testHarness.shardRoutingOnNodeExceedingUtilThreshold, testHarness.nearThresholdRoutingNode, testHarness.routingAllocation ), Decision.Type.NOT_PREFERRED, "The high utilization threshold of [0.900000] would be exceeded on node [*] with utilization [0.89] " + "if shard [[test-index][0]] with estimated additional utilisation [0.06250] (write load [0.50000] / threads [8]) were " + "assigned to it. Cannot allocate shard to node without risking increased write latencies." ); } /** * Test the {@link WriteLoadConstraintDecider#canRemain} implementation. */ public void testWriteLoadDeciderCanRemain() { String indexName = "test-index"; var testHarness = createClusterStateAndRoutingAllocation(indexName); testHarness.routingAllocation.debugDecision(true); var writeLoadDecider = createWriteLoadConstraintDecider( Settings.builder() .put( WriteLoadConstraintSettings.WRITE_LOAD_DECIDER_ENABLED_SETTING.getKey(), WriteLoadConstraintSettings.WriteLoadDeciderStatus.ENABLED ) .build() ); assertEquals( "A shard on a node below the util threshold should remain on its node", Decision.Type.YES, writeLoadDecider.canRemain( testHarness.clusterState.metadata().getProject().index(indexName), testHarness.shardRoutingOnNodeBelowUtilThreshold, testHarness.belowThresholdRoutingNode, testHarness.routingAllocation ).type() ); assertEquals( "A shard on a node above the util threshold should remain on its node", Decision.Type.YES, writeLoadDecider.canRemain( testHarness.clusterState.metadata().getProject().index(indexName), testHarness.shardRoutingOnNodeExceedingUtilThreshold, testHarness.exceedingThresholdRoutingNode, testHarness.routingAllocation ).type() ); assertEquals( "A shard on a node with queuing below the threshold should remain on its node", Decision.Type.YES, writeLoadDecider.canRemain( testHarness.clusterState.metadata().getProject().index(indexName), testHarness.shardRoutingOnNodeBelowQueueThreshold, testHarness.belowQueuingThresholdRoutingNode, testHarness.routingAllocation ).type() ); assertEquals( "A shard on a node with queuing above the threshold should not remain", Decision.Type.NOT_PREFERRED, writeLoadDecider.canRemain( testHarness.clusterState.metadata().getProject().index(indexName), testHarness.shardRoutingOnNodeAboveQueueThreshold, testHarness.aboveQueuingThresholdRoutingNode, testHarness.routingAllocation ).type() ); assertEquals( "A shard with no write load can still return NOT_PREFERRED", Decision.Type.NOT_PREFERRED, writeLoadDecider.canRemain( testHarness.clusterState.metadata().getProject().index(indexName), testHarness.shardRoutingNoWriteLoad, testHarness.aboveQueuingThresholdRoutingNode, testHarness.routingAllocation ).type() ); } public void testWriteLoadDeciderShouldPreventBalancerMovingShardsBack() { final var indexName = randomIdentifier(); final int numThreads = randomIntBetween(1, 10); final float highUtilizationThreshold = randomFloatBetween(0.5f, 0.9f, true); final long highLatencyThreshold = randomLongBetween(1000, 10000); final var settings = Settings.builder() .put( WriteLoadConstraintSettings.WRITE_LOAD_DECIDER_ENABLED_SETTING.getKey(), WriteLoadConstraintSettings.WriteLoadDeciderStatus.ENABLED ) .put(WriteLoadConstraintSettings.WRITE_LOAD_DECIDER_HIGH_UTILIZATION_THRESHOLD_SETTING.getKey(), highUtilizationThreshold) .put( WriteLoadConstraintSettings.WRITE_LOAD_DECIDER_QUEUE_LATENCY_THRESHOLD_SETTING.getKey(), TimeValue.timeValueMillis(highLatencyThreshold) ) .build(); final var state = ClusterStateCreationUtils.state(2, new String[] { indexName }, 4); final var balancedShardsAllocator = new BalancedShardsAllocator(settings); final var overloadedNode = randomFrom(state.nodes().getAllNodes()); final var otherNode = state.nodes().stream().filter(node -> node != overloadedNode).findFirst().orElseThrow(); final var clusterInfo = ClusterInfo.builder() .nodeUsageStatsForThreadPools( Map.of( overloadedNode.getId(), new NodeUsageStatsForThreadPools( overloadedNode.getId(), Map.of( ThreadPool.Names.WRITE, new ThreadPoolUsageStats( numThreads, randomFloatBetween(highUtilizationThreshold, 1.1f, false), randomLongBetween(highLatencyThreshold, highLatencyThreshold * 2) ) ) ), otherNode.getId(), new NodeUsageStatsForThreadPools( otherNode.getId(), Map.of( ThreadPool.Names.WRITE, new ThreadPoolUsageStats( numThreads, randomFloatBetween(0.0f, highUtilizationThreshold / 2, true), randomLongBetween(0, highLatencyThreshold / 2) ) ) ) ) ) // simulate all zero or missing shard write loads .shardWriteLoads( state.routingTable(ProjectId.DEFAULT) .allShards() .filter(ignored -> randomBoolean()) // some write-loads are missing altogether .collect(Collectors.toMap(ShardRouting::shardId, ignored -> 0.0d)) // the rest are zero ) .build(); final var clusterSettings = createBuiltInClusterSettings(settings); final var writeLoadConstraintDecider = new WriteLoadConstraintDecider(clusterSettings); final var routingAllocation = new RoutingAllocation( new AllocationDeciders(List.of(writeLoadConstraintDecider)), state.getRoutingNodes().mutableCopy(), state, clusterInfo, SnapshotShardSizeInfo.EMPTY, randomLong() ); // This should move a shard in an attempt to resolve the hot-spot balancedShardsAllocator.allocate(routingAllocation); assertEquals(1, routingAllocation.routingNodes().node(overloadedNode.getId()).numberOfOwningShards()); assertEquals(3, routingAllocation.routingNodes().node(otherNode.getId()).numberOfOwningShards()); final var clusterInfoSimulator = new ClusterInfoSimulator(routingAllocation); final var movedShards = new HashSet<ShardRouting>(); for (RoutingNode routingNode : routingAllocation.routingNodes()) { movedShards.addAll(routingNode.shardsWithState(ShardRoutingState.INITIALIZING).collect(Collectors.toSet())); } movedShards.forEach(shardRouting -> { routingAllocation.routingNodes().startShard(shardRouting, new RoutingChangesObserver() { }, randomNonNegativeLong()); clusterInfoSimulator.simulateShardStarted(shardRouting); }); // This should run through the balancer without moving any shards back ClusterInfo simulatedClusterInfo = clusterInfoSimulator.getClusterInfo(); balancedShardsAllocator.allocate( new RoutingAllocation( routingAllocation.deciders(), routingAllocation.routingNodes(), routingAllocation.getClusterState(), simulatedClusterInfo, routingAllocation.snapshotShardSizeInfo(), randomLong() ) ); assertEquals(1, routingAllocation.routingNodes().node(overloadedNode.getId()).numberOfOwningShards()); assertEquals(3, routingAllocation.routingNodes().node(otherNode.getId()).numberOfOwningShards()); } /** * Carries all the cluster state objects needed for testing after {@link #createClusterStateAndRoutingAllocation} sets them up. */ private record TestHarness( ClusterState clusterState, RoutingAllocation routingAllocation, RoutingNode exceedingThresholdRoutingNode, RoutingNode belowThresholdRoutingNode, RoutingNode nearThresholdRoutingNode, RoutingNode belowQueuingThresholdRoutingNode, RoutingNode aboveQueuingThresholdRoutingNode, ShardRouting shardRoutingOnNodeExceedingUtilThreshold, ShardRouting shardRoutingOnNodeBelowUtilThreshold, ShardRouting shardRoutingNoWriteLoad, ShardRouting shardRoutingOnNodeBelowQueueThreshold, ShardRouting shardRoutingOnNodeAboveQueueThreshold, ShardRouting unassignedShardRouting ) {} /** * Creates all the cluster state and objects needed to test the {@link WriteLoadConstraintDecider}. */ private TestHarness createClusterStateAndRoutingAllocation(String indexName) { /** * Create the ClusterState for multiple nodes and multiple index shards. */ int numberOfShards = 6; ClusterState clusterState = ClusterStateCreationUtils.stateWithAssignedPrimariesAndReplicas( new String[] { indexName }, numberOfShards, 3 ); // The number of data nodes the util method above creates is numberOfReplicas+2, and five data nodes are needed for this test. assertEquals(5, clusterState.nodes().size()); assertEquals(1, clusterState.metadata().getTotalNumberOfIndices()); /** * Fetch references to the nodes and index shards from the generated ClusterState, so the ClusterInfo can be created from them. */ var discoveryNodeIterator = clusterState.nodes().iterator(); assertTrue(discoveryNodeIterator.hasNext()); var exceedingThresholdDiscoveryNode = discoveryNodeIterator.next(); assertTrue(discoveryNodeIterator.hasNext()); var belowThresholdDiscoveryNode2 = discoveryNodeIterator.next(); assertTrue(discoveryNodeIterator.hasNext()); var nearThresholdDiscoveryNode3 = discoveryNodeIterator.next(); assertTrue(discoveryNodeIterator.hasNext()); var queuingBelowThresholdDiscoveryNode4 = discoveryNodeIterator.next(); assertTrue(discoveryNodeIterator.hasNext()); var queuingAboveThresholdDiscoveryNode5 = discoveryNodeIterator.next(); assertFalse(discoveryNodeIterator.hasNext()); var indexIterator = clusterState.metadata().indicesAllProjects().iterator(); assertTrue(indexIterator.hasNext()); IndexMetadata testIndexMetadata = indexIterator.next(); assertFalse(indexIterator.hasNext()); Index testIndex = testIndexMetadata.getIndex(); assertEquals(numberOfShards, testIndexMetadata.getNumberOfShards()); ShardId testShardId1 = new ShardId(testIndex, 0); ShardId testShardId2 = new ShardId(testIndex, 1); ShardId testShardId3NoWriteLoad = new ShardId(testIndex, 2); ShardId testShardId4 = new ShardId(testIndex, 3); ShardId testShardId5 = new ShardId(testIndex, 4); ShardId testShardId6Unassigned = new ShardId(testIndex, 5); /** * Create a ClusterInfo that includes the node and shard level write load estimates for a variety of node capacity situations. */ var nodeThreadPoolStatsWithWriteExceedingThreshold = createNodeUsageStatsForThreadPools( exceedingThresholdDiscoveryNode, 8, 0.99f, 0 ); var nodeThreadPoolStatsWithWriteBelowThreshold = createNodeUsageStatsForThreadPools(belowThresholdDiscoveryNode2, 8, 0.50f, 0); var nodeThreadPoolStatsWithWriteNearThreshold = createNodeUsageStatsForThreadPools(nearThresholdDiscoveryNode3, 8, 0.89f, 0); var nodeThreadPoolStatsWithQueuingBelowThreshold = createNodeUsageStatsForThreadPools( exceedingThresholdDiscoveryNode, 8, 0.99f, 5_000 ); var nodeThreadPoolStatsWithQueuingAboveThreshold = createNodeUsageStatsForThreadPools( exceedingThresholdDiscoveryNode, 8, 0.99f, 15_000 ); // Create a map of usage per node. var nodeIdToNodeUsageStatsForThreadPools = new HashMap<String, NodeUsageStatsForThreadPools>(); nodeIdToNodeUsageStatsForThreadPools.put(exceedingThresholdDiscoveryNode.getId(), nodeThreadPoolStatsWithWriteExceedingThreshold); nodeIdToNodeUsageStatsForThreadPools.put(belowThresholdDiscoveryNode2.getId(), nodeThreadPoolStatsWithWriteBelowThreshold); nodeIdToNodeUsageStatsForThreadPools.put(nearThresholdDiscoveryNode3.getId(), nodeThreadPoolStatsWithWriteNearThreshold); nodeIdToNodeUsageStatsForThreadPools.put(queuingBelowThresholdDiscoveryNode4.getId(), nodeThreadPoolStatsWithQueuingBelowThreshold); nodeIdToNodeUsageStatsForThreadPools.put(queuingAboveThresholdDiscoveryNode5.getId(), nodeThreadPoolStatsWithQueuingAboveThreshold); // Create a map of usage per shard. var shardIdToWriteLoadEstimate = new HashMap<ShardId, Double>(); shardIdToWriteLoadEstimate.put(testShardId1, 0.5); shardIdToWriteLoadEstimate.put(testShardId2, 0.5); shardIdToWriteLoadEstimate.put(testShardId3NoWriteLoad, 0d); shardIdToWriteLoadEstimate.put(testShardId4, 0.5); shardIdToWriteLoadEstimate.put(testShardId5, 0.5d); if (randomBoolean()) { shardIdToWriteLoadEstimate.put(testShardId6Unassigned, randomDoubleBetween(0.0, 2.0, true)); } ClusterInfo clusterInfo = ClusterInfo.builder() .nodeUsageStatsForThreadPools(nodeIdToNodeUsageStatsForThreadPools) .shardWriteLoads(shardIdToWriteLoadEstimate) .build(); /** * Create the RoutingAllocation from the ClusterState and ClusterInfo above, and set up the other input for the WriteLoadDecider. */ var routingAllocation = new RoutingAllocation( null, RoutingNodes.immutable(clusterState.globalRoutingTable(), clusterState.nodes()), clusterState, clusterInfo, null, System.nanoTime() ); ShardRouting shardRoutingOnNodeExceedingUtilThreshold = TestShardRouting.newShardRouting( testShardId1, exceedingThresholdDiscoveryNode.getId(), null, true, ShardRoutingState.STARTED ); ShardRouting shardRoutingOnNodeBelowUtilThreshold = TestShardRouting.newShardRouting( testShardId2, belowThresholdDiscoveryNode2.getId(), null, true, ShardRoutingState.STARTED ); ShardRouting shardRoutingNoWriteLoad = TestShardRouting.newShardRouting( testShardId3NoWriteLoad, belowThresholdDiscoveryNode2.getId(), null, true, ShardRoutingState.STARTED ); ShardRouting shardRoutingOnNodeBelowQueueThreshold = TestShardRouting.newShardRouting( testShardId4, queuingBelowThresholdDiscoveryNode4.getId(), null, true, ShardRoutingState.STARTED ); ShardRouting shardRoutingOnNodeAboveQueueThreshold = TestShardRouting.newShardRouting( testShardId5, queuingAboveThresholdDiscoveryNode5.getId(), null, true, ShardRoutingState.STARTED ); ShardRouting unassignedShardRouting = TestShardRouting.newShardRouting( testShardId6Unassigned, null, true, ShardRoutingState.UNASSIGNED ); RoutingNode exceedingThresholdRoutingNode = RoutingNodesHelper.routingNode( exceedingThresholdDiscoveryNode.getId(), exceedingThresholdDiscoveryNode, shardRoutingOnNodeExceedingUtilThreshold ); RoutingNode belowThresholdRoutingNode = RoutingNodesHelper.routingNode( belowThresholdDiscoveryNode2.getId(), belowThresholdDiscoveryNode2, shardRoutingOnNodeBelowUtilThreshold ); RoutingNode nearThresholdRoutingNode = RoutingNodesHelper.routingNode( nearThresholdDiscoveryNode3.getId(), nearThresholdDiscoveryNode3 ); RoutingNode belowQueuingThresholdRoutingNode = RoutingNodesHelper.routingNode( queuingBelowThresholdDiscoveryNode4.getId(), queuingBelowThresholdDiscoveryNode4, shardRoutingOnNodeBelowQueueThreshold ); RoutingNode aboveQueuingThresholdRoutingNode = RoutingNodesHelper.routingNode( queuingAboveThresholdDiscoveryNode5.getId(), queuingAboveThresholdDiscoveryNode5, shardRoutingOnNodeAboveQueueThreshold ); return new TestHarness( clusterState, routingAllocation, exceedingThresholdRoutingNode, belowThresholdRoutingNode, nearThresholdRoutingNode, belowQueuingThresholdRoutingNode, aboveQueuingThresholdRoutingNode, shardRoutingOnNodeExceedingUtilThreshold, shardRoutingOnNodeBelowUtilThreshold, shardRoutingNoWriteLoad, shardRoutingOnNodeBelowQueueThreshold, shardRoutingOnNodeAboveQueueThreshold, unassignedShardRouting ); } private WriteLoadConstraintDecider createWriteLoadConstraintDecider(Settings settings) { return new WriteLoadConstraintDecider(createBuiltInClusterSettings(settings)); } /** * Helper to create a {@link NodeUsageStatsForThreadPools} for the given node with the given WRITE thread pool usage stats. */ private NodeUsageStatsForThreadPools createNodeUsageStatsForThreadPools( DiscoveryNode discoveryNode, int totalWriteThreadPoolThreads, float averageWriteThreadPoolUtilization, long averageWriteThreadPoolQueueLatencyMillis ) { // Create thread pool usage stats map for node1. var writeThreadPoolUsageStats = new ThreadPoolUsageStats( totalWriteThreadPoolThreads, averageWriteThreadPoolUtilization, averageWriteThreadPoolQueueLatencyMillis ); var threadPoolUsageMap = new HashMap<String, ThreadPoolUsageStats>(); threadPoolUsageMap.put(ThreadPool.Names.WRITE, writeThreadPoolUsageStats); // Create the node's thread pool usage map return new NodeUsageStatsForThreadPools(discoveryNode.getId(), threadPoolUsageMap); } }
WriteLoadConstraintDeciderTests
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/string_/StringAssert_asByte_Test.java
{ "start": 1464, "end": 3076 }
class ____ extends StringAssertBaseTest { @Override protected StringAssert invoke_api_method() { // Verify disabled as the asByte cast throws an AssertionError when the assertion's string is not a valid byte. // Tested below. return null; } @Override protected void verify_internal_effects() { // Verify disabled as the asByte cast have no internal effect. } @Override public void should_return_this() { // Test disabled as the assertion does not return this. } @ParameterizedTest @CsvSource({ "127, 127", "-128, -128", "0, 0" }) void should_parse_string_as_byte_for_valid_input(String string, byte expectedByte) { assertThat(string).asByte().isEqualTo(expectedByte); } @ParameterizedTest @NullSource @ValueSource(strings = { "1024", "1L", "foo" }) void should_throw_AssertionError_for_null_or_invalid_string(String string) { // WHEN var assertionError = expectAssertionError(() -> assertThat(string).asByte()); // WHEN/ then(assertionError).hasMessage(shouldBeNumeric(string, NumericType.BYTE).create()); } @Test void should_work_with_soft_assertions() { // GIVEN SoftAssertions softAssertions = new SoftAssertions(); // WHEN softAssertions.assertThat("127").asByte() .isEqualTo(124) .isEqualTo(125); // THEN List<Throwable> errorsCollected = softAssertions.errorsCollected(); then(errorsCollected).hasSize(2); then(errorsCollected.get(0)).hasMessageContaining("124"); then(errorsCollected.get(1)).hasMessageContaining("125"); } }
StringAssert_asByte_Test
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/NodeManagerTestBase.java
{ "start": 2679, "end": 4608 }
class ____ { // temp fix until metrics system can auto-detect itself running in unit test: static { DefaultMetricsSystem.setMiniClusterMode(true); } protected static final Logger LOG = LoggerFactory.getLogger(TestNodeStatusUpdater.class); protected static final File basedir = new File("target", TestNodeStatusUpdater.class.getName()); protected static final File nmLocalDir = new File(basedir, "nm0"); protected static final File tmpDir = new File(basedir, "tmpDir"); protected static final File remoteLogsDir = new File(basedir, "remotelogs"); protected static final File logsDir = new File(basedir, "logs"); protected static final RecordFactory recordFactory = RecordFactoryProvider .getRecordFactory(null); protected Configuration conf; protected YarnConfiguration createNMConfig() throws IOException { return createNMConfig(ServerSocketUtil.getPort(49170, 10)); } protected YarnConfiguration createNMConfig(int port) throws IOException { YarnConfiguration conf = new YarnConfiguration(); String localhostAddress = null; try { localhostAddress = InetAddress.getByName("localhost") .getCanonicalHostName(); } catch (UnknownHostException e) { fail("Unable to get localhost address: " + e.getMessage()); } conf.setInt(YarnConfiguration.NM_PMEM_MB, 5 * 1024); // 5GB conf.set(YarnConfiguration.NM_ADDRESS, localhostAddress + ":" + port); conf.set(YarnConfiguration.NM_LOCALIZER_ADDRESS, localhostAddress + ":" + ServerSocketUtil.getPort(49160, 10)); conf.set(YarnConfiguration.NM_LOG_DIRS, logsDir.getAbsolutePath()); conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, remoteLogsDir.getAbsolutePath()); conf.set(YarnConfiguration.NM_LOCAL_DIRS, nmLocalDir.getAbsolutePath()); conf.setLong(YarnConfiguration.NM_LOG_RETAIN_SECONDS, 1); return conf; } public static
NodeManagerTestBase
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/resource/jdbc/ResourceRegistry.java
{ "start": 341, "end": 1983 }
interface ____ { /** * Does this registry currently have any registered resources? * * @return True if the registry does have registered resources; false otherwise. */ boolean hasRegisteredResources(); void releaseResources(); /** * Register a JDBC statement. * * @param statement The statement to register. * @param cancelable Is the statement being registered capable of being cancelled? In other words, * should we register it to be the target of subsequent {@link #cancelLastQuery()} calls? */ void register(Statement statement, boolean cancelable); /** * Release a previously registered statement. * * @param statement The statement to release. */ void release(Statement statement); /** * Register a JDBC result set. * <p> * Implementation note: Second parameter has been introduced to prevent * multiple registrations of the same statement in case {@link ResultSet#getStatement()} * does not return original {@link Statement} object. * * @param resultSet The result set to register. * @param statement Statement from which {@link ResultSet} has been generated. */ void register(ResultSet resultSet, Statement statement); /** * Release a previously registered result set. * * @param resultSet The result set to release. * @param statement Statement from which {@link ResultSet} has been generated. */ void release(ResultSet resultSet, Statement statement); void register(Blob blob); void release(Blob blob); void register(Clob clob); void release(Clob clob); void register(NClob nclob); void release(NClob nclob); void cancelLastQuery(); }
ResourceRegistry
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/spatial/SpatialExtentGroupingStateWrappedLongitudeState.java
{ "start": 6442, "end": 9498 }
class ____ i = values.getFirstValueIndex(p); int top = values.getInt(i++); int bottom = values.getInt(i++); int negLeft = values.getInt(i++); int negRight = values.getInt(i++); int posLeft = values.getInt(i++); int posRight = values.getInt(i); add(groupId, top, bottom, negLeft, negRight, posLeft, posRight); } public void add(int groupId, int top, int bottom, int negLeft, int negRight, int posLeft, int posRight) { ensureCapacity(groupId); if (hasValue(groupId)) { tops.set(groupId, Math.max(tops.get(groupId), top)); bottoms.set(groupId, Math.min(bottoms.get(groupId), bottom)); negLefts.set(groupId, Math.min(negLefts.get(groupId), negLeft)); negRights.set(groupId, SpatialAggregationUtils.maxNeg(negRights.get(groupId), negRight)); posLefts.set(groupId, SpatialAggregationUtils.minPos(posLefts.get(groupId), posLeft)); posRights.set(groupId, Math.max(posRights.get(groupId), posRight)); } else { tops.set(groupId, top); bottoms.set(groupId, bottom); negLefts.set(groupId, negLeft); negRights.set(groupId, negRight); posLefts.set(groupId, posLeft); posRights.set(groupId, posRight); } trackGroupId(groupId); } private void ensureCapacity(int groupId) { long requiredSize = groupId + 1; if (negLefts.size() < requiredSize) { tops = bigArrays.grow(tops, requiredSize); bottoms = bigArrays.grow(bottoms, requiredSize); negLefts = bigArrays.grow(negLefts, requiredSize); negRights = bigArrays.grow(negRights, requiredSize); posLefts = bigArrays.grow(posLefts, requiredSize); posRights = bigArrays.grow(posRights, requiredSize); } } public Block toBlock(IntVector selected, DriverContext driverContext) { try (var builder = driverContext.blockFactory().newBytesRefBlockBuilder(selected.getPositionCount())) { for (int i = 0; i < selected.getPositionCount(); i++) { int si = selected.getInt(i); if (hasValue(si)) { builder.appendBytesRef( new BytesRef( WellKnownBinary.toWKB( asRectangle( tops.get(si), bottoms.get(si), negLefts.get(si), negRights.get(si), posLefts.get(si), posRights.get(si) ), ByteOrder.LITTLE_ENDIAN ) ) ); } else { builder.appendNull(); } } return builder.build(); } } }
int
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/InternalClusterInfoServiceSchedulingTests.java
{ "start": 11756, "end": 13312 }
class ____ implements EstimatedHeapUsageCollector { @Override public void collectClusterHeapUsage(ActionListener<Map<String, Long>> listener) { listener.onResponse(Map.of()); } } private static void runFor(DeterministicTaskQueue deterministicTaskQueue, long duration) { final long endTime = deterministicTaskQueue.getCurrentTimeMillis() + duration; while (deterministicTaskQueue.getCurrentTimeMillis() < endTime && (deterministicTaskQueue.hasRunnableTasks() || deterministicTaskQueue.hasDeferredTasks())) { if (deterministicTaskQueue.hasDeferredTasks() && randomBoolean()) { deterministicTaskQueue.advanceTime(); } else if (deterministicTaskQueue.hasRunnableTasks()) { deterministicTaskQueue.runRandomTask(); } } } private static void runUntilFlag(DeterministicTaskQueue deterministicTaskQueue, AtomicBoolean flag) { while (flag.get() == false) { if (deterministicTaskQueue.hasDeferredTasks() && randomBoolean()) { deterministicTaskQueue.advanceTime(); } else if (deterministicTaskQueue.hasRunnableTasks()) { deterministicTaskQueue.runRandomTask(); } } } private static ActionListener<Void> setFlagOnSuccess(AtomicBoolean flag) { return ActionTestUtils.assertNoFailureListener(ignored -> assertTrue(flag.compareAndSet(false, true))); } private static
StubEstimatedEstimatedHeapUsageCollector
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/Aws2TranslateComponentBuilderFactory.java
{ "start": 1400, "end": 1931 }
interface ____ { /** * AWS Translate (camel-aws2-translate) * Translate texts using AWS Translate and AWS SDK version 2.x. * * Category: cloud,management * Since: 3.1 * Maven coordinates: org.apache.camel:camel-aws2-translate * * @return the dsl builder */ static Aws2TranslateComponentBuilder aws2Translate() { return new Aws2TranslateComponentBuilderImpl(); } /** * Builder for the AWS Translate component. */
Aws2TranslateComponentBuilderFactory
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext1/SimpleExt.java
{ "start": 1050, "end": 1304 }
interface ____ { // @Adaptive example, do not specify a explicit key. @Adaptive String echo(URL url, String s); @Adaptive({"key1", "key2"}) String yell(URL url, String s); // no @Adaptive String bang(URL url, int i); }
SimpleExt
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/concurrent/CallableBackgroundInitializer.java
{ "start": 1429, "end": 1572 }
interface ____ a standard mechanism * of the JDK to define tasks to be executed by another thread. The {@code * CallableBackgroundInitializer}
is
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/http/impl/websocket/ServerWebSocketImpl.java
{ "start": 713, "end": 1982 }
class ____ extends WebSocketImplBase<ServerWebSocketImpl> implements ServerWebSocket { private final String scheme; private final HostAndPort authority; private final String uri; private final String path; private final String query; ServerWebSocketImpl(ContextInternal context, WebSocketConnectionImpl conn, boolean supportsContinuation, Http1xServerRequest request, int maxWebSocketFrameSize, int maxWebSocketMessageSize, boolean registerWebSocketWriteHandlers) { super(context, conn, request.headers(), supportsContinuation, maxWebSocketFrameSize, maxWebSocketMessageSize, registerWebSocketWriteHandlers); this.scheme = request.scheme(); this.authority = request.authority(); this.uri = request.uri(); this.path = request.path(); this.query = request.query(); } @Override public String scheme() { return scheme; } @Override public HostAndPort authority() { return authority; } @Override public String uri() { return uri; } @Override public String path() { return path; } @Override public String query() { return query; } }
ServerWebSocketImpl
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/criteria/JpaExpression.java
{ "start": 369, "end": 1321 }
interface ____<T> extends JpaSelection<T>, Expression<T> { JpaExpression<Long> asLong(); JpaExpression<Integer> asInteger(); JpaExpression<Float> asFloat(); JpaExpression<Double> asDouble(); JpaExpression<BigDecimal> asBigDecimal(); JpaExpression<BigInteger> asBigInteger(); JpaExpression<String> asString(); @Override <X> JpaExpression<X> as(Class<X> type); @Override JpaPredicate isNull(); @Override JpaPredicate isNotNull(); @Override JpaPredicate in(Object... values); @Override JpaPredicate in(Expression<?>... values); @Override JpaPredicate in(Collection<?> values); @Override JpaPredicate in(Expression<Collection<?>> values); @Override JpaPredicate equalTo(Expression<?> value); @Override JpaPredicate equalTo(Object value); @Override <X> JpaExpression<X> cast(Class<X> type); @Override JpaPredicate notEqualTo(Expression<?> value); @Override JpaPredicate notEqualTo(Object value); }
JpaExpression
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2ClientConfigurer.java
{ "start": 4143, "end": 7139 }
class ____<B extends HttpSecurityBuilder<B>> extends AbstractHttpConfigurer<OAuth2ClientConfigurer<B>, B> { private AuthorizationCodeGrantConfigurer authorizationCodeGrantConfigurer = new AuthorizationCodeGrantConfigurer(); private ClientRegistrationRepository clientRegistrationRepository; private OAuth2AuthorizedClientRepository authorizedClientRepository; /** * Sets the repository of client registrations. * @param clientRegistrationRepository the repository of client registrations * @return the {@link OAuth2ClientConfigurer} for further configuration */ public OAuth2ClientConfigurer<B> clientRegistrationRepository( ClientRegistrationRepository clientRegistrationRepository) { Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null"); this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository); this.clientRegistrationRepository = clientRegistrationRepository; return this; } /** * Sets the repository for authorized client(s). * @param authorizedClientRepository the authorized client repository * @return the {@link OAuth2ClientConfigurer} for further configuration */ public OAuth2ClientConfigurer<B> authorizedClientRepository( OAuth2AuthorizedClientRepository authorizedClientRepository) { Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null"); this.getBuilder().setSharedObject(OAuth2AuthorizedClientRepository.class, authorizedClientRepository); this.authorizedClientRepository = authorizedClientRepository; return this; } /** * Sets the service for authorized client(s). * @param authorizedClientService the authorized client service * @return the {@link OAuth2ClientConfigurer} for further configuration */ public OAuth2ClientConfigurer<B> authorizedClientService(OAuth2AuthorizedClientService authorizedClientService) { Assert.notNull(authorizedClientService, "authorizedClientService cannot be null"); this.authorizedClientRepository( new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService)); return this; } /** * Configures the OAuth 2.0 Authorization Code Grant. * @param authorizationCodeGrantCustomizer the {@link Customizer} to provide more * options for the {@link AuthorizationCodeGrantConfigurer} * @return the {@link OAuth2ClientConfigurer} for further customizations */ public OAuth2ClientConfigurer<B> authorizationCodeGrant( Customizer<AuthorizationCodeGrantConfigurer> authorizationCodeGrantCustomizer) { authorizationCodeGrantCustomizer.customize(this.authorizationCodeGrantConfigurer); return this; } @Override public void init(B builder) { this.authorizationCodeGrantConfigurer.init(builder); } @Override public void configure(B builder) { this.authorizationCodeGrantConfigurer.configure(builder); } /** * Configuration options for the OAuth 2.0 Authorization Code Grant. */ public final
OAuth2ClientConfigurer
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/lib/chain/TestMapReduceChain.java
{ "start": 6609, "end": 7506 }
class ____ extends Mapper<LongWritable, Text, LongWritable, Text> { private String name; private String prop; public IDMap(String name, String prop) { this.name = name; this.prop = prop; } public void setup(Context context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); assertEquals(prop, conf.get("a")); writeFlag(conf, "map.setup." + name); } public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { writeFlag(context.getConfiguration(), "map." + name + ".value." + value); context.write(key, new Text(value + name)); } public void cleanup(Context context) throws IOException, InterruptedException { writeFlag(context.getConfiguration(), "map.cleanup." + name); } } public static
IDMap
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/alterTable/MySqlAlterTableAddIndex_9.java
{ "start": 1053, "end": 7105 }
class ____ extends TestCase { public void test_0() throws Exception { String sql = "ALTER TABLE t_order ADD FULLTEXT INDEX `g_i_buyer` (`buyer_id`);"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); assertEquals("ALTER TABLE t_order\n" + "\tADD FULLTEXT INDEX `g_i_buyer` (`buyer_id`);", SQLUtils.toMySqlString(stmt)); assertEquals("alter table t_order\n" + "\tadd fulltext index `g_i_buyer` (`buyer_id`);", SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); SchemaStatVisitor visitor = new SQLUtils().createSchemaStatVisitor(JdbcConstants.MYSQL); stmt.accept(visitor); TableStat tableStat = visitor.getTableStat("t_order"); assertNotNull(tableStat); assertEquals(1, tableStat.getAlterCount()); assertEquals(1, tableStat.getCreateIndexCount()); } public void test_1() throws Exception { String sql = "ALTER TABLE t_order ADD CLUSTERED INDEX `g_i_buyer` (`buyer_id`);"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); assertEquals("ALTER TABLE t_order\n" + "\tADD CLUSTERED INDEX `g_i_buyer` (`buyer_id`);", SQLUtils.toMySqlString(stmt)); assertEquals("alter table t_order\n" + "\tadd clustered index `g_i_buyer` (`buyer_id`);", SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); SchemaStatVisitor visitor = new SQLUtils().createSchemaStatVisitor(JdbcConstants.MYSQL); stmt.accept(visitor); TableStat tableStat = visitor.getTableStat("t_order"); assertNotNull(tableStat); assertEquals(1, tableStat.getAlterCount()); assertEquals(1, tableStat.getCreateIndexCount()); } public void test_2() throws Exception { String sql = "ALTER TABLE t_order ADD CLUSTERED KEY `g_i_buyer` (`buyer_id`);"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); assertEquals("ALTER TABLE t_order\n" + "\tADD CLUSTERED KEY `g_i_buyer` (`buyer_id`);", SQLUtils.toMySqlString(stmt)); assertEquals("alter table t_order\n" + "\tadd clustered key `g_i_buyer` (`buyer_id`);", SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); SchemaStatVisitor visitor = new SQLUtils().createSchemaStatVisitor(JdbcConstants.MYSQL); stmt.accept(visitor); TableStat tableStat = visitor.getTableStat("t_order"); assertNotNull(tableStat); assertEquals(1, tableStat.getAlterCount()); assertEquals(1, tableStat.getCreateIndexCount()); } public void test_3() throws Exception { String sql = "alter table xxx add key `idx_001`(`col1`,`current_date`,`col2`)"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); assertEquals("ALTER TABLE xxx\n" + "\tADD KEY `idx_001` (`col1`, `current_date`, `col2`)", SQLUtils.toMySqlString(stmt)); assertEquals("alter table xxx\n" + "\tadd key `idx_001` (`col1`, `current_date`, `col2`)", SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); SchemaStatVisitor visitor = new SQLUtils().createSchemaStatVisitor(JdbcConstants.MYSQL); stmt.accept(visitor); TableStat tableStat = visitor.getTableStat("xxx"); assertNotNull(tableStat); assertEquals(1, tableStat.getAlterCount()); assertEquals(1, tableStat.getCreateIndexCount()); } public void test_4() throws Exception { String sql = "alter table xxx add key `idx_001`(`col1`,`current_time`,`col2`)"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); assertEquals("ALTER TABLE xxx\n" + "\tADD KEY `idx_001` (`col1`, `current_time`, `col2`)", SQLUtils.toMySqlString(stmt)); assertEquals("alter table xxx\n" + "\tadd key `idx_001` (`col1`, `current_time`, `col2`)", SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); SchemaStatVisitor visitor = new SQLUtils().createSchemaStatVisitor(JdbcConstants.MYSQL); stmt.accept(visitor); TableStat tableStat = visitor.getTableStat("xxx"); assertNotNull(tableStat); assertEquals(1, tableStat.getAlterCount()); assertEquals(1, tableStat.getCreateIndexCount()); } public void test_5() throws Exception { String sql = "alter table xxx add key `idx_001`(`current_timestamp`,`curdate`,`LOCALTIME`, `LOCALTIMESTAMP`)"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); assertEquals("ALTER TABLE xxx\n" + "\tADD KEY `idx_001` (`current_timestamp`, `curdate`, `LOCALTIME`, `LOCALTIMESTAMP`)", SQLUtils.toMySqlString(stmt)); assertEquals("alter table xxx\n" + "\tadd key `idx_001` (`current_timestamp`, `curdate`, `LOCALTIME`, `LOCALTIMESTAMP`)", SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); SchemaStatVisitor visitor = new SQLUtils().createSchemaStatVisitor(JdbcConstants.MYSQL); stmt.accept(visitor); TableStat tableStat = visitor.getTableStat("xxx"); assertNotNull(tableStat); assertEquals(1, tableStat.getAlterCount()); assertEquals(1, tableStat.getCreateIndexCount()); } }
MySqlAlterTableAddIndex_9
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/records/tofix/RecordUnwrapped5115Test.java
{ "start": 796, "end": 2468 }
class ____ { @JsonUnwrapped public FooPojo5115 a; public int c; } private final ObjectMapper MAPPER = newJsonMapper(); @Test void unwrappedPojoShouldRoundTrip() throws Exception { BarPojo5115 input = new BarPojo5115(); input.a = new FooPojo5115(); input.c = 4; input.a.a = 1; input.a.b = 2; String json = MAPPER.writeValueAsString(input); BarPojo5115 output = MAPPER.readValue(json, BarPojo5115.class); assertEquals(4, output.c); assertEquals(1, output.a.a); assertEquals(2, output.a.b); } @Test void unwrappedRecordShouldRoundTripPass() throws Exception { BarRecordPass5115 input = new BarRecordPass5115(new FooRecord5115(1, 2), 3); // Serialize String json = MAPPER.writeValueAsString(input); // Deserialize (currently fails) BarRecordPass5115 output = MAPPER.readValue(json, BarRecordPass5115.class); // Should match after bug is fixed assertEquals(input, output); } @JacksonTestFailureExpected @Test void unwrappedRecordShouldRoundTrip() throws Exception { BarRecordFail5115 input = new BarRecordFail5115(new FooRecord5115(1, 2), 3); // Serialize String json = MAPPER.writeValueAsString(input); // Once the bug is fixed, this assertion will pass and the // @JacksonTestFailureExpected annotation can be removed. BarRecordFail5115 output = MAPPER.readValue(json, BarRecordFail5115.class); // Should match after bug is fixed assertEquals(input, output); } }
BarPojo5115
java
google__guava
android/guava-tests/test/com/google/common/collect/TableCollectionTest.java
{ "start": 29972, "end": 30590 }
class ____ extends MapInterfaceTest<String, Integer> { MapTests( boolean allowsNullValues, boolean supportsPut, boolean supportsRemove, boolean supportsClear, boolean supportsIteratorRemove) { super( false, allowsNullValues, supportsPut, supportsRemove, supportsClear, supportsIteratorRemove); } @Override protected String getKeyNotInPopulatedMap() { return "four"; } @Override protected Integer getValueNotInPopulatedMap() { return 4; } } abstract static
MapTests
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/protocolPB/RouterGetUserMappingsProtocolServerSideTranslatorPB.java
{ "start": 1485, "end": 2469 }
class ____ extends GetUserMappingsProtocolServerSideTranslatorPB { private final RouterRpcServer server; private final boolean isAsyncRpc; public RouterGetUserMappingsProtocolServerSideTranslatorPB(GetUserMappingsProtocol impl) { super(impl); this.server = (RouterRpcServer) impl; this.isAsyncRpc = server.isAsync(); } @Override public GetGroupsForUserResponseProto getGroupsForUser( RpcController controller, GetGroupsForUserRequestProto request) throws ServiceException { if (!isAsyncRpc) { return super.getGroupsForUser(controller, request); } asyncRouterServer(() -> server.getGroupsForUser(request.getUser()), groups -> { GetGroupsForUserResponseProto.Builder builder = GetGroupsForUserResponseProto .newBuilder(); for (String g : groups) { builder.addGroups(g); } return builder.build(); }); return null; } }
RouterGetUserMappingsProtocolServerSideTranslatorPB
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/state/v2/StateSerializerReference.java
{ "start": 2961, "end": 5104 }
class ____ describe the type. " + "For example, to describe 'Tuple2<String, String>' as a generic type, use " + "'new PravegaDeserializationSchema<>(new TypeHint<Tuple2<String, String>>(){}, serializer);'", e); } } public TypeInformation<T> getTypeInformation() { return typeInfo; } /** * Checks whether the serializer has been initialized. Serializer initialization is lazy, to * allow parametrization of serializers with an {@link ExecutionConfig} via {@link * #initializeUnlessSet(ExecutionConfig)}. * * @return True if the serializers have been initialized, false otherwise. */ public boolean isInitialized() { return get() != null; } /** * Initializes the serializer, unless it has been initialized before. * * @param executionConfig The execution config to use when creating the serializer. */ public void initializeUnlessSet(ExecutionConfig executionConfig) { initializeUnlessSet( new SerializerFactory() { @Override public <T> TypeSerializer<T> createSerializer( TypeInformation<T> typeInformation) { return typeInformation.createSerializer( executionConfig == null ? null : executionConfig.getSerializerConfig()); } }); } @Internal public void initializeUnlessSet(SerializerFactory serializerFactory) { if (get() == null) { checkState(typeInfo != null, "type information should not be null."); // try to instantiate and set the serializer TypeSerializer<T> serializer = serializerFactory.createSerializer(typeInfo); // use cas to assure the singleton if (!compareAndSet(null, serializer)) { LOG.debug("Someone else beat us at initializing the serializer."); } } } }
to
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/inject/utils/NativeElementsHelper.java
{ "start": 1471, "end": 1877 }
class ____ to cleanup */ public void cleanupForClass(Object nativeClassType) { processedClasses.remove(nativeClassType); overridesCache.entrySet().removeIf(e -> e.getKey().classKey.equals(nativeClassType)); } /** * Check if one method overrides another. * * @param m1 The override method * @param m2 The overridden method * @param owner The
type
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/collection/bag/Item.java
{ "start": 180, "end": 560 }
class ____ { private Long id; private String name; private Order order; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } }
Item
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/operators/GenericDataSinkBaseTest.java
{ "start": 1903, "end": 5236 }
class ____ implements java.io.Serializable { private static final TestNonRichInputFormat in = new TestNonRichInputFormat(); final GenericDataSourceBase<String, TestNonRichInputFormat> source = new GenericDataSourceBase<>( in, new OperatorInformation<>(BasicTypeInfo.STRING_TYPE_INFO), "testSource"); @Test void testDataSourcePlain() throws Exception { TestNonRichOutputFormat out = new TestNonRichOutputFormat(); GenericDataSinkBase<String> sink = new GenericDataSinkBase<>( out, new UnaryOperatorInformation<>( BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.getInfoFor(Nothing.class)), "test_sink"); sink.setInput(source); ExecutionConfig executionConfig = new ExecutionConfig(); executionConfig.disableObjectReuse(); in.reset(); sink.executeOnCollections(asList(TestIOData.NAMES), null, executionConfig); assertThat(asList(TestIOData.NAMES)).isEqualTo(out.output); executionConfig.enableObjectReuse(); out.clear(); in.reset(); sink.executeOnCollections(asList(TestIOData.NAMES), null, executionConfig); assertThat(asList(TestIOData.NAMES)).isEqualTo(out.output); } @Test void testDataSourceWithRuntimeContext() throws Exception { TestRichOutputFormat out = new TestRichOutputFormat(); GenericDataSinkBase<String> sink = new GenericDataSinkBase<>( out, new UnaryOperatorInformation<>( BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.getInfoFor(Nothing.class)), "test_sink"); sink.setInput(source); ExecutionConfig executionConfig = new ExecutionConfig(); final HashMap<String, Accumulator<?, ?>> accumulatorMap = new HashMap<>(); final HashMap<String, Future<Path>> cpTasks = new HashMap<>(); final TaskInfo taskInfo = new TaskInfoImpl("test_sink", 1, 0, 1, 0); executionConfig.disableObjectReuse(); in.reset(); sink.executeOnCollections( asList(TestIOData.NAMES), new RuntimeUDFContext( taskInfo, null, executionConfig, cpTasks, accumulatorMap, UnregisteredMetricsGroup.createOperatorMetricGroup()), executionConfig); assertThat(asList(TestIOData.RICH_NAMES)).isEqualTo(out.output); executionConfig.enableObjectReuse(); out.clear(); in.reset(); sink.executeOnCollections( asList(TestIOData.NAMES), new RuntimeUDFContext( taskInfo, null, executionConfig, cpTasks, accumulatorMap, UnregisteredMetricsGroup.createOperatorMetricGroup()), executionConfig); assertThat(asList(TestIOData.RICH_NAMES)).isEqualTo(out.output); } }
GenericDataSinkBaseTest
java
apache__hadoop
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/datatypes/QueueName.java
{ "start": 901, "end": 1224 }
class ____ extends DefaultAnonymizableDataType { private final String queueName; public QueueName(String queueName) { super(); this.queueName = queueName; } @Override public String getValue() { return queueName; } @Override protected String getPrefix() { return "queue"; }; }
QueueName
java
apache__dubbo
dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouter.java
{ "start": 977, "end": 1176 }
class ____<T> extends ListenableStateRouter<T> { public static final String NAME = "APP_ROUTER"; public AppStateRouter(URL url) { super(url, url.getApplication()); } }
AppStateRouter
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/config/JpaAuditingRegistrar.java
{ "start": 2149, "end": 5245 }
class ____ extends AuditingBeanDefinitionRegistrarSupport { private static final String BEAN_CONFIGURER_ASPECT_CLASS_NAME = "org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect"; @Override protected Class<? extends Annotation> getAnnotation() { return EnableJpaAuditing.class; } @Override protected String getAuditingHandlerBeanName() { return "jpaAuditingHandler"; } @Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null"); Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); registerBeanConfigurerAspectIfNecessary(registry); super.registerBeanDefinitions(annotationMetadata, registry); registerInfrastructureBeanWithId( BeanDefinitionBuilder.rootBeanDefinition(AuditingBeanFactoryPostProcessor.class).getRawBeanDefinition(), AuditingBeanFactoryPostProcessor.class.getName(), registry); } @Override protected void registerAuditListenerBeanDefinition(BeanDefinition auditingHandlerDefinition, BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(JPA_MAPPING_CONTEXT_BEAN_NAME)) { registry.registerBeanDefinition(JPA_MAPPING_CONTEXT_BEAN_NAME, // new RootBeanDefinition(JpaMetamodelMappingContextFactoryBean.class)); } BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(AuditingEntityListener.class); builder.addPropertyValue("auditingHandler", ParsingUtils.getObjectFactoryBeanDefinition(getAuditingHandlerBeanName(), null)); registerInfrastructureBeanWithId(builder.getRawBeanDefinition(), AuditingEntityListener.class.getName(), registry); } @Override protected void postProcess(BeanDefinitionBuilder builder, AuditingConfiguration configuration, BeanDefinitionRegistry registry) { builder.setFactoryMethod("from").addConstructorArgReference(JPA_MAPPING_CONTEXT_BEAN_NAME); } /** * @param registry, the {@link BeanDefinitionRegistry} to be used to register the * {@link AnnotationBeanConfigurerAspect}. */ private void registerBeanConfigurerAspectIfNecessary(BeanDefinitionRegistry registry) { if (registry.containsBeanDefinition(BEAN_CONFIGURER_ASPECT_BEAN_NAME)) { return; } if (!ClassUtils.isPresent(BEAN_CONFIGURER_ASPECT_CLASS_NAME, getClass().getClassLoader())) { throw new BeanDefinitionStoreException(BEAN_CONFIGURER_ASPECT_CLASS_NAME + " not found; \n" + "Could not configure Spring Data JPA auditing-feature because" + " spring-aspects.jar is not on the classpath;\n" + "If you want to use auditing please add spring-aspects.jar to the classpath"); } RootBeanDefinition def = new RootBeanDefinition(); def.setBeanClassName(BEAN_CONFIGURER_ASPECT_CLASS_NAME); def.setFactoryMethodName("aspectOf"); def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN_CONFIGURER_ASPECT_BEAN_NAME, new BeanComponentDefinition(def, BEAN_CONFIGURER_ASPECT_BEAN_NAME).getBeanDefinition()); } }
JpaAuditingRegistrar
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/byte_/ByteAssert_isNotNegative_Test.java
{ "start": 888, "end": 1201 }
class ____ extends ByteAssertBaseTest { @Override protected ByteAssert invoke_api_method() { return assertions.isNotNegative(); } @Override protected void verify_internal_effects() { verify(bytes).assertIsNotNegative(getInfo(assertions), getActual(assertions)); } }
ByteAssert_isNotNegative_Test
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/ast/tree/expression/FunctionExpression.java
{ "start": 313, "end": 438 }
interface ____ extends Expression { String getFunctionName(); List<? extends SqlAstNode> getArguments(); }
FunctionExpression
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/doc/RestTestsFromDocSnippetTask.java
{ "start": 5401, "end": 23832 }
class ____ { /** * These languages aren't supported by the syntax highlighter so we * shouldn't use them. */ private static final List BAD_LANGUAGES = List.of("json", "javascript"); String method = "(?<method>GET|PUT|POST|HEAD|OPTIONS|DELETE)"; String pathAndQuery = "(?<pathAndQuery>[^\\n]+)"; String badBody = "GET|PUT|POST|HEAD|OPTIONS|DELETE|startyaml|#"; String body = "(?<body>(?:\\n(?!" + badBody + ")[^\\n]+)+)"; String rawRequest = "(?:" + method + "\\s+" + pathAndQuery + body + "?)"; String yamlRequest = "(?:startyaml(?s)(?<yaml>.+?)(?-s)endyaml)"; String nonComment = "(?:" + rawRequest + "|" + yamlRequest + ")"; String comment = "(?<comment>#.+)"; String SYNTAX = "(?:" + comment + "|" + nonComment + ")\\n+"; /** * Files containing all snippets that *probably* should be converted * to `// CONSOLE` but have yet to be converted. All files are paths * relative to the docs dir. */ private Set<String> unconvertedCandidates = new HashSet<>(); /** * The last non-TESTRESPONSE snippet. */ Snippet previousTest; /** * The file in which we saw the last snippet that made a test. */ Path lastDocsPath; /** * The file we're building. */ PrintWriter current; Set<String> names = new HashSet<>(); /** * Called each time a snippet is encountered. Tracks the snippets and * calls buildTest to actually build the test. */ public void handleSnippet(Snippet snippet) { if (snippet.isConsoleCandidate()) { unconvertedCandidates.add(snippet.path().toString().replace('\\', '/')); } if (BAD_LANGUAGES.contains(snippet.language())) { throw new InvalidUserDataException(snippet + ": Use `js` instead of `" + snippet.language() + "`."); } if (snippet.testSetup()) { testSetup(snippet); previousTest = snippet; return; } if (snippet.testTearDown()) { testTearDown(snippet); previousTest = snippet; return; } if (snippet.testResponse() || snippet.language().equals("console-result")) { if (previousTest == null) { throw new InvalidUserDataException(snippet + ": No paired previous test"); } if (previousTest.path().equals(snippet.path()) == false) { throw new InvalidUserDataException(snippet + ": Result can't be first in file"); } response(snippet); return; } if (("js".equals(snippet.language())) && snippet.console() != null && snippet.console()) { throw new InvalidUserDataException(snippet + ": Use `[source,console]` instead of `// CONSOLE`."); } if (snippet.test() || snippet.language().equals("console")) { test(snippet); previousTest = snippet; } // Must be an unmarked snippet.... } private void test(Snippet test) { setupCurrent(test); if (test.continued()) { /* Catch some difficult to debug errors with // TEST[continued] * and throw a helpful error message. */ if (previousTest == null || previousTest.path().equals(test.path()) == false) { throw new InvalidUserDataException("// TEST[continued] " + "cannot be on first snippet in a file: " + test); } if (previousTest != null && previousTest.testSetup()) { throw new InvalidUserDataException("// TEST[continued] " + "cannot immediately follow // TESTSETUP: " + test); } if (previousTest != null && previousTest.testSetup()) { throw new InvalidUserDataException("// TEST[continued] " + "cannot immediately follow // TEARDOWN: " + test); } } else { current.println("---"); if (test.name() != null && test.name().isBlank() == false) { if (names.add(test.name()) == false) { throw new InvalidUserDataException("Duplicated snippet name '" + test.name() + "': " + test); } current.println("\"" + test.name() + "\":"); } else { current.println("\"line_" + test.start() + "\":"); } /* The Elasticsearch test runner doesn't support quite a few * constructs unless we output this skip. We don't know if * we're going to use these constructs, but we might so we * output the skip just in case. */ current.println(" - skip:"); current.println(" features:"); current.println(" - default_shards"); current.println(" - stash_in_key"); current.println(" - stash_in_path"); current.println(" - stash_path_replace"); current.println(" - warnings"); } if (test.skip() != null) { if (test.continued()) { throw new InvalidUserDataException("Continued snippets " + "can't be skipped"); } current.println(" - always_skip"); current.println(" reason: " + test.skip()); } if (test.setup() != null) { setup(test); } body(test, false); if (test.teardown() != null) { teardown(test); } } private void response(Snippet response) { if (null == response.skip()) { current.println(" - match:"); current.println(" $body:"); replaceBlockQuote(response.contents()).lines().forEach(line -> current.println(" " + line)); } } private void teardown(final Snippet snippet) { // insert a teardown defined outside of the docs for (final String name : snippet.teardown().split(",")) { final String teardown = getTeardowns().get().get(name); if (teardown == null) { throw new InvalidUserDataException("Couldn't find named teardown $name for " + snippet); } current.println("# Named teardown " + name); current.println(teardown); } } private void testTearDown(Snippet snippet) { if (previousTest != null && previousTest.testSetup() == false && lastDocsPath.equals(snippet.path())) { throw new InvalidUserDataException(snippet + " must follow test setup or be first"); } setupCurrent(snippet); current.println("---"); current.println("teardown:"); body(snippet, true); } void emitDo( String method, String pathAndQuery, String body, String catchPart, List<String> warnings, boolean inSetup, boolean skipShardFailures ) { String[] tokenized = pathAndQuery.split("\\?"); String path = tokenized[0]; String query = tokenized.length > 1 ? tokenized[1] : null; if (path == null) { path = ""; // Catch requests to the root... } else { path = path.replace("<", "%3C").replace(">", "%3E"); } current.println(" - do:"); if (catchPart != null) { current.println(" catch: " + catchPart); } if (false == warnings.isEmpty()) { current.println(" warnings:"); for (String warning : warnings) { // Escape " because we're going to quote the warning String escaped = warning.replaceAll("\"", "\\\\\""); /* Quote the warning in case it starts with [ which makes * it look too much like an array. */ current.println(" - \"" + escaped + "\""); } } current.println(" raw:"); current.println(" method: " + method); current.println(" path: \"" + path + "\""); if (query != null) { for (String param : query.split("&")) { String[] tokenizedQuery = param.split("="); String paramName = tokenizedQuery[0]; String paramValue = tokenizedQuery.length > 1 ? tokenizedQuery[1] : null; if (paramValue == null) { paramValue = ""; } current.println(" " + paramName + ": \"" + paramValue + "\""); } } if (body != null) { // Throw out the leading newline we get from parsing the body body = body.substring(1); // Replace """ quoted strings with valid json ones body = replaceBlockQuote(body); current.println(" body: |"); body.lines().forEach(line -> current.println(" " + line)); } /* Catch any shard failures. These only cause a non-200 response if * no shard succeeds. But we need to fail the tests on all of these * because they mean invalid syntax or broken queries or something * else that we don't want to teach people to do. The REST test * framework doesn't allow us to have assertions in the setup * section so we have to skip it there. We also omit the assertion * from APIs that don't return a JSON object */ if (false == inSetup && skipShardFailures == false && shouldAddShardFailureCheck(path)) { current.println(" - is_false: _shards.failures"); } } private void body(Snippet snippet, boolean inSetup) { ParsingUtils.parse(snippet.contents(), SYNTAX, (matcher, last) -> { if (matcher.group("comment") != null) { // Comment return; } String yamlRequest = matcher.group("yaml"); if (yamlRequest != null) { current.println(yamlRequest); return; } String method = matcher.group("method"); String pathAndQuery = matcher.group("pathAndQuery"); String body = matcher.group("body"); String catchPart = last ? snippet.catchPart() : null; if (pathAndQuery.startsWith("/")) { // Leading '/'s break the generated paths pathAndQuery = pathAndQuery.substring(1); } emitDo(method, pathAndQuery, body, catchPart, snippet.warnings(), inSetup, snippet.skipShardsFailures()); }); } private PrintWriter setupCurrent(Snippet test) { if (test.path().equals(lastDocsPath)) { return current; } names.clear(); finishLastTest(); lastDocsPath = test.path(); // Make the destination file: // Shift the path into the destination directory tree Path dest = getOutputRoot().toPath().resolve(test.path()); // Replace the extension String fileName = dest.getName(dest.getNameCount() - 1).toString(); if (hasMultipleDocImplementations(test.path())) { String fileNameWithoutExt = dest.getName(dest.getNameCount() - 1).toString().replace(".asciidoc", "").replace(".mdx", ""); if (getMigrationMode().get() == false) { throw new InvalidUserDataException( "Found multiple files with the same name '" + fileNameWithoutExt + "' but different extensions: [asciidoc, mdx]" ); } getLogger().warn("Found multiple doc file types for " + test.path() + ". Generating tests for all of them."); dest = dest.getParent().resolve(fileName + ".yml"); } else { dest = dest.getParent().resolve(fileName.replace(".asciidoc", ".yml").replace(".mdx", ".yml")); } // Now setup the writer try { Files.createDirectories(dest.getParent()); current = new PrintWriter(dest.toFile(), StandardCharsets.UTF_8); return current; } catch (IOException e) { throw new RuntimeException(e); } } private void testSetup(Snippet snippet) { if (lastDocsPath == snippet.path()) { throw new InvalidUserDataException( snippet + ": wasn't first. TESTSETUP can only be used in the first snippet of a document." ); } setupCurrent(snippet); current.println("---"); current.println("setup:"); if (snippet.setup() != null) { setup(snippet); } body(snippet, true); } private void setup(final Snippet snippet) { // insert a setup defined outside of the docs for (final String name : snippet.setup().split(",")) { final String setup = getSetups().get(name); if (setup == null) { throw new InvalidUserDataException("Couldn't find named setup " + name + " for " + snippet); } current.println("# Named setup " + name); current.println(setup); } } public void checkUnconverted() { List<String> listedButNotFound = new ArrayList<>(); for (String listed : getExpectedUnconvertedCandidates().get()) { if (false == unconvertedCandidates.remove(listed)) { listedButNotFound.add(listed); } } String message = ""; if (false == listedButNotFound.isEmpty()) { Collections.sort(listedButNotFound); listedButNotFound = listedButNotFound.stream().map(notfound -> " " + notfound).collect(Collectors.toList()); message += "Expected unconverted snippets but none found in:\n"; message += listedButNotFound.stream().collect(Collectors.joining("\n")); } if (false == unconvertedCandidates.isEmpty()) { List<String> foundButNotListed = new ArrayList<>(unconvertedCandidates); Collections.sort(foundButNotListed); foundButNotListed = foundButNotListed.stream().map(f -> " " + f).collect(Collectors.toList()); if (false == "".equals(message)) { message += "\n"; } message += "Unexpected unconverted snippets:\n"; message += foundButNotListed.stream().collect(Collectors.joining("\n")); } if (false == "".equals(message)) { throw new InvalidUserDataException(message); } } public void finishLastTest() { if (current != null) { current.close(); current = null; } } } private void assertEqualTestSnippetFromMigratedDocs() { getTestRoot().getAsFileTree().matching(patternSet -> { patternSet.include("**/*asciidoc.yml"); }).forEach(asciidocFile -> { File mdxFile = new File(asciidocFile.getAbsolutePath().replace(".asciidoc.yml", ".mdx.yml")); if (mdxFile.exists() == false) { throw new InvalidUserDataException("Couldn't find the corresponding mdx file for " + asciidocFile.getAbsolutePath()); } try { List<String> asciidocLines = Files.readAllLines(asciidocFile.toPath()); List<String> mdxLines = Files.readAllLines(mdxFile.toPath()); if (asciidocLines.size() != mdxLines.size()) { throw new GradleException( "Yaml rest specs (" + asciidocFile.toPath() + " and " + mdxFile.getAbsolutePath() + ") are not equal, different line count" ); } for (int i = 0; i < asciidocLines.size(); i++) { if (asciidocLines.get(i) .replaceAll("line_\\d+", "line_0") .equals(mdxLines.get(i).replaceAll("line_\\d+", "line_0")) == false) { throw new GradleException( "Yaml rest specs (" + asciidocFile.toPath() + " and " + mdxFile.getAbsolutePath() + ") are not equal, difference on line: " + (i + 1) ); } } } catch (IOException e) { throw new RuntimeException(e); } }); } private boolean hasMultipleDocImplementations(Path path) { File dir = getDocs().getDir(); String fileName = path.getName(path.getNameCount() - 1).toString(); if (fileName.endsWith("asciidoc")) { return new File(dir, path.toString().replace(".asciidoc", ".mdx")).exists(); } else if (fileName.endsWith("mdx")) { return new File(dir, path.toString().replace(".mdx", ".asciidoc")).exists(); } return false; } }
TestBuilder
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/transport/AbstractLinkedProjectConfigService.java
{ "start": 602, "end": 792 }
class ____ {@link LinkedProjectConfigService} implementations. * Provides common functionality for managing a list of registered listeners and notifying them of updates. */ public abstract
for
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/integration/MockitoBeanWithMultipleExistingBeansAndOnePrimaryIntegrationTests.java
{ "start": 2302, "end": 2840 }
class ____ { @MockitoBean StringExampleGenericService mock; @Autowired ExampleGenericServiceCaller caller; @Test void test() { assertIsMock(mock); assertMockName(mock, "two"); given(mock.greeting()).willReturn("mocked"); assertThat(caller.sayGreeting()).isEqualTo("I say mocked 123"); then(mock).should().greeting(); } @Configuration(proxyBeanMethods = false) @Import({ ExampleGenericServiceCaller.class, IntegerExampleGenericService.class }) static
MockitoBeanWithMultipleExistingBeansAndOnePrimaryIntegrationTests
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/ManagedEndpointInjectRefEndpointTest.java
{ "start": 1465, "end": 3586 }
class ____ extends SpringTestSupport { @Override protected boolean useJmx() { return true; } @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext( "org/apache/camel/spring/management/ManagedEndpointInjectRefEndpointTest.xml"); } protected MBeanServer getMBeanServer() { return context.getManagementStrategy().getManagementAgent().getMBeanServer(); } @Test public void testRef() throws Exception { // fire a message to get it running getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("foo").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); MBeanServer mbeanServer = getMBeanServer(); Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=producers,*"), null); assertEquals(2, set.size()); for (ObjectName on : set) { boolean registered = mbeanServer.isRegistered(on); assertEquals(true, registered, "Should be registered"); String uri = (String) mbeanServer.getAttribute(on, "EndpointUri"); assertTrue(uri.equals("mock://foo") || uri.equals("mock://result"), uri); // should be started String state = (String) mbeanServer.getAttribute(on, "State"); assertEquals(ServiceStatus.Started.name(), state, "Should be started"); } set = mbeanServer.queryNames(new ObjectName("*:type=endpoints,*"), null); assertEquals(4, set.size()); for (ObjectName on : set) { boolean registered = mbeanServer.isRegistered(on); assertEquals(true, registered, "Should be registered"); String uri = (String) mbeanServer.getAttribute(on, "EndpointUri"); assertTrue(uri.equals("direct://start") || uri.equals("mock://foo") || uri.equals("mock://result") || uri.equals("ref://foo"), uri); } } }
ManagedEndpointInjectRefEndpointTest
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/utils/Loggers.java
{ "start": 826, "end": 2577 }
class ____ { public static final Logger AUTH = LoggerFactory.getLogger("com.alibaba.nacos.core.auth"); public static final Logger CORE = LoggerFactory.getLogger("com.alibaba.nacos.core"); public static final Logger RAFT = LoggerFactory.getLogger("com.alibaba.nacos.core.protocol.raft"); public static final Logger DISTRO = LoggerFactory.getLogger("com.alibaba.nacos.core.protocol.distro"); public static final Logger CLUSTER = LoggerFactory.getLogger("com.alibaba.nacos.core.cluster"); public static final Logger REMOTE = LoggerFactory.getLogger("com.alibaba.nacos.core.remote"); public static final Logger REMOTE_PUSH = LoggerFactory.getLogger("com.alibaba.nacos.core.remote.push"); public static final Logger REMOTE_DIGEST = LoggerFactory.getLogger("com.alibaba.nacos.core.remote.digest"); public static void setLogLevel(String logName, String level) { switch (logName) { case "core-auth": ((ch.qos.logback.classic.Logger) AUTH).setLevel(Level.valueOf(level)); break; case "core": ((ch.qos.logback.classic.Logger) CORE).setLevel(Level.valueOf(level)); break; case "core-raft": ((ch.qos.logback.classic.Logger) RAFT).setLevel(Level.valueOf(level)); break; case "core-distro": ((ch.qos.logback.classic.Logger) DISTRO).setLevel(Level.valueOf(level)); break; case "core-cluster": ((ch.qos.logback.classic.Logger) CLUSTER).setLevel(Level.valueOf(level)); break; default: break; } } }
Loggers
java
square__retrofit
retrofit/src/main/java/retrofit2/http/PartMap.java
{ "start": 1734, "end": 1855 }
interface ____ { /** The {@code Content-Transfer-Encoding} of the parts. */ String encoding() default "binary"; }
PartMap
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java
{ "start": 45667, "end": 46070 }
class ____ { public void doTest() { long four = (1 + 1) * 2; } } """) .doTest(); } // b/365094947 // b/375421323 @Test public void inlinerReplacesParameterValueInPackageName() { refactoringTestHelper .addInputLines( "Bar.java", """ package foo; public
Caller
java
elastic__elasticsearch
modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ConvertProcessor.java
{ "start": 7412, "end": 8416 }
class ____ implements Processor.Factory { @Override public ConvertProcessor create( Map<String, Processor.Factory> registry, String processorTag, String description, Map<String, Object> config, ProjectId projectId ) throws Exception { String field = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "field"); String typeProperty = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "type"); String targetField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "target_field", field); Type convertType = Type.fromString(processorTag, "type", typeProperty); boolean ignoreMissing = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "ignore_missing", false); return new ConvertProcessor(processorTag, description, field, targetField, convertType, ignoreMissing); } } }
Factory
java
spring-projects__spring-boot
module/spring-boot-transaction/src/test/java/org/springframework/boot/transaction/autoconfigure/TransactionAutoConfigurationTests.java
{ "start": 2177, "end": 8053 }
class ____ { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(TransactionAutoConfiguration.class)); @Test void whenThereIsNoPlatformTransactionManagerNoTransactionTemplateIsAutoConfigured() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(TransactionTemplate.class)); } @Test void whenThereIsASinglePlatformTransactionManagerATransactionTemplateIsAutoConfigured() { this.contextRunner.withUserConfiguration(SinglePlatformTransactionManagerConfiguration.class).run((context) -> { PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class); TransactionTemplate transactionTemplate = context.getBean(TransactionTemplate.class); assertThat(transactionTemplate.getTransactionManager()).isSameAs(transactionManager); }); } @Test void whenThereIsASingleReactiveTransactionManagerATransactionalOperatorIsAutoConfigured() { this.contextRunner.withUserConfiguration(SingleReactiveTransactionManagerConfiguration.class).run((context) -> { ReactiveTransactionManager transactionManager = context.getBean(ReactiveTransactionManager.class); TransactionalOperator transactionalOperator = context.getBean(TransactionalOperator.class); assertThat(transactionalOperator).extracting("transactionManager").isSameAs(transactionManager); }); } @Test void whenThereAreBothReactiveAndPlatformTransactionManagersATemplateAndAnOperatorAreAutoConfigured() { this.contextRunner .withUserConfiguration(SinglePlatformTransactionManagerConfiguration.class, SingleReactiveTransactionManagerConfiguration.class) .withPropertyValues("spring.datasource.url:jdbc:h2:mem:" + UUID.randomUUID()) .run((context) -> { PlatformTransactionManager platformTransactionManager = context .getBean(PlatformTransactionManager.class); TransactionTemplate transactionTemplate = context.getBean(TransactionTemplate.class); assertThat(transactionTemplate.getTransactionManager()).isSameAs(platformTransactionManager); ReactiveTransactionManager reactiveTransactionManager = context .getBean(ReactiveTransactionManager.class); TransactionalOperator transactionalOperator = context.getBean(TransactionalOperator.class); assertThat(transactionalOperator).extracting("transactionManager").isSameAs(reactiveTransactionManager); }); } @Test void whenThereAreSeveralPlatformTransactionManagersNoTransactionTemplateIsAutoConfigured() { this.contextRunner.withUserConfiguration(SeveralPlatformTransactionManagersConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(TransactionTemplate.class)); } @Test void whenThereAreSeveralReactiveTransactionManagersNoTransactionOperatorIsAutoConfigured() { this.contextRunner.withUserConfiguration(SeveralReactiveTransactionManagersConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(TransactionalOperator.class)); } @Test void whenAUserProvidesATransactionTemplateTheAutoConfiguredTemplateBacksOff() { this.contextRunner.withUserConfiguration(CustomPlatformTransactionManagerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(TransactionTemplate.class); assertThat(context.getBean("transactionTemplateFoo")).isInstanceOf(TransactionTemplate.class); }); } @Test void whenAUserProvidesATransactionalOperatorTheAutoConfiguredOperatorBacksOff() { this.contextRunner .withUserConfiguration(SingleReactiveTransactionManagerConfiguration.class, CustomTransactionalOperatorConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(TransactionalOperator.class); assertThat(context.getBean("customTransactionalOperator")).isInstanceOf(TransactionalOperator.class); }); } @Test void transactionNotManagedWithNoTransactionManager() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) .run((context) -> assertThat(context.getBean(TransactionalService.class).isTransactionActive()).isFalse()); } @Test void transactionManagerUsesCglibByDefault() { this.contextRunner.withUserConfiguration(PlatformTransactionManagersConfiguration.class).run((context) -> { assertThat(context.getBean(AnotherServiceImpl.class).isTransactionActive()).isTrue(); assertThat(context.getBeansOfType(TransactionalServiceImpl.class)).hasSize(1); }); } @Test void transactionManagerCanBeConfiguredToJdkProxy() { this.contextRunner.withUserConfiguration(PlatformTransactionManagersConfiguration.class) .withPropertyValues("spring.aop.proxy-target-class=false") .run((context) -> { assertThat(context.getBean(AnotherService.class).isTransactionActive()).isTrue(); assertThat(context).doesNotHaveBean(AnotherServiceImpl.class); assertThat(context).doesNotHaveBean(TransactionalServiceImpl.class); }); } @Test void customEnableTransactionManagementTakesPrecedence() { this.contextRunner .withUserConfiguration(CustomTransactionManagementConfiguration.class, PlatformTransactionManagersConfiguration.class) .withPropertyValues("spring.aop.proxy-target-class=true") .run((context) -> { assertThat(context.getBean(AnotherService.class).isTransactionActive()).isTrue(); assertThat(context).doesNotHaveBean(AnotherServiceImpl.class); assertThat(context).doesNotHaveBean(TransactionalServiceImpl.class); }); } @Test void excludesAbstractTransactionAspectFromLazyInit() { this.contextRunner.withUserConfiguration(AspectJTransactionManagementConfiguration.class).run((context) -> { LazyInitializationExcludeFilter filter = context.getBean(LazyInitializationExcludeFilter.class); assertThat(filter.isExcluded("bean", mock(BeanDefinition.class), AbstractTransactionAspect.class)).isTrue(); }); } @Configuration static
TransactionAutoConfigurationTests
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/create_function/MySql_Create_Function_0.java
{ "start": 933, "end": 2841 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "CREATE FUNCTION hello (s CHAR(20))\n" + " RETURNS CHAR(50) DETERMINISTIC\n" + " RETURN CONCAT('Hello, ',s,'!');"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLStatement stmt = statementList.get(0); assertEquals(1, statementList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.MYSQL); stmt.accept(visitor); assertEquals("CREATE FUNCTION hello (\n" + "\ts CHAR(20)\n" + ")\n" + "RETURNS CHAR(50) DETERMINISTIC\n" + "RETURN CONCAT('Hello, ', s, '!');", // SQLUtils.toMySqlString(stmt)); assertEquals("create function hello (\n" + "\ts CHAR(20)\n" + ")\n" + "returns CHAR(50) deterministic\n" + "return CONCAT('Hello, ', s, '!');", // SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(0, visitor.getTables().size()); assertEquals(1, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("City"))); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("t2"))); // assertTrue(visitor.getColumns().contains(new Column("t2", "id"))); } }
MySql_Create_Function_0
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/availability/AvailabilityChangeEventTests.java
{ "start": 3531, "end": 3853 }
enum ____ implements AvailabilityState { ONE { @Override String getDescription() { return "I have been overridden"; } }, TWO { @Override String getDescription() { return "I have also been overridden"; } }; abstract String getDescription(); } @Configuration static
SubClassedEnum
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/QueryToken.java
{ "start": 940, "end": 1195 }
interface ____ extends QueryTokenStream { /** * @return the token value (i.e. its content). */ String value(); /** * @return {@code true} if the token represents an expression. */ default boolean isExpression() { return false; } }
QueryToken
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/NullProperties.java
{ "start": 732, "end": 3091 }
class ____ { private Integer id1; private Integer id2; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { id1 = scope.fromTransaction( em -> { BasicTestEntity1 bte1 = new BasicTestEntity1( "x", 1 ); em.persist( bte1 ); return bte1.getId(); } ); id2 = scope.fromTransaction( em -> { BasicTestEntity1 bte2 = new BasicTestEntity1( null, 20 ); em.persist( bte2 ); return bte2.getId(); } ); scope.inTransaction( em -> { BasicTestEntity1 bte1 = em.find( BasicTestEntity1.class, id1 ); bte1.setLong1( 1 ); bte1.setStr1( null ); } ); scope.inTransaction( em -> { BasicTestEntity1 bte2 = em.find( BasicTestEntity1.class, id2 ); bte2.setLong1( 20 ); bte2.setStr1( "y2" ); } ); } @Test public void testRevisionsCounts(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); assertEquals( Arrays.asList( 1, 3 ), auditReader.getRevisions( BasicTestEntity1.class, id1 ) ); assertEquals( Arrays.asList( 2, 4 ), auditReader.getRevisions( BasicTestEntity1.class, id2 ) ); } ); } @Test public void testHistoryOfId1(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); BasicTestEntity1 ver1 = new BasicTestEntity1( id1, "x", 1 ); BasicTestEntity1 ver2 = new BasicTestEntity1( id1, null, 1 ); assertEquals( ver1, auditReader.find( BasicTestEntity1.class, id1, 1 ) ); assertEquals( ver1, auditReader.find( BasicTestEntity1.class, id1, 2 ) ); assertEquals( ver2, auditReader.find( BasicTestEntity1.class, id1, 3 ) ); assertEquals( ver2, auditReader.find( BasicTestEntity1.class, id1, 4 ) ); } ); } @Test public void testHistoryOfId2(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); BasicTestEntity1 ver1 = new BasicTestEntity1( id2, null, 20 ); BasicTestEntity1 ver2 = new BasicTestEntity1( id2, "y2", 20 ); assertNull( auditReader.find( BasicTestEntity1.class, id2, 1 ) ); assertEquals( ver1, auditReader.find( BasicTestEntity1.class, id2, 2 ) ); assertEquals( ver1, auditReader.find( BasicTestEntity1.class, id2, 3 ) ); assertEquals( ver2, auditReader.find( BasicTestEntity1.class, id2, 4 ) ); } ); } }
NullProperties
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng2744checksumVerificationTest.java
{ "start": 1062, "end": 2228 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Tests that hex digits of checksums are compared without regard to case. * * @throws Exception in case of failure */ @Test public void testitMNG2744() throws Exception { File testDir = extractResources("/mng-2744"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteArtifacts("org.apache.maven.its.mng2744"); verifier.filterFile("settings-template.xml", "settings.xml"); verifier.addCliArgument("--settings"); verifier.addCliArgument("settings.xml"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyArtifactPresent("org.apache.maven.its.mng2744", "a", "1", "jar"); verifier.verifyArtifactPresent("org.apache.maven.its.mng2744", "a", "1", "pom"); verifier.verifyArtifactPresent("org.apache.maven.its.mng2744", "b", "1", "jar"); verifier.verifyArtifactPresent("org.apache.maven.its.mng2744", "b", "1", "pom"); } }
MavenITmng2744checksumVerificationTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Athena2EndpointBuilderFactory.java
{ "start": 27091, "end": 32426 }
interface ____ extends EndpointProducerBuilder { default Athena2EndpointBuilder basic() { return (Athena2EndpointBuilder) this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedAthena2EndpointBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedAthena2EndpointBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * The AmazonAthena instance to use as the client. * * The option is a: * <code>software.amazon.awssdk.services.athena.AthenaClient</code> * type. * * Group: advanced * * @param amazonAthenaClient the value to set * @return the dsl builder */ default AdvancedAthena2EndpointBuilder amazonAthenaClient(software.amazon.awssdk.services.athena.AthenaClient amazonAthenaClient) { doSetProperty("amazonAthenaClient", amazonAthenaClient); return this; } /** * The AmazonAthena instance to use as the client. * * The option will be converted to a * <code>software.amazon.awssdk.services.athena.AthenaClient</code> * type. * * Group: advanced * * @param amazonAthenaClient the value to set * @return the dsl builder */ default AdvancedAthena2EndpointBuilder amazonAthenaClient(String amazonAthenaClient) { doSetProperty("amazonAthenaClient", amazonAthenaClient); return this; } /** * A unique string to ensure issues queries are idempotent. It is * unlikely you will need to set this. * * The option is a: <code>java.lang.String</code> type. * * Group: advanced * * @param clientRequestToken the value to set * @return the dsl builder */ default AdvancedAthena2EndpointBuilder clientRequestToken(String clientRequestToken) { doSetProperty("clientRequestToken", clientRequestToken); return this; } /** * Include useful trace information at the beginning of queries as an * SQL comment (prefixed with --). * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param includeTrace the value to set * @return the dsl builder */ default AdvancedAthena2EndpointBuilder includeTrace(boolean includeTrace) { doSetProperty("includeTrace", includeTrace); return this; } /** * Include useful trace information at the beginning of queries as an * SQL comment (prefixed with --). * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param includeTrace the value to set * @return the dsl builder */ default AdvancedAthena2EndpointBuilder includeTrace(String includeTrace) { doSetProperty("includeTrace", includeTrace); return this; } } public
AdvancedAthena2EndpointBuilder
java
quarkusio__quarkus
extensions/panache/panache-common/deployment/src/main/java/io/quarkus/panache/common/deployment/PanacheEntityEnhancer.java
{ "start": 200, "end": 707 }
class ____ implements BiFunction<String, ClassVisitor, ClassVisitor> { protected final IndexView indexView; protected final List<PanacheMethodCustomizer> methodCustomizers; public PanacheEntityEnhancer(IndexView index, List<PanacheMethodCustomizer> methodCustomizers) { this.indexView = index; this.methodCustomizers = methodCustomizers; } @Override public abstract ClassVisitor apply(String className, ClassVisitor outputClassVisitor); }
PanacheEntityEnhancer
java
apache__maven
impl/maven-testing/src/main/java/org/apache/maven/api/plugin/testing/stubs/RepositorySystemSupplier.java
{ "start": 11345, "end": 11576 }
class ____ access to various components via public getters, and allows even partial object * graph construction. * <p> * Extend this class {@code createXXX()} methods and override to customize, if needed. The contract of this
offers
java
quarkusio__quarkus
extensions/kafka-streams/runtime-dev/src/main/java/io/quarkus/kafka/streams/runtime/dev/ui/KafkaStreamsJsonRPCService.java
{ "start": 458, "end": 1858 }
class ____ { @Inject Instance<Topology> topologyProvider; @NonBlocking public JsonObject getTopology() { var topologyDescription = ""; if (topologyProvider.isResolvable()) { final var describe = topologyProvider.get().describe(); topologyDescription = describe != null ? describe.toString() : ""; } return parseTopologyDescription(topologyDescription); } JsonObject parseTopologyDescription(String topologyDescription) { final var res = new JsonObject(); final var context = new TopologyParserContext(); Arrays.stream(topologyDescription.split("\n")) .map(String::trim) .forEachOrdered(line -> Stream.of(SUB_TOPOLOGY, SOURCE, PROCESSOR, SINK, RIGHT_ARROW) .filter(itemParser -> itemParser.test(line)) .forEachOrdered(itemParser -> itemParser.accept(context))); res .put("describe", topologyDescription) .put("subTopologies", context.subTopologies) .put("sources", context.sources) .put("sinks", context.sinks) .put("stores", context.stores) .put("graphviz", context.graphviz.toGraph()) .put("mermaid", context.mermaid.toGraph()); return res; } private
KafkaStreamsJsonRPCService
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hql/MapJoinKeyValueTests.java
{ "start": 3186, "end": 3305 }
class ____ { @Id String isbn; String title; @ManyToMany Map<Language, Book> translations; } @Entity static
Book
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/integration/BlockingConnectorTest.java
{ "start": 29526, "end": 29785 }
class ____ extends BlockingSourceTask { public InitializeBlockingSourceTask() { super(SOURCE_TASK_INITIALIZE); } } } // Used to test blocks in SinkTask methods public static
InitializeBlockingSourceTask
java
apache__camel
components/camel-web3j/src/main/java/org/apache/camel/component/web3j/Web3jHelper.java
{ "start": 1002, "end": 1739 }
class ____ { private Web3jHelper() { } public static DefaultBlockParameter toDefaultBlockParameter(String block) { DefaultBlockParameter defaultBlockParameter = null; if (block != null) { for (DefaultBlockParameterName defaultBlockParameterName : DefaultBlockParameterName.values()) { if (block.equalsIgnoreCase(defaultBlockParameterName.getValue())) { defaultBlockParameter = defaultBlockParameterName; } } if (defaultBlockParameter == null) { defaultBlockParameter = DefaultBlockParameter.valueOf(new BigInteger(block)); } } return defaultBlockParameter; } }
Web3jHelper
java
alibaba__nacos
plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/IdentityContextTest.java
{ "start": 920, "end": 1952 }
class ____ { private static final String TEST = "test"; private IdentityContext identityContext; @BeforeEach void setUp() throws Exception { identityContext = new IdentityContext(); } @Test void testGetParameter() { assertNull(identityContext.getParameter(TEST)); identityContext.setParameter(TEST, TEST); assertEquals(TEST, identityContext.getParameter(TEST)); } @Test void testGetParameterWithDefaultValue() { assertEquals(TEST, identityContext.getParameter(TEST, TEST)); identityContext.setParameter(TEST, TEST + "new"); assertEquals(TEST + "new", identityContext.getParameter(TEST, TEST)); long actual = identityContext.getParameter(TEST, 1L); assertEquals(1L, actual); } @Test void testGetParameterWithNullDefaultValue() { assertThrows(IllegalArgumentException.class, () -> { identityContext.getParameter(TEST, null); }); } }
IdentityContextTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/assumptions/BDDAssumptionsTest.java
{ "start": 8691, "end": 9064 }
class ____ { private final Long actual = 1L; @Test void should_run_test_when_assumption_passes() { thenCode(() -> given(actual).isOne()).doesNotThrowAnyException(); } @Test void should_ignore_test_when_assumption_fails() { expectAssumptionNotMetException(() -> given(actual).isZero()); } } @Nested
BDDAssumptions_given_Long_Test
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/client/observation/ClientHttpObservationDocumentation.java
{ "start": 1292, "end": 1880 }
enum ____ implements ObservationDocumentation { /** * HTTP exchanges observations for clients. */ HTTP_CLIENT_EXCHANGES { @Override public Class<? extends ObservationConvention<? extends Observation.Context>> getDefaultConvention() { return DefaultClientRequestObservationConvention.class; } @Override public KeyName[] getLowCardinalityKeyNames() { return LowCardinalityKeyNames.values(); } @Override public KeyName[] getHighCardinalityKeyNames() { return new KeyName[] {HighCardinalityKeyNames.HTTP_URL}; } }; public
ClientHttpObservationDocumentation
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/basics/BookControllerSpec.java
{ "start": 1244, "end": 3053 }
class ____ { private EmbeddedServer embeddedServer; private HttpClient client; @BeforeEach void setup() { embeddedServer = ApplicationContext.run(EmbeddedServer.class); client = embeddedServer.getApplicationContext().createBean( HttpClient.class, embeddedServer.getURL()); } @AfterEach void cleanup() { embeddedServer.stop(); client.stop(); } @Test void testPostWithURITemplate() { // tag::posturitemplate[] Flux<HttpResponse<Book>> call = Flux.from(client.exchange( POST("/amazon/book/{title}", new Book("The Stand")), Book.class )); // end::posturitemplate[] HttpResponse<Book> response = call.blockFirst(); Optional<Book> message = response.getBody(Book.class); // <2> // check the status assertEquals(HttpStatus.CREATED, response.getStatus()); // <3> // check the body assertTrue(message.isPresent()); assertEquals("The Stand", message.get().getTitle()); } @Test void testPostFormData() { // tag::postform[] Flux<HttpResponse<Book>> call = Flux.from(client.exchange( POST("/amazon/book/{title}", new Book("The Stand")) .contentType(MediaType.APPLICATION_FORM_URLENCODED), Book.class )); // end::postform[] HttpResponse<Book> response = call.blockFirst(); Optional<Book> message = response.getBody(Book.class); // <2> // check the status assertEquals(HttpStatus.CREATED, response.getStatus()); // <3> // check the body assertTrue(message.isPresent()); assertEquals("The Stand", message.get().getTitle()); } }
BookControllerSpec
java
quarkusio__quarkus
test-framework/junit5/src/main/java/io/quarkus/test/junit/classloading/FacadeClassLoader.java
{ "start": 3429, "end": 3944 }
class ____ loaded with private static final Map<String, CuratedApplication> curatedApplications = new HashMap<>(); // JUnit discovery is single threaded, so no need for concurrency on this map private final Map<String, QuarkusClassLoader> runtimeClassLoaders = new HashMap<>(); private static final String NO_PROFILE = "no-profile"; /* * A 'disposable' loader for holding temporary instances of the classes to allow us to inspect them. * * It seems kind of wasteful to load every
is
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/ShortAssert.java
{ "start": 1029, "end": 1172 }
class ____ extends AbstractShortAssert<ShortAssert> { public ShortAssert(Short actual) { super(actual, ShortAssert.class); } }
ShortAssert
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/tasks/TaskExecutor.java
{ "start": 1070, "end": 3672 }
interface ____ { /** * @return ID name string of the task executor. */ String name(); /** * Starts the task executor. * Idempotent operation - will have no effect if thread is already started. */ void start(); /** * Returns true if the task executor thread is running. */ boolean isRunning(); /** * Asks the task executor to shut down. * Idempotent operation - will have no effect if thread was already asked to shut down * * @throws * org.apache.kafka.streams.errors.StreamsException if the state updater thread cannot shutdown within the timeout */ void requestShutdown(); /** * Shuts down the task processor updater. * Idempotent operation - will have no effect if thread is already shut down. * Must call `requestShutdown` first. * * @param timeout duration how long to wait until the state updater is shut down * * @throws * org.apache.kafka.streams.errors.StreamsException if the state updater thread does not shutdown within the timeout */ void awaitShutdown(final Duration timeout); /** * Get the current assigned processing task. The task returned is read-only and cannot be modified. * * @return the current processing task */ ReadOnlyTask currentTask(); /** * Unassign the current processing task from the task processor and give it back to the state manager. * * Note there is an asymmetry between assignment and unassignment between {@link TaskManager} and {@link TaskExecutor}, * since assigning a task from task manager to task executor is always initiated by the task executor itself, by calling * {@link TaskManager#assignNextTask(TaskExecutor)}, * while unassigning a task and returning it to task manager could be triggered either by the task executor proactively * when it finds the task not processable anymore, or by the task manager when it needs to commit / close it. * This function is used for the second case, where task manager will call this function asking the task executor * to give back the task. * * The task must be flushed before being unassigned, since it may be committed or closed by the task manager next. * * This method does not block, instead a future is returned; when the task executor finishes * unassigning the task this future will then complete. * * @return the future capturing the completion of the unassign process */ KafkaFuture<StreamTask> unassign(); }
TaskExecutor
java
google__auto
common/src/test/java/com/google/auto/common/BasicAnnotationProcessorTest.java
{ "start": 14728, "end": 15147 }
class ____ {}"); requiresGeneratedCodeDeferralTest(dependentTestFileObject, generatesCodeFileObject); } @Test public void properlyDefersProcessing_typeElement() { JavaFileObject dependentTestFileObject = JavaFileObjects.forSourceLines( "test.ClassA", "package test;", "", "@" + RequiresGeneratedCode.class.getCanonicalName(), "public
ClassB
java
micronaut-projects__micronaut-core
inject-java/src/main/java/io/micronaut/annotation/processing/visitor/JavaParameterElement.java
{ "start": 1564, "end": 6423 }
class ____ extends AbstractTypeAwareJavaElement implements ParameterElement, TypedElement { private final JavaClassElement owningType; private final JavaMethodElement methodElement; private ClassElement typeElement; private ClassElement genericTypeElement; /** * Default constructor. * * @param owningType The owning class * @param methodElement The method element * @param nativeElement The native element * @param annotationMetadataFactory The annotation metadata factory * @param visitorContext The visitor context */ JavaParameterElement(JavaClassElement owningType, JavaMethodElement methodElement, JavaNativeElement.Variable nativeElement, ElementAnnotationMetadataFactory annotationMetadataFactory, JavaVisitorContext visitorContext) { super(nativeElement, annotationMetadataFactory, visitorContext); this.owningType = owningType; this.methodElement = methodElement; } @Override public JavaNativeElement.@NonNull Variable getNativeType() { return (JavaNativeElement.Variable) super.getNativeType(); } @Override protected AbstractJavaElement copyThis() { return new JavaParameterElement(owningType, methodElement, getNativeType(), elementAnnotationMetadataFactory, visitorContext); } @Override public ParameterElement withAnnotationMetadata(AnnotationMetadata annotationMetadata) { return (ParameterElement) super.withAnnotationMetadata(annotationMetadata); } @Override protected boolean hasNullMarked() { return methodElement.hasNullMarked(); } @Override public boolean isPrimitive() { return getType().isPrimitive(); } @Override public boolean isArray() { return getType().isArray(); } @Override public int getArrayDimensions() { return getType().getArrayDimensions(); } @Override @NonNull public ClassElement getType() { if (typeElement == null) { typeElement = newClassElement(getNativeType(), getNativeType().element().asType(), Collections.emptyMap()); } return typeElement; } @NonNull @Override public ClassElement getGenericType() { if (genericTypeElement == null) { genericTypeElement = newClassElement(getNativeType(), getNativeType().element().asType(), methodElement.getTypeArguments()); } return genericTypeElement; } @Override public MethodElement getMethodElement() { return methodElement; } @Override protected AnnotationMetadata getTypeAnnotationMetadata() { return getType().getTypeAnnotationMetadata(); } @Override public Optional<String> getDocumentation(boolean parse) { if (!parse) { return Optional.empty(); } try { String methodDocComment = visitorContext.getElements().getDocComment(methodElement.getNativeType().element()); if (methodDocComment != null) { String parameterDoc = findParameterDoc(methodDocComment, getName()); if (parameterDoc != null) { return Optional.of(parameterDoc); } } if (owningType.isRecord() && methodElement instanceof ConstructorElement constructor) { final List<PropertyElement> beanProperties = constructor .getDeclaringType() .getBeanProperties(); final ParameterElement[] parameters = constructor.getParameters(); if (beanProperties.size() == parameters.length) { String docComment = visitorContext.getElements().getDocComment(owningType.getNativeType().element()); if (docComment != null) { return Optional.ofNullable(findParameterDoc(docComment, getName())); } } } return Optional.empty(); } catch (Exception ignore) { return Optional.empty(); } } @Nullable private static String findParameterDoc(String javadocString, String name) { try { Javadoc javadoc = StaticJavaParser.parseJavadoc(javadocString); if (javadoc == null) { return null; } for (JavadocBlockTag t : javadoc.getBlockTags()) { if (t.getType() == JavadocBlockTag.Type.PARAM && t.getName().map(n -> n.equals(name)).orElse(false)) { return t.getContent().toText(); } } return null; } catch (Exception ignored) { return null; } } }
JavaParameterElement
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1005/OrderDto.java
{ "start": 232, "end": 400 }
class ____ { private String key; public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
OrderDto
java
google__dagger
javatests/dagger/functional/producers/ProducerFactoryTest.java
{ "start": 2206, "end": 2332 }
class ____ { @ProductionComponent(modules = {ExecutorModule.class, MonitorModule.class, TestModule.class})
ProducerFactoryTest
java
apache__dubbo
dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Parameter.java
{ "start": 1151, "end": 1474 }
enum ____ { PATH("path"), QUERY("query"), HEADER("header"), COOKIE("cookie"); private final String value; In(String value) { this.value = value; } @Override public String toString() { return value; } } public
In
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/filter/InternalFilter.java
{ "start": 933, "end": 1954 }
class ____ extends InternalSingleBucketAggregation { InternalFilter(String name, long docCount, InternalAggregations subAggregations, Map<String, Object> metadata) { super(name, docCount, subAggregations, metadata); } /** * Stream from a stream. */ public InternalFilter(StreamInput in) throws IOException { super(in); } @Override public String getWriteableName() { return FilterAggregationBuilder.NAME; } @Override protected InternalSingleBucketAggregation newAggregation(String name, long docCount, InternalAggregations subAggregations) { return new InternalFilter(name, docCount, subAggregations, getMetadata()); } @Override public InternalAggregation finalizeSampling(SamplingContext samplingContext) { return newAggregation( name, samplingContext.scaleUp(getDocCount()), InternalAggregations.finalizeSampling(getAggregations(), samplingContext) ); } }
InternalFilter
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java
{ "start": 83239, "end": 83571 }
interface ____ extends RelRule.Config { @Override default RemoveSingleAggregateRule toRule() { return new RemoveSingleAggregateRule(this); } } } /** Planner rule that removes correlations for scalar projects. */ public static final
RemoveSingleAggregateRuleConfig
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/VelocityEndpointBuilderFactory.java
{ "start": 15902, "end": 16229 }
class ____ extends AbstractEndpointBuilder implements VelocityEndpointBuilder, AdvancedVelocityEndpointBuilder { public VelocityEndpointBuilderImpl(String path) { super(componentName, path); } } return new VelocityEndpointBuilderImpl(path); } }
VelocityEndpointBuilderImpl
java
hibernate__hibernate-orm
hibernate-graalvm/src/test/java/org/hibernate/graalvm/internal/StaticClassListsTest.java
{ "start": 4161, "end": 5083 }
class ____ { @ParameterizedTest @EnumSource(TypesNeedingDefaultConstructorAccessible_Category.class) void containsAllExpectedClasses(TypesNeedingDefaultConstructorAccessible_Category category) { assertThat( StaticClassLists.typesNeedingDefaultConstructorAccessible() ) .containsAll( category.classes().collect( Collectors.toSet() ) ); } @Test void meta_noMissingTestCategory() { assertThat( Arrays.stream( TypesNeedingDefaultConstructorAccessible_Category.values() ).flatMap( TypesNeedingDefaultConstructorAccessible_Category::classes ) ) .as( "If this fails, a category is missing in " + TypesNeedingDefaultConstructorAccessible_Category.class ) .contains( StaticClassLists.typesNeedingDefaultConstructorAccessible() ); } } // TODO ORM 7: Move this inside TypesNeedingDefaultConstructorAccessible (requires JDK 17) and rename to simple Category
TypesNeedingDefaultConstructorAccessible
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalizedResource.java
{ "start": 10094, "end": 10533 }
class ____ implements ArgumentMatcher<ContainerEvent> { private final ContainerId idRef; private final ContainerEventType type; public ContainerEventMatcher(ContainerId idRef, ContainerEventType type) { this.idRef = idRef; this.type = type; } @Override public boolean matches(ContainerEvent evt) { return idRef == evt.getContainerID() && type == evt.getType(); } } }
ContainerEventMatcher
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/support/replication/ReplicationOperation.java
{ "start": 24409, "end": 27766 }
interface ____< RequestT extends ReplicationRequest<RequestT>, ReplicaRequestT extends ReplicationRequest<ReplicaRequestT>, PrimaryResultT extends PrimaryResult<ReplicaRequestT>> { /** * routing entry for this primary */ ShardRouting routingEntry(); /** * Fail the primary shard. * * @param message the failure message * @param exception the exception that triggered the failure */ void failShard(String message, Exception exception); /** * Performs the given request on this primary. Yes, this returns as soon as it can with the request for the replicas and calls a * listener when the primary request is completed. Yes, the primary request might complete before the method returns. Yes, it might * also complete after. Deal with it. * * @param request the request to perform * @param listener result listener */ void perform(RequestT request, ActionListener<PrimaryResultT> listener); /** * Notifies the primary of a local checkpoint for the given allocation. * * Note: The primary will use this information to advance the global checkpoint if possible. * * @param allocationId allocation ID of the shard corresponding to the supplied local checkpoint * @param checkpoint the *local* checkpoint for the shard */ void updateLocalCheckpointForShard(String allocationId, long checkpoint); /** * Update the local knowledge of the global checkpoint for the specified allocation ID. * * @param allocationId the allocation ID to update the global checkpoint for * @param globalCheckpoint the global checkpoint */ void updateGlobalCheckpointForShard(String allocationId, long globalCheckpoint); /** * Returns the persisted local checkpoint on the primary shard. * * @return the local checkpoint */ long localCheckpoint(); /** * Returns the global checkpoint computed on the primary shard. * * @return the computed global checkpoint */ long computedGlobalCheckpoint(); /** * Returns the persisted global checkpoint on the primary shard. * * @return the persisted global checkpoint */ long globalCheckpoint(); /** * Returns the maximum seq_no of updates (index operations overwrite Lucene) or deletes on the primary. * This value must be captured after the execution of a replication request on the primary is completed. */ long maxSeqNoOfUpdatesOrDeletes(); /** * Returns the current replication group on the primary shard * * @return the replication group */ ReplicationGroup getReplicationGroup(); /** * Returns the pending replication actions on the primary shard * * @return the pending replication actions */ PendingReplicationActions getPendingReplicationActions(); } /** * An encapsulation of an operation that will be executed on the replica shards, if present. */ public
Primary
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2300/Issue2346.java
{ "start": 838, "end": 973 }
class ____{ } } @JSONType(builder = TestEntity2.TestEntity2Builder.class) @Getter public static
TestEntityBuilder
java
mockito__mockito
mockito-core/src/main/java/org/mockito/Incubating.java
{ "start": 987, "end": 1238 }
interface ____ with this annotation should also * be considered to be incubating, as the underlying implementation may be subject to future change * before it is finalized. */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @
annotated
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnThreadingCondition.java
{ "start": 1210, "end": 2171 }
class ____ extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Map<String, @Nullable Object> attributes = metadata .getAnnotationAttributes(ConditionalOnThreading.class.getName()); Assert.state(attributes != null, "'attributes' must not be null"); Threading threading = (Threading) attributes.get("value"); Assert.state(threading != null, "'threading' must not be null"); return getMatchOutcome(context.getEnvironment(), threading); } private ConditionOutcome getMatchOutcome(Environment environment, Threading threading) { String name = threading.name(); ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnThreading.class); if (threading.isActive(environment)) { return ConditionOutcome.match(message.foundExactly(name)); } return ConditionOutcome.noMatch(message.didNotFind(name).atAll()); } }
OnThreadingCondition
java
quarkusio__quarkus
integration-tests/logging-min-level-unset/src/test/java/io/quarkus/it/logging/minlevel/unset/SetCategoryRuntimeLogLevels.java
{ "start": 177, "end": 707 }
class ____ implements QuarkusTestResourceLifecycleManager { @Override public Map<String, String> start() { final Map<String, String> systemProperties = new HashMap<>(); systemProperties.put("quarkus.log.category.\"io.quarkus.it.logging.minlevel.unset.above\".level", "WARN"); systemProperties.put("quarkus.log.category.\"io.quarkus.it.logging.minlevel.unset.promote\".level", "TRACE"); return systemProperties; } @Override public void stop() { } }
SetCategoryRuntimeLogLevels
java
google__guava
android/guava-tests/benchmark/com/google/common/hash/HashStringBenchmark.java
{ "start": 987, "end": 5395 }
class ____ { final int value; /** * Convert the input string to a code point. Accepts regular decimal numerals, hex strings, and * some symbolic names meaningful to humans. */ private static int decode(String userFriendly) { try { return Integer.decode(userFriendly); } catch (NumberFormatException ignored) { if (userFriendly.matches("(?i)(?:American|English|ASCII)")) { // 1-byte UTF-8 sequences - "American" ASCII text return 0x80; } else if (userFriendly.matches("(?i)(?:French|Latin|Western.*European)")) { // Mostly 1-byte UTF-8 sequences, mixed with occasional 2-byte // sequences - "Western European" text return 0x90; } else if (userFriendly.matches("(?i)(?:Branch.*Prediction.*Hostile)")) { // Defeat branch predictor for: c < 0x80 ; branch taken 50% of the time. return 0x100; } else if (userFriendly.matches("(?i)(?:Greek|Cyrillic|European|ISO.?8859)")) { // Mostly 2-byte UTF-8 sequences - "European" text return 0x800; } else if (userFriendly.matches("(?i)(?:Chinese|Han|Asian|BMP)")) { // Mostly 3-byte UTF-8 sequences - "Asian" text return Character.MIN_SUPPLEMENTARY_CODE_POINT; } else if (userFriendly.matches("(?i)(?:Cuneiform|rare|exotic|supplementary.*)")) { // Mostly 4-byte UTF-8 sequences - "rare exotic" text return Character.MAX_CODE_POINT; } else { throw new IllegalArgumentException("Can't decode codepoint " + userFriendly); } } } public static MaxCodePoint valueOf(String userFriendly) { return new MaxCodePoint(userFriendly); } public MaxCodePoint(String userFriendly) { value = decode(userFriendly); } } /** * The default values of maxCodePoint below provide pretty good performance models of different * kinds of common human text. * * @see MaxCodePoint#decode */ @Param({"0x80", "0x90", "0x100", "0x800", "0x10000", "0x10ffff"}) MaxCodePoint maxCodePoint; @Param({"16384"}) int charCount; @Param({"MURMUR3_32", "MURMUR3_128", "SHA1"}) HashFunctionEnum hashFunctionEnum; private String[] strings; static final int SAMPLES = 0x100; static final int SAMPLE_MASK = 0xFF; /** * Compute arrays of valid unicode text, and store it in 3 forms: byte arrays, Strings, and * StringBuilders (in a CharSequence[] to make it a little harder for the JVM). */ @BeforeExperiment void setUp() { long seed = 99; Random rnd = new Random(seed); strings = new String[SAMPLES]; for (int i = 0; i < SAMPLES; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < charCount; j++) { int codePoint; // discard illegal surrogate "codepoints" do { codePoint = rnd.nextInt(maxCodePoint.value); } while (Character.isSurrogate((char) codePoint)); sb.appendCodePoint(codePoint); } strings[i] = sb.toString(); } } @Benchmark int hashUtf8(int reps) { int res = 0; for (int i = 0; i < reps; i++) { res += System.identityHashCode( hashFunctionEnum.getHashFunction().hashString(strings[i & SAMPLE_MASK], UTF_8)); } return res; } @Benchmark int hashUtf8Hasher(int reps) { int res = 0; for (int i = 0; i < reps; i++) { res += System.identityHashCode( hashFunctionEnum .getHashFunction() .newHasher() .putString(strings[i & SAMPLE_MASK], UTF_8) .hash()); } return res; } @Benchmark int hashUtf8GetBytes(int reps) { int res = 0; for (int i = 0; i < reps; i++) { res += System.identityHashCode( hashFunctionEnum .getHashFunction() .hashBytes(strings[i & SAMPLE_MASK].getBytes(UTF_8))); } return res; } @Benchmark int hashUtf8GetBytesHasher(int reps) { int res = 0; for (int i = 0; i < reps; i++) { res += System.identityHashCode( hashFunctionEnum .getHashFunction() .newHasher() .putBytes(strings[i & SAMPLE_MASK].getBytes(UTF_8)) .hash()); } return res; } }
MaxCodePoint
java
apache__camel
components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcConstants.java
{ "start": 938, "end": 3311 }
interface ____ { String GRPC_SERVICE_CLASS_POSTFIX = "Grpc"; String GRPC_SERVER_IMPL_POSTFIX = "ImplBase"; String GRPC_SERVICE_SYNC_STUB_METHOD = "newBlockingStub"; String GRPC_SERVICE_ASYNC_STUB_METHOD = "newStub"; String GRPC_SERVICE_FUTURE_STUB_METHOD = "newFutureStub"; String GRPC_SERVICE_STUB_CALL_CREDS_METHOD = "withCallCredentials"; /* * JSON Web Tokens specific constants */ String GRPC_JWT_TOKEN_KEY = "jwt"; String GRPC_USER_ID_KEY = "userId"; Metadata.Key<String> GRPC_JWT_METADATA_KEY = Metadata.Key.of(GRPC_JWT_TOKEN_KEY, Metadata.ASCII_STRING_MARSHALLER); Context.Key<String> GRPC_JWT_CTX_KEY = Context.key(GRPC_JWT_TOKEN_KEY); Context.Key<String> GRPC_JWT_USER_ID_CTX_KEY = Context.key(GRPC_USER_ID_KEY); /* * This headers will be set after gRPC consumer method is invoked */ @org.apache.camel.spi.Metadata(label = "consumer", description = "Method name handled by the consumer service", javaType = "String") String GRPC_METHOD_NAME_HEADER = "CamelGrpcMethodName"; @org.apache.camel.spi.Metadata(label = "consumer", description = "If provided, the given agent will prepend the gRPC library's user agent information", javaType = "String") String GRPC_USER_AGENT_HEADER = "CamelGrpcUserAgent"; @org.apache.camel.spi.Metadata(label = "consumer", description = "Received event type from the sent request.\n\n" + "Possible values:\n\n" + "* onNext\n" + "* onCompleted\n" + "* onError", javaType = "String") String GRPC_EVENT_TYPE_HEADER = "CamelGrpcEventType"; String GRPC_EVENT_TYPE_ON_NEXT = "onNext"; String GRPC_EVENT_TYPE_ON_ERROR = "onError"; String GRPC_EVENT_TYPE_ON_COMPLETED = "onCompleted"; /* * The registry key to lookup a custom BindableServiceFactory */ String GRPC_BINDABLE_SERVICE_FACTORY_NAME = "grpcBindableServiceFactory"; String GRPC_RESPONSE_OBSERVER = "grpcResponseObserver"; }
GrpcConstants
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnResourceTests.java
{ "start": 2437, "end": 2615 }
class ____ { @Bean String foo() { return "foo"; } } @Configuration(proxyBeanMethods = false) @ConditionalOnResource(resources = "${schema}") static
BasicConfiguration
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/webmonitor/threadinfo/ThreadInfoRequestCoordinatorTest.java
{ "start": 2539, "end": 13139 }
class ____ { private static final Duration REQUEST_TIMEOUT = Duration.ofMillis(100); private static final String REQUEST_TIMEOUT_MESSAGE = "Request timeout."; private static final int DEFAULT_NUMBER_OF_SAMPLES = 1; private static final int DEFAULT_MAX_STACK_TRACE_DEPTH = 100; private static final Duration DEFAULT_DELAY_BETWEEN_SAMPLES = Duration.ofMillis(50); private static ScheduledExecutorService executorService; private ThreadInfoRequestCoordinator coordinator; @BeforeAll static void setUp() { executorService = new ScheduledThreadPoolExecutor(1); } @AfterAll static void tearDown() { if (executorService != null) { executorService.shutdown(); } } @BeforeEach void initCoordinator() { coordinator = new ThreadInfoRequestCoordinator(executorService, REQUEST_TIMEOUT); } @AfterEach void shutdownCoordinator() { if (coordinator != null) { // verify no more pending request assertThat(coordinator.getNumberOfPendingRequests()).isZero(); coordinator.shutDown(); } } /** Tests successful thread info stats request. */ @Test void testSuccessfulThreadInfoRequest() throws Exception { Map<ImmutableSet<ExecutionAttemptID>, CompletableFuture<TaskExecutorThreadInfoGateway>> executionWithGateways = createMockSubtaskWithGateways( CompletionType.SUCCESSFULLY, CompletionType.SUCCESSFULLY); CompletableFuture<VertexThreadInfoStats> requestFuture = coordinator.triggerThreadInfoRequest( executionWithGateways, DEFAULT_NUMBER_OF_SAMPLES, DEFAULT_DELAY_BETWEEN_SAMPLES, DEFAULT_MAX_STACK_TRACE_DEPTH); VertexThreadInfoStats threadInfoStats = requestFuture.get(); // verify the request result assertThat(threadInfoStats.getRequestId()).isEqualTo(0); Map<ExecutionAttemptID, Collection<ThreadInfoSample>> samplesBySubtask = threadInfoStats.getSamplesBySubtask(); for (Collection<ThreadInfoSample> result : samplesBySubtask.values()) { StackTraceElement[] stackTrace = result.iterator().next().getStackTrace(); assertThat(stackTrace).isNotEmpty(); } } /** Tests that failed thread info request to one of the tasks fails the future. */ @Test void testThreadInfoRequestWithException() throws Exception { Map<ImmutableSet<ExecutionAttemptID>, CompletableFuture<TaskExecutorThreadInfoGateway>> executionWithGateways = createMockSubtaskWithGateways( CompletionType.SUCCESSFULLY, CompletionType.EXCEPTIONALLY); CompletableFuture<VertexThreadInfoStats> requestFuture = coordinator.triggerThreadInfoRequest( executionWithGateways, DEFAULT_NUMBER_OF_SAMPLES, DEFAULT_DELAY_BETWEEN_SAMPLES, DEFAULT_MAX_STACK_TRACE_DEPTH); assertThatThrownBy(requestFuture::get, "The request must be failed.") .isInstanceOf(ExecutionException.class) .hasCauseInstanceOf(RuntimeException.class); } /** Tests that thread info stats request times out if not finished in time. */ @Test void testThreadInfoRequestTimeout() throws Exception { Map<ImmutableSet<ExecutionAttemptID>, CompletableFuture<TaskExecutorThreadInfoGateway>> executionWithGateways = createMockSubtaskWithGateways( CompletionType.SUCCESSFULLY, CompletionType.TIMEOUT); CompletableFuture<VertexThreadInfoStats> requestFuture = coordinator.triggerThreadInfoRequest( executionWithGateways, DEFAULT_NUMBER_OF_SAMPLES, DEFAULT_DELAY_BETWEEN_SAMPLES, DEFAULT_MAX_STACK_TRACE_DEPTH); try { assertThatThrownBy(requestFuture::get, "The request must be failed.") .satisfies(anyCauseMatches(REQUEST_TIMEOUT_MESSAGE)); } finally { coordinator.shutDown(); } } /** Tests that shutdown fails all pending requests and future request triggers. */ @Test void testShutDown() throws Exception { Map<ImmutableSet<ExecutionAttemptID>, CompletableFuture<TaskExecutorThreadInfoGateway>> executionWithGateways = createMockSubtaskWithGateways( // request future will only be completed after all gateways // successfully return thread infos. CompletionType.SUCCESSFULLY, CompletionType.NEVER_COMPLETE); List<CompletableFuture<VertexThreadInfoStats>> requestFutures = new ArrayList<>(); CompletableFuture<VertexThreadInfoStats> requestFuture1 = coordinator.triggerThreadInfoRequest( executionWithGateways, DEFAULT_NUMBER_OF_SAMPLES, DEFAULT_DELAY_BETWEEN_SAMPLES, DEFAULT_MAX_STACK_TRACE_DEPTH); CompletableFuture<VertexThreadInfoStats> requestFuture2 = coordinator.triggerThreadInfoRequest( executionWithGateways, DEFAULT_NUMBER_OF_SAMPLES, DEFAULT_DELAY_BETWEEN_SAMPLES, DEFAULT_MAX_STACK_TRACE_DEPTH); // trigger request requestFutures.add(requestFuture1); requestFutures.add(requestFuture2); for (CompletableFuture<VertexThreadInfoStats> future : requestFutures) { assertThat(future).isNotDone(); } // shut down coordinator.shutDown(); // verify all completed for (CompletableFuture<VertexThreadInfoStats> future : requestFutures) { assertThat(future).isCompletedExceptionally(); } // verify new trigger returns failed future CompletableFuture<VertexThreadInfoStats> future = coordinator.triggerThreadInfoRequest( executionWithGateways, DEFAULT_NUMBER_OF_SAMPLES, DEFAULT_DELAY_BETWEEN_SAMPLES, DEFAULT_MAX_STACK_TRACE_DEPTH); assertThat(future).isCompletedExceptionally(); } private static CompletableFuture<TaskExecutorThreadInfoGateway> createMockTaskManagerGateway( CompletionType completionType) throws Exception { final CompletableFuture<TaskThreadInfoResponse> responseFuture = new CompletableFuture<>(); switch (completionType) { case SUCCESSFULLY: Set<IdleTestTask> tasks = new HashSet<>(); executeWithTerminationGuarantee( () -> { tasks.add(new IdleTestTask()); tasks.add(new IdleTestTask()); Map<Long, ExecutionAttemptID> threads = tasks.stream() .collect( Collectors.toMap( task -> task.getExecutingThread() .getId(), IdleTestTask::getExecutionId)); Map<ExecutionAttemptID, Collection<ThreadInfoSample>> threadInfoSample = JvmUtils.createThreadInfoSample(threads.keySet(), 100) .entrySet() .stream() .collect( Collectors.toMap( entry -> threads.get(entry.getKey()), entry -> Collections.singletonList( entry.getValue()))); responseFuture.complete(new TaskThreadInfoResponse(threadInfoSample)); }, tasks); break; case EXCEPTIONALLY: responseFuture.completeExceptionally(new RuntimeException("Request failed.")); break; case TIMEOUT: executorService.schedule( () -> responseFuture.completeExceptionally( new TimeoutException(REQUEST_TIMEOUT_MESSAGE)), REQUEST_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); break; case NEVER_COMPLETE: // do nothing break; default: throw new RuntimeException("Unknown completion type."); } final TaskExecutorThreadInfoGateway executorGateway = (taskExecutionAttemptId, requestParams, timeout) -> responseFuture; return CompletableFuture.completedFuture(executorGateway); } private static Map< ImmutableSet<ExecutionAttemptID>, CompletableFuture<TaskExecutorThreadInfoGateway>> createMockSubtaskWithGateways(CompletionType... completionTypes) throws Exception { final Map< ImmutableSet<ExecutionAttemptID>, CompletableFuture<TaskExecutorThreadInfoGateway>> result = new HashMap<>(); for (CompletionType completionType : completionTypes) { ImmutableSet<ExecutionAttemptID> ids = ImmutableSet.of(createExecutionAttemptId(), createExecutionAttemptId()); result.put(ids, createMockTaskManagerGateway(completionType)); } return result; } /** Completion types of the request future. */ private
ThreadInfoRequestCoordinatorTest
java
quarkusio__quarkus
integration-tests/oidc-token-propagation-reactive/src/main/java/io/quarkus/it/keycloak/AccessTokenPropagationService.java
{ "start": 475, "end": 588 }
interface ____ { @GET @Produces("text/plain") Uni<String> getUserName(); }
AccessTokenPropagationService
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/body/stream/UpstreamBalancer.java
{ "start": 9347, "end": 9718 }
class ____ extends UpstreamImpl { FastestUpstreamImpl(boolean inv) { super(inv); } @Override public void start() { upstream.start(); } @Override public void onBytesConsumed(long bytesConsumed) { addFastest(inv, bytesConsumed); } } private final
FastestUpstreamImpl
java
spring-projects__spring-framework
spring-orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaVendorAdapter.java
{ "start": 7856, "end": 8062 }
class ____ for the given target database. * <p>The default implementation covers the common community dialect for Derby. * @param database the target database * @return the Hibernate database dialect
name
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/builder/multiple/Task.java
{ "start": 238, "end": 1078 }
class ____ { private final String builderCreationMethod; private final String buildMethod; private String name; public Task() { this.builderCreationMethod = null; this.buildMethod = "constructor"; } public Task(Builder builder, String buildMethod) { this.builderCreationMethod = builder.builderCreationMethod; this.buildMethod = buildMethod; this.name = builder.name; } public String getBuilderCreationMethod() { return builderCreationMethod; } public String getBuildMethod() { return buildMethod; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static Builder builder() { return new Builder( "builder" ); } public static
Task
java
google__guava
android/guava-tests/test/com/google/common/eventbus/outside/AnnotatedNotAbstractInSuperclassTest.java
{ "start": 2305, "end": 4323 }
class ____ extends SuperClass { final List<Object> differentlyOverriddenNotAnnotatedInSubclassGoodEvents = new ArrayList<>(); final List<Object> differentlyOverriddenAnnotatedInSubclassGoodEvents = new ArrayList<>(); @Override public void overriddenNotAnnotatedInSubclass(Object o) { super.overriddenNotAnnotatedInSubclass(o); } @Subscribe @Override // We are testing how we treat an override with the same behavior and annotations. @SuppressWarnings("RedundantOverride") public void overriddenAndAnnotatedInSubclass(Object o) { super.overriddenAndAnnotatedInSubclass(o); } @Override public void differentlyOverriddenNotAnnotatedInSubclass(Object o) { differentlyOverriddenNotAnnotatedInSubclassGoodEvents.add(o); } @Subscribe @Override public void differentlyOverriddenAnnotatedInSubclass(Object o) { differentlyOverriddenAnnotatedInSubclassGoodEvents.add(o); } } public void testNotOverriddenInSubclass() { assertThat(getSubscriber().notOverriddenInSubclassEvents).contains(EVENT); } public void testOverriddenNotAnnotatedInSubclass() { assertThat(getSubscriber().overriddenNotAnnotatedInSubclassEvents).contains(EVENT); } public void testDifferentlyOverriddenNotAnnotatedInSubclass() { assertThat(getSubscriber().differentlyOverriddenNotAnnotatedInSubclassGoodEvents) .contains(EVENT); assertThat(getSubscriber().differentlyOverriddenNotAnnotatedInSubclassBadEvents).isEmpty(); } public void testOverriddenAndAnnotatedInSubclass() { assertThat(getSubscriber().overriddenAndAnnotatedInSubclassEvents).contains(EVENT); } public void testDifferentlyOverriddenAndAnnotatedInSubclass() { assertThat(getSubscriber().differentlyOverriddenAnnotatedInSubclassGoodEvents).contains(EVENT); assertThat(getSubscriber().differentlyOverriddenAnnotatedInSubclassBadEvents).isEmpty(); } @Override SubClass createSubscriber() { return new SubClass(); } }
SubClass
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/split/JobSplit.java
{ "start": 6289, "end": 7049 }
class ____ { private String splitLocation; private long startOffset; public TaskSplitIndex(){ this("", 0); } public TaskSplitIndex(String splitLocation, long startOffset) { this.splitLocation = splitLocation; this.startOffset = startOffset; } public long getStartOffset() { return startOffset; } public String getSplitLocation() { return splitLocation; } public void readFields(DataInput in) throws IOException { splitLocation = Text.readString(in); startOffset = WritableUtils.readVLong(in); } public void write(DataOutput out) throws IOException { Text.writeString(out, splitLocation); WritableUtils.writeVLong(out, startOffset); } } }
TaskSplitIndex
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/ProgramDriver.java
{ "start": 1537, "end": 1729 }
class ____ { static final Class<?>[] paramTypes = new Class<?>[] {String[].class}; /** * Create a description of an example program. * @param mainClass the
ProgramDescription
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/ssl/pem/PemContent.java
{ "start": 1569, "end": 5581 }
class ____ { private static final Pattern PEM_HEADER = Pattern.compile("-+BEGIN\\s+[^-]*-+", Pattern.CASE_INSENSITIVE); private static final Pattern PEM_FOOTER = Pattern.compile("-+END\\s+[^-]*-+", Pattern.CASE_INSENSITIVE); private final String text; private PemContent(String text) { this.text = text.lines().map(String::trim).collect(Collectors.joining("\n")); } /** * Parse and return all {@link X509Certificate certificates} from the PEM content. * Most PEM files either contain a single certificate or a certificate chain. * @return the certificates * @throws IllegalStateException if no certificates could be loaded */ public List<X509Certificate> getCertificates() { return PemCertificateParser.parse(this.text); } /** * Parse and return the {@link PrivateKey private keys} from the PEM content. * @return the private keys * @throws IllegalStateException if no private key could be loaded */ public @Nullable PrivateKey getPrivateKey() { return getPrivateKey(null); } /** * Parse and return the {@link PrivateKey private keys} from the PEM content or * {@code null} if there is no private key. * @param password the password to decrypt the private keys or {@code null} * @return the private keys */ public @Nullable PrivateKey getPrivateKey(@Nullable String password) { return PemPrivateKeyParser.parse(this.text, password); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return Objects.equals(this.text, ((PemContent) obj).text); } @Override public int hashCode() { return Objects.hash(this.text); } @Override public String toString() { return this.text; } /** * Load {@link PemContent} from the given content (either the PEM content itself or a * reference to the resource to load). * @param content the content to load * @param resourceLoader the resource loader used to load content * @return a new {@link PemContent} instance or {@code null} * @throws IOException on IO error */ static @Nullable PemContent load(@Nullable String content, ResourceLoader resourceLoader) throws IOException { if (!StringUtils.hasLength(content)) { return null; } if (isPresentInText(content)) { return new PemContent(content); } try (InputStream in = resourceLoader.getResource(content).getInputStream()) { return load(in); } catch (IOException | UncheckedIOException ex) { throw new IOException("Error reading certificate or key from file '%s'".formatted(content), ex); } } /** * Load {@link PemContent} from the given {@link Path}. * @param path a path to load the content from * @return the loaded PEM content * @throws IOException on IO error */ public static PemContent load(Path path) throws IOException { Assert.notNull(path, "'path' must not be null"); try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) { return load(in); } } /** * Load {@link PemContent} from the given {@link InputStream}. * @param in an input stream to load the content from * @return the loaded PEM content * @throws IOException on IO error */ public static PemContent load(InputStream in) throws IOException { return of(StreamUtils.copyToString(in, StandardCharsets.UTF_8)); } /** * Return a new {@link PemContent} instance containing the given text. * @param text the text containing PEM encoded content * @return a new {@link PemContent} instance */ @Contract("!null -> !null") public static @Nullable PemContent of(@Nullable String text) { return (text != null) ? new PemContent(text) : null; } /** * Return if PEM content is present in the given text. * @param text the text to check * @return if the text includes PEM encoded content. */ public static boolean isPresentInText(@Nullable String text) { return text != null && PEM_HEADER.matcher(text).find() && PEM_FOOTER.matcher(text).find(); } }
PemContent
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/compress/ZstdCompression.java
{ "start": 1636, "end": 5085 }
class ____ implements Compression { private final int level; private ZstdCompression(int level) { this.level = level; } @Override public CompressionType type() { return ZSTD; } @Override public OutputStream wrapForOutput(ByteBufferOutputStream bufferStream, byte messageVersion) { try { // Set input buffer (uncompressed) to 16 KB (none by default) to ensure reasonable performance // in cases where the caller passes a small number of bytes to write (potentially a single byte). return new BufferedOutputStream(new ZstdOutputStreamNoFinalizer(bufferStream, RecyclingBufferPool.INSTANCE, level), 16 * 1024); } catch (Throwable e) { throw new KafkaException(e); } } @Override public InputStream wrapForInput(ByteBuffer buffer, byte messageVersion, BufferSupplier decompressionBufferSupplier) { try { return new ChunkedBytesStream(wrapForZstdInput(buffer, decompressionBufferSupplier), decompressionBufferSupplier, decompressionOutputSize(), false); } catch (Throwable e) { throw new KafkaException(e); } } // visible for testing public static ZstdInputStreamNoFinalizer wrapForZstdInput(ByteBuffer buffer, BufferSupplier decompressionBufferSupplier) throws IOException { // We use our own BufferSupplier instead of com.github.luben.zstd.RecyclingBufferPool since our // implementation doesn't require locking or soft references. The buffer allocated by this buffer pool is // used by zstd-jni for 1\ reading compressed data from input stream into a buffer before passing it over JNI // 2\ implementation of skip inside zstd-jni where buffer is obtained and released with every call final BufferPool bufferPool = new BufferPool() { @Override public ByteBuffer get(int capacity) { return decompressionBufferSupplier.get(capacity); } @Override public void release(ByteBuffer buffer) { decompressionBufferSupplier.release(buffer); } }; // Ideally, data from ZstdInputStreamNoFinalizer should be read in a bulk because every call to // `ZstdInputStreamNoFinalizer#read()` is a JNI call. The caller is expected to // balance the tradeoff between reading large amount of data vs. making multiple JNI calls. return new ZstdInputStreamNoFinalizer(new ByteBufferInputStream(buffer), bufferPool); } /** * Size of intermediate buffer which contains uncompressed data. * This size should be <= ZSTD_BLOCKSIZE_MAX * see: https://github.com/facebook/zstd/blob/189653a9c10c9f4224a5413a6d6a69dd01d7c3bd/lib/zstd.h#L854 */ @Override public int decompressionOutputSize() { // 16KB has been chosen based on legacy implementation introduced in https://github.com/apache/kafka/pull/6785 return 16 * 1024; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ZstdCompression that = (ZstdCompression) o; return level == that.level; } @Override public int hashCode() { return Objects.hash(level); } public static
ZstdCompression
java
apache__camel
components/camel-flink/src/test/java/org/apache/camel/component/flink/DataStreamBatchProcessingIT.java
{ "start": 1539, "end": 12783 }
class ____ extends CamelTestSupport { // Create separate environments for isolation StreamExecutionEnvironment batchEnv = Flinks.createStreamExecutionEnvironment(); StreamExecutionEnvironment transformEnv = Flinks.createStreamExecutionEnvironment(); @BindToRegistry("numberStream") private DataStreamSource<Integer> numberStream = batchEnv.fromElements(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); @BindToRegistry("textStream") private DataStreamSource<String> textStream = transformEnv.fromElements("apache", "camel", "flink", "integration", "test"); @BindToRegistry("multiplyCallback") public DataStreamCallback multiplyCallback() { return new VoidDataStreamCallback() { @Override public void doOnDataStream(DataStream ds, Object... payloads) throws Exception { int multiplier = (Integer) payloads[0]; ds.map((MapFunction<Integer, Integer>) value -> value * multiplier) .print(); } }; } @Test public void testBatchProcessingWithTransformation() { // Verify that the callback executes without error and the transformation is set up template.sendBodyAndHeader( "direct:batchTransform", null, FlinkConstants.FLINK_DATASTREAM_CALLBACK_HEADER, new VoidDataStreamCallback() { @Override public void doOnDataStream(DataStream ds, Object... payloads) throws Exception { // Verify environment is configured with batch mode and parallelism=2 StreamExecutionEnvironment env = ds.getExecutionEnvironment(); Assertions.assertThat(env.getParallelism()).isEqualTo(2); // Set up transformation (won't execute in test context) ds.map((MapFunction<Integer, Integer>) value -> value * 2).print(); } }); } @Test public void testBatchProcessingWithPayload() { List<Integer> results = new ArrayList<>(); template.sendBodyAndHeader( "direct:withPayload", 3, // multiplier FlinkConstants.FLINK_DATASTREAM_CALLBACK_HEADER, new VoidDataStreamCallback() { @Override public void doOnDataStream(DataStream ds, Object... payloads) throws Exception { Assertions.assertThat(payloads).hasSize(1); int multiplier = (Integer) payloads[0]; Assertions.assertThat(multiplier).isEqualTo(3); ds.map((MapFunction<Integer, Integer>) value -> value * multiplier) .print(); } }); } @Test public void testBatchProcessingWithFilter() { // Verify filter operation can be set up template.sendBodyAndHeader( "direct:batchFilter", null, FlinkConstants.FLINK_DATASTREAM_CALLBACK_HEADER, new VoidDataStreamCallback() { @Override public void doOnDataStream(DataStream ds, Object... payloads) throws Exception { // Verify environment configuration StreamExecutionEnvironment env = ds.getExecutionEnvironment(); Assertions.assertThat(env.getParallelism()).isEqualTo(1); // Set up filter (won't execute in test context) ds.filter(value -> ((Integer) value) % 2 == 0).print(); } }); } @Test public void testStringProcessingWithBatchMode() { // Verify string transformation can be set up template.sendBodyAndHeader( "direct:stringTransform", null, FlinkConstants.FLINK_DATASTREAM_CALLBACK_HEADER, new VoidDataStreamCallback() { @Override public void doOnDataStream(DataStream ds, Object... payloads) throws Exception { // Verify environment configuration StreamExecutionEnvironment env = ds.getExecutionEnvironment(); Assertions.assertThat(env.getParallelism()).isEqualTo(3); // Set up transformation ds.map((MapFunction<String, String>) String::toUpperCase).print(); } }); } @Test public void testHighParallelismProcessing() { // Verify high parallelism configuration template.sendBodyAndHeader( "direct:highParallelism", null, FlinkConstants.FLINK_DATASTREAM_CALLBACK_HEADER, new VoidDataStreamCallback() { @Override public void doOnDataStream(DataStream ds, Object... payloads) throws Exception { StreamExecutionEnvironment env = ds.getExecutionEnvironment(); // Verify high parallelism was set Assertions.assertThat(env.getParallelism()).isEqualTo(16); Assertions.assertThat(env.getMaxParallelism()).isEqualTo(256); // Set up transformation ds.map((MapFunction<Integer, Integer>) value -> value * value).print(); } }); } @Test public void testCallbackFromRegistry() { // Track that the callback was actually invoked final boolean[] callbackInvoked = { false }; // Send body with multiplier and verify callback executes template.sendBodyAndHeader( "direct:registryCallback", 5, FlinkConstants.FLINK_DATASTREAM_CALLBACK_HEADER, new VoidDataStreamCallback() { @Override public void doOnDataStream(DataStream ds, Object... payloads) throws Exception { // Verify the callback is invoked callbackInvoked[0] = true; // Verify environment configuration StreamExecutionEnvironment env = ds.getExecutionEnvironment(); Assertions.assertThat(env.getParallelism()).isEqualTo(4); // Verify payload was passed correctly Assertions.assertThat(payloads).hasSize(1); Assertions.assertThat(payloads[0]).isEqualTo(5); // Set up the transformation (using the registry callback pattern) ds.map((MapFunction<Integer, Integer>) value -> value * (Integer) payloads[0]).print(); } }); // Verify callback was executed Assertions.assertThat(callbackInvoked[0]).isTrue(); } @Test public void testMultipleOperations() { // Verify chained operations can be set up template.sendBodyAndHeader( "direct:multipleOps", null, FlinkConstants.FLINK_DATASTREAM_CALLBACK_HEADER, new VoidDataStreamCallback() { @Override public void doOnDataStream(DataStream ds, Object... payloads) throws Exception { // Verify environment configuration StreamExecutionEnvironment env = ds.getExecutionEnvironment(); Assertions.assertThat(env.getParallelism()).isEqualTo(4); // Set up chained operations ds.filter(value -> ((Integer) value) > 3) .map((MapFunction<Integer, Integer>) value -> value * 10) .map((MapFunction<Integer, Integer>) value -> value + 5) .print(); } }); } @Test public void testConfigurationPersistsAcrossInvocations() { // First invocation template.sendBodyAndHeader( "direct:batchTransform", null, FlinkConstants.FLINK_DATASTREAM_CALLBACK_HEADER, new VoidDataStreamCallback() { @Override public void doOnDataStream(DataStream ds, Object... payloads) throws Exception { StreamExecutionEnvironment env = ds.getExecutionEnvironment(); Assertions.assertThat(env.getParallelism()).isEqualTo(2); } }); // Second invocation - should have same configuration template.sendBodyAndHeader( "direct:batchTransform", null, FlinkConstants.FLINK_DATASTREAM_CALLBACK_HEADER, new VoidDataStreamCallback() { @Override public void doOnDataStream(DataStream ds, Object... payloads) throws Exception { StreamExecutionEnvironment env = ds.getExecutionEnvironment(); Assertions.assertThat(env.getParallelism()).isEqualTo(2); } }); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:batchTransform") .to("flink:datastream?dataStream=#numberStream" + "&executionMode=BATCH" + "&parallelism=2"); from("direct:withPayload") .to("flink:datastream?dataStream=#numberStream" + "&executionMode=BATCH"); from("direct:batchFilter") .to("flink:datastream?dataStream=#numberStream" + "&executionMode=BATCH" + "&parallelism=1"); from("direct:stringTransform") .to("flink:datastream?dataStream=#textStream" + "&executionMode=BATCH" + "&parallelism=3"); from("direct:highParallelism") .to("flink:datastream?dataStream=#numberStream" + "&executionMode=BATCH" + "&parallelism=16" + "&maxParallelism=256"); from("direct:registryCallback") .to("flink:datastream?dataStream=#numberStream" + "&dataStreamCallback=#multiplyCallback" + "&executionMode=BATCH" + "&parallelism=4"); from("direct:multipleOps") .to("flink:datastream?dataStream=#numberStream" + "&executionMode=BATCH" + "&parallelism=4"); } }; } }
DataStreamBatchProcessingIT