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
elastic__elasticsearch
qa/lucene-index-compatibility/src/javaRestTest/java/org/elasticsearch/lucene/FullClusterRestartSearchableSnapshotIndexCompatibilityIT.java
{ "start": 773, "end": 7432 }
class ____ extends FullClusterRestartIndexCompatibilityTestCase { static { clusterConfig = config -> config.setting("xpack.license.self_generated.type", "trial") .setting("xpack.searchable.snapshot.shared_cache.size", "16MB") .setting("xpack.searchable.snapshot.shared_cache.region_size", "256KB"); } public FullClusterRestartSearchableSnapshotIndexCompatibilityIT(Version version) { super(version); } /** * Creates an index and a snapshot on N-2, then mounts the snapshot on N. */ public void testSearchableSnapshot() throws Exception { final String repository = suffix("repository"); final String snapshot = suffix("snapshot"); final String index = suffix("index"); final int numDocs = 1234; if (isFullyUpgradedTo(VERSION_MINUS_2)) { logger.debug("--> registering repository [{}]", repository); registerRepository(client(), repository, FsRepository.TYPE, true, repositorySettings()); logger.debug("--> creating index [{}]", index); createIndex( client(), index, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0).build() ); logger.debug("--> indexing [{}] docs in [{}]", numDocs, index); indexDocs(index, numDocs); logger.debug("--> creating snapshot [{}]", snapshot); createSnapshot(client(), repository, snapshot, true); return; } if (isFullyUpgradedTo(VERSION_MINUS_1)) { ensureGreen(index); assertThat(indexVersion(index), equalTo(VERSION_MINUS_2)); assertDocCount(client(), index, numDocs); logger.debug("--> deleting index [{}]", index); deleteIndex(index); return; } if (isFullyUpgradedTo(VERSION_CURRENT)) { var mountedIndex = suffix("index-mounted"); logger.debug("--> mounting index [{}] as [{}]", index, mountedIndex); mountIndex(repository, snapshot, index, randomBoolean(), mountedIndex); ensureGreen(mountedIndex); assertThat(indexVersion(mountedIndex), equalTo(VERSION_MINUS_2)); assertDocCount(client(), mountedIndex, numDocs); updateRandomIndexSettings(mountedIndex); updateRandomMappings(mountedIndex); logger.debug("--> adding replica to test peer-recovery"); updateIndexSettings(mountedIndex, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1)); ensureGreen(mountedIndex); logger.debug("--> closing index [{}]", mountedIndex); closeIndex(mountedIndex); ensureGreen(mountedIndex); logger.debug("--> adding replica to test peer-recovery for closed shards"); updateIndexSettings(mountedIndex, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 2)); ensureGreen(mountedIndex); logger.debug("--> re-opening index [{}]", mountedIndex); openIndex(mountedIndex); ensureGreen(mountedIndex); assertDocCount(client(), mountedIndex, numDocs); logger.debug("--> deleting index [{}]", mountedIndex); deleteIndex(mountedIndex); } } /** * Creates an index and a snapshot on N-2, mounts the snapshot on N -1 and then upgrades to N. */ public void testSearchableSnapshotUpgrade() throws Exception { final String mountedIndex = suffix("index-mounted"); final String repository = suffix("repository"); final String snapshot = suffix("snapshot"); final String index = suffix("index"); final int numDocs = 4321; if (isFullyUpgradedTo(VERSION_MINUS_2)) { logger.debug("--> registering repository [{}]", repository); registerRepository(client(), repository, FsRepository.TYPE, true, repositorySettings()); logger.debug("--> creating index [{}]", index); createIndex( client(), index, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0).build() ); logger.debug("--> indexing [{}] docs in [{}]", numDocs, index); indexDocs(index, numDocs); logger.debug("--> creating snapshot [{}]", snapshot); createSnapshot(client(), repository, snapshot, true); logger.debug("--> deleting index [{}]", index); deleteIndex(index); return; } if (isFullyUpgradedTo(VERSION_MINUS_1)) { logger.debug("--> mounting index [{}] as [{}]", index, mountedIndex); mountIndex(repository, snapshot, index, randomBoolean(), mountedIndex); ensureGreen(mountedIndex); updateRandomIndexSettings(mountedIndex); updateRandomMappings(mountedIndex); assertThat(indexVersion(mountedIndex), equalTo(VERSION_MINUS_2)); assertDocCount(client(), mountedIndex, numDocs); if (randomBoolean()) { logger.debug("--> adding replica to test upgrade with replica"); updateIndexSettings(mountedIndex, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1)); ensureGreen(mountedIndex); } if (randomBoolean()) { logger.debug("--> random closing of index [{}] before upgrade", mountedIndex); closeIndex(mountedIndex); ensureGreen(mountedIndex); } return; } if (isFullyUpgradedTo(VERSION_CURRENT)) { ensureGreen(mountedIndex); if (isIndexClosed(mountedIndex)) { logger.debug("--> re-opening index [{}] after upgrade", mountedIndex); openIndex(mountedIndex); ensureGreen(mountedIndex); } assertThat(indexVersion(mountedIndex), equalTo(VERSION_MINUS_2)); assertDocCount(client(), mountedIndex, numDocs); updateRandomIndexSettings(mountedIndex); updateRandomMappings(mountedIndex); logger.debug("--> adding replica to test peer-recovery"); updateIndexSettings(mountedIndex, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 2)); ensureGreen(mountedIndex); } } }
FullClusterRestartSearchableSnapshotIndexCompatibilityIT
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/processor/ExecutableMethodProcessor.java
{ "start": 1453, "end": 1727 }
class ____ implements ExecutableMethodProcessor<Scheduled> { * }} * </pre> * NOTE: The processor will only be invoked for methods that needs to be processed at startup. * * @author Graeme Rocher * @since 1.0 */ @Indexed(ExecutableMethodProcessor.class) public
MyProcessor
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/ConstructorInjectionTestClassScopedExtensionContextNestedTests.java
{ "start": 3756, "end": 4246 }
class ____ { final String bar; final int answer; SpelConstructorParameterTests(@Autowired String bar, TestInfo testInfo, @Value("#{ 6 * 7 }") int answer) { this.bar = bar; this.answer = answer; } @Test void nestedTest() { assertThat(foo).isEqualTo("foo"); assertThat(bar).isEqualTo("bar"); assertThat(answer).isEqualTo(42); } } // ------------------------------------------------------------------------- @Configuration static
SpelConstructorParameterTests
java
alibaba__druid
core/src/test/java/com/alibaba/druid/pool/TestMySqlPing.java
{ "start": 807, "end": 1458 }
class ____ extends TestCase { public void test_ping() throws Exception { String url = "jdbc:mysql://a.b.c.d:3308/dragoon_v25_masterdb"; String user = "dragoon_admin"; String password = "dragoon_root"; Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection(url, user, password); ping(conn); conn.close(); } public void ping(Connection conn) throws Exception { System.out.println(conn.getClass()); Method method = conn.getClass().getMethod("pring"); method.invoke(conn); } }
TestMySqlPing
java
spring-projects__spring-boot
module/spring-boot-hibernate/src/main/java/org/springframework/boot/hibernate/autoconfigure/HibernateProperties.java
{ "start": 1639, "end": 4423 }
class ____ { private static final String DISABLED_SCANNER_CLASS = "org.hibernate.boot.archive.scan.internal.DisabledScanner"; private final Naming naming = new Naming(); /** * DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. * Defaults to "create-drop" when using an embedded database and no schema manager was * detected. Otherwise, defaults to "none". */ private @Nullable String ddlAuto; public @Nullable String getDdlAuto() { return this.ddlAuto; } public void setDdlAuto(@Nullable String ddlAuto) { this.ddlAuto = ddlAuto; } public Naming getNaming() { return this.naming; } /** * Determine the configuration properties for the initialization of the main Hibernate * EntityManagerFactory based on standard JPA properties and * {@link HibernateSettings}. * @param jpaProperties standard JPA properties * @param settings the settings to apply when determining the configuration properties * @return the Hibernate properties to use */ public Map<String, Object> determineHibernateProperties(Map<String, String> jpaProperties, HibernateSettings settings) { Assert.notNull(jpaProperties, "'jpaProperties' must not be null"); Assert.notNull(settings, "'settings' must not be null"); return getAdditionalProperties(jpaProperties, settings); } private Map<String, Object> getAdditionalProperties(Map<String, String> existing, HibernateSettings settings) { Map<String, Object> result = new HashMap<>(existing); applyScanner(result); getNaming().applyNamingStrategies(result); String ddlAuto = determineDdlAuto(existing, settings::getDdlAuto); if (StringUtils.hasText(ddlAuto) && !"none".equals(ddlAuto)) { result.put(SchemaToolingSettings.HBM2DDL_AUTO, ddlAuto); } else { result.remove(SchemaToolingSettings.HBM2DDL_AUTO); } Collection<HibernatePropertiesCustomizer> customizers = settings.getHibernatePropertiesCustomizers(); if (!ObjectUtils.isEmpty(customizers)) { customizers.forEach((customizer) -> customizer.customize(result)); } return result; } private void applyScanner(Map<String, Object> result) { if (!result.containsKey(PersistenceSettings.SCANNER) && ClassUtils.isPresent(DISABLED_SCANNER_CLASS, null)) { result.put(PersistenceSettings.SCANNER, DISABLED_SCANNER_CLASS); } } private @Nullable String determineDdlAuto(Map<String, String> existing, Supplier<@Nullable String> defaultDdlAuto) { String ddlAuto = existing.get(SchemaToolingSettings.HBM2DDL_AUTO); if (ddlAuto != null) { return ddlAuto; } if (this.ddlAuto != null) { return this.ddlAuto; } if (existing.get(SchemaToolingSettings.JAKARTA_HBM2DDL_DATABASE_ACTION) != null) { return null; } return defaultDdlAuto.get(); } public static
HibernateProperties
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameCache.java
{ "start": 1514, "end": 1605 }
class ____ be synchronized externally. * * @param <K> name to be added to the cache */
must
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/aot/InstanceSupplierCodeGenerator.java
{ "start": 4177, "end": 18699 }
class ____ of the bean to instantiate * @param generatedMethods the generated methods * @param allowDirectSupplierShortcut whether a direct supplier may be used rather * than always needing an {@link InstanceSupplier} */ public InstanceSupplierCodeGenerator(GenerationContext generationContext, ClassName className, GeneratedMethods generatedMethods, boolean allowDirectSupplierShortcut) { this.generationContext = generationContext; this.className = className; this.generatedMethods = generatedMethods; this.allowDirectSupplierShortcut = allowDirectSupplierShortcut; } /** * Generate the instance supplier code. * @param registeredBean the bean to handle * @param constructorOrFactoryMethod the executable to use to create the bean * @return the generated code * @deprecated in favor of {@link #generateCode(RegisteredBean, InstantiationDescriptor)} */ @Deprecated(since = "6.1.7") public CodeBlock generateCode(RegisteredBean registeredBean, Executable constructorOrFactoryMethod) { return generateCode(registeredBean, new InstantiationDescriptor( constructorOrFactoryMethod, constructorOrFactoryMethod.getDeclaringClass())); } /** * Generate the instance supplier code. * @param registeredBean the bean to handle * @param instantiationDescriptor the executable to use to create the bean * @return the generated code * @since 6.1.7 */ public CodeBlock generateCode(RegisteredBean registeredBean, InstantiationDescriptor instantiationDescriptor) { Executable constructorOrFactoryMethod = instantiationDescriptor.executable(); registerRuntimeHintsIfNecessary(registeredBean, constructorOrFactoryMethod); if (constructorOrFactoryMethod instanceof Constructor<?> constructor) { return generateCodeForConstructor(registeredBean, constructor); } if (constructorOrFactoryMethod instanceof Method method && !KotlinDetector.isSuspendingFunction(method)) { return generateCodeForFactoryMethod(registeredBean, method, instantiationDescriptor.targetClass()); } throw new AotBeanProcessingException(registeredBean, "no suitable constructor or factory method found"); } private void registerRuntimeHintsIfNecessary(RegisteredBean registeredBean, Executable constructorOrFactoryMethod) { if (registeredBean.getBeanFactory() instanceof DefaultListableBeanFactory dlbf) { RuntimeHints runtimeHints = this.generationContext.getRuntimeHints(); ProxyRuntimeHintsRegistrar registrar = new ProxyRuntimeHintsRegistrar(dlbf.getAutowireCandidateResolver()); registrar.registerRuntimeHints(runtimeHints, constructorOrFactoryMethod); } } private CodeBlock generateCodeForConstructor(RegisteredBean registeredBean, Constructor<?> constructor) { ConstructorDescriptor descriptor = new ConstructorDescriptor( registeredBean.getBeanName(), constructor, registeredBean.getBeanClass()); Class<?> publicType = descriptor.publicType(); if (KOTLIN_REFLECT_PRESENT && KotlinDetector.isKotlinType(publicType) && KotlinDelegate.hasConstructorWithOptionalParameter(publicType)) { return generateCodeForInaccessibleConstructor(descriptor, hints -> hints.registerType(publicType, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)); } if (!isVisible(constructor, constructor.getDeclaringClass()) || registeredBean.getMergedBeanDefinition().hasMethodOverrides()) { return generateCodeForInaccessibleConstructor(descriptor, hints -> hints.registerConstructor(constructor, ExecutableMode.INVOKE)); } return generateCodeForAccessibleConstructor(descriptor); } private CodeBlock generateCodeForAccessibleConstructor(ConstructorDescriptor descriptor) { Constructor<?> constructor = descriptor.constructor(); this.generationContext.getRuntimeHints().reflection().registerType(constructor.getDeclaringClass()); if (constructor.getParameterCount() == 0) { if (!this.allowDirectSupplierShortcut) { return CodeBlock.of("$T.using($T::new)", InstanceSupplier.class, descriptor.actualType()); } if (!isThrowingCheckedException(constructor)) { return CodeBlock.of("$T::new", descriptor.actualType()); } return CodeBlock.of("$T.of($T::new)", ThrowingSupplier.class, descriptor.actualType()); } GeneratedMethod generatedMethod = generateGetInstanceSupplierMethod(method -> buildGetInstanceMethodForConstructor(method, descriptor, PRIVATE_STATIC)); return generateReturnStatement(generatedMethod); } private CodeBlock generateCodeForInaccessibleConstructor(ConstructorDescriptor descriptor, Consumer<ReflectionHints> hints) { Constructor<?> constructor = descriptor.constructor(); CodeWarnings codeWarnings = new CodeWarnings(); codeWarnings.detectDeprecation(constructor.getDeclaringClass(), constructor) .detectDeprecation(Arrays.stream(constructor.getParameters()).map(Parameter::getType)); hints.accept(this.generationContext.getRuntimeHints().reflection()); GeneratedMethod generatedMethod = generateGetInstanceSupplierMethod(method -> { method.addJavadoc("Get the bean instance supplier for '$L'.", descriptor.beanName()); method.addModifiers(PRIVATE_STATIC); codeWarnings.suppress(method); method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, descriptor.publicType())); method.addStatement(generateResolverForConstructor(descriptor)); }); return generateReturnStatement(generatedMethod); } private void buildGetInstanceMethodForConstructor(MethodSpec.Builder method, ConstructorDescriptor descriptor, javax.lang.model.element.Modifier... modifiers) { Constructor<?> constructor = descriptor.constructor(); Class<?> publicType = descriptor.publicType(); Class<?> actualType = descriptor.actualType(); CodeWarnings codeWarnings = new CodeWarnings(); codeWarnings.detectDeprecation(actualType, constructor) .detectDeprecation(Arrays.stream(constructor.getParameters()).map(Parameter::getType)); method.addJavadoc("Get the bean instance supplier for '$L'.", descriptor.beanName()); method.addModifiers(modifiers); codeWarnings.suppress(method); method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, publicType)); CodeBlock.Builder code = CodeBlock.builder(); code.add(generateResolverForConstructor(descriptor)); boolean hasArguments = constructor.getParameterCount() > 0; boolean onInnerClass = ClassUtils.isInnerClass(actualType); CodeBlock arguments = hasArguments ? new AutowiredArgumentsCodeGenerator(actualType, constructor) .generateCode(constructor.getParameterTypes(), (onInnerClass ? 1 : 0)) : NO_ARGS; CodeBlock newInstance = generateNewInstanceCodeForConstructor(actualType, arguments); code.add(generateWithGeneratorCode(hasArguments, newInstance)); method.addStatement(code.build()); } private CodeBlock generateResolverForConstructor(ConstructorDescriptor descriptor) { CodeBlock parameterTypes = generateParameterTypesCode(descriptor.constructor().getParameterTypes()); return CodeBlock.of("return $T.<$T>forConstructor($L)", BeanInstanceSupplier.class, descriptor.publicType(), parameterTypes); } private CodeBlock generateNewInstanceCodeForConstructor(Class<?> declaringClass, CodeBlock args) { if (ClassUtils.isInnerClass(declaringClass)) { return CodeBlock.of("$L.getBeanFactory().getBean($T.class).new $L($L)", REGISTERED_BEAN_PARAMETER_NAME, declaringClass.getEnclosingClass(), declaringClass.getSimpleName(), args); } return CodeBlock.of("new $T($L)", declaringClass, args); } private CodeBlock generateCodeForFactoryMethod( RegisteredBean registeredBean, Method factoryMethod, Class<?> targetClass) { if (!isVisible(factoryMethod, targetClass)) { return generateCodeForInaccessibleFactoryMethod(registeredBean.getBeanName(), factoryMethod, targetClass); } return generateCodeForAccessibleFactoryMethod(registeredBean.getBeanName(), factoryMethod, targetClass, registeredBean.getMergedBeanDefinition().getFactoryBeanName()); } private CodeBlock generateCodeForAccessibleFactoryMethod(String beanName, Method factoryMethod, Class<?> targetClass, @Nullable String factoryBeanName) { this.generationContext.getRuntimeHints().reflection().registerType(factoryMethod.getDeclaringClass()); if (factoryBeanName == null && factoryMethod.getParameterCount() == 0) { Class<?> suppliedType = ClassUtils.resolvePrimitiveIfNecessary(factoryMethod.getReturnType()); CodeBlock.Builder code = CodeBlock.builder(); code.add("$T.<$T>forFactoryMethod($T.class, $S)", BeanInstanceSupplier.class, suppliedType, targetClass, factoryMethod.getName()); code.add(".withGenerator(($L) -> $T.$L())", REGISTERED_BEAN_PARAMETER_NAME, ClassUtils.getUserClass(targetClass), factoryMethod.getName()); return code.build(); } GeneratedMethod getInstanceMethod = generateGetInstanceSupplierMethod(method -> buildGetInstanceMethodForFactoryMethod(method, beanName, factoryMethod, targetClass, factoryBeanName, PRIVATE_STATIC)); return generateReturnStatement(getInstanceMethod); } private CodeBlock generateCodeForInaccessibleFactoryMethod( String beanName, Method factoryMethod, Class<?> targetClass) { this.generationContext.getRuntimeHints().reflection().registerMethod(factoryMethod, ExecutableMode.INVOKE); GeneratedMethod getInstanceMethod = generateGetInstanceSupplierMethod(method -> { CodeWarnings codeWarnings = new CodeWarnings(); Class<?> suppliedType = ClassUtils.resolvePrimitiveIfNecessary(factoryMethod.getReturnType()); codeWarnings.detectDeprecation(suppliedType, factoryMethod); method.addJavadoc("Get the bean instance supplier for '$L'.", beanName); method.addModifiers(PRIVATE_STATIC); codeWarnings.suppress(method); method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, suppliedType)); method.addStatement(generateInstanceSupplierForFactoryMethod( factoryMethod, suppliedType, targetClass, factoryMethod.getName())); }); return generateReturnStatement(getInstanceMethod); } private void buildGetInstanceMethodForFactoryMethod(MethodSpec.Builder method, String beanName, Method factoryMethod, Class<?> targetClass, @Nullable String factoryBeanName, javax.lang.model.element.Modifier... modifiers) { String factoryMethodName = factoryMethod.getName(); Class<?> suppliedType = ClassUtils.resolvePrimitiveIfNecessary(factoryMethod.getReturnType()); CodeWarnings codeWarnings = new CodeWarnings(); codeWarnings.detectDeprecation(ClassUtils.getUserClass(targetClass), factoryMethod, suppliedType) .detectDeprecation(Arrays.stream(factoryMethod.getParameters()).map(Parameter::getType)); method.addJavadoc("Get the bean instance supplier for '$L'.", beanName); method.addModifiers(modifiers); codeWarnings.suppress(method); method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, suppliedType)); CodeBlock.Builder code = CodeBlock.builder(); code.add(generateInstanceSupplierForFactoryMethod( factoryMethod, suppliedType, targetClass, factoryMethodName)); boolean hasArguments = factoryMethod.getParameterCount() > 0; CodeBlock arguments = hasArguments ? new AutowiredArgumentsCodeGenerator(ClassUtils.getUserClass(targetClass), factoryMethod) .generateCode(factoryMethod.getParameterTypes()) : NO_ARGS; CodeBlock newInstance = generateNewInstanceCodeForMethod( factoryBeanName, ClassUtils.getUserClass(targetClass), factoryMethodName, arguments); code.add(generateWithGeneratorCode(hasArguments, newInstance)); method.addStatement(code.build()); } private CodeBlock generateInstanceSupplierForFactoryMethod(Method factoryMethod, Class<?> suppliedType, Class<?> targetClass, String factoryMethodName) { if (factoryMethod.getParameterCount() == 0) { return CodeBlock.of("return $T.<$T>forFactoryMethod($T.class, $S)", BeanInstanceSupplier.class, suppliedType, targetClass, factoryMethodName); } CodeBlock parameterTypes = generateParameterTypesCode(factoryMethod.getParameterTypes()); return CodeBlock.of("return $T.<$T>forFactoryMethod($T.class, $S, $L)", BeanInstanceSupplier.class, suppliedType, targetClass, factoryMethodName, parameterTypes); } private CodeBlock generateNewInstanceCodeForMethod(@Nullable String factoryBeanName, Class<?> targetClass, String factoryMethodName, CodeBlock args) { if (factoryBeanName == null) { return CodeBlock.of("$T.$L($L)", targetClass, factoryMethodName, args); } return CodeBlock.of("$L.getBeanFactory().getBean(\"$L\", $T.class).$L($L)", REGISTERED_BEAN_PARAMETER_NAME, factoryBeanName, targetClass, factoryMethodName, args); } private CodeBlock generateReturnStatement(GeneratedMethod generatedMethod) { return generatedMethod.toMethodReference().toInvokeCodeBlock( ArgumentCodeGenerator.none(), this.className); } private CodeBlock generateWithGeneratorCode(boolean hasArguments, CodeBlock newInstance) { CodeBlock lambdaArguments = (hasArguments ? CodeBlock.of("($L, $L)", REGISTERED_BEAN_PARAMETER_NAME, ARGS_PARAMETER_NAME) : CodeBlock.of("($L)", REGISTERED_BEAN_PARAMETER_NAME)); Builder code = CodeBlock.builder(); code.add("\n"); code.indent().indent(); code.add(".withGenerator($L -> $L)", lambdaArguments, newInstance); code.unindent().unindent(); return code.build(); } private boolean isVisible(Member member, Class<?> targetClass) { AccessControl classAccessControl = AccessControl.forClass(targetClass); AccessControl memberAccessControl = AccessControl.forMember(member); Visibility visibility = AccessControl.lowest(classAccessControl, memberAccessControl).getVisibility(); return (visibility == Visibility.PUBLIC || (visibility != Visibility.PRIVATE && member.getDeclaringClass().getPackageName().equals(this.className.packageName()))); } private CodeBlock generateParameterTypesCode(Class<?>[] parameterTypes) { CodeBlock.Builder code = CodeBlock.builder(); for (int i = 0; i < parameterTypes.length; i++) { code.add(i > 0 ? ", " : ""); code.add("$T.class", parameterTypes[i]); } return code.build(); } private GeneratedMethod generateGetInstanceSupplierMethod(Consumer<MethodSpec.Builder> method) { return this.generatedMethods.add("getInstanceSupplier", method); } private boolean isThrowingCheckedException(Executable executable) { return Arrays.stream(executable.getGenericExceptionTypes()) .map(ResolvableType::forType) .map(ResolvableType::toClass) .anyMatch(Exception.class::isAssignableFrom); } /** * Inner
name
java
quarkusio__quarkus
extensions/security-jpa-reactive/deployment/src/test/java/io/quarkus/security/jpa/reactive/NaturalIdConfigurationTest.java
{ "start": 150, "end": 635 }
class ____ extends JpaSecurityRealmTest { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(testClasses) .addClass(NaturalIdUserEntity.class) .addAsResource("minimal-config/import.sql", "import.sql") .addAsResource("minimal-config/application.properties", "application.properties")); }
NaturalIdConfigurationTest
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanInstanceSupplierTests.java
{ "start": 3649, "end": 30837 }
class ____ { private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); @Test void forConstructorWhenParameterTypesIsNullThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> BeanInstanceSupplier.forConstructor((Class<?>[]) null)) .withMessage("'parameterTypes' must not be null"); } @Test void forConstructorWhenParameterTypesContainsNullThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> BeanInstanceSupplier.forConstructor(String.class, null)) .withMessage("'parameterTypes' must not contain null elements"); } @Test void forConstructorWhenNotFoundThrowsException() { BeanInstanceSupplier<InputStream> resolver = BeanInstanceSupplier.forConstructor(InputStream.class); Source source = new Source(SingleArgConstructor.class, resolver); RegisteredBean registerBean = source.registerBean(this.beanFactory); assertThatIllegalArgumentException() .isThrownBy(() -> resolver.get(registerBean)).withMessage( "Constructor with parameter types [java.io.InputStream] cannot be found on " + SingleArgConstructor.class.getName()); } @Test void forConstructorReturnsNullFactoryMethod() { BeanInstanceSupplier<Object> resolver = BeanInstanceSupplier.forConstructor(String.class); assertThat(resolver.getFactoryMethod()).isNull(); } @Test void forFactoryMethodWhenDeclaringClassIsNullThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> BeanInstanceSupplier.forFactoryMethod(null, "test")) .withMessage("'declaringClass' must not be null"); } @Test void forFactoryMethodWhenNameIsEmptyThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> BeanInstanceSupplier.forFactoryMethod(SingleArgFactory.class, "")) .withMessage("'methodName' must not be empty"); } @Test void forFactoryMethodWhenParameterTypesIsNullThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> BeanInstanceSupplier.forFactoryMethod( SingleArgFactory.class, "single", (Class<?>[]) null)) .withMessage("'parameterTypes' must not be null"); } @Test void forFactoryMethodWhenParameterTypesContainsNullThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> BeanInstanceSupplier.forFactoryMethod( SingleArgFactory.class, "single", String.class, null)) .withMessage("'parameterTypes' must not contain null elements"); } @Test void forFactoryMethodWhenNotFoundThrowsException() { BeanInstanceSupplier<InputStream> resolver = BeanInstanceSupplier.forFactoryMethod( SingleArgFactory.class, "single", InputStream.class); Source source = new Source(String.class, resolver); RegisteredBean registerBean = source.registerBean(this.beanFactory); assertThatIllegalArgumentException() .isThrownBy(() -> resolver.get(registerBean)).withMessage( "Factory method 'single' with parameter types [java.io.InputStream] declared on class " + SingleArgFactory.class.getName() + " cannot be found"); } @Test void forFactoryMethodReturnsFactoryMethod() { BeanInstanceSupplier<String> resolver = BeanInstanceSupplier.forFactoryMethod( SingleArgFactory.class, "single", String.class); Method factoryMethod = ReflectionUtils.findMethod(SingleArgFactory.class, "single", String.class); assertThat(factoryMethod).isNotNull(); assertThat(resolver.getFactoryMethod()).isEqualTo(factoryMethod); } @Test void withGeneratorWhenBiFunctionIsNullThrowsException() { BeanInstanceSupplier<Object> resolver = BeanInstanceSupplier.forConstructor(); assertThatIllegalArgumentException() .isThrownBy(() -> resolver.withGenerator((ThrowingBiFunction<RegisteredBean, AutowiredArguments, Object>) null)) .withMessage("'generator' must not be null"); } @Test void withGeneratorWhenFunctionIsNullThrowsException() { BeanInstanceSupplier<Object> resolver = BeanInstanceSupplier.forConstructor(); assertThatIllegalArgumentException() .isThrownBy(() -> resolver.withGenerator((ThrowingFunction<RegisteredBean, Object>) null)) .withMessage("'generator' must not be null"); } @Test void getWithConstructorDoesNotSetResolvedFactoryMethod() { BeanInstanceSupplier<SingleArgConstructor> resolver = BeanInstanceSupplier.forConstructor(String.class); this.beanFactory.registerSingleton("one", "1"); Source source = new Source(SingleArgConstructor.class, resolver); RegisteredBean registerBean = source.registerBean(this.beanFactory); assertThat(registerBean.getMergedBeanDefinition().getResolvedFactoryMethod()).isNull(); source.getSupplier().get(registerBean); assertThat(registerBean.getMergedBeanDefinition().getResolvedFactoryMethod()).isNull(); } @Test void getWithFactoryMethodSetsResolvedFactoryMethod() { Method factoryMethod = ReflectionUtils.findMethod(SingleArgFactory.class, "single", String.class); assertThat(factoryMethod).isNotNull(); BeanInstanceSupplier<String> resolver = BeanInstanceSupplier .forFactoryMethod(SingleArgFactory.class, "single", String.class); RootBeanDefinition bd = new RootBeanDefinition(String.class); assertThat(bd.getResolvedFactoryMethod()).isNull(); bd.setInstanceSupplier(resolver); assertThat(bd.getResolvedFactoryMethod()).isEqualTo(factoryMethod); } @Test void getWithGeneratorCallsBiFunction() { BeanRegistrar registrar = new BeanRegistrar(SingleArgConstructor.class); this.beanFactory.registerSingleton("one", "1"); RegisteredBean registerBean = registrar.registerBean(this.beanFactory); List<Object> result = new ArrayList<>(); BeanInstanceSupplier<Object> resolver = BeanInstanceSupplier.forConstructor(String.class) .withGenerator((registeredBean, args) -> result.add(args)); resolver.get(registerBean); assertThat(result).hasSize(1); assertThat(((AutowiredArguments) result.get(0)).toArray()).containsExactly("1"); } @Test void getWithGeneratorCallsFunction() { BeanRegistrar registrar = new BeanRegistrar(SingleArgConstructor.class); this.beanFactory.registerSingleton("one", "1"); RegisteredBean registerBean = registrar.registerBean(this.beanFactory); BeanInstanceSupplier<String> resolver = BeanInstanceSupplier.<String>forConstructor(String.class) .withGenerator(registeredBean -> "1"); assertThat(resolver.get(registerBean)).isInstanceOf(String.class).isEqualTo("1"); } @Test void getWhenRegisteredBeanIsNullThrowsException() { BeanInstanceSupplier<Object> resolver = BeanInstanceSupplier.forConstructor(String.class); assertThatIllegalArgumentException().isThrownBy(() -> resolver.get((RegisteredBean) null)) .withMessage("'registeredBean' must not be null"); } @ParameterizedResolverTest(Sources.SINGLE_ARG) void getWithNoGeneratorUsesReflection(Source source) { this.beanFactory.registerSingleton("one", "1"); this.beanFactory.registerSingleton("testFactory", new SingleArgFactory()); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> bd.setFactoryBeanName("testFactory")); Object instance = source.getSupplier().get(registerBean); if (instance instanceof SingleArgConstructor singleArgConstructor) { instance = singleArgConstructor.getString(); } assertThat(instance).isEqualTo("1"); } @ParameterizedResolverTest(Sources.INNER_CLASS_SINGLE_ARG) void getNestedWithNoGeneratorUsesReflection(Source source) { this.beanFactory.registerSingleton("one", "1"); this.beanFactory.registerSingleton("testFactory", new Enclosing.InnerSingleArgFactory()); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> bd.setFactoryBeanName("testFactory")); Object instance = source.getSupplier().get(registerBean); if (instance instanceof InnerSingleArgConstructor innerSingleArgConstructor) { instance = innerSingleArgConstructor.getString(); } assertThat(instance).isEqualTo("1"); } @Test // gh-33180 void getWithNestedInvocationRetainsFactoryMethod() { AtomicReference<Method> testMethodReference = new AtomicReference<>(); AtomicReference<Method> anotherMethodReference = new AtomicReference<>(); Enhancer enhancer = new Enhancer(); enhancer.setCallbackType(NoOp.class); enhancer.setSuperclass(AnotherTestStringFactory.class); Class<?> nestedSupplierClass = enhancer.createClass(); enhancer.setSuperclass(TestStringFactory.class); Class<?> supplierClass = enhancer.createClass(); BeanInstanceSupplier<Object> nestedInstanceSupplier = BeanInstanceSupplier .forFactoryMethod(nestedSupplierClass, "another") .withGenerator(registeredBean -> { anotherMethodReference.set(SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod()); return "Another"; }); RegisteredBean nestedRegisteredBean = new Source(String.class, nestedInstanceSupplier).registerBean(this.beanFactory); BeanInstanceSupplier<Object> instanceSupplier = BeanInstanceSupplier .forFactoryMethod(supplierClass, "test") .withGenerator(registeredBean -> { Object nested = nestedInstanceSupplier.get(nestedRegisteredBean); testMethodReference.set(SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod()); return "custom" + nested; }); RegisteredBean registeredBean = new Source(String.class, instanceSupplier).registerBean(this.beanFactory); Object value = instanceSupplier.get(registeredBean); assertThat(value).isEqualTo("customAnother"); assertThat(testMethodReference.get()).isEqualTo(instanceSupplier.getFactoryMethod()); assertThat(anotherMethodReference.get()).isEqualTo(nestedInstanceSupplier.getFactoryMethod()); } @Test void resolveArgumentsWithNoArgConstructor() { RootBeanDefinition bd = new RootBeanDefinition(NoArgConstructor.class); this.beanFactory.registerBeanDefinition("test", bd); RegisteredBean registeredBean = RegisteredBean.of(this.beanFactory, "test"); AutowiredArguments resolved = BeanInstanceSupplier.forConstructor().resolveArguments(registeredBean); assertThat(resolved.toArray()).isEmpty(); } @ParameterizedResolverTest(Sources.SINGLE_ARG) void resolveArgumentsWithSingleArgConstructor(Source source) { this.beanFactory.registerSingleton("one", "1"); RegisteredBean registeredBean = source.registerBean(this.beanFactory); assertThat(source.getSupplier().resolveArguments(registeredBean).toArray()) .containsExactly("1"); } @ParameterizedResolverTest(Sources.INNER_CLASS_SINGLE_ARG) void resolveArgumentsWithNestedSingleArgConstructor(Source source) { this.beanFactory.registerSingleton("one", "1"); RegisteredBean registeredBean = source.registerBean(this.beanFactory); assertThat(source.getSupplier().resolveArguments(registeredBean).toArray()) .containsExactly("1"); } @ParameterizedResolverTest(Sources.SINGLE_ARG) void resolveArgumentsWithRequiredDependencyNotPresentThrowsUnsatisfiedDependencyException(Source source) { RegisteredBean registeredBean = source.registerBean(this.beanFactory); assertThatExceptionOfType(UnsatisfiedDependencyException.class) .isThrownBy(() -> source.getSupplier().resolveArguments(registeredBean)) .satisfies(ex -> { assertThat(ex.getBeanName()).isEqualTo("testBean"); assertThat(ex.getInjectionPoint()).isNotNull(); assertThat(ex.getInjectionPoint().getMember()) .isEqualTo(source.lookupExecutable(registeredBean)); }); } @Test void resolveArgumentsInInstanceSupplierWithSelfReferenceThrowsException() { // SingleArgFactory.single(...) expects a String to be injected // and our own bean is a String, so it's a valid candidate this.beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor()); RootBeanDefinition bd = new RootBeanDefinition(String.class); bd.setInstanceSupplier(InstanceSupplier.of(registeredBean -> { AutowiredArguments args = BeanInstanceSupplier .forFactoryMethod(SingleArgFactory.class, "single", String.class) .resolveArguments(registeredBean); return new SingleArgFactory().single(args.get(0)); })); this.beanFactory.registerBeanDefinition("test", bd); assertThatExceptionOfType(UnsatisfiedDependencyException.class) .isThrownBy(() -> this.beanFactory.getBean("test")); } @ParameterizedResolverTest(Sources.ARRAY_OF_BEANS) void resolveArgumentsWithArrayOfBeans(Source source) { this.beanFactory.registerSingleton("one", "1"); this.beanFactory.registerSingleton("two", "2"); RegisteredBean registerBean = source.registerBean(this.beanFactory); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat((Object[]) arguments.get(0)).containsExactly("1", "2"); } @ParameterizedResolverTest(Sources.ARRAY_OF_BEANS) void resolveArgumentsWithRequiredArrayOfBeansInjectEmptyArray(Source source) { RegisteredBean registerBean = source.registerBean(this.beanFactory); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat((Object[]) arguments.get(0)).isEmpty(); } @ParameterizedResolverTest(Sources.LIST_OF_BEANS) void resolveArgumentsWithListOfBeans(Source source) { this.beanFactory.registerSingleton("one", "1"); this.beanFactory.registerSingleton("two", "2"); RegisteredBean registerBean = source.registerBean(this.beanFactory); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat(arguments.getObject(0)).isInstanceOf(List.class).asInstanceOf(LIST) .containsExactly("1", "2"); } @ParameterizedResolverTest(Sources.LIST_OF_BEANS) void resolveArgumentsWithRequiredListOfBeansInjectEmptyList(Source source) { RegisteredBean registerBean = source.registerBean(this.beanFactory); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat((List<?>) arguments.get(0)).isEmpty(); } @ParameterizedResolverTest(Sources.SET_OF_BEANS) @SuppressWarnings("unchecked") void resolveArgumentsWithSetOfBeans(Source source) { this.beanFactory.registerSingleton("one", "1"); this.beanFactory.registerSingleton("two", "2"); RegisteredBean registerBean = source.registerBean(this.beanFactory); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat((Set<String>) arguments.get(0)).containsExactly("1", "2"); } @ParameterizedResolverTest(Sources.SET_OF_BEANS) void resolveArgumentsWithRequiredSetOfBeansInjectEmptySet(Source source) { RegisteredBean registerBean = source.registerBean(this.beanFactory); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat((Set<?>) arguments.get(0)).isEmpty(); } @ParameterizedResolverTest(Sources.MAP_OF_BEANS) @SuppressWarnings("unchecked") void resolveArgumentsWithMapOfBeans(Source source) { this.beanFactory.registerSingleton("one", "1"); this.beanFactory.registerSingleton("two", "2"); RegisteredBean registerBean = source.registerBean(this.beanFactory); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat((Map<String, String>) arguments.get(0)) .containsExactly(entry("one", "1"), entry("two", "2")); } @ParameterizedResolverTest(Sources.MAP_OF_BEANS) void resolveArgumentsWithRequiredMapOfBeansInjectEmptySet(Source source) { RegisteredBean registerBean = source.registerBean(this.beanFactory); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat((Map<?, ?>) arguments.get(0)).isEmpty(); } @ParameterizedResolverTest(Sources.MULTI_ARGS) void resolveArgumentsWithMultiArgsConstructor(Source source) { ResourceLoader resourceLoader = new DefaultResourceLoader(); Environment environment = mock(); this.beanFactory.registerResolvableDependency(ResourceLoader.class, resourceLoader); this.beanFactory.registerSingleton("environment", environment); this.beanFactory.registerSingleton("one", "1"); RegisteredBean registerBean = source.registerBean(this.beanFactory); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(3); assertThat(arguments.getObject(0)).isEqualTo(resourceLoader); assertThat(arguments.getObject(1)).isEqualTo(environment); assertThat(((ObjectProvider<?>) arguments.get(2)).getIfAvailable()).isEqualTo("1"); } @ParameterizedResolverTest(Sources.MIXED_ARGS) void resolveArgumentsWithMixedArgsConstructorWithIndexedUserValue(Source source) { ResourceLoader resourceLoader = new DefaultResourceLoader(); Environment environment = mock(); this.beanFactory.registerResolvableDependency(ResourceLoader.class, resourceLoader); this.beanFactory.registerSingleton("environment", environment); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> { bd.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); bd.getConstructorArgumentValues().addIndexedArgumentValue(1, "user-value"); }); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(3); assertThat(arguments.getObject(0)).isEqualTo(resourceLoader); assertThat(arguments.getObject(1)).isEqualTo("user-value"); assertThat(arguments.getObject(2)).isEqualTo(environment); } @ParameterizedResolverTest(Sources.MIXED_ARGS) void resolveArgumentsWithMixedArgsConstructorWithGenericUserValue(Source source) { ResourceLoader resourceLoader = new DefaultResourceLoader(); Environment environment = mock(); this.beanFactory.registerResolvableDependency(ResourceLoader.class, resourceLoader); this.beanFactory.registerSingleton("environment", environment); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> { bd.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); bd.getConstructorArgumentValues().addGenericArgumentValue("user-value"); }); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(3); assertThat(arguments.getObject(0)).isEqualTo(resourceLoader); assertThat(arguments.getObject(1)).isEqualTo("user-value"); assertThat(arguments.getObject(2)).isEqualTo(environment); } @ParameterizedResolverTest(Sources.MIXED_ARGS) void resolveArgumentsWithMixedArgsConstructorAndIndexedUserBeanReference(Source source) { ResourceLoader resourceLoader = new DefaultResourceLoader(); Environment environment = mock(); this.beanFactory.registerResolvableDependency(ResourceLoader.class, resourceLoader); this.beanFactory.registerSingleton("environment", environment); this.beanFactory.registerSingleton("one", "1"); this.beanFactory.registerSingleton("two", "2"); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> { bd.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); bd.getConstructorArgumentValues().addIndexedArgumentValue( 1, new RuntimeBeanReference("two")); }); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(3); assertThat(arguments.getObject(0)).isEqualTo(resourceLoader); assertThat(arguments.getObject(1)).isEqualTo("2"); assertThat(arguments.getObject(2)).isEqualTo(environment); } @ParameterizedResolverTest(Sources.MIXED_ARGS) void resolveArgumentsWithMixedArgsConstructorAndGenericUserBeanReference(Source source) { ResourceLoader resourceLoader = new DefaultResourceLoader(); Environment environment = mock(); this.beanFactory.registerResolvableDependency(ResourceLoader.class, resourceLoader); this.beanFactory.registerSingleton("environment", environment); this.beanFactory.registerSingleton("one", "1"); this.beanFactory.registerSingleton("two", "2"); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> { bd.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); bd.getConstructorArgumentValues().addGenericArgumentValue(new RuntimeBeanReference("two")); }); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(3); assertThat(arguments.getObject(0)).isEqualTo(resourceLoader); assertThat(arguments.getObject(1)).isEqualTo("2"); assertThat(arguments.getObject(2)).isEqualTo(environment); } @Test void resolveIndexedArgumentsWithUserValueWithTypeConversionRequired() { Source source = new Source(CharDependency.class, BeanInstanceSupplier.forConstructor(char.class)); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> { bd.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); bd.getConstructorArgumentValues().addIndexedArgumentValue(0, "\\"); }); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat(arguments.getObject(0)).isInstanceOf(Character.class).isEqualTo('\\'); } @Test void resolveGenericArgumentsWithUserValueWithTypeConversionRequired() { Source source = new Source(CharDependency.class, BeanInstanceSupplier.forConstructor(char.class)); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> { bd.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); bd.getConstructorArgumentValues().addGenericArgumentValue("\\", char.class.getName()); }); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat(arguments.getObject(0)).isInstanceOf(Character.class).isEqualTo('\\'); } @ParameterizedResolverTest(Sources.SINGLE_ARG) void resolveIndexedArgumentsWithUserValueWithBeanReference(Source source) { this.beanFactory.registerSingleton("stringBean", "string"); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> bd.getConstructorArgumentValues() .addIndexedArgumentValue(0, new RuntimeBeanReference("stringBean"))); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat(arguments.getObject(0)).isEqualTo("string"); } @ParameterizedResolverTest(Sources.SINGLE_ARG) void resolveGenericArgumentsWithUserValueWithBeanReference(Source source) { this.beanFactory.registerSingleton("stringBean", "string"); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> bd.getConstructorArgumentValues() .addGenericArgumentValue(new RuntimeBeanReference("stringBean"))); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat(arguments.getObject(0)).isEqualTo("string"); } @ParameterizedResolverTest(Sources.SINGLE_ARG) void resolveIndexedArgumentsWithUserValueWithBeanDefinition(Source source) { AbstractBeanDefinition userValue = BeanDefinitionBuilder.rootBeanDefinition( String.class, () -> "string").getBeanDefinition(); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> bd.getConstructorArgumentValues().addIndexedArgumentValue(0, userValue)); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat(arguments.getObject(0)).isEqualTo("string"); } @ParameterizedResolverTest(Sources.SINGLE_ARG) void resolveGenericArgumentsWithUserValueWithBeanDefinition(Source source) { AbstractBeanDefinition userValue = BeanDefinitionBuilder.rootBeanDefinition( String.class, () -> "string").getBeanDefinition(); RegisteredBean registerBean = source.registerBean(this.beanFactory, bd -> bd.getConstructorArgumentValues().addGenericArgumentValue(userValue)); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat(arguments.getObject(0)).isEqualTo("string"); } @ParameterizedResolverTest(Sources.SINGLE_ARG) void resolveIndexedArgumentsWithUserValueThatIsAlreadyResolved(Source source) { RegisteredBean registerBean = source.registerBean(this.beanFactory); BeanDefinition mergedBeanDefinition = this.beanFactory.getMergedBeanDefinition("testBean"); ValueHolder valueHolder = new ValueHolder("a"); valueHolder.setConvertedValue("this is an a"); mergedBeanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, valueHolder); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat(arguments.getObject(0)).isEqualTo("this is an a"); } @ParameterizedResolverTest(Sources.SINGLE_ARG) void resolveGenericArgumentsWithUserValueThatIsAlreadyResolved(Source source) { RegisteredBean registerBean = source.registerBean(this.beanFactory); BeanDefinition mergedBeanDefinition = this.beanFactory.getMergedBeanDefinition("testBean"); ValueHolder valueHolder = new ValueHolder("a"); valueHolder.setConvertedValue("this is an a"); mergedBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(valueHolder); AutowiredArguments arguments = source.getSupplier().resolveArguments(registerBean); assertThat(arguments.toArray()).hasSize(1); assertThat(arguments.getObject(0)).isEqualTo("this is an a"); } @Test void resolveArgumentsWhenUsingShortcutsInjectsDirectly() { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory() { @Override protected Map<String, Object> findAutowireCandidates(String beanName, Class<?> requiredType, DependencyDescriptor descriptor) { throw new AssertionError("Should be shortcut"); } }; BeanInstanceSupplier<Object> resolver = BeanInstanceSupplier.forConstructor(String.class); Source source = new Source(String.class, resolver); beanFactory.registerSingleton("one", "1"); RegisteredBean registeredBean = source.registerBean(beanFactory); assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> resolver.resolveArguments(registeredBean)); assertThat(resolver.withShortcut("one").resolveArguments(registeredBean).toArray()) .containsExactly("1"); } @Test void resolveArgumentsRegistersDependantBeans() { BeanInstanceSupplier<Object> resolver = BeanInstanceSupplier.forConstructor(String.class); Source source = new Source(SingleArgConstructor.class, resolver); this.beanFactory.registerSingleton("one", "1"); RegisteredBean registeredBean = source.registerBean(this.beanFactory); resolver.resolveArguments(registeredBean); assertThat(this.beanFactory.getDependentBeans("one")).containsExactly("testBean"); } /** * Parameterized test backed by a {@link Sources}. */ @Retention(RetentionPolicy.RUNTIME) @ParameterizedTest @ArgumentsSource(SourcesArguments.class) @
BeanInstanceSupplierTests
java
quarkusio__quarkus
extensions/websockets-next/runtime/src/main/java/io/quarkus/websockets/next/runtime/WebSocketEndpoint.java
{ "start": 2074, "end": 2296 }
enum ____ { WORKER_THREAD, VIRTUAL_THREAD, EVENT_LOOP, NONE; boolean isBlocking() { return this == WORKER_THREAD || this == VIRTUAL_THREAD; } } }
ExecutionModel
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_44_with_cte.java
{ "start": 924, "end": 4061 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "WITH RECURSIVE cte AS\n" + "(\n" + " SELECT 1 AS n, 1 AS p, -1 AS q\n" + " UNION ALL\n" + " SELECT n + 1, q * 2, p * 2 FROM cte WHERE n < 5\n" + ")\n" + "SELECT * FROM cte;"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL, true); SQLStatement stmt = statementList.get(0); assertEquals(1, statementList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.MYSQL); stmt.accept(visitor); // 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(0, visitor.getColumns().size()); // assertEquals(0, visitor.getConditions().size()); // assertEquals(0, visitor.getOrderByColumns().size()); { String output = SQLUtils.toMySqlString(stmt); assertEquals("WITH RECURSIVE cte AS (\n" + "\t\tSELECT 1 AS n, 1 AS p, -1 AS q\n" + "\t\tUNION ALL\n" + "\t\tSELECT n + 1, q * 2\n" + "\t\t\t, p * 2\n" + "\t\tFROM cte\n" + "\t\tWHERE n < 5\n" + "\t)\n" + "SELECT *\n" + "FROM cte;", // output); } { String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION); assertEquals("with recursive cte as (\n" + "\t\tselect 1 as n, 1 as p, -1 as q\n" + "\t\tunion all\n" + "\t\tselect n + 1, q * 2\n" + "\t\t\t, p * 2\n" + "\t\tfrom cte\n" + "\t\twhere n < 5\n" + "\t)\n" + "select *\n" + "from cte;", // output); } { String output = SQLUtils.toMySqlString(stmt, new SQLUtils.FormatOption(true, true, true)); assertEquals("WITH RECURSIVE cte AS (\n" + "\t\tSELECT ? AS n, ? AS p, ? AS q\n" + "\t\tUNION ALL\n" + "\t\tSELECT n + ?, q * ?\n" + "\t\t\t, p * ?\n" + "\t\tFROM cte\n" + "\t\tWHERE n < ?\n" + "\t)\n" + "SELECT *\n" + "FROM cte;", // output); } } }
MySqlSelectTest_44_with_cte
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/co/KeyedCoProcessOperator.java
{ "start": 2072, "end": 4735 }
class ____<K, IN1, IN2, OUT> extends AbstractUdfStreamOperator<OUT, KeyedCoProcessFunction<K, IN1, IN2, OUT>> implements TwoInputStreamOperator<IN1, IN2, OUT>, Triggerable<K, VoidNamespace> { private static final long serialVersionUID = 1L; private transient TimestampedCollector<OUT> collector; private transient ContextImpl<K, IN1, IN2, OUT> context; private transient OnTimerContextImpl<K, IN1, IN2, OUT> onTimerContext; public KeyedCoProcessOperator(KeyedCoProcessFunction<K, IN1, IN2, OUT> keyedCoProcessFunction) { super(keyedCoProcessFunction); } @Override public void open() throws Exception { super.open(); collector = new TimestampedCollector<>(output); InternalTimerService<VoidNamespace> internalTimerService = getInternalTimerService("user-timers", VoidNamespaceSerializer.INSTANCE, this); TimerService timerService = new SimpleTimerService(internalTimerService); context = new ContextImpl<>(userFunction, timerService); onTimerContext = new OnTimerContextImpl<>(userFunction, timerService); } @Override public void processElement1(StreamRecord<IN1> element) throws Exception { collector.setTimestamp(element); context.element = element; userFunction.processElement1(element.getValue(), context, collector); context.element = null; } @Override public void processElement2(StreamRecord<IN2> element) throws Exception { collector.setTimestamp(element); context.element = element; userFunction.processElement2(element.getValue(), context, collector); context.element = null; } @Override public void onEventTime(InternalTimer<K, VoidNamespace> timer) throws Exception { collector.setAbsoluteTimestamp(timer.getTimestamp()); onTimerContext.timeDomain = TimeDomain.EVENT_TIME; onTimerContext.timer = timer; userFunction.onTimer(timer.getTimestamp(), onTimerContext, collector); onTimerContext.timeDomain = null; onTimerContext.timer = null; } @Override public void onProcessingTime(InternalTimer<K, VoidNamespace> timer) throws Exception { collector.eraseTimestamp(); onTimerContext.timeDomain = TimeDomain.PROCESSING_TIME; onTimerContext.timer = timer; userFunction.onTimer(timer.getTimestamp(), onTimerContext, collector); onTimerContext.timeDomain = null; onTimerContext.timer = null; } protected TimestampedCollector<OUT> getCollector() { return collector; } private
KeyedCoProcessOperator
java
redisson__redisson
redisson/src/main/java/org/redisson/client/protocol/decoder/MapKeyDecoder.java
{ "start": 851, "end": 1334 }
class ____<T> implements MultiDecoder<Object> { private final MultiDecoder<Object> decoder; public MapKeyDecoder(MultiDecoder<Object> decoder) { this.decoder = decoder; } @Override public Decoder<Object> getDecoder(Codec codec, int paramNum, State state, long size) { return codec.getMapKeyDecoder(); } @Override public T decode(List<Object> parts, State state) { return (T) decoder.decode(parts, state); } }
MapKeyDecoder
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/util/NetUtils.java
{ "start": 3905, "end": 4085 }
interface ____ defined here as * the {@link java.net.NetworkInterface} that is both up and not a loopback interface. * * @return the MAC address of the local network
is
java
google__dagger
javatests/artifacts/dagger/build-tests/src/test/java/buildtests/TransitiveSubcomponentQualifierTest.java
{ "start": 4180, "end": 4317 }
class ____ extends MyBaseSubcomponent {", " @Subcomponent.Factory", " public abstract static
MySubcomponent
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/InputHandler.java
{ "start": 2351, "end": 4240 }
class ____ implements ServerHttpRequest.ReadCallback { final ResteasyReactiveRequestContext context; int dataCount; final List<ByteBuffer> data = new ArrayList<>(); InputListener(ResteasyReactiveRequestContext context) { this.context = context; } @Override public void done() { //super inefficient //TODO: write a stream that just uses the existing vert.x buffers byte[] ar = new byte[dataCount]; int count = 0; for (ByteBuffer i : data) { int remaining = i.remaining(); i.get(ar, count, remaining); count += remaining; } context.setInputStream(new ByteArrayInputStream(ar)); Thread.currentThread().setContextClassLoader(originalTCCL); context.resume(); } @Override public void data(ByteBuffer event) { dataCount += event.remaining(); data.add(event); if (dataCount > maxBufferSize) { context.serverRequest().pauseRequestInput(); if (workerExecutor == null) { workerExecutor = workerExecutorSupplier.get(); } //super inefficient //TODO: write a stream that just uses the existing vert.x buffers int count = 0; byte[] ar = new byte[dataCount]; for (ByteBuffer i : data) { int remaining = i.remaining(); i.get(ar, count, remaining); count += remaining; } //todo timeout context.setInputStream(context.serverRequest().createInputStream(ByteBuffer.wrap(ar))); context.resume(workerExecutor); } } } }
InputListener
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/text/translate/UnicodeUnpairedSurrogateRemoverTest.java
{ "start": 1296, "end": 1992 }
class ____ extends AbstractLangTest { final UnicodeUnpairedSurrogateRemover subject = new UnicodeUnpairedSurrogateRemover(); final CharArrayWriter writer = new CharArrayWriter(); // nothing is ever written to it @Test void testInvalidCharacters() throws IOException { assertTrue(subject.translate(0xd800, writer)); assertTrue(subject.translate(0xdfff, writer)); assertEquals(0, writer.size()); } @Test void testValidCharacters() throws IOException { assertFalse(subject.translate(0xd7ff, writer)); assertFalse(subject.translate(0xe000, writer)); assertEquals(0, writer.size()); } }
UnicodeUnpairedSurrogateRemoverTest
java
apache__dubbo
dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/context/ZookeeperContext.java
{ "start": 1077, "end": 2645 }
class ____ implements Context { /** * The config of zookeeper. */ private ZookeeperConfig config = new ZookeeperConfig(); /** * The the source file path of downloaded zookeeper binary archive. */ private Path sourceFile; /** * The directory after unpacked zookeeper archive binary file. */ private String unpackedDirectory; /** * Sets the source file path of downloaded zookeeper binary archive. */ public void setSourceFile(Path sourceFile) { this.sourceFile = sourceFile; } /** * Returns the source file path of downloaded zookeeper binary archive. */ public Path getSourceFile() { return this.sourceFile; } /** * Returns the directory after unpacked zookeeper archive binary file. */ public String getUnpackedDirectory() { return unpackedDirectory; } /** * Sets the directory after unpacked zookeeper archive binary file. */ public void setUnpackedDirectory(String unpackedDirectory) { this.unpackedDirectory = unpackedDirectory; } /** * Returns the zookeeper's version. */ public String getVersion() { return config.getVersion(); } /** * Returns the client ports of zookeeper. */ public int[] getClientPorts() { return config.getClientPorts(); } /** * Returns the admin server ports of zookeeper. */ public int[] getAdminServerPorts() { return config.getAdminServerPorts(); } }
ZookeeperContext
java
spring-projects__spring-framework
spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java
{ "start": 5961, "end": 6094 }
class ____ extends RepositoryInterfaceImpl implements StereotypedInterface { } public
MyInterfaceStereotypedRepositoryInterfaceImpl
java
google__guava
android/guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java
{ "start": 960, "end": 11042 }
class ____ extends RateLimiter { /* * How is the RateLimiter designed, and why? * * The primary feature of a RateLimiter is its "stable rate", the maximum rate that it should * allow in normal conditions. This is enforced by "throttling" incoming requests as needed. For * example, we could compute the appropriate throttle time for an incoming request, and make the * calling thread wait for that time. * * The simplest way to maintain a rate of QPS is to keep the timestamp of the last granted * request, and ensure that (1/QPS) seconds have elapsed since then. For example, for a rate of * QPS=5 (5 tokens per second), if we ensure that a request isn't granted earlier than 200ms after * the last one, then we achieve the intended rate. If a request comes and the last request was * granted only 100ms ago, then we wait for another 100ms. At this rate, serving 15 fresh permits * (i.e. for an acquire(15) request) naturally takes 3 seconds. * * It is important to realize that such a RateLimiter has a very superficial memory of the past: * it only remembers the last request. What if the RateLimiter was unused for a long period of * time, then a request arrived and was immediately granted? This RateLimiter would immediately * forget about that past underutilization. This may result in either underutilization or * overflow, depending on the real world consequences of not using the expected rate. * * Past underutilization could mean that excess resources are available. Then, the RateLimiter * should speed up for a while, to take advantage of these resources. This is important when the * rate is applied to networking (limiting bandwidth), where past underutilization typically * translates to "almost empty buffers", which can be filled immediately. * * On the other hand, past underutilization could mean that "the server responsible for handling * the request has become less ready for future requests", i.e. its caches become stale, and * requests become more likely to trigger expensive operations (a more extreme case of this * example is when a server has just booted, and it is mostly busy with getting itself up to * speed). * * To deal with such scenarios, we add an extra dimension, that of "past underutilization", * modeled by "storedPermits" variable. This variable is zero when there is no underutilization, * and it can grow up to maxStoredPermits, for sufficiently large underutilization. So, the * requested permits, by an invocation acquire(permits), are served from: * * - stored permits (if available) * * - fresh permits (for any remaining permits) * * How this works is best explained with an example: * * For a RateLimiter that produces 1 token per second, every second that goes by with the * RateLimiter being unused, we increase storedPermits by 1. Say we leave the RateLimiter unused * for 10 seconds (i.e., we expected a request at time X, but we are at time X + 10 seconds before * a request actually arrives; this is also related to the point made in the last paragraph), thus * storedPermits becomes 10.0 (assuming maxStoredPermits >= 10.0). At that point, a request of * acquire(3) arrives. We serve this request out of storedPermits, and reduce that to 7.0 (how * this is translated to throttling time is discussed later). Immediately after, assume that an * acquire(10) request arriving. We serve the request partly from storedPermits, using all the * remaining 7.0 permits, and the remaining 3.0, we serve them by fresh permits produced by the * rate limiter. * * We already know how much time it takes to serve 3 fresh permits: if the rate is * "1 token per second", then this will take 3 seconds. But what does it mean to serve 7 stored * permits? As explained above, there is no unique answer. If we are primarily interested to deal * with underutilization, then we want stored permits to be given out /faster/ than fresh ones, * because underutilization = free resources for the taking. If we are primarily interested to * deal with overflow, then stored permits could be given out /slower/ than fresh ones. Thus, we * require a (different in each case) function that translates storedPermits to throttling time. * * This role is played by storedPermitsToWaitTime(double storedPermits, double permitsToTake). The * underlying model is a continuous function mapping storedPermits (from 0.0 to maxStoredPermits) * onto the 1/rate (i.e. intervals) that is effective at the given storedPermits. "storedPermits" * essentially measure unused time; we spend unused time buying/storing permits. Rate is * "permits / time", thus "1 / rate = time / permits". Thus, "1/rate" (time / permits) times * "permits" gives time, i.e., integrals on this function (which is what storedPermitsToWaitTime() * computes) correspond to minimum intervals between subsequent requests, for the specified number * of requested permits. * * Here is an example of storedPermitsToWaitTime: If storedPermits == 10.0, and we want 3 permits, * we take them from storedPermits, reducing them to 7.0, and compute the throttling for these as * a call to storedPermitsToWaitTime(storedPermits = 10.0, permitsToTake = 3.0), which will * evaluate the integral of the function from 7.0 to 10.0. * * Using integrals guarantees that the effect of a single acquire(3) is equivalent to { * acquire(1); acquire(1); acquire(1); }, or { acquire(2); acquire(1); }, etc, since the integral * of the function in [7.0, 10.0] is equivalent to the sum of the integrals of [7.0, 8.0], [8.0, * 9.0], [9.0, 10.0] (and so on), no matter what the function is. This guarantees that we handle * correctly requests of varying weight (permits), /no matter/ what the actual function is - so we * can tweak the latter freely. (The only requirement, obviously, is that we can compute its * integrals). * * Note well that if, for this function, we chose a horizontal line, at height of exactly (1/QPS), * then the effect of the function is non-existent: we serve storedPermits at exactly the same * cost as fresh ones (1/QPS is the cost for each). We use this trick later. * * If we pick a function that goes /below/ that horizontal line, it means that we reduce the area * of the function, thus time. Thus, the RateLimiter becomes /faster/ after a period of * underutilization. If, on the other hand, we pick a function that goes /above/ that horizontal * line, then it means that the area (time) is increased, thus storedPermits are more costly than * fresh permits, thus the RateLimiter becomes /slower/ after a period of underutilization. * * Last, but not least: consider a RateLimiter with rate of 1 permit per second, currently * completely unused, and an expensive acquire(100) request comes. It would be nonsensical to just * wait for 100 seconds, and /then/ start the actual task. Why wait without doing anything? A much * better approach is to /allow/ the request right away (as if it was an acquire(1) request * instead), and postpone /subsequent/ requests as needed. In this version, we allow starting the * task immediately, and postpone by 100 seconds future requests, thus we allow for work to get * done in the meantime instead of waiting idly. * * This has important consequences: it means that the RateLimiter doesn't remember the time of the * _last_ request, but it remembers the (expected) time of the _next_ request. This also enables * us to tell immediately (see tryAcquire(timeout)) whether a particular timeout is enough to get * us to the point of the next scheduling time, since we always maintain that. And what we mean by * "an unused RateLimiter" is also defined by that notion: when we observe that the * "expected arrival time of the next request" is actually in the past, then the difference (now - * past) is the amount of time that the RateLimiter was formally unused, and it is that amount of * time which we translate to storedPermits. (We increase storedPermits with the amount of permits * that would have been produced in that idle time). So, if rate == 1 permit per second, and * arrivals come exactly one second after the previous, then storedPermits is _never_ increased -- * we would only increase it for arrivals _later_ than the expected one second. */ /** * This implements the following function where coldInterval = coldFactor * stableInterval. * * <pre> * ^ throttling * | * cold + / * interval | /. * | / . * | / . ← "warmup period" is the area of the trapezoid between * | / . thresholdPermits and maxPermits * | / . * | / . * | / . * stable +----------/ WARM . * interval | . UP . * | . PERIOD. * | . . * 0 +----------+-------+--------------→ storedPermits * 0 thresholdPermits maxPermits * </pre> * * Before going into the details of this particular function, let's keep in mind the basics: * * <ol> * <li>The state of the RateLimiter (storedPermits) is a vertical line in this figure. * <li>When the RateLimiter is not used, this goes right (up to maxPermits) * <li>When the RateLimiter is used, this goes left (down to zero), since if we have * storedPermits, we serve from those first * <li>When _unused_, we go right at a constant rate! The rate at which we move to the right is * chosen as maxPermits / warmupPeriod. This ensures that the time it takes to go from 0 to * maxPermits is equal to warmupPeriod. * <li>When _used_, the time it takes, as explained in the introductory
SmoothRateLimiter
java
apache__camel
components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketHelper.java
{ "start": 1046, "end": 3206 }
class ____ { private VertxWebsocketHelper() { // Utility class } /** * Creates a VertxWebsocketHostKey from a given VertxWebsocketConfiguration */ public static VertxWebsocketHostKey createHostKey(URI websockerURI) { return new VertxWebsocketHostKey(websockerURI.getHost(), websockerURI.getPort()); } /** * Appends a header value to exchange headers, using a List if there are multiple items for the same key */ @SuppressWarnings("unchecked") public static void appendHeader(Map<String, Object> headers, String key, Object value) { CollectionHelper.appendEntry(headers, key, value); } /** * Determines whether the path of a WebSocket host (the vertx-websocket consumer) matches a target path (the * vertx-websocket producer), taking path parameters and wildcard paths into consideration. */ public static boolean webSocketHostPathMatches(String hostPath, String targetPath) { boolean exactPathMatch = true; if (ObjectHelper.isEmpty(hostPath) || ObjectHelper.isEmpty(targetPath)) { // This scenario should not really be possible as the input args come from the vertx-websocket consumer / producer URI return false; } // Paths ending with '*' are Vert.x wildcard routes so match on the path prefix if (hostPath.endsWith("*")) { exactPathMatch = false; hostPath = hostPath.substring(0, hostPath.lastIndexOf('*')); } String normalizedHostPath = HttpUtils.normalizePath(hostPath + "/"); String normalizedTargetPath = HttpUtils.normalizePath(targetPath + "/"); String[] hostPathElements = normalizedHostPath.split("/"); String[] targetPathElements = normalizedTargetPath.split("/"); if (exactPathMatch && hostPathElements.length != targetPathElements.length) { return false; } if (exactPathMatch) { return normalizedHostPath.equals(normalizedTargetPath); } else { return normalizedTargetPath.startsWith(normalizedHostPath); } } }
VertxWebsocketHelper
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoBuilderCompilationTest.java
{ "start": 19108, "end": 19303 }
class ____ {", " private static Baz of() {", " return new Baz();", " }", "", " @AutoBuilder(callMethod = \"of\")", "
Baz
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/Product.java
{ "start": 567, "end": 1143 }
class ____ implements Serializable { private static final long serialVersionUID = 6956478993159505828L; @Id public Integer id; @Column(name="product_idnf", length=18, nullable=false, unique=true, columnDefinition="char(18)") public String productIdnf; @Column(name="description", nullable=false) public String description; @ManyToOne @JoinFormula(value="{fn substring(product_idnf, 1, 3)}", referencedColumnName="product_idnf") @Fetch(FetchMode.JOIN) private Product productFamily; public Product getProductFamily() { return productFamily; } }
Product
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/TreatCorrelatedTest.java
{ "start": 2680, "end": 2992 }
class ____ { @Id private Long id; private String name; @ManyToOne(fetch = FetchType.LAZY) private VersionedRoot owner; @OneToMany(fetch = FetchType.LAZY, mappedBy = "version", cascade = CascadeType.PERSIST) private List<Node> nodes; } @Entity @DiscriminatorValue(value = "2") public static
Version
java
quarkusio__quarkus
independent-projects/tools/devtools-testing/src/main/java/io/quarkus/devtools/testing/FakeExtensionCatalog.java
{ "start": 348, "end": 2083 }
class ____ { private static final String FAKE_EXTENSION_CATALOG_PATH = "/fake-catalog.json"; public static final ExtensionCatalog FAKE_EXTENSION_CATALOG = newFakeExtensionCatalog(); public static final QuarkusCodestartCatalog FAKE_QUARKUS_CODESTART_CATALOG = getQuarkusCodestartCatalog(); private FakeExtensionCatalog() { } private static QuarkusCodestartCatalog getQuarkusCodestartCatalog() { try { return QuarkusCodestartCatalog.fromBaseCodestartsResources( MessageWriter.info(), QuarkusCodestartCatalog.buildExtensionsMapping(FAKE_EXTENSION_CATALOG.getExtensions())); } catch (IOException e) { throw new UncheckedIOException(e); } } public static ExtensionCatalog newFakeExtensionCatalog() { InputStream inputString = FakeExtensionCatalog.class.getResourceAsStream(FAKE_EXTENSION_CATALOG_PATH); if (inputString == null) { throw new IllegalStateException("Failed to locate " + FAKE_EXTENSION_CATALOG_PATH + " on the classpath"); } try { return ExtensionCatalog.fromStream(inputString); } catch (IOException e) { throw new UncheckedIOException(e); } } public static String getDefaultCodestart() { var map = FAKE_EXTENSION_CATALOG.getMetadata().get("project"); if (map != null) { if (map instanceof Map) { var defaultCodestart = ((Map<?, ?>) map).get("default-codestart"); if (defaultCodestart instanceof String) { return defaultCodestart.toString(); } } } return null; } }
FakeExtensionCatalog
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/hierarchies/MockitoSpyBeanByNameInParentAndChildContextHierarchyV2Tests.java
{ "start": 1628, "end": 1799 }
class ____ different names for the context hierarchy levels: * level-1 and level-2 instead of parent and child. * * <p>If the context cache is broken, either this test
uses
java
elastic__elasticsearch
modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/histogram/AutoDateHistogramAggregatorSupplier.java
{ "start": 984, "end": 1451 }
interface ____ { Aggregator build( String name, AggregatorFactories factories, int numBuckets, AutoDateHistogramAggregationBuilder.RoundingInfo[] roundingInfos, @Nullable ValuesSourceConfig valuesSourceConfig, AggregationContext aggregationContext, Aggregator parent, CardinalityUpperBound cardinality, Map<String, Object> metadata ) throws IOException; }
AutoDateHistogramAggregatorSupplier
java
apache__camel
components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcUtils.java
{ "start": 3736, "end": 5009 }
class ____ found: " + serviceClassName); } return grpcStub; } @SuppressWarnings("rawtypes") public static Object addClientCallCredentials(Object grpcStub, final CallCredentials creds) { Class[] paramCallCreds = { CallCredentials.class }; Object grpcStubWithCreds = null; Method callCredsMethod = ReflectionHelper.findMethod(grpcStub.getClass(), GrpcConstants.GRPC_SERVICE_STUB_CALL_CREDS_METHOD, paramCallCreds); grpcStubWithCreds = ObjectHelper.invokeMethod(callCredsMethod, grpcStub, creds); return grpcStubWithCreds; } @SuppressWarnings("rawtypes") public static Class constructGrpcImplBaseClass(String packageName, String serviceName, final CamelContext context) { Class grpcServerImpl; String serverBaseImpl = constructFullClassName(packageName, serviceName + GrpcConstants.GRPC_SERVICE_CLASS_POSTFIX + "$" + serviceName + GrpcConstants.GRPC_SERVER_IMPL_POSTFIX); try { grpcServerImpl = context.getClassResolver().resolveMandatoryClass(serverBaseImpl); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("gRPC server base
not
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/support/xml/Jdbc4SqlXmlHandler.java
{ "start": 5935, "end": 6012 }
class ____ {@link SqlXmlValue} implementations. */ private abstract static
for
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/io/InitializeOnMaster.java
{ "start": 1215, "end": 1650 }
interface ____ { /** * The method is invoked on the master (JobManager) before the distributed program execution * starts. * * @param parallelism The parallelism with which the format or functions will be run. * @throws IOException The initialization may throw exceptions, which may cause the job to * abort. */ void initializeGlobal(int parallelism) throws IOException; }
InitializeOnMaster
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/restore/RestoreClusterStateListener.java
{ "start": 4040, "end": 4716 }
class ____ implements ClusterStateObserver.Listener { protected final ActionListener<RestoreSnapshotResponse> listener; private final DiscoveryNode localNode; protected RestoreListener(ActionListener<RestoreSnapshotResponse> listener, DiscoveryNode localNode) { this.listener = listener; this.localNode = localNode; } @Override public void onClusterServiceClose() { listener.onFailure(new NodeClosedException(localNode)); } @Override public void onTimeout(TimeValue timeout) { assert false : "impossible, no timeout set"; } } }
RestoreListener
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1719/TargetElement.java
{ "start": 225, "end": 1346 }
class ____ { private int id; private String name; private Target target; public TargetElement() { } public TargetElement(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Target getTarget() { return target; } /** * intentionally not a setter, to not further complicate this test case. * * @param target */ public void updateTarget(Target target) { this.target = target; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } TargetElement that = (TargetElement) o; return id == that.id; } @Override public int hashCode() { return Objects.hash( id ); } }
TargetElement
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
{ "start": 105018, "end": 105729 }
interface ____ { String apply(String b); } void test(ImmutableFunction f) { test( x -> { Test t = new Test(); return t.xs.get(0) + t.getXs().get(0) + t.t.t.xs.get(0); }); } } """) .doTest(); } @Test public void anonymousClass_cannotCloseAroundMutableLocal() { compilationHelper .addSourceLines( "Test.java", """ import com.google.errorprone.annotations.Immutable; import java.util.List; import java.util.ArrayList;
ImmutableFunction
java
spring-projects__spring-boot
module/spring-boot-security-oauth2-client/src/main/java/org/springframework/boot/security/oauth2/client/autoconfigure/OAuth2ClientProperties.java
{ "start": 2144, "end": 4842 }
class ____ { /** * Reference to the OAuth 2.0 provider to use. May reference an element from the * 'provider' property or used one of the commonly used providers (google, github, * facebook, okta). */ private @Nullable String provider; /** * Client ID for the registration. */ private @Nullable String clientId; /** * Client secret of the registration. */ private @Nullable String clientSecret; /** * Client authentication method. May be left blank when using a pre-defined * provider. */ private @Nullable String clientAuthenticationMethod; /** * Authorization grant type. May be left blank when using a pre-defined provider. */ private @Nullable String authorizationGrantType; /** * Redirect URI. May be left blank when using a pre-defined provider. */ private @Nullable String redirectUri; /** * Authorization scopes. When left blank the provider's default scopes, if any, * will be used. */ private @Nullable Set<String> scope; /** * Client name. May be left blank when using a pre-defined provider. */ private @Nullable String clientName; public @Nullable String getProvider() { return this.provider; } public void setProvider(@Nullable String provider) { this.provider = provider; } public @Nullable String getClientId() { return this.clientId; } public void setClientId(@Nullable String clientId) { this.clientId = clientId; } public @Nullable String getClientSecret() { return this.clientSecret; } public void setClientSecret(@Nullable String clientSecret) { this.clientSecret = clientSecret; } public @Nullable String getClientAuthenticationMethod() { return this.clientAuthenticationMethod; } public void setClientAuthenticationMethod(@Nullable String clientAuthenticationMethod) { this.clientAuthenticationMethod = clientAuthenticationMethod; } public @Nullable String getAuthorizationGrantType() { return this.authorizationGrantType; } public void setAuthorizationGrantType(@Nullable String authorizationGrantType) { this.authorizationGrantType = authorizationGrantType; } public @Nullable String getRedirectUri() { return this.redirectUri; } public void setRedirectUri(@Nullable String redirectUri) { this.redirectUri = redirectUri; } public @Nullable Set<String> getScope() { return this.scope; } public void setScope(@Nullable Set<String> scope) { this.scope = scope; } public @Nullable String getClientName() { return this.clientName; } public void setClientName(@Nullable String clientName) { this.clientName = clientName; } } public static
Registration
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/factories/TestDynamicTableFactory.java
{ "start": 1988, "end": 6256 }
class ____ implements DynamicTableSourceFactory, DynamicTableSinkFactory { public static final String IDENTIFIER = "test-connector"; public static final ConfigOption<String> TARGET = ConfigOptions.key("target") .stringType() .noDefaultValue() .withDeprecatedKeys("deprecated-target"); public static final ConfigOption<Long> BUFFER_SIZE = ConfigOptions.key("buffer-size") .longType() .defaultValue(100L) .withFallbackKeys("fallback-buffer-size"); public static final ConfigOption<String> PASSWORD = ConfigOptions.key("password").stringType().noDefaultValue(); public static final ConfigOption<String> KEY_FORMAT = ConfigOptions.key("key" + FORMAT_SUFFIX).stringType().noDefaultValue(); public static final ConfigOption<String> VALUE_FORMAT = ConfigOptions.key("value" + FORMAT_SUFFIX).stringType().noDefaultValue(); @Override public DynamicTableSource createDynamicTableSource(Context context) { final TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context); final Optional<DecodingFormat<DeserializationSchema<RowData>>> keyFormat = helper.discoverOptionalDecodingFormat( DeserializationFormatFactory.class, KEY_FORMAT); final DecodingFormat<DeserializationSchema<RowData>> valueFormat = helper.discoverOptionalDecodingFormat(DeserializationFormatFactory.class, FORMAT) .orElseGet( () -> helper.discoverDecodingFormat( DeserializationFormatFactory.class, VALUE_FORMAT)); helper.validate(); return new DynamicTableSourceMock( helper.getOptions().get(TARGET), helper.getOptions().getOptional(PASSWORD).orElse(null), keyFormat.orElse(null), valueFormat); } @Override public DynamicTableSink createDynamicTableSink(Context context) { final TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context); final Optional<EncodingFormat<SerializationSchema<RowData>>> keyFormat = helper.discoverOptionalEncodingFormat(SerializationFormatFactory.class, KEY_FORMAT); final EncodingFormat<SerializationSchema<RowData>> valueFormat = helper.discoverOptionalEncodingFormat(SerializationFormatFactory.class, FORMAT) .orElseGet( () -> helper.discoverEncodingFormat( SerializationFormatFactory.class, VALUE_FORMAT)); helper.validate(); return new DynamicTableSinkMock( helper.getOptions().get(TARGET), helper.getOptions().get(BUFFER_SIZE), keyFormat.orElse(null), valueFormat); } @Override public String factoryIdentifier() { return IDENTIFIER; } @Override public Set<ConfigOption<?>> requiredOptions() { final Set<ConfigOption<?>> options = new HashSet<>(); options.add(TARGET); return options; } @Override public Set<ConfigOption<?>> optionalOptions() { final Set<ConfigOption<?>> options = new HashSet<>(); options.add(BUFFER_SIZE); options.add(KEY_FORMAT); options.add(FORMAT); options.add(VALUE_FORMAT); options.add(PASSWORD); return options; } @Override public Set<ConfigOption<?>> forwardOptions() { final Set<ConfigOption<?>> options = new HashSet<>(); options.add(BUFFER_SIZE); options.add(PASSWORD); return options; } // -------------------------------------------------------------------------------------------- // Table source // -------------------------------------------------------------------------------------------- /** {@link DynamicTableSource} for testing. */ public static
TestDynamicTableFactory
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/serde/ExecNodeGraphJsonSerializer.java
{ "start": 1576, "end": 2427 }
class ____ extends StdSerializer<ExecNodeGraph> { private static final long serialVersionUID = 1L; ExecNodeGraphJsonSerializer() { super(ExecNodeGraph.class); } @Override public void serialize( ExecNodeGraph execNodeGraph, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { validate(execNodeGraph); serializerProvider.defaultSerializeValue( JsonPlanGraph.fromExecNodeGraph(execNodeGraph), jsonGenerator); } /** Check whether the given {@link ExecNodeGraph} is completely legal. */ private static void validate(ExecNodeGraph execGraph) { ExecNodeVisitor visitor = new ExecNodeGraphValidator(); execGraph.getRootNodes().forEach(visitor::visit); } }
ExecNodeGraphJsonSerializer
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/bugs/FinalHashCodeAndEqualsRaiseNPEInInitMocksTest.java
{ "start": 326, "end": 705 }
class ____ { @Mock private Charset charset; @InjectMocks private FieldCharsetHolder fieldCharsetHolder; @InjectMocks private ConstructorCharsetHolder constructorCharsetHolder; @Test public void dont_raise_NullPointerException() throws Exception { MockitoAnnotations.openMocks(this); } private static
FinalHashCodeAndEqualsRaiseNPEInInitMocksTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/orderby/EmbeddedIdOrderByAndAggregateFunctionTest.java
{ "start": 3032, "end": 3202 }
class ____ { private long id1; private long id2; public ChildId() { } public ChildId(long id1, long id2) { this.id1 = id1; this.id2 = id2; } } }
ChildId
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/idclass/CompositeIdClassTest.java
{ "start": 783, "end": 1249 }
class ____ { @Test @WithClasses(MyEntity.class) void test() { System.out.println( getMetaModelSourceAsString( MyEntity.class ) ); assertMetamodelClassGeneratedFor( MyEntity.class ); assertPresenceOfNameFieldInMetamodelFor( MyEntity.class, "QUERY_FIND_BY_ID", "Missing named query attribute." ); assertPresenceOfMethodInMetamodelFor( MyEntity.class, "findById", EntityManager.class, MyEntityId.class ); } }
CompositeIdClassTest
java
google__guava
android/guava/src/com/google/common/util/concurrent/AtomicDouble.java
{ "start": 1301, "end": 2136 }
class ____ primitive {@code double} values in methods such as * {@link #compareAndSet} by comparing their bitwise representation using {@link * Double#doubleToRawLongBits}, which differs from both the primitive double {@code ==} operator and * from {@link Double#equals}, as if implemented by: * * {@snippet : * static boolean bitEquals(double x, double y) { * long xBits = Double.doubleToRawLongBits(x); * long yBits = Double.doubleToRawLongBits(y); * return xBits == yBits; * } * } * * <p>It is possible to write a more scalable updater, at the cost of giving up strict atomicity. * See for example <a * href="http://gee.cs.oswego.edu/dl/jsr166/dist/docs/java.base/java/util/concurrent/atomic/DoubleAdder.html"> * DoubleAdder</a>. * * @author Doug Lea * @author Martin Buchholz * @since 11.0 */ public
compares
java
spring-projects__spring-framework
spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessageHeaderAccessorTests.java
{ "start": 1062, "end": 2967 }
class ____ { @Test void getShortLogMessage() { assertThat(SimpMessageHeaderAccessor.create().getShortLogMessage("p")) .isEqualTo("MESSAGE session=null payload=p"); } @Test void getLogMessageWithValuesSet() { SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setDestination("/destination"); accessor.setSubscriptionId("subscription"); accessor.setSessionId("session"); accessor.setUser(new TestPrincipal("user")); accessor.setSessionAttributes(Collections.singletonMap("key", "value")); assertThat(accessor.getShortLogMessage("p")) .isEqualTo(("MESSAGE destination=/destination subscriptionId=subscription " + "session=session user=user attributes[1] payload=p")); } @Test void getDetailedLogMessageWithValuesSet() { SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setDestination("/destination"); accessor.setSubscriptionId("subscription"); accessor.setSessionId("session"); accessor.setUser(new TestPrincipal("user")); accessor.setSessionAttributes(Collections.singletonMap("key", "value")); accessor.setNativeHeader("nativeKey", "nativeValue"); assertThat(accessor.getDetailedLogMessage("p")) .isEqualTo(("MESSAGE destination=/destination subscriptionId=subscription " + "session=session user=user attributes={key=value} nativeHeaders=" + "{nativeKey=[nativeValue]} payload=p")); } @Test void userChangeCallback() { UserCallback userCallback = new UserCallback(); SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); accessor.setUserChangeCallback(userCallback); Principal user1 = mock(); accessor.setUser(user1); assertThat(userCallback.getUser()).isEqualTo(user1); Principal user2 = mock(); accessor.setUser(user2); assertThat(userCallback.getUser()).isEqualTo(user2); } private static
SimpMessageHeaderAccessorTests
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ShouldHavePropertyOrFieldWithValue.java
{ "start": 813, "end": 1927 }
class ____ extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldHavePropertyOrFieldWithValue}</code>. * * @param actual the actual value in the failed assertion. * @param name expected name of the field of this class * @param expectedValue expected value of the field of the class * @param actualValue actual value of the field of the class * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldHavePropertyOrFieldWithValue(Object actual, String name, Object expectedValue, Object actualValue) { return new ShouldHavePropertyOrFieldWithValue(actual, name, expectedValue, actualValue); } private ShouldHavePropertyOrFieldWithValue(Object actual, String name, Object expectedValue, Object actualValue) { super("%nExpecting%n %s%nto have a property or a field named %s with value%n %s%nbut value was:%n %s%n(static and synthetic fields are ignored)", actual, name, expectedValue, actualValue); } }
ShouldHavePropertyOrFieldWithValue
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/ast/spi/SqlAliasBaseGenerator.java
{ "start": 231, "end": 379 }
interface ____ { /** * Generate the SqlAliasBase based on the given stem. */ SqlAliasBase createSqlAliasBase(String stem); }
SqlAliasBaseGenerator
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/PlanCacheManager.java
{ "start": 1328, "end": 2332 }
class ____ { private final Cache<String, CachedPlan> planCache; public PlanCacheManager(long maximumCapacity, Duration ttl) { planCache = CacheBuilder.newBuilder() .maximumSize(maximumCapacity) .expireAfterWrite(ttl) .recordStats() .build(); } public Optional<CachedPlan> getPlan(String query) { CachedPlan cachedPlan = planCache.getIfPresent(query); return Optional.ofNullable(cachedPlan); } public void putPlan(String query, CachedPlan cachedPlan) { Preconditions.checkNotNull(query, "query can not be null"); Preconditions.checkNotNull(cachedPlan, "cachedPlan can not be null"); planCache.put(query, cachedPlan); } public void invalidateAll() { planCache.invalidateAll(); } @VisibleForTesting public CacheStats getCacheStats() { return planCache.stats(); } }
PlanCacheManager
java
quarkusio__quarkus
extensions/micrometer-opentelemetry/deployment/src/test/java/io/quarkus/micrometer/opentelemetry/deployment/common/ServletEndpoint.java
{ "start": 392, "end": 655 }
class ____ extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.getWriter().println("OK"); } }
ServletEndpoint
java
apache__camel
components/camel-jgroups-raft/src/main/java/org/apache/camel/component/jgroups/raft/cluster/JGroupsRaftClusterService.java
{ "start": 974, "end": 2758 }
class ____ extends AbstractCamelClusterService<JGroupsRaftClusterView> { private static final String DEFAULT_JGROUPS_CONFIG = "raft.xml"; private static final String DEFAULT_JGROUPS_CLUSTERNAME = "jgroupsraft-master"; private String jgroupsConfig; private String jgroupsClusterName; private RaftHandle raftHandle; private String raftId; public JGroupsRaftClusterService() { this.jgroupsConfig = DEFAULT_JGROUPS_CONFIG; this.jgroupsClusterName = DEFAULT_JGROUPS_CLUSTERNAME; } public JGroupsRaftClusterService(String jgroupsConfig, String jgroupsClusterName, RaftHandle raftHandle, String raftId) { this.jgroupsConfig = jgroupsConfig; this.jgroupsClusterName = jgroupsClusterName; this.raftHandle = raftHandle; this.raftId = raftId; } @Override protected JGroupsRaftClusterView createView(String namespace) throws Exception { return new JGroupsRaftClusterView(this, namespace, jgroupsConfig, jgroupsClusterName, raftHandle, raftId); } public RaftHandle getRaftHandle() { return raftHandle; } public void setRaftHandle(RaftHandle raftHandle) { this.raftHandle = raftHandle; } public String getRaftId() { return raftId; } public void setRaftId(String raftId) { this.raftId = raftId; } public String getJgroupsConfig() { return jgroupsConfig; } public void setJgroupsConfig(String jgroupsConfig) { this.jgroupsConfig = jgroupsConfig; } public String getJgroupsClusterName() { return jgroupsClusterName; } public void setJgroupsClusterName(String jgroupsClusterName) { this.jgroupsClusterName = jgroupsClusterName; } }
JGroupsRaftClusterService
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/InstanceOfAssertFactoriesTest.java
{ "start": 87070, "end": 87711 }
class ____ { private final Object actual = Stream.of(1, 2, 3); @Test void createAssert() { // WHEN ListAssert<Object> result = STREAM.createAssert(actual); // THEN result.containsExactly(1, 2, 3); } @Test void createAssert_with_ValueProvider() { // GIVEN ValueProvider<?> valueProvider = mockThatDelegatesTo(type -> actual); // WHEN ListAssert<Object> result = STREAM.createAssert(valueProvider); // THEN result.containsExactly(1, 2, 3); verify(valueProvider).apply(parameterizedType(Stream.class, Object.class)); } } @Nested
Stream_Factory
java
apache__avro
lang/java/ipc/src/test/java/org/apache/avro/io/Perf.java
{ "start": 44660, "end": 44952 }
class ____ extends GenericResolving { GenericWithPromotion() throws IOException { super("GenericWithPromotion_"); } @Override protected Schema getReaderSchema() { return new Schema.Parser().parse(RECORD_SCHEMA_WITH_PROMOTION); } } static
GenericWithPromotion
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/AbstractAsynchronousOperationHandlersTest.java
{ "start": 9527, "end": 9704 }
class ____ extends OperationKey { protected TestOperationKey(TriggerId triggerId) { super(triggerId); } } private static final
TestOperationKey
java
elastic__elasticsearch
test/external-modules/multi-project/src/test/java/org/elasticsearch/multiproject/action/DeleteProjectActionTests.java
{ "start": 1351, "end": 4738 }
class ____ extends ESTestCase { private DeleteProjectAction.DeleteProjectExecutor executor; @Before public void init() { executor = new DeleteProjectAction.DeleteProjectExecutor(); } public void testSimpleDelete() throws Exception { var projects = randomList(1, 5, ESTestCase::randomUniqueProjectId); var deletedProjects = randomSubsetOf(projects); var state = buildState(projects); var tasks = deletedProjects.stream().map(this::createTask).toList(); var result = ClusterStateTaskExecutorUtils.executeAndAssertSuccessful(state, executor, tasks); for (ProjectId deletedProject : deletedProjects) { assertNull(result.metadata().projects().get(deletedProject)); assertNull(result.globalRoutingTable().routingTables().get(deletedProject)); } for (ProjectId project : projects) { if (deletedProjects.contains(project)) { continue; } assertNotNull(result.metadata().projects().get(project)); assertNotNull(result.globalRoutingTable().routingTables().get(project)); } } public void testDeleteNonExisting() throws Exception { var projects = randomList(1, 5, ESTestCase::randomUniqueProjectId); var deletedProjects = randomSubsetOf(projects); var state = buildState(projects); var listener = ActionListener.assertAtLeastOnce( ActionTestUtils.<AcknowledgedResponse>assertNoSuccessListener(e -> assertTrue(e instanceof IllegalArgumentException)) ); var nonExistingTask = createTask(randomUniqueProjectId(), listener); var tasks = Stream.concat(Stream.of(nonExistingTask), deletedProjects.stream().map(this::createTask)).toList(); var result = ClusterStateTaskExecutorUtils.executeHandlingResults(state, executor, tasks, t -> {}, DeleteProjectTask::onFailure); for (ProjectId deletedProject : deletedProjects) { assertNull(result.metadata().projects().get(deletedProject)); assertNull(result.globalRoutingTable().routingTables().get(deletedProject)); } for (ProjectId project : projects) { if (deletedProjects.contains(project)) { continue; } assertNotNull(result.metadata().projects().get(project)); assertNotNull(result.globalRoutingTable().routingTables().get(project)); } } private DeleteProjectTask createTask(ProjectId projectId) { return createTask(projectId, ActionListener.running(() -> {})); } private DeleteProjectTask createTask(ProjectId projectId, ActionListener<AcknowledgedResponse> listener) { return new DeleteProjectTask(new DeleteProjectAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, projectId), listener); } private ClusterState buildState(List<ProjectId> projects) { var metadata = Metadata.builder(); var routingTable = GlobalRoutingTable.builder(); for (ProjectId projectId : projects) { metadata.put(ProjectMetadata.builder(projectId).build()); routingTable.put(projectId, RoutingTable.EMPTY_ROUTING_TABLE); } return ClusterState.builder(ClusterName.DEFAULT).metadata(metadata.build()).routingTable(routingTable.build()).build(); } }
DeleteProjectActionTests
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/Annotation.java
{ "start": 553, "end": 1316 }
class ____ extends ModelElement { private final Type type; private List<AnnotationElement> properties; public Annotation(Type type) { this( type, Collections.emptyList() ); } public Annotation(Type type, List<AnnotationElement> properties) { this.type = type; this.properties = properties; } public Type getType() { return type; } @Override public Set<Type> getImportTypes() { Set<Type> types = new HashSet<>(); for ( AnnotationElement prop : properties ) { types.addAll( prop.getImportTypes() ); } types.add( type ); return types; } public List<AnnotationElement> getProperties() { return properties; } }
Annotation
java
elastic__elasticsearch
x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExportBulk.java
{ "start": 1841, "end": 7564 }
class ____ extends ExportBulk { private static final Logger logger = LogManager.getLogger(HttpExportBulk.class); /** * The {@link RestClient} managed by the {@link HttpExporter}. */ private final RestClient client; /** * The querystring parameters to pass along with every bulk request. */ private final Map<String, String> params; /** * {@link DateTimeFormatter} used to resolve timestamped index name. */ private final DateFormatter formatter; /** * The compressed bytes payload that represents the bulk body is created via {@link #doAdd(Collection)}. */ private BytesReference payload = null; /** * Uncompressed length of {@link #payload} contents. */ private long payloadLength = -1L; HttpExportBulk( final String name, final RestClient client, final Map<String, String> parameters, final DateFormatter dateTimeFormatter, final ThreadContext threadContext ) { super(name, threadContext); this.client = client; this.params = parameters; this.formatter = dateTimeFormatter; } @Override public void doAdd(Collection<MonitoringDoc> docs) throws ExportException { try { if (docs != null && docs.isEmpty() == false) { final BytesStreamOutput scratch = new BytesStreamOutput(); final CountingOutputStream countingStream; try (OutputStream payload = CompressorFactory.COMPRESSOR.threadLocalOutputStream(scratch)) { countingStream = new CountingOutputStream(payload); for (MonitoringDoc monitoringDoc : docs) { writeDocument(monitoringDoc, countingStream); } } payloadLength = countingStream.bytesWritten; // store the payload until we flush this.payload = scratch.bytes(); } } catch (Exception e) { throw new ExportException("failed to add documents to export bulk [{}]", e, name); } } @Override public void doFlush(ActionListener<Void> listener) throws ExportException { if (payload == null) { listener.onFailure(new ExportException("unable to send documents because none were loaded for export bulk [{}]", name)); } else if (payload.length() != 0) { final Request request = new Request("POST", "/_bulk"); for (Map.Entry<String, String> param : params.entrySet()) { request.addParameter(param.getKey(), param.getValue()); } try { // Don't use a thread-local decompressing stream since the HTTP client does not give strong guarantees about // thread-affinity when reading and closing the request entity request.setEntity( new InputStreamEntity( DeflateCompressor.inputStream(payload.streamInput(), false), payloadLength, ContentType.APPLICATION_JSON ) ); } catch (IOException e) { listener.onFailure(e); return; } // null out serialized docs to make things easier on the GC payload = null; client.performRequestAsync(request, new ResponseListener() { @Override public void onSuccess(Response response) { try { HttpExportBulkResponseListener.INSTANCE.onSuccess(response); } finally { listener.onResponse(null); } } @Override public void onFailure(Exception exception) { try { HttpExportBulkResponseListener.INSTANCE.onFailure(exception); } finally { listener.onFailure(exception); } } }); } } private void writeDocument(MonitoringDoc doc, OutputStream out) throws IOException { final XContentType xContentType = XContentType.JSON; final XContent xContent = xContentType.xContent(); final String index = MonitoringTemplateUtils.indexName(formatter, doc.getSystem(), doc.getTimestamp()); final String id = doc.getId(); try (XContentBuilder builder = new XContentBuilder(xContent, out)) { // Builds the bulk action metadata line builder.startObject(); { builder.startObject("index"); { builder.field("_index", index); if (id != null) { builder.field("_id", id); } } builder.endObject(); } builder.endObject(); } // Adds action metadata line bulk separator out.write(xContent.bulkSeparator()); // Adds the source of the monitoring document try (XContentBuilder builder = new XContentBuilder(xContent, out)) { doc.toXContent(builder, ToXContent.EMPTY_PARAMS); } // Adds final bulk separator out.write(xContent.bulkSeparator()); logger.trace("http exporter [{}] - added index request [index={}, id={}, monitoring data type={}]", name, index, id, doc.getType()); } // Counting input stream used to record the uncompressed size of the bulk payload when writing it to a compressed stream private static final
HttpExportBulk
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/io/stream/AbstractWriteableEnumTestCase.java
{ "start": 2161, "end": 2531 }
enum ____ void assertReadFromStream(final int ordinal, final Writeable expected) throws IOException { try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeVInt(ordinal); try (StreamInput in = out.bytes().streamInput()) { assertThat(reader.read(in), equalTo(expected)); } } } }
protected
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/ext/ExternalTypeIdWithCreator3045Test.java
{ "start": 1892, "end": 2242 }
class ____ { @JsonAnySetter public HashMap<String,Object> data = new HashMap<>(); public int size() { return data.size(); } public Object find(String key) { return data.get(key); } @Override public String toString() { return String.valueOf(data); } } public static
MyData
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/HasChangedOneToManyInComponent.java
{ "start": 1301, "end": 3014 }
class ____ extends AbstractModifiedFlagsEntityTest { private Integer otmcte_id1; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { // Revision 1 em.getTransaction().begin(); StrTestEntity ste1 = new StrTestEntity(); ste1.setStr( "str1" ); StrTestEntity ste2 = new StrTestEntity(); ste2.setStr( "str2" ); em.persist( ste1 ); em.persist( ste2 ); em.getTransaction().commit(); // Revision 2 em.getTransaction().begin(); OneToManyComponentTestEntity otmcte1 = new OneToManyComponentTestEntity( new OneToManyComponent( "data1" ) ); otmcte1.getComp1().getEntities().add( ste1 ); em.persist( otmcte1 ); em.getTransaction().commit(); // Revision 3 em.getTransaction().begin(); OneToManyComponentTestEntity otmcte1Ref = em.find( OneToManyComponentTestEntity.class, otmcte1.getId() ); otmcte1Ref.getComp1().getEntities().add( ste2 ); em.getTransaction().commit(); otmcte_id1 = otmcte1.getId(); } ); } @Test public void testHasChangedId1(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); List list = AbstractModifiedFlagsEntityTest.queryForPropertyHasChanged( auditReader, OneToManyComponentTestEntity.class, otmcte_id1, "comp1" ); assertEquals( 2, list.size() ); assertEquals( makeList( 2, 3 ), extractRevisionNumbers( list ) ); list = AbstractModifiedFlagsEntityTest.queryForPropertyHasNotChanged( auditReader, OneToManyComponentTestEntity.class, otmcte_id1, "comp1" ); assertEquals( 0, list.size() ); } ); } }
HasChangedOneToManyInComponent
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/ReplicaWaitingToBeRecovered.java
{ "start": 1151, "end": 1550 }
class ____ a replica that is waiting to be recovered. * After a datanode restart, any replica in "rbw" directory is loaded * as a replica waiting to be recovered. * A replica waiting to be recovered does not provision read nor * participates in any pipeline recovery. It will become outdated if its * client continues to write or be recovered as a result of * lease recovery. */ public
represents
java
grpc__grpc-java
istio-interop-testing/src/generated/main/grpc/io/istio/test/EchoTestServiceGrpc.java
{ "start": 14577, "end": 15157 }
class ____ implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { EchoTestServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return io.istio.test.Echo.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("EchoTestService"); } } private static final
EchoTestServiceBaseDescriptorSupplier
java
elastic__elasticsearch
x-pack/plugin/autoscaling/src/test/java/org/elasticsearch/xpack/autoscaling/storage/ProactiveStorageDeciderServiceTests.java
{ "start": 2923, "end": 20154 }
class ____ extends AutoscalingTestCase { public void testScale() { @FixForMultiProject(description = "Use non-default project ID and remove last boolean parameter") ProjectMetadata originalProject = DataStreamTestHelper.getProjectWithDataStreams( Metadata.DEFAULT_PROJECT_ID, List.of(Tuple.tuple("test", between(1, 10))), List.of(), System.currentTimeMillis(), Settings.EMPTY, 0, randomBoolean(), false ); ClusterState.Builder stateBuilder = ClusterState.builder(ClusterName.DEFAULT); IntStream.range(0, between(1, 10)).forEach(i -> ReactiveStorageDeciderServiceTests.addNode(stateBuilder)); stateBuilder.putRoutingTable( originalProject.id(), addRouting(originalProject, RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY)).build() ); stateBuilder.putProjectMetadata( applyCreatedDates(originalProject, (DataStream) originalProject.getIndicesLookup().get("test"), System.currentTimeMillis(), 1) ); ClusterState interimState = stateBuilder.build(); final ClusterState state = startAll(interimState); final ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); Collection<AllocationDecider> allocationDecidersList = new ArrayList<>( ClusterModule.createAllocationDeciders(Settings.EMPTY, clusterSettings, Collections.emptyList()) ); allocationDecidersList.add(new AllocationDecider() { @Override public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { return allocation.decision(Decision.NO, DiskThresholdDecider.NAME, "test"); } }); AllocationDeciders allocationDeciders = new AllocationDeciders(allocationDecidersList); ProactiveStorageDeciderService service = new ProactiveStorageDeciderService( Settings.EMPTY, clusterSettings, allocationDeciders, TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY ); AutoscalingCapacity currentCapacity = ReactiveStorageDeciderDecisionTests.randomCurrentCapacity(); ClusterInfo info = randomClusterInfo(state.projectState(originalProject.id())); AutoscalingDeciderContext context = new AutoscalingDeciderContext() { @Override public ClusterState state() { return state; } @Override public AutoscalingCapacity currentCapacity() { return currentCapacity; } @Override public Set<DiscoveryNode> nodes() { return Sets.newHashSet(state.nodes()); } @Override public Set<DiscoveryNodeRole> roles() { return Set.of(DiscoveryNodeRole.DATA_ROLE); } @Override public ClusterInfo info() { return info; } @Override public SnapshotShardSizeInfo snapshotShardSizeInfo() { return null; } @Override public void ensureNotCancelled() {} }; AutoscalingDeciderResult deciderResult = service.scale(Settings.EMPTY, context); if (currentCapacity != null) { assertThat(deciderResult.requiredCapacity().total().storage(), Matchers.greaterThan(currentCapacity.total().storage())); assertThat(deciderResult.reason().summary(), startsWith("not enough storage available, needs ")); ProactiveStorageDeciderService.ProactiveReason reason = (ProactiveStorageDeciderService.ProactiveReason) deciderResult.reason(); assertThat( reason.forecasted(), equalTo(deciderResult.requiredCapacity().total().storage().getBytes() - currentCapacity.total().storage().getBytes()) ); assertThat( reason.forecasted(), lessThanOrEqualTo( totalSize( state.metadata().getProject(originalProject.id()).dataStreams().get("test").getIndices(), state.routingTable(originalProject.id()), info ) ) ); deciderResult = service.scale( Settings.builder().put(ProactiveStorageDeciderService.FORECAST_WINDOW.getKey(), TimeValue.ZERO).build(), context ); assertThat(deciderResult.requiredCapacity().total().storage(), Matchers.equalTo(currentCapacity.total().storage())); assertThat(deciderResult.reason().summary(), equalTo("storage ok")); reason = (ProactiveStorageDeciderService.ProactiveReason) deciderResult.reason(); assertThat(reason.forecasted(), equalTo(0L)); } else { assertThat(deciderResult.requiredCapacity(), is(nullValue())); assertThat(deciderResult.reason().summary(), equalTo("current capacity not available")); } } public void testForecastNoDates() { @FixForMultiProject(description = "Use non-default project ID and remove last boolean parameter") ProjectMetadata originalProject = DataStreamTestHelper.getProjectWithDataStreams( Metadata.DEFAULT_PROJECT_ID, List.of(Tuple.tuple("test", between(1, 10))), List.of(), System.currentTimeMillis(), Settings.EMPTY, between(0, 4), randomBoolean(), false ); ClusterState state = ClusterState.builder(ClusterName.DEFAULT) .putProjectMetadata(originalProject) .putRoutingTable( originalProject.id(), addRouting(originalProject, RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY)).build() ) .build(); ReactiveStorageDeciderService.AllocationState allocationState = new ReactiveStorageDeciderService.AllocationState( state, null, TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY, null, null, null, Set.of(), Set.of() ); assertThat(allocationState.forecast(Long.MAX_VALUE, System.currentTimeMillis()), Matchers.sameInstance(allocationState)); } public void testForecastZero() { @FixForMultiProject(description = "Use non-default project ID and remove last two boolean parameters") ProjectMetadata originalProject = DataStreamTestHelper.getProjectWithDataStreams( Metadata.DEFAULT_PROJECT_ID, List.of(Tuple.tuple("test", between(1, 10))), List.of(), System.currentTimeMillis(), Settings.EMPTY, between(0, 4), false, false ); ClusterState.Builder stateBuilder = ClusterState.builder(ClusterName.DEFAULT); IntStream.range(0, between(1, 10)).forEach(i -> ReactiveStorageDeciderServiceTests.addNode(stateBuilder)); stateBuilder.putRoutingTable( originalProject.id(), addRouting(originalProject, RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY)).build() ); long lastCreated = randomNonNegativeLong(); stateBuilder.putProjectMetadata( applyCreatedDates(originalProject, (DataStream) originalProject.getIndicesLookup().get("test"), lastCreated, 1) ); ClusterState state = stateBuilder.build(); state = randomAllocate(state); ReactiveStorageDeciderService.AllocationState allocationState = new ReactiveStorageDeciderService.AllocationState( state, null, TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY, null, randomClusterInfo(state.projectState(originalProject.id())), null, Sets.newHashSet(state.nodes()), Set.of() ); assertThat(allocationState.forecast(0, lastCreated + between(-3, 1)), Matchers.sameInstance(allocationState)); assertThat(allocationState.forecast(10, lastCreated + 1), Matchers.not(Matchers.sameInstance(allocationState))); } public void testForecast() { int indices = between(1, 10); int shardCopies = between(1, 2); @FixForMultiProject(description = "Use non-default project ID and remove last boolean parameter") final var projectId = Metadata.DEFAULT_PROJECT_ID; ProjectMetadata originalProject = DataStreamTestHelper.getProjectWithDataStreams( projectId, List.of(Tuple.tuple("test", indices)), List.of(), System.currentTimeMillis(), Settings.EMPTY, shardCopies - 1, randomBoolean(), false ); ClusterState.Builder stateBuilder = ClusterState.builder(ClusterName.DEFAULT); stateBuilder.putRoutingTable( projectId, addRouting(originalProject, RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY)).build() ); IntStream.range(0, between(1, 10)).forEach(i -> ReactiveStorageDeciderServiceTests.addNode(stateBuilder)); long lastCreated = randomNonNegativeLong(); stateBuilder.putProjectMetadata( applyCreatedDates(originalProject, (DataStream) originalProject.getIndicesLookup().get("test"), lastCreated, 1) ); ClusterState state = stateBuilder.build(); state = randomAllocate(state); DataStream dataStream = state.metadata().getProject(projectId).dataStreams().get("test"); ClusterInfo info = randomClusterInfo(state.projectState(projectId)); ReactiveStorageDeciderService.AllocationState allocationState = new ReactiveStorageDeciderService.AllocationState( state, null, TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY, null, info, null, Sets.newHashSet(state.nodes()), Set.of() ); for (int window = 0; window < between(1, 20); ++window) { ReactiveStorageDeciderService.AllocationState forecast = allocationState.forecast(window, lastCreated + 1); int actualWindow = Math.min(window, indices); int expectedIndices = actualWindow + indices; assertThat(forecast.state().metadata().getProject(projectId).indices().size(), Matchers.equalTo(expectedIndices)); DataStream forecastDataStream = forecast.state().metadata().getProject(projectId).dataStreams().get("test"); assertThat(forecastDataStream.getIndices().size(), Matchers.equalTo(expectedIndices)); assertThat(forecastDataStream.getIndices().subList(0, indices), Matchers.equalTo(dataStream.getIndices())); RoutingTable forecastRoutingTable = forecast.state().routingTable(projectId); assertThat(forecastRoutingTable.allShards().count(), Matchers.equalTo((long) (expectedIndices) * shardCopies)); forecastDataStream.getIndices() .forEach(index -> assertThat(forecastRoutingTable.allShards(index.getName()).size(), Matchers.equalTo(shardCopies))); forecastRoutingTable.allShards().forEach(s -> assertThat(forecast.info().getShardSize(s), Matchers.notNullValue())); long expectedTotal = totalSize( dataStream.getIndices().subList(indices - actualWindow, indices), state.routingTable(projectId), info ); List<Index> addedIndices = forecastDataStream.getIndices().subList(indices, forecastDataStream.getIndices().size()); long actualTotal = totalSize(addedIndices, forecastRoutingTable, forecast.info()); // three round downs -> max 3 bytes lower and never above. assertThat(actualTotal, Matchers.lessThanOrEqualTo(expectedTotal)); assertThat(actualTotal, Matchers.greaterThanOrEqualTo(actualTotal - 3)); // omit last index, since it is reduced a bit for rounding. Total validated above so it all adds up. for (int i = 0; i < addedIndices.size() - 1; ++i) { forecastRoutingTable.allShards(addedIndices.get(i).getName()) .forEach( shard -> assertThat( forecast.info().getShardSize(shard), Matchers.equalTo(((expectedTotal - 1) / addedIndices.size() + 1) / shardCopies) ) ); } } } private long totalSize(List<Index> indices, RoutingTable routingTable, ClusterInfo info) { return indices.stream().flatMap(i -> routingTable.allShards(i.getName()).stream()).mapToLong(info::getShardSize).sum(); } private ClusterState randomAllocate(ClusterState state) { RoutingAllocation allocation = new RoutingAllocation( new AllocationDeciders(List.of()), state.mutableRoutingNodes(), state, null, null, System.nanoTime() ); randomAllocate(allocation); return ReactiveStorageDeciderServiceTests.updateClusterState(state, allocation); } private void randomAllocate(RoutingAllocation allocation) { RoutingNodes.UnassignedShards unassigned = allocation.routingNodes().unassigned(); Set<ShardRouting> primaries = StreamSupport.stream(unassigned.spliterator(), false) .filter(ShardRouting::primary) .collect(Collectors.toSet()); List<ShardRouting> primariesToAllocate = randomSubsetOf(between(1, primaries.size()), primaries); for (RoutingNodes.UnassignedShards.UnassignedIterator iterator = unassigned.iterator(); iterator.hasNext();) { if (primariesToAllocate.contains(iterator.next())) { iterator.initialize( randomFrom(Sets.newHashSet(allocation.routingNodes())).nodeId(), null, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE, allocation.changes() ); } } } private ClusterState startAll(ClusterState state) { RoutingAllocation allocation = new RoutingAllocation( new AllocationDeciders(List.of()), state.mutableRoutingNodes(), state, null, null, System.nanoTime() ); startAll(allocation); return ReactiveStorageDeciderServiceTests.updateClusterState(state, allocation); } private void startAll(RoutingAllocation allocation) { for (RoutingNodes.UnassignedShards.UnassignedIterator iterator = allocation.routingNodes().unassigned().iterator(); iterator .hasNext();) { ShardRouting unassignedShard = iterator.next(); assert unassignedShard.primary(); ShardRouting shardRouting = iterator.initialize( randomFrom(Sets.newHashSet(allocation.routingNodes())).nodeId(), null, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE, allocation.changes() ); allocation.routingNodes().startShard(shardRouting, allocation.changes(), ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE); } } private RoutingTable.Builder addRouting(Iterable<IndexMetadata> indices, RoutingTable.Builder builder) { indices.forEach(indexMetadata -> builder.addAsNew(indexMetadata)); return builder; } private ClusterInfo randomClusterInfo(ProjectState projectState) { Map<String, Long> shardSizes = projectState.routingTable() .allShards() .map(ClusterInfo::shardIdentifierFromRouting) .collect(Collectors.toMap(Function.identity(), id -> randomLongBetween(1, 1000), (v1, v2) -> v1)); Map<String, DiskUsage> diskUsage = new HashMap<>(); for (var id : projectState.cluster().nodes().getDataNodes().keySet()) { diskUsage.put(id, new DiskUsage(id, id, "/test", Long.MAX_VALUE, Long.MAX_VALUE)); } return ClusterInfo.builder().leastAvailableSpaceUsage(diskUsage).mostAvailableSpaceUsage(diskUsage).shardSizes(shardSizes).build(); } private ProjectMetadata applyCreatedDates(ProjectMetadata project, DataStream ds, long last, long decrement) { ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(project); List<Index> indices = ds.getIndices(); long start = last - (decrement * (indices.size() - 1)); for (int i = 0; i < indices.size(); ++i) { IndexMetadata previousInstance = project.index(indices.get(i)); projectBuilder.put(IndexMetadata.builder(previousInstance).creationDate(start + (i * decrement)).build(), false); } return projectBuilder.build(); } }
ProactiveStorageDeciderServiceTests
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/discovery/NestedMethodSelector.java
{ "start": 9032, "end": 9905 }
class ____ implements DiscoverySelectorIdentifierParser { private static final String PREFIX = "nested-method"; public IdentifierParser() { } @Override public String getPrefix() { return PREFIX; } @Override public Optional<NestedMethodSelector> parse(DiscoverySelectorIdentifier identifier, Context context) { List<String> parts = Arrays.asList(identifier.getValue().split("/")); List<String> enclosingClassNames = parts.subList(0, parts.size() - 1); String[] methodParts = ReflectionUtils.parseFullyQualifiedMethodName(parts.get(parts.size() - 1)); String nestedClassName = methodParts[0]; String methodName = methodParts[1]; String parameterTypeNames = methodParts[2]; return Optional.of(DiscoverySelectors.selectNestedMethod(enclosingClassNames, nestedClassName, methodName, parameterTypeNames)); } } }
IdentifierParser
java
spring-projects__spring-framework
spring-websocket/src/test/java/org/springframework/web/socket/WebSocketHandshakeTests.java
{ "start": 3889, "end": 4942 }
class ____ extends AbstractWebSocketHandler { private List<WebSocketMessage> receivedMessages = new ArrayList<>(); private int waitMessageCount; private final CountDownLatch latch = new CountDownLatch(1); private Throwable transportError; public void setWaitMessageCount(int waitMessageCount) { this.waitMessageCount = waitMessageCount; } public List<WebSocketMessage> getReceivedMessages() { return this.receivedMessages; } public Throwable getTransportError() { return this.transportError; } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) { this.receivedMessages.add(message); if (this.receivedMessages.size() >= this.waitMessageCount) { this.latch.countDown(); } } @Override public void handleTransportError(WebSocketSession session, Throwable exception) { this.transportError = exception; this.latch.countDown(); } public void await() throws InterruptedException { this.latch.await(5, TimeUnit.SECONDS); } } }
TestWebSocketHandler
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/clause/ConditionValue.java
{ "start": 1297, "end": 1400 }
enum ____ { SQLSTATE, SELF, SYSTEM, MYSQL_ERROR_CODE } }
ConditionType
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java
{ "start": 80037, "end": 80375 }
class ____ { @Autowired private Map<String, Runnable> testBeans; @Bean Runnable testBean() { return () -> {}; } // Unrelated, not to be considered as a factory method @SuppressWarnings("unused") private boolean testBean(boolean param) { return param; } } @Configuration abstract static
MapInjectionConfiguration
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/spatial/SpatialAggregationUtils.java
{ "start": 652, "end": 2268 }
class ____ { private SpatialAggregationUtils() { /* Utility class */ } public static Geometry decode(BytesRef wkb) { return WellKnownBinary.fromWKB(GeometryValidator.NOOP, false /* coerce */, wkb.bytes, wkb.offset, wkb.length); } public static Point decodePoint(BytesRef wkb) { return (Point) decode(wkb); } public static double decodeX(long encoded) { return XYEncodingUtils.decode(extractFirst(encoded)); } public static int extractFirst(long encoded) { return (int) (encoded >>> 32); } public static double decodeY(long encoded) { return XYEncodingUtils.decode(extractSecond(encoded)); } public static int extractSecond(long encoded) { return (int) (encoded & 0xFFFFFFFFL); } public static double decodeLongitude(long encoded) { return GeoEncodingUtils.decodeLongitude((int) (encoded & 0xFFFFFFFFL)); } public static double decodeLatitude(long encoded) { return GeoEncodingUtils.decodeLatitude((int) (encoded >>> 32)); } public static int encodeLongitude(double d) { return Double.isFinite(d) ? GeoEncodingUtils.encodeLongitude(d) : encodeInfinity(d); } private static int encodeInfinity(double d) { return d == Double.NEGATIVE_INFINITY ? Integer.MIN_VALUE : Integer.MAX_VALUE; } public static int maxNeg(int a, int b) { return a <= 0 && b <= 0 ? Math.max(a, b) : Math.min(a, b); } public static int minPos(int a, int b) { return a >= 0 && b >= 0 ? Math.min(a, b) : Math.max(a, b); } }
SpatialAggregationUtils
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/common/spatial/H3SphericalUtil.java
{ "start": 921, "end": 1028 }
class ____ org.elasticsearch.xpack.spatial.common, we should find a common location for it. */ public final
in
java
google__dagger
javatests/dagger/internal/codegen/ProducerModuleFactoryGeneratorTest.java
{ "start": 10616, "end": 10911 }
class ____ {}"); Source moduleFile = CompilerTests.javaSource( "test.FooModule", "package test;", "", "import dagger.producers.ProducerModule;", "", "@ProducerModule(includes = X.class)", "public final
X
java
quarkusio__quarkus
extensions/reactive-mssql-client/deployment/src/main/java/io/quarkus/reactive/mssql/client/deployment/MSSQLPoolBuildItem.java
{ "start": 348, "end": 1041 }
class ____ extends MultiBuildItem { private final String dataSourceName; private final Function<SyntheticCreationalContext<MSSQLPool>, MSSQLPool> mssqlPool; public MSSQLPoolBuildItem(String dataSourceName, Function<SyntheticCreationalContext<MSSQLPool>, MSSQLPool> mssqlPool) { this.dataSourceName = dataSourceName; this.mssqlPool = mssqlPool; } public String getDataSourceName() { return dataSourceName; } public Function<SyntheticCreationalContext<MSSQLPool>, MSSQLPool> getMSSQLPool() { return mssqlPool; } public boolean isDefault() { return DataSourceUtil.isDefault(dataSourceName); } }
MSSQLPoolBuildItem
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-traditional/src/main/java/smoketest/traditional/config/WebConfig.java
{ "start": 1366, "end": 2070 }
class ____ implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("home"); } @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Bean // Only used when running in embedded servlet public DispatcherServlet dispatcherServlet() { return new DispatcherServlet(); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
WebConfig
java
quarkusio__quarkus
extensions/infinispan-client/deployment/src/test/java/io/quarkus/infinispan/test/CreateADefaultRemoteCacheManagerWithEmptyConfTest.java
{ "start": 415, "end": 1137 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withConfigurationResource("empty-application-infinispan-client.properties"); @Test public void remoteCacheManagerDefaultBeansAccessible() { assertThat(Arc.container().instance(RemoteCacheManager.class, Default.Literal.INSTANCE).get()).isNotNull(); assertThat(Arc.container().instance(CounterManager.class, Default.Literal.INSTANCE).get()).isNotNull(); assertThat(Arc.container().listAll(RemoteCacheManager.class).size()).isEqualTo(1); assertThat(Arc.container().listAll(CounterManager.class).size()).isEqualTo(1); } }
CreateADefaultRemoteCacheManagerWithEmptyConfTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EntityJoinTest.java
{ "start": 10667, "end": 11157 }
class ____ { private Integer id; private String name; public Customer() { } public Customer(Integer id, String name) { this.id = id; this.name = name; } @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity(name = "FinancialRecord") @Table(name = "`a:financial_record`") public static
Customer
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schematools/EnumCheckTests.java
{ "start": 5640, "end": 6249 }
class ____ { @Id private Integer id; @Basic private String name; @Enumerated(EnumType.STRING) RetentionPolicy retentionPolicy; @Convert(converter=YesNoConverter.class) private boolean yesNo; @Convert(converter= NumericBooleanConverter.class) private boolean oneZero; private SimpleEntity() { // for use by Hibernate } public SimpleEntity(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
SimpleEntity
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/sort/LimitOperator.java
{ "start": 1182, "end": 1907 }
class ____ extends TableStreamOperator<RowData> implements OneInputStreamOperator<RowData, RowData> { private final boolean isGlobal; private final long limitStart; private final long limitEnd; private transient int count = 0; public LimitOperator(boolean isGlobal, long limitStart, long limitEnd) { this.isGlobal = isGlobal; this.limitStart = limitStart; this.limitEnd = limitEnd; } @Override public void processElement(StreamRecord<RowData> element) throws Exception { if (count < limitEnd) { count++; if (!isGlobal || count > limitStart) { output.collect(element); } } } }
LimitOperator
java
google__guava
android/guava/src/com/google/common/cache/LongAdder.java
{ "start": 1055, "end": 1389 }
class ____ usually preferable to {@link AtomicLong} when multiple threads update a common * sum that is used for purposes such as collecting statistics, not for fine-grained synchronization * control. Under low update contention, the two classes have similar characteristics. But under * high contention, expected throughput of this
is
java
dropwizard__dropwizard
dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/JacksonMessageBodyProviderTest.java
{ "start": 1300, "end": 1422 }
class ____ { private static final Annotation[] NONE = new Annotation[0]; public static
JacksonMessageBodyProviderTest
java
google__guava
android/guava-tests/test/com/google/common/reflect/TypeTokenTest.java
{ "start": 67320, "end": 69924 }
class ____<T> { List<T>[] matrix; void setList(List<T> list) {} } public void testWildcardCaptured_methodParameter_upperBound() throws Exception { TypeToken<Holder<?>> type = new TypeToken<Holder<?>>() {}; ImmutableList<Parameter> parameters = type.method(Holder.class.getDeclaredMethod("setList", List.class)).getParameters(); assertThat(parameters).hasSize(1); TypeToken<?> parameterType = parameters.get(0).getType(); assertEquals(List.class, parameterType.getRawType()); assertFalse( parameterType.getType().toString(), parameterType.isSupertypeOf(new TypeToken<List<Integer>>() {})); } public void testWildcardCaptured_field_upperBound() throws Exception { TypeToken<Holder<?>> type = new TypeToken<Holder<?>>() {}; TypeToken<?> matrixType = type.resolveType(Holder.class.getDeclaredField("matrix").getGenericType()); assertEquals(List[].class, matrixType.getRawType()); assertThat(matrixType.getType()).isNotEqualTo(new TypeToken<List<?>[]>() {}.getType()); } public void testWildcardCaptured_wildcardWithImplicitBound() throws Exception { TypeToken<Holder<?>> type = new TypeToken<Holder<?>>() {}; ImmutableList<Parameter> parameters = type.method(Holder.class.getDeclaredMethod("setList", List.class)).getParameters(); assertThat(parameters).hasSize(1); TypeToken<?> parameterType = parameters.get(0).getType(); Type[] typeArgs = ((ParameterizedType) parameterType.getType()).getActualTypeArguments(); assertThat(typeArgs).hasLength(1); TypeVariable<?> captured = (TypeVariable<?>) typeArgs[0]; assertThat(captured.getBounds()).asList().containsExactly(Object.class); assertThat(new TypeToken<List<?>>() {}.isSupertypeOf(parameterType)).isTrue(); } public void testWildcardCaptured_wildcardWithExplicitBound() throws Exception { TypeToken<Holder<? extends Number>> type = new TypeToken<Holder<? extends Number>>() {}; ImmutableList<Parameter> parameters = type.method(Holder.class.getDeclaredMethod("setList", List.class)).getParameters(); assertThat(parameters).hasSize(1); TypeToken<?> parameterType = parameters.get(0).getType(); Type[] typeArgs = ((ParameterizedType) parameterType.getType()).getActualTypeArguments(); assertThat(typeArgs).hasLength(1); TypeVariable<?> captured = (TypeVariable<?>) typeArgs[0]; assertThat(captured.getBounds()).asList().containsExactly(Number.class); assertThat(new TypeToken<List<? extends Number>>() {}.isSupertypeOf(parameterType)).isTrue(); } private static
Holder
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromIterableTest.java
{ "start": 1618, "end": 34864 }
class ____ extends RxJavaTest { @Test public void listIterable() { Flowable<String> flowable = Flowable.fromIterable(Arrays.<String> asList("one", "two", "three")); Subscriber<String> subscriber = TestHelper.mockSubscriber(); flowable.subscribe(subscriber); verify(subscriber, times(1)).onNext("one"); verify(subscriber, times(1)).onNext("two"); verify(subscriber, times(1)).onNext("three"); verify(subscriber, Mockito.never()).onError(any(Throwable.class)); verify(subscriber, times(1)).onComplete(); } /** * This tests the path that can not optimize based on size so must use setProducer. */ @Test public void rawIterable() { Iterable<String> it = new Iterable<String>() { @Override public Iterator<String> iterator() { return new Iterator<String>() { int i; @Override public boolean hasNext() { return i < 3; } @Override public String next() { return String.valueOf(++i); } @Override public void remove() { } }; } }; Flowable<String> flowable = Flowable.fromIterable(it); Subscriber<String> subscriber = TestHelper.mockSubscriber(); flowable.subscribe(subscriber); verify(subscriber, times(1)).onNext("1"); verify(subscriber, times(1)).onNext("2"); verify(subscriber, times(1)).onNext("3"); verify(subscriber, Mockito.never()).onError(any(Throwable.class)); verify(subscriber, times(1)).onComplete(); } @Test public void observableFromIterable() { Flowable<String> flowable = Flowable.fromIterable(Arrays.<String> asList("one", "two", "three")); Subscriber<String> subscriber = TestHelper.mockSubscriber(); flowable.subscribe(subscriber); verify(subscriber, times(1)).onNext("one"); verify(subscriber, times(1)).onNext("two"); verify(subscriber, times(1)).onNext("three"); verify(subscriber, Mockito.never()).onError(any(Throwable.class)); verify(subscriber, times(1)).onComplete(); } @Test public void backpressureViaRequest() { ArrayList<Integer> list = new ArrayList<>(Flowable.bufferSize()); for (int i = 1; i <= Flowable.bufferSize() + 1; i++) { list.add(i); } Flowable<Integer> f = Flowable.fromIterable(list); TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(0L); ts.assertNoValues(); ts.request(1); f.subscribe(ts); ts.assertValue(1); ts.request(2); ts.assertValues(1, 2, 3); ts.request(3); ts.assertValues(1, 2, 3, 4, 5, 6); ts.request(list.size()); ts.assertTerminated(); } @Test public void noBackpressure() { Flowable<Integer> f = Flowable.fromIterable(Arrays.asList(1, 2, 3, 4, 5)); TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(0L); ts.assertNoValues(); ts.request(Long.MAX_VALUE); // infinite f.subscribe(ts); ts.assertValues(1, 2, 3, 4, 5); ts.assertTerminated(); } @Test public void subscribeMultipleTimes() { Flowable<Integer> f = Flowable.fromIterable(Arrays.asList(1, 2, 3)); for (int i = 0; i < 10; i++) { TestSubscriber<Integer> ts = new TestSubscriber<>(); f.subscribe(ts); ts.assertValues(1, 2, 3); ts.assertNoErrors(); ts.assertComplete(); } } @Test public void fromIterableRequestOverflow() throws InterruptedException { Flowable<Integer> f = Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)); final int expectedCount = 4; final CountDownLatch latch = new CountDownLatch(expectedCount); f.subscribeOn(Schedulers.computation()) .subscribe(new DefaultSubscriber<Integer>() { @Override public void onStart() { request(2); } @Override public void onComplete() { //ignore } @Override public void onError(Throwable e) { throw new RuntimeException(e); } @Override public void onNext(Integer t) { latch.countDown(); request(Long.MAX_VALUE - 1); }}); assertTrue(latch.await(10, TimeUnit.SECONDS)); } @Test public void fromEmptyIterableWhenZeroRequestedShouldStillEmitOnCompletedEagerly() { final AtomicBoolean completed = new AtomicBoolean(false); Flowable.fromIterable(Collections.emptyList()).subscribe(new DefaultSubscriber<Object>() { @Override public void onStart() { // request(0); } @Override public void onComplete() { completed.set(true); } @Override public void onError(Throwable e) { } @Override public void onNext(Object t) { }}); assertTrue(completed.get()); } @Test public void doesNotCallIteratorHasNextMoreThanRequiredWithBackpressure() { final AtomicBoolean called = new AtomicBoolean(false); Iterable<Integer> iterable = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int count = 1; @Override public void remove() { // ignore } @Override public boolean hasNext() { if (count > 1) { called.set(true); return false; } return true; } @Override public Integer next() { return count++; } }; } }; Flowable.fromIterable(iterable).take(1).subscribe(); assertFalse(called.get()); } @Test public void doesNotCallIteratorHasNextMoreThanRequiredFastPath() { final AtomicBoolean called = new AtomicBoolean(false); Iterable<Integer> iterable = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public void remove() { // ignore } int count = 1; @Override public boolean hasNext() { if (count > 1) { called.set(true); return false; } return true; } @Override public Integer next() { return count++; } }; } }; Flowable.fromIterable(iterable).subscribe(new DefaultSubscriber<Integer>() { @Override public void onComplete() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer t) { // unsubscribe on first emission cancel(); } }); assertFalse(called.get()); } @Test public void getIteratorThrows() { Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { throw new TestException("Forced failure"); } }; TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.fromIterable(it).subscribe(ts); ts.assertNoValues(); ts.assertError(TestException.class); ts.assertNotComplete(); } @Test public void hasNextThrowsImmediately() { Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { throw new TestException("Forced failure"); } @Override public Integer next() { return null; } @Override public void remove() { // ignored } }; } }; TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.fromIterable(it).subscribe(ts); ts.assertNoValues(); ts.assertError(TestException.class); ts.assertNotComplete(); } @Test public void hasNextThrowsSecondTimeFastpath() { Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int count; @Override public boolean hasNext() { if (++count >= 2) { throw new TestException("Forced failure"); } return true; } @Override public Integer next() { return 1; } @Override public void remove() { // ignored } }; } }; TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.fromIterable(it).subscribe(ts); ts.assertValues(1); ts.assertError(TestException.class); ts.assertNotComplete(); } @Test public void hasNextThrowsSecondTimeSlowpath() { Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int count; @Override public boolean hasNext() { if (++count >= 2) { throw new TestException("Forced failure"); } return true; } @Override public Integer next() { return 1; } @Override public void remove() { // ignored } }; } }; TestSubscriber<Integer> ts = new TestSubscriber<>(5); Flowable.fromIterable(it).subscribe(ts); ts.assertValues(1); ts.assertError(TestException.class); ts.assertNotComplete(); } @Test public void nextThrowsFastpath() { Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { throw new TestException("Forced failure"); } @Override public void remove() { // ignored } }; } }; TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.fromIterable(it).subscribe(ts); ts.assertNoValues(); ts.assertError(TestException.class); ts.assertNotComplete(); } @Test public void nextThrowsSlowpath() { Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { throw new TestException("Forced failure"); } @Override public void remove() { // ignored } }; } }; TestSubscriber<Integer> ts = new TestSubscriber<>(5); Flowable.fromIterable(it).subscribe(ts); ts.assertNoValues(); ts.assertError(TestException.class); ts.assertNotComplete(); } @Test public void deadOnArrival() { Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { throw new NoSuchElementException(); } @Override public void remove() { // ignored } }; } }; TestSubscriber<Integer> ts = new TestSubscriber<>(5); ts.cancel(); Flowable.fromIterable(it).subscribe(ts); ts.assertNoValues(); ts.assertNoErrors(); ts.assertNotComplete(); } @Test public void fusionWithConcatMap() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)).concatMap( new Function<Integer, Flowable <Integer>>() { @Override public Flowable<Integer> apply(Integer v) { return Flowable.range(v, 2); } }).subscribe(ts); ts.assertValues(1, 2, 2, 3, 3, 4, 4, 5); ts.assertNoErrors(); ts.assertComplete(); } @Test public void fusedAPICalls() { Flowable.fromIterable(Arrays.asList(1, 2, 3)) .subscribe(new FlowableSubscriber<Integer>() { @Override public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") QueueSubscription<Integer> qs = (QueueSubscription<Integer>)s; assertFalse(qs.isEmpty()); try { assertEquals(1, qs.poll().intValue()); } catch (Throwable ex) { throw new AssertionError(ex); } assertFalse(qs.isEmpty()); qs.clear(); List<Throwable> errors = TestHelper.trackPluginErrors(); try { qs.request(-99); TestHelper.assertError(errors, 0, IllegalArgumentException.class, "n > 0 required but it was -99"); } finally { RxJavaPlugins.reset(); } } @Override public void onNext(Integer t) { } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }); } @Test public void normalConditional() { Flowable.fromIterable(Arrays.asList(1, 2, 3, 4, 5)) .filter(Functions.alwaysTrue()) .test() .assertResult(1, 2, 3, 4, 5); } @Test public void normalConditionalBackpressured() { Flowable.fromIterable(Arrays.asList(1, 2, 3, 4, 5)) .filter(Functions.alwaysTrue()) .test(5L) .assertResult(1, 2, 3, 4, 5); } @Test public void normalConditionalBackpressured2() { Flowable.fromIterable(Arrays.asList(1, 2, 3, 4, 5)) .filter(Functions.alwaysTrue()) .to(TestHelper.<Integer>testSubscriber(4L)) .assertSubscribed() .assertValues(1, 2, 3, 4) .assertNoErrors() .assertNotComplete(); } @Test public void emptyConditional() { Flowable.fromIterable(Arrays.asList(1, 2, 3, 4, 5)) .filter(Functions.alwaysFalse()) .test() .assertResult(); } @Test public void nullConditional() { Flowable.fromIterable(Arrays.asList(1, null, 3, 4, 5)) .filter(Functions.alwaysTrue()) .test() .assertFailure(NullPointerException.class, 1); } @Test public void nullConditionalBackpressured() { Flowable.fromIterable(Arrays.asList(1, null, 3, 4, 5)) .filter(Functions.alwaysTrue()) .test(5L) .assertFailure(NullPointerException.class, 1); } @Test public void normalConditionalCrash() { Flowable.fromIterable(new CrashingIterable(100, 2, 100)) .filter(Functions.alwaysTrue()) .test() .assertFailure(TestException.class, 0); } @Test public void normalConditionalCrash2() { Flowable.fromIterable(new CrashingIterable(100, 100, 2)) .filter(Functions.alwaysTrue()) .test() .assertFailure(TestException.class, 0); } @Test public void normalConditionalCrashBackpressured() { Flowable.fromIterable(new CrashingIterable(100, 2, 100)) .filter(Functions.alwaysTrue()) .test(5L) .assertFailure(TestException.class, 0); } @Test public void normalConditionalCrashBackpressured2() { Flowable.fromIterable(new CrashingIterable(100, 100, 2)) .filter(Functions.alwaysTrue()) .test(5L) .assertFailure(TestException.class, 0); } @Test public void normalConditionalLong() { Flowable.fromIterable(new CrashingIterable(100, 10 * 1000 * 1000, 10 * 1000 * 1000)) .filter(Functions.alwaysTrue()) .take(1000 * 1000) .to(TestHelper.<Integer>testConsumer()) .assertSubscribed() .assertValueCount(1000 * 1000) .assertNoErrors() .assertComplete(); } @Test public void normalConditionalLong2() { Flowable.fromIterable(new CrashingIterable(100, 10 * 1000 * 1000, 10 * 1000 * 1000)) .filter(Functions.alwaysTrue()) .rebatchRequests(128) .take(1000 * 1000) .to(TestHelper.<Integer>testConsumer()) .assertSubscribed() .assertValueCount(1000 * 1000) .assertNoErrors() .assertComplete(); } @Test public void requestRaceConditional() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber<Integer> ts = new TestSubscriber<>(0L); Runnable r = new Runnable() { @Override public void run() { ts.request(1); } }; Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)) .filter(Functions.alwaysTrue()) .subscribe(ts); TestHelper.race(r, r); } } @Test public void requestRaceConditional2() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber<Integer> ts = new TestSubscriber<>(0L); Runnable r = new Runnable() { @Override public void run() { ts.request(1); } }; Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)) .filter(Functions.alwaysFalse()) .subscribe(ts); TestHelper.race(r, r); } } @Test public void requestCancelConditionalRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber<Integer> ts = new TestSubscriber<>(0L); Runnable r1 = new Runnable() { @Override public void run() { ts.request(1); } }; Runnable r2 = new Runnable() { @Override public void run() { ts.cancel(); } }; Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)) .filter(Functions.alwaysTrue()) .subscribe(ts); TestHelper.race(r1, r2); } } @Test public void requestCancelConditionalRace2() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber<Integer> ts = new TestSubscriber<>(0L); Runnable r1 = new Runnable() { @Override public void run() { ts.request(Long.MAX_VALUE); } }; Runnable r2 = new Runnable() { @Override public void run() { ts.cancel(); } }; Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)) .filter(Functions.alwaysTrue()) .subscribe(ts); TestHelper.race(r1, r2); } } @Test public void requestCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber<Integer> ts = new TestSubscriber<>(0L); Runnable r1 = new Runnable() { @Override public void run() { ts.request(1); } }; Runnable r2 = new Runnable() { @Override public void run() { ts.cancel(); } }; Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)) .subscribe(ts); TestHelper.race(r1, r2); } } @Test public void requestCancelRace2() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber<Integer> ts = new TestSubscriber<>(0L); Runnable r1 = new Runnable() { @Override public void run() { ts.request(Long.MAX_VALUE); } }; Runnable r2 = new Runnable() { @Override public void run() { ts.cancel(); } }; Flowable.fromIterable(Arrays.asList(1, 2, 3, 4)) .subscribe(ts); TestHelper.race(r1, r2); } } @Test public void fusionRejected() { TestSubscriberEx<Integer> ts = new TestSubscriberEx<Integer>().setInitialFusionMode(QueueFuseable.ASYNC); Flowable.fromIterable(Arrays.asList(1, 2, 3)) .subscribe(ts); ts.assertFusionMode(QueueFuseable.NONE) .assertResult(1, 2, 3); } @Test public void fusionClear() { Flowable.fromIterable(Arrays.asList(1, 2, 3)) .subscribe(new FlowableSubscriber<Integer>() { @Override public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") QueueSubscription<Integer> qs = (QueueSubscription<Integer>)s; qs.requestFusion(QueueFuseable.ANY); try { assertEquals(1, qs.poll().intValue()); } catch (Throwable ex) { fail(ex.toString()); } qs.clear(); try { assertNull(qs.poll()); } catch (Throwable ex) { fail(ex.toString()); } } @Override public void onNext(Integer value) { } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } @Test public void iteratorThrows() { Flowable.fromIterable(new CrashingIterable(1, 100, 100)) .to(TestHelper.<Integer>testConsumer()) .assertFailureAndMessage(TestException.class, "iterator()"); } @Test public void hasNext2Throws() { Flowable.fromIterable(new CrashingIterable(100, 2, 100)) .to(TestHelper.<Integer>testConsumer()) .assertFailureAndMessage(TestException.class, "hasNext()", 0); } @Test public void hasNextCancels() { final TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.fromIterable(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int count; @Override public boolean hasNext() { if (++count == 2) { ts.cancel(); } return true; } @Override public Integer next() { return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }) .subscribe(ts); ts.assertValue(1) .assertNoErrors() .assertNotComplete(); } @Test public void hasNextCancelsAndCompletesFastPath() { final TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.fromIterable(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int count; @Override public boolean hasNext() { if (++count == 2) { ts.cancel(); return false; } return true; } @Override public Integer next() { return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }) .subscribe(ts); ts.assertValue(1) .assertNoErrors() .assertNotComplete(); } @Test public void hasNextCancelsAndCompletesSlowPath() { final TestSubscriber<Integer> ts = new TestSubscriber<>(10L); Flowable.fromIterable(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int count; @Override public boolean hasNext() { if (++count == 2) { ts.cancel(); return false; } return true; } @Override public Integer next() { return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }) .subscribe(ts); ts.assertValue(1) .assertNoErrors() .assertNotComplete(); } @Test public void hasNextCancelsAndCompletesFastPathConditional() { final TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.fromIterable(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int count; @Override public boolean hasNext() { if (++count == 2) { ts.cancel(); return false; } return true; } @Override public Integer next() { return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }) .filter(v -> true) .subscribe(ts); ts.assertValue(1) .assertNoErrors() .assertNotComplete(); } @Test public void hasNextCancelsAndCompletesSlowPathConditional() { final TestSubscriber<Integer> ts = new TestSubscriber<>(10); Flowable.fromIterable(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int count; @Override public boolean hasNext() { if (++count == 2) { ts.cancel(); return false; } return true; } @Override public Integer next() { return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }) .filter(v -> true) .subscribe(ts); ts.assertValue(1) .assertNoErrors() .assertNotComplete(); } @Test public void fusedPoll() throws Throwable { AtomicReference<SimpleQueue<?>> queue = new AtomicReference<>(); Flowable.fromIterable(Arrays.asList(1)) .subscribe(new FlowableSubscriber<Integer>() { @Override public void onSubscribe(@NonNull Subscription s) { queue.set((SimpleQueue<?>)s); ((QueueSubscription<?>)s).requestFusion(QueueFuseable.ANY); } @Override public void onNext(Integer t) { } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }); SimpleQueue<?> q = queue.get(); assertFalse(q.isEmpty()); assertEquals(1, q.poll()); assertTrue(q.isEmpty()); q.clear(); assertTrue(q.isEmpty()); } @Test public void disposeWhileIteratorNext() { final TestSubscriber<Integer> ts = new TestSubscriber<>(10); Flowable.fromIterable(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { ts.cancel(); return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }) .subscribe(ts); ts.assertEmpty(); } @Test public void disposeWhileIteratorNextConditional() { final TestSubscriber<Integer> ts = new TestSubscriber<>(10); Flowable.fromIterable(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { ts.cancel(); return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }) .filter(v -> true) .subscribe(ts); ts.assertEmpty(); } }
FlowableFromIterableTest
java
grpc__grpc-java
xds/src/generated/thirdparty/grpc/io/envoyproxy/envoy/service/auth/v3/AuthorizationGrpc.java
{ "start": 6317, "end": 7385 }
class ____ extends io.grpc.stub.AbstractAsyncStub<AuthorizationStub> { private AuthorizationStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected AuthorizationStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new AuthorizationStub(channel, callOptions); } /** * <pre> * Performs authorization check based on the attributes associated with the * incoming request, and returns status `OK` or not `OK`. * </pre> */ public void check(io.envoyproxy.envoy.service.auth.v3.CheckRequest request, io.grpc.stub.StreamObserver<io.envoyproxy.envoy.service.auth.v3.CheckResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCheckMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service Authorization. * <pre> * A generic
AuthorizationStub
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/converter/UnsupportedPropertyException.java
{ "start": 979, "end": 1193 }
class ____ extends RuntimeException { private static final long serialVersionUID = 5468104026818355871L; public UnsupportedPropertyException(String message) { super(message); } }
UnsupportedPropertyException
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/GeoShapeParser.java
{ "start": 932, "end": 2598 }
class ____ extends AbstractGeometryFieldMapper.Parser<Geometry> { private final GeometryParser geometryParser; private final Orientation orientation; public GeoShapeParser(GeometryParser geometryParser, Orientation orientation) { this.geometryParser = geometryParser; this.orientation = orientation; } @Override public void parse( XContentParser parser, CheckedConsumer<Geometry, IOException> consumer, AbstractGeometryFieldMapper.MalformedValueHandler malformedHandler ) throws IOException { try { if (parser.currentToken() == XContentParser.Token.START_ARRAY) { while (parser.nextToken() != XContentParser.Token.END_ARRAY) { parse(parser, consumer, malformedHandler); } } else { consumer.accept(geometryParser.parse(parser)); } } catch (ParseException | ElasticsearchParseException | IllegalArgumentException e) { malformedHandler.notify(e); } } @Override public Geometry normalizeFromSource(Geometry geometry) { // GeometryNormalizer contains logic for validating the input geometry, // so it needs to be run always at indexing time. When run over source we can skip // the validation, and we run normalization (which is expensive) only when we need // to split geometries around the dateline. if (GeometryNormalizer.needsNormalize(orientation, geometry)) { return GeometryNormalizer.apply(orientation, geometry); } else { return geometry; } } }
GeoShapeParser
java
netty__netty
testsuite/src/main/java/io/netty/testsuite/transport/udt/UDTClientServerConnectionTest.java
{ "start": 5694, "end": 6839 }
class ____ extends SimpleChannelInboundHandler<Object> { static final Logger log = LoggerFactory.getLogger(ClientHandler.class); volatile boolean isActive; @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { isActive = true; log.info("Client active {}", ctx.channel()); super.channelActive(ctx); } @Override public void channelInactive(final ChannelHandlerContext ctx) throws Exception { isActive = false; log.info("Client inactive {}", ctx.channel()); super.channelInactive(ctx); } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { log.warn("Client unexpected exception from downstream.", cause); ctx.close(); } @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { log.info("Client received: " + msg); } } static
ClientHandler
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/bigquery/AggregateTest.java
{ "start": 375, "end": 1367 }
class ____ { @Test public void test_agg() { String sql = "SELECT lag(date(d,'Asia/Jakarta')) over(partition by id order by n) FROM t1"; SQLSelectStatement stmt = (SQLSelectStatement) SQLUtils.parseSingleStatement(sql, DbType.bigquery); SQLSelectQueryBlock queryBlock = stmt.getSelect().getQueryBlock(); SQLAggregateExpr expr = (SQLAggregateExpr) queryBlock.getSelectList().get(0).getExpr(); assertSame(expr, expr.getArgument(0).getParent()); } @Test public void test_agg_1() { String sql = "SELECT xx(date(d,'Asia/Jakarta')) over(partition by id order by n) FROM t1"; SQLSelectStatement stmt = (SQLSelectStatement) SQLUtils.parseSingleStatement(sql, DbType.bigquery); SQLSelectQueryBlock queryBlock = stmt.getSelect().getQueryBlock(); SQLAggregateExpr expr = (SQLAggregateExpr) queryBlock.getSelectList().get(0).getExpr(); assertSame(expr, expr.getArgument(0).getParent()); } }
AggregateTest
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/RemoveRaftVoterResult.java
{ "start": 1230, "end": 1553 }
class ____ { private final KafkaFuture<Void> result; RemoveRaftVoterResult(KafkaFuture<Void> result) { this.result = result; } /** * Returns a future that completes when the voter has been removed. */ public KafkaFuture<Void> all() { return result; } }
RemoveRaftVoterResult
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/aggregate/Last.java
{ "start": 2223, "end": 6225 }
class ____ extends AggregateFunction implements ToAggregator { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(Expression.class, "Last", Last::readFrom); private final Expression sort; // TODO: support all types @FunctionInfo( type = FunctionType.AGGREGATE, returnType = { "long", "integer", "double", "keyword" }, description = "Calculates the latest value of a field.", appliesTo = { @FunctionAppliesTo(lifeCycle = FunctionAppliesToLifecycle.GA, version = "9.3.0") }, examples = @Example(file = "stats_last", tag = "last") ) public Last( Source source, @Param( name = "value", type = { "long", "integer", "double", "keyword", "text" }, description = "Values to return" ) Expression field, @Param(name = "sort", type = { "date", "date_nanos" }, description = "Sort key") Expression sort ) { this(source, field, Literal.TRUE, NO_WINDOW, sort); } private Last(Source source, Expression field, Expression filter, Expression window, Expression sort) { super(source, field, filter, window, List.of(sort)); this.sort = sort; } private static Last readFrom(StreamInput in) throws IOException { Source source = Source.readFrom((PlanStreamInput) in); Expression field = in.readNamedWriteable(Expression.class); Expression filter = in.readNamedWriteable(Expression.class); Expression window = readWindow(in); List<Expression> params = in.readNamedWriteableCollectionAsList(Expression.class); Expression sort = params.getFirst(); return new Last(source, field, filter, window, sort); } @Override public String getWriteableName() { return ENTRY.name; } @Override protected NodeInfo<Last> info() { return NodeInfo.create(this, Last::new, field(), sort); } @Override public Last replaceChildren(List<Expression> newChildren) { return new Last(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2), newChildren.get(3)); } @Override public Last withFilter(Expression filter) { return new Last(source(), field(), filter, window(), sort); } public Expression sort() { return sort; } @Override public DataType dataType() { return field().dataType().noText(); } @Override protected TypeResolution resolveType() { return isType( field(), dt -> dt == DataType.BOOLEAN || dt == DataType.DATETIME || DataType.isString(dt) || (dt.isNumeric() && dt != DataType.UNSIGNED_LONG), sourceText(), FIRST, "boolean", "date", "ip", "string", "numeric except unsigned_long or counter types" ).and( isType( sort, dt -> dt == DataType.LONG || dt == DataType.DATETIME || dt == DataType.DATE_NANOS, sourceText(), SECOND, "long or date_nanos or datetime" ) ); } @Override public AggregatorFunctionSupplier supplier() { final DataType type = field().dataType(); return switch (type) { case LONG -> new LastLongByTimestampAggregatorFunctionSupplier(); case INTEGER -> new LastIntByTimestampAggregatorFunctionSupplier(); case DOUBLE -> new LastDoubleByTimestampAggregatorFunctionSupplier(); case FLOAT -> new LastFloatByTimestampAggregatorFunctionSupplier(); case KEYWORD, TEXT -> new LastBytesRefByTimestampAggregatorFunctionSupplier(); default -> throw EsqlIllegalArgumentException.illegalDataType(type); }; } @Override public String toString() { return "last(" + field() + ", " + sort + ")"; } }
Last
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationBeanRegistrationAotProcessorTests.java
{ "start": 8837, "end": 9110 }
class ____ { private final String name; public ConstructorParameterLevelConstraint(@Exists String name) { this.name = name; } public String hello() { return "Hello " + this.name; } } @SuppressWarnings("unused") static
ConstructorParameterLevelConstraint
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java
{ "start": 28944, "end": 29131 }
class ____ { private String name; public Person(String name) { this.name = name; } public String getName() { return this.name; } } @TestQualifier private static
Person
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/util/ForwardingOutputStream.java
{ "start": 1137, "end": 1873 }
class ____ extends OutputStream { private final OutputStream delegate; public ForwardingOutputStream(OutputStream delegate) { this.delegate = Preconditions.checkNotNull(delegate); } @Override public void write(int b) throws IOException { delegate.write(b); } @Override public void write(byte[] b) throws IOException { delegate.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { delegate.write(b, off, len); } @Override public void flush() throws IOException { delegate.flush(); } @Override public void close() throws IOException { delegate.close(); } }
ForwardingOutputStream
java
quarkusio__quarkus
extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/QuarkusTransactionException.java
{ "start": 166, "end": 722 }
class ____ extends RuntimeException { public QuarkusTransactionException(Throwable cause) { super(cause); } public QuarkusTransactionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public QuarkusTransactionException(String message) { super(message); } public QuarkusTransactionException(String message, Throwable cause) { super(message, cause); } }
QuarkusTransactionException
java
apache__camel
tooling/maven/camel-package-maven-plugin/src/test/java/org/apache/camel/maven/packaging/JavadocTest.java
{ "start": 5505, "end": 7608 }
class ____ {\n" + "}"; public static final String JAVADOC_2 = "Sets how requests and responses will be mapped to/from Camel. Two values are possible:\n" + "<ul>\n<li>SimpleConsumer: This binding style processes request parameters, multiparts, etc. " + "and maps them to IN headers, IN attachments and to the message body.\nIt aims to eliminate " + "low-level processing of {@link org.apache.cxf.message.MessageContentsList}.\nIt also also adds more " + "flexibility and simplicity to the response mapping.\nOnly available for consumers.\n</li>\n" + "<li>Default: The default style. For consumers this passes on a MessageContentsList to the " + "route, requiring low-level processing in the route.\nThis is the traditional binding style, " + "which simply dumps the {@link org.apache.cxf.message.MessageContentsList} coming in from the CXF " + "stack\nonto the IN message body. The user is then responsible for processing it according " + "to the contract defined by the JAX-RS method signature.\n</li>\n<li>Custom: allows you to " + "specify a custom binding through the binding option.</li>\n</ul>"; public static final String SOURCE_CLASS_3 = " /**\n" + " * Sets the alias used to query the KeyStore for keys and {@link java.security.cert.Certificate Certificates}\n" + " * to be used in signing and verifying exchanges. This value can be provided at runtime via the message header\n" + " * {@link org.apache.camel.component.crypto.DigitalSignatureConstants#KEYSTORE_ALIAS}\n" + " */\n" + "
Test
java
alibaba__fastjson
src/main/java/com/alibaba/fastjson/serializer/ToStringSerializer.java
{ "start": 109, "end": 637 }
class ____ implements ObjectSerializer { public static final ToStringSerializer instance = new ToStringSerializer(); @Override public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { SerializeWriter out = serializer.out; if (object == null) { out.writeNull(); return; } String strVal = object.toString(); out.writeString(strVal); } }
ToStringSerializer
java
apache__camel
components/camel-docker/src/test/java/org/apache/camel/component/docker/headers/PauseContainerCmdHeaderTest.java
{ "start": 1279, "end": 2059 }
class ____ extends BaseDockerHeaderTest<PauseContainerCmd> { @Mock private PauseContainerCmd mockObject; @Test void pauseHeaderTest() { String containerId = "9c09acd48a25"; Map<String, Object> headers = getDefaultParameters(); headers.put(DockerConstants.DOCKER_CONTAINER_ID, containerId); template.sendBodyAndHeaders("direct:in", "", headers); Mockito.verify(dockerClient, Mockito.times(1)).pauseContainerCmd(containerId); } @Override protected void setupMocks() { Mockito.when(dockerClient.pauseContainerCmd(anyString())).thenReturn(mockObject); } @Override protected DockerOperation getOperation() { return DockerOperation.PAUSE_CONTAINER; } }
PauseContainerCmdHeaderTest
java
apache__spark
sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/operation/TableTypeMapping.java
{ "start": 1079, "end": 1525 }
interface ____ { /** * Map client's table type name to hive's table type * @param clientTypeName * @return */ String[] mapToHiveType(String clientTypeName); /** * Map hive's table type name to client's table type * @param hiveTypeName * @return */ String mapToClientType(String hiveTypeName); /** * Get all the table types of this mapping * @return */ Set<String> getTableTypeNames(); }
TableTypeMapping
java
FasterXML__jackson-core
src/test/java/tools/jackson/core/unittest/io/BufferRecyclerPoolTest.java
{ "start": 3252, "end": 3694 }
class ____ extends OutputStream { protected int size = 0; NopOutputStream() { } @Override public void write(int b) throws IOException { ++size; } @Override public void write(byte[] b) throws IOException { size += b.length; } @Override public void write(byte[] b, int offset, int len) throws IOException { size += len; } } @SuppressWarnings("serial")
NopOutputStream
java
spring-projects__spring-boot
module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/autoconfigure/RabbitProperties.java
{ "start": 16290, "end": 16826 }
class ____ { /** * Connection factory cache mode. */ private CacheMode mode = CacheMode.CHANNEL; /** * Number of connections to cache. Only applies when mode is CONNECTION. */ private @Nullable Integer size; public CacheMode getMode() { return this.mode; } public void setMode(CacheMode mode) { this.mode = mode; } public @Nullable Integer getSize() { return this.size; } public void setSize(@Nullable Integer size) { this.size = size; } } } public
Connection
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/insert/OracleInsertTest16.java
{ "start": 1062, "end": 2462 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = "INSERT INTO departments " + " VALUES (departments_seq.nextval, 'Entertainment', 162, 1400); "; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); // print(statementList); assertEquals(1, statementList.size()); assertEquals("INSERT INTO departments" + "\nVALUES (departments_seq.NEXTVAL, 'Entertainment', 162, 1400);", SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE)); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("relationships : " + visitor.getRelationships()); assertEquals(1, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("departments"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("employees", "salary"))); } }
OracleInsertTest16
java
google__dagger
javatests/dagger/functional/producers/optional/OptionalBindingComponents.java
{ "start": 3816, "end": 4129 }
class ____ { @Provides static Value value() { return Value.VALUE; } @Provides @SomeQualifier static Value qualifiedValue() { return Value.QUALIFIED_VALUE; } @Provides @Nullable static Object nullableObject() { return null; } }
ConcreteBindingModule
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/leaderelection/ZooKeeperLeaderElectionTest.java
{ "start": 28471, "end": 29923 }
class ____ implements CuratorCacheListener { final CompletableFuture<Boolean> deletedPromise = new CompletableFuture<>(); final CuratorCache cache; public static DeletedCacheListener createWithNodeExistValidation( CuratorCache cache, String path) { Preconditions.checkState( cache.get(path).isPresent(), "The given path %s should lead to an already existing node. This listener will then check that the node was properly deleted.", path); return new DeletedCacheListener(cache); } private DeletedCacheListener(final CuratorCache cache) { this.cache = cache; } public Future<Boolean> nodeDeleted() { return deletedPromise; } @Override public void event(Type type, ChildData oldData, ChildData data) { if ((type == Type.NODE_DELETED || data == null) && !deletedPromise.isDone()) { deletedPromise.complete(true); cache.listenable().removeListener(this); } } } private ZooKeeperLeaderElectionDriver createAndInitLeaderElectionDriver( CuratorFramework client, TestingLeaderElectionListener electionEventHandler) throws Exception { return new ZooKeeperLeaderElectionDriverFactory(client).create(electionEventHandler); } }
DeletedCacheListener
java
spring-projects__spring-framework
spring-oxm/src/main/java/org/springframework/oxm/Unmarshaller.java
{ "start": 1092, "end": 1664 }
class ____ this unmarshaller is being asked if it can marshal * @return {@code true} if this unmarshaller can indeed unmarshal to the supplied class; * {@code false} otherwise */ boolean supports(Class<?> clazz); /** * Unmarshal the given {@link Source} into an object graph. * @param source the source to marshal from * @return the object graph * @throws IOException if an I/O error occurs * @throws XmlMappingException if the given source cannot be mapped to an object */ Object unmarshal(Source source) throws IOException, XmlMappingException; }
that
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/usertype/DynamicParameterizedType.java
{ "start": 1427, "end": 1770 }
interface ____ { Class<?> getReturnedClass(); @Incubating default Type getReturnedJavaType() { return getReturnedClass(); } Annotation[] getAnnotationsMethod(); String getCatalog(); String getSchema(); String getTable(); boolean isPrimaryKey(); String[] getColumns(); Long[] getColumnLengths(); } }
ParameterType
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/persistent/PersistentTaskInitializationFailureIT.java
{ "start": 1643, "end": 3052 }
class ____ extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return List.of(FailingInitializationPersistentTasksPlugin.class); } public void testPersistentTasksThatFailDuringInitializationAreRemovedFromClusterState() throws Exception { PersistentTasksService persistentTasksService = internalCluster().getInstance(PersistentTasksService.class); PlainActionFuture<PersistentTasksCustomMetadata.PersistentTask<FailingInitializationTaskParams>> startPersistentTaskFuture = new PlainActionFuture<>(); persistentTasksService.sendStartRequest( UUIDs.base64UUID(), FailingInitializationPersistentTaskExecutor.TASK_NAME, new FailingInitializationTaskParams(), TEST_REQUEST_TIMEOUT, startPersistentTaskFuture ); startPersistentTaskFuture.actionGet(); assertBusy(() -> { final ClusterService clusterService = internalCluster().getAnyMasterNodeInstance(ClusterService.class); List<PersistentTasksCustomMetadata.PersistentTask<?>> tasks = findTasks( clusterService.state(), FailingInitializationPersistentTaskExecutor.TASK_NAME ); assertThat(tasks.toString(), tasks, empty()); }); } public static
PersistentTaskInitializationFailureIT
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/audit/impl/LoggingAuditor.java
{ "start": 18187, "end": 20919 }
class ____ extends LoggingAuditSpan { private WarningSpan( final String name, final CommonAuditContext context, final String spanId, final String path1, final String path2) { super(spanId, name, context, path1, path2); } @Override public void start() { LOG.warn("[{}] {} Start {}", currentThreadID(), getSpanId(), getDescription()); } @Override public AuditSpanS3A activate() { LOG.warn("[{}] {} Activate {}", currentThreadID(), getSpanId(), getDescription()); return this; } @Override public boolean isValidSpan() { return false; } @Override public void requestCreated(final SdkRequest.Builder builder) { String error = "Creating a request outside an audit span " + analyzer.analyze(builder.build()); LOG.info(error); if (LOG.isDebugEnabled()) { LOG.debug(error, new AuditFailureException("unaudited")); } } /** * Handle requests made without a real context by logging and * increment the failure count. * Some requests (e.g. copy part) are not expected in spans due * to how they are executed; these do not trigger failures. * @param context The current state of the execution, including * the unmodified SDK request from the service * client call. * @param executionAttributes A mutable set of attributes scoped * to one specific request/response * cycle that can be used to give data * to future lifecycle methods. */ @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { String error = "executing a request outside an audit span " + analyzer.analyze(context.request()); final String unaudited = getSpanId() + " " + UNAUDITED_OPERATION + " " + error; // If request is attached to a span in the modifyHttpRequest, as is the case for requests made by AAL, treat it // as an audited request. if (isRequestNotAlwaysInSpan(context.request())) { // can get by auditing during a copy, so don't overreact. LOG.debug(unaudited); } else if (!isRequestAuditedOutsideOfCurrentSpan(executionAttributes)) { final RuntimeException ex = new AuditFailureException(unaudited); LOG.debug(unaudited, ex); if (isRejectOutOfSpan()) { throw ex; } } // now hand off to the superclass for its normal preparation super.beforeExecution(context, executionAttributes); } } }
WarningSpan
java
apache__kafka
trogdor/src/test/java/org/apache/kafka/trogdor/common/TopologyTest.java
{ "start": 1394, "end": 2457 }
class ____ { @Test public void testAgentNodeNames() { TreeMap<String, Node> nodes = new TreeMap<>(); final int numNodes = 5; for (int i = 0; i < numNodes; i++) { Map<String, String> conf = new HashMap<>(); if (i == 0) { conf.put(Platform.Config.TROGDOR_COORDINATOR_PORT, String.valueOf(Coordinator.DEFAULT_PORT)); } else { conf.put(Platform.Config.TROGDOR_AGENT_PORT, String.valueOf(Agent.DEFAULT_PORT)); } BasicNode node = new BasicNode(String.format("node%02d", i), String.format("node%d.example.com", i), conf, new HashSet<>()); nodes.put(node.name(), node); } Topology topology = new BasicTopology(nodes); Set<String> names = Topology.Util.agentNodeNames(topology); assertEquals(4, names.size()); for (int i = 1; i < numNodes - 1; i++) { assertTrue(names.contains(String.format("node%02d", i))); } } }
TopologyTest