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
server/src/main/java/org/elasticsearch/indices/analysis/wrappers/StableApiWrappers.java
{ "start": 1907, "end": 9881 }
class ____ { public static Map<String, AnalysisModule.AnalysisProvider<org.elasticsearch.index.analysis.CharFilterFactory>> oldApiForStableCharFilterFactory(StablePluginsRegistry stablePluginRegistry) { return mapStablePluginApiToOld(stablePluginRegistry, CharFilterFactory.class, StableApiWrappers::wrapCharFilterFactory); } public static Map<String, AnalysisModule.AnalysisProvider<org.elasticsearch.index.analysis.TokenFilterFactory>> oldApiForTokenFilterFactory(StablePluginsRegistry stablePluginRegistry) { return mapStablePluginApiToOld(stablePluginRegistry, TokenFilterFactory.class, StableApiWrappers::wrapTokenFilterFactory); } public static Map<String, AnalysisModule.AnalysisProvider<org.elasticsearch.index.analysis.TokenizerFactory>> oldApiForTokenizerFactory( StablePluginsRegistry stablePluginRegistry ) { return mapStablePluginApiToOld(stablePluginRegistry, TokenizerFactory.class, StableApiWrappers::wrapTokenizerFactory); } public static Map<String, AnalysisModule.AnalysisProvider<org.elasticsearch.index.analysis.AnalyzerProvider<?>>> oldApiForAnalyzerFactory(StablePluginsRegistry stablePluginRegistry) { return mapStablePluginApiToOld(stablePluginRegistry, AnalyzerFactory.class, StableApiWrappers::wrapAnalyzerFactory); } private static <T, F> Map<String, AnalysisModule.AnalysisProvider<T>> mapStablePluginApiToOld( StablePluginsRegistry stablePluginRegistry, Class<F> charFilterFactoryClass, Function<F, T> wrapper ) { Collection<PluginInfo> pluginInfosForExtensible = stablePluginRegistry.getPluginInfosForExtensible( charFilterFactoryClass.getCanonicalName() ); Map<String, AnalysisModule.AnalysisProvider<T>> oldApiComponents = pluginInfosForExtensible.stream() .collect(Collectors.toMap(PluginInfo::name, p -> analysisProviderWrapper(p, wrapper))); return oldApiComponents; } @SuppressWarnings("unchecked") private static <F, T> AnalysisModule.AnalysisProvider<T> analysisProviderWrapper(PluginInfo pluginInfo, Function<F, T> wrapper) { return new AnalysisModule.AnalysisProvider<T>() { @Override public T get(IndexSettings indexSettings, Environment environment, String name, Settings settings) throws IOException { try { Class<? extends F> clazz = (Class<? extends F>) pluginInfo.loader().loadClass(pluginInfo.className()); F instance = createInstance(clazz, indexSettings, environment.settings(), settings, environment); return wrapper.apply(instance); } catch (ClassNotFoundException e) { throw new IllegalStateException("Plugin classloader cannot find class " + pluginInfo.className(), e); } } }; } private static org.elasticsearch.index.analysis.CharFilterFactory wrapCharFilterFactory(CharFilterFactory charFilterFactory) { return new org.elasticsearch.index.analysis.CharFilterFactory() { @Override public String name() { return charFilterFactory.name(); } @Override public Reader create(Reader reader) { return charFilterFactory.create(reader); } @Override public Reader normalize(Reader reader) { return charFilterFactory.normalize(reader); } }; } private static org.elasticsearch.index.analysis.TokenFilterFactory wrapTokenFilterFactory(TokenFilterFactory f) { return new org.elasticsearch.index.analysis.TokenFilterFactory() { @Override public String name() { return f.name(); } @Override public TokenStream create(TokenStream tokenStream) { return f.create(tokenStream); } @Override public TokenStream normalize(TokenStream tokenStream) { return f.normalize(tokenStream); } @Override public org.elasticsearch.index.analysis.AnalysisMode getAnalysisMode() { return mapAnalysisMode(f.getAnalysisMode()); } private static org.elasticsearch.index.analysis.AnalysisMode mapAnalysisMode(AnalysisMode analysisMode) { return org.elasticsearch.index.analysis.AnalysisMode.valueOf(analysisMode.name()); } }; } private static org.elasticsearch.index.analysis.TokenizerFactory wrapTokenizerFactory(TokenizerFactory f) { return new org.elasticsearch.index.analysis.TokenizerFactory() { @Override public String name() { return f.name(); } @Override public Tokenizer create() { return f.create(); } }; } private static org.elasticsearch.index.analysis.AnalyzerProvider<?> wrapAnalyzerFactory(AnalyzerFactory f) { return new org.elasticsearch.index.analysis.AnalyzerProvider<>() { @Override public String name() { return f.name(); } @Override public org.elasticsearch.index.analysis.AnalyzerScope scope() { return org.elasticsearch.index.analysis.AnalyzerScope.GLOBAL;// TODO is this right? } @Override public Analyzer get() { return f.create(); } }; } @SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> T createInstance( Class<T> clazz, IndexSettings indexSettings, Settings nodeSettings, Settings analysisSettings, Environment environment ) { try { Constructor<?>[] constructors = clazz.getConstructors(); if (constructors.length > 1) { throw new IllegalStateException("Plugin can only have one public constructor."); } Constructor<?> constructor = constructors[0]; if (constructor.getParameterCount() == 0) { return (T) constructor.newInstance(); } else { Inject inject = constructor.getAnnotation(Inject.class); if (inject != null) { Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] parameters = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Object settings = createSettings(parameterTypes[i], indexSettings, nodeSettings, analysisSettings, environment); parameters[i] = settings; } return (T) constructor.newInstance(parameters); } else { throw new IllegalStateException( "Missing @" + Inject.class.getCanonicalName() + " annotation for constructor with settings." ); } } } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("Cannot create instance of " + clazz, e); } } @SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> T createSettings( Class<T> settingsClass, IndexSettings indexSettings, Settings nodeSettings, Settings analysisSettings, Environment environment ) { if (settingsClass.getAnnotationsByType(AnalysisSettings.class).length > 0) { return SettingsInvocationHandler.create(analysisSettings, settingsClass, environment); } throw new IllegalArgumentException("Parameter is not instance of a
StableApiWrappers
java
apache__flink
flink-clients/src/test/java/org/apache/flink/client/program/PackagedProgramUtilsPipelineTest.java
{ "start": 7873, "end": 8156 }
class ____ { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.fromData("hello").print(); env.execute(); } } }
DataStreamTestProgram
java
spring-projects__spring-boot
documentation/spring-boot-actuator-docs/src/test/java/org/springframework/boot/actuate/docs/web/mappings/MappingsEndpointServletDocumentationTests.java
{ "start": 9604, "end": 10675 }
class ____ { @Bean TomcatServletWebServerFactory tomcat() { return new TomcatServletWebServerFactory(0); } @Bean DispatcherServletsMappingDescriptionProvider dispatcherServletsMappingDescriptionProvider() { return new DispatcherServletsMappingDescriptionProvider(); } @Bean ServletsMappingDescriptionProvider servletsMappingDescriptionProvider() { return new ServletsMappingDescriptionProvider(); } @Bean FiltersMappingDescriptionProvider filtersMappingDescriptionProvider() { return new FiltersMappingDescriptionProvider(); } @Bean MappingsEndpoint mappingsEndpoint(Collection<MappingDescriptionProvider> descriptionProviders, ConfigurableApplicationContext context) { return new MappingsEndpoint(descriptionProviders, context); } @Bean ExampleController exampleController() { return new ExampleController(); } @Bean RouterFunction<ServerResponse> exampleRouter() { return RouterFunctions.route(GET("/foo"), (request) -> ServerResponse.ok().build()); } } @RestController static
TestConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/joined/JoinedInheritanceWithConcreteRootTest.java
{ "start": 1396, "end": 5803 }
class ____ { @Test public void basicTest(SessionFactoryScope scope) { final EntityPersister customerDescriptor = scope.getSessionFactory() .getMappingMetamodel() .findEntityDescriptor( Customer.class ); final EntityPersister domesticCustomerDescriptor = scope.getSessionFactory() .getMappingMetamodel() .findEntityDescriptor( DomesticCustomer.class ); final EntityPersister foreignCustomerDescriptor = scope.getSessionFactory() .getMappingMetamodel() .findEntityDescriptor( ForeignCustomer.class ); assert customerDescriptor instanceof JoinedSubclassEntityPersister; assert customerDescriptor.isTypeOrSuperType( customerDescriptor ); assert !customerDescriptor.isTypeOrSuperType( domesticCustomerDescriptor ); assert !customerDescriptor.isTypeOrSuperType( foreignCustomerDescriptor ); assert domesticCustomerDescriptor instanceof JoinedSubclassEntityPersister; assert domesticCustomerDescriptor.isTypeOrSuperType( customerDescriptor ); assert domesticCustomerDescriptor.isTypeOrSuperType( domesticCustomerDescriptor ); assert !domesticCustomerDescriptor.isTypeOrSuperType( foreignCustomerDescriptor ); assert foreignCustomerDescriptor instanceof JoinedSubclassEntityPersister; assert foreignCustomerDescriptor.isTypeOrSuperType( customerDescriptor ); assert !foreignCustomerDescriptor.isTypeOrSuperType( domesticCustomerDescriptor ); assert foreignCustomerDescriptor.isTypeOrSuperType( foreignCustomerDescriptor ); } @Test public void rootQueryExecutionTest(SessionFactoryScope scope) { scope.inTransaction( session -> { { // [name, taxId, vat] final List<Customer> results = session.createQuery( "select c from Customer c", Customer.class ).list(); assertThat( results.size(), is( 3 ) ); boolean foundDomesticCustomer = false; boolean foundForeignCustomer = false; boolean foundCustomer = false; for ( Customer result : results ) { if ( result.getId() == 1 ) { assertThat( result, instanceOf( DomesticCustomer.class ) ); final DomesticCustomer customer = (DomesticCustomer) result; assertThat( customer.getName(), is( "domestic" ) ); assertThat( ( customer ).getTaxId(), is( "123" ) ); foundDomesticCustomer = true; } else if ( result.getId() == 2 ) { final ForeignCustomer customer = (ForeignCustomer) result; assertThat( customer.getName(), is( "foreign" ) ); assertThat( ( customer ).getVat(), is( "987" ) ); foundForeignCustomer = true; } else { assertThat( result.getId(), is( 3 ) ); final Customer customer = result; assertThat( customer.getName(), is( "customer" ) ); foundCustomer = true; } } assertTrue( foundDomesticCustomer ); assertTrue( foundForeignCustomer ); assertTrue( foundCustomer ); } } ); } @Test public void subclassQueryExecutionTest(SessionFactoryScope scope) { scope.inTransaction( session -> { { final DomesticCustomer result = session.createQuery( "select c from DomesticCustomer c", DomesticCustomer.class ).uniqueResult(); assertThat( result, notNullValue() ); assertThat( result.getId(), is( 1 ) ); assertThat( result.getName(), is( "domestic" ) ); assertThat( result.getTaxId(), is( "123" ) ); } { final ForeignCustomer result = session.createQuery( "select c from ForeignCustomer c", ForeignCustomer.class ).uniqueResult(); assertThat( result, notNullValue() ); assertThat( result.getId(), is( 2 ) ); assertThat( result.getName(), is( "foreign" ) ); assertThat( result.getVat(), is( "987" ) ); } } ); } @BeforeEach public void createTestData(SessionFactoryScope scope) { scope.inTransaction( session -> { session.persist( new DomesticCustomer( 1, "domestic", "123" ) ); session.persist( new ForeignCustomer( 2, "foreign", "987" ) ); session.persist( new Customer( 3, "customer" ) ); } ); } @AfterEach public void cleanupTestData(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Entity(name = "Customer") @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "Customer") public static
JoinedInheritanceWithConcreteRootTest
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/classes/Classes_assertHasPublicFields_Test.java
{ "start": 1459, "end": 4596 }
class ____ extends ClassesBaseTest { @BeforeEach void setupActual() { actual = AnnotatedClass.class; } @Test void should_fail_if_actual_is_null() { actual = null; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> classes.assertHasPublicFields(someInfo(), actual)) .withMessage(actualIsNull()); } @Test void should_pass_if_class_has_expected_public_fields() { classes.assertHasPublicFields(someInfo(), actual, "publicField"); classes.assertHasPublicFields(someInfo(), actual, "publicField", "publicField2"); } @Test void should_pass_if_class_has_no_public_fields_and_none_are_expected() { classes.assertHasPublicFields(someInfo(), NoField.class); } @Test void should_fail_if_expected_fields_are_protected_or_private() { String[] expected = array("publicField", "protectedField", "privateField"); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> classes.assertHasPublicFields(someInfo(), actual, expected)) .withMessage(shouldHaveFields(actual, newLinkedHashSet(expected), newLinkedHashSet("protectedField", "privateField")).create() .formatted()); } @Test void should_fail_if_actual_does_not_have_all_expected_fields() { String[] expected = array("missingField", "publicField"); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> classes.assertHasPublicFields(someInfo(), actual, expected)) .withMessage(shouldHaveFields(actual, newLinkedHashSet(expected), newLinkedHashSet("missingField")).create() .formatted()); } @Test void should_fail_if_no_public_fields_are_expected_and_class_has_some() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> classes.assertHasPublicFields(someInfo(), actual)) .withMessage(shouldHaveNoPublicFields(actual, newLinkedHashSet("publicField", "publicField2")).create()); } }
Classes_assertHasPublicFields_Test
java
spring-projects__spring-security
messaging/src/main/java/org/springframework/security/messaging/access/intercept/MessageMatcherDelegatingAuthorizationManager.java
{ "start": 2022, "end": 4205 }
class ____ implements AuthorizationManager<Message<?>> { private final Log logger = LogFactory.getLog(getClass()); private final List<Entry<AuthorizationManager<MessageAuthorizationContext<?>>>> mappings; private MessageMatcherDelegatingAuthorizationManager( List<Entry<AuthorizationManager<MessageAuthorizationContext<?>>>> mappings) { Assert.notEmpty(mappings, "mappings cannot be empty"); this.mappings = mappings; } @Override public @Nullable AuthorizationResult authorize(Supplier<? extends @Nullable Authentication> authentication, Message<?> message) { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Authorizing message")); } for (Entry<AuthorizationManager<MessageAuthorizationContext<?>>> mapping : this.mappings) { MessageMatcher<?> matcher = mapping.getMessageMatcher(); MessageAuthorizationContext<?> authorizationContext = authorizationContext(matcher, message); if (authorizationContext != null) { AuthorizationManager<MessageAuthorizationContext<?>> manager = mapping.getEntry(); if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Checking authorization on message using %s", manager)); } return manager.authorize(authentication, authorizationContext); } } this.logger.trace("Abstaining since did not find matching MessageMatcher"); return null; } private @Nullable MessageAuthorizationContext<?> authorizationContext(MessageMatcher<?> matcher, Message<?> message) { MessageMatcher.MatchResult matchResult = matcher.matcher((Message) message); if (!matchResult.isMatch()) { return null; } if (!CollectionUtils.isEmpty(matchResult.getVariables())) { return new MessageAuthorizationContext<>(message, matchResult.getVariables()); } return new MessageAuthorizationContext<>(message); } /** * Creates a builder for {@link MessageMatcherDelegatingAuthorizationManager}. * @return the new {@link Builder} instance */ public static Builder builder() { return new Builder(); } /** * A builder for {@link MessageMatcherDelegatingAuthorizationManager}. */ public static final
MessageMatcherDelegatingAuthorizationManager
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/injectionstrategy/jsr330/setter/Jsr330SetterMapperTest.java
{ "start": 1793, "end": 3754 }
class ____ { @RegisterExtension final GeneratedSource generatedSource = new GeneratedSource(); @Autowired private CustomerJsr330SetterMapper customerMapper; private ConfigurableApplicationContext context; @BeforeEach public void springUp() { context = new AnnotationConfigApplicationContext( getClass() ); context.getAutowireCapableBeanFactory().autowireBean( this ); } @AfterEach public void springDown() { if ( context != null ) { context.close(); } } @ProcessorTest public void shouldConvertToTarget() { // given CustomerEntity customerEntity = new CustomerEntity(); customerEntity.setName( "Samuel" ); customerEntity.setGender( Gender.MALE ); // when CustomerDto customerDto = customerMapper.asTarget( customerEntity ); // then assertThat( customerDto ).isNotNull(); assertThat( customerDto.getName() ).isEqualTo( "Samuel" ); assertThat( customerDto.getGender() ).isEqualTo( GenderDto.M ); } @ProcessorTest public void shouldHaveSetterInjection() { String method = "@Inject" + lineSeparator() + " public void setGenderJsr330SetterMapper(GenderJsr330SetterMapper genderJsr330SetterMapper) {" + lineSeparator() + " this.genderJsr330SetterMapper = genderJsr330SetterMapper;" + lineSeparator() + " }"; generatedSource.forMapper( CustomerJsr330SetterMapper.class ) .content() .contains( "import javax.inject.Inject;" ) .contains( "import javax.inject.Named;" ) .contains( "import javax.inject.Singleton;" ) .contains( "private GenderJsr330SetterMapper genderJsr330SetterMapper;" ) .doesNotContain( "@Inject" + lineSeparator() + " private GenderJsr330SetterMapper" ) .contains( method ); } }
Jsr330SetterMapperTest
java
quarkusio__quarkus
extensions/kotlin/deployment/src/main/java/io/quarkus/kotlin/deployment/IsDataClassWithDefaultValuesPredicate.java
{ "start": 481, "end": 1530 }
class ____ implements Predicate<ClassInfo> { @Override public boolean test(ClassInfo classInfo) { int ctorCount = 0; boolean hasCopyMethod = false; boolean hasStaticCopyMethod = false; boolean hasComponent1Method = false; List<MethodInfo> methods = classInfo.methods(); for (MethodInfo method : methods) { String methodName = method.name(); if ("<init>".equals(methodName)) { ctorCount++; } else if ("component1".equals(methodName) && Modifier.isFinal(method.flags())) { hasComponent1Method = true; } else if ("copy".equals(methodName) && Modifier.isFinal(method.flags())) { hasCopyMethod = true; } else if ("copy$default".equals(methodName) && Modifier.isStatic(method.flags())) { hasStaticCopyMethod = true; } } return ctorCount > 1 && hasComponent1Method && hasCopyMethod && hasStaticCopyMethod; } }
IsDataClassWithDefaultValuesPredicate
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/separatecompilationunits/SeparateCompilationUnitsTest.java
{ "start": 754, "end": 988 }
class ____ { @Test @WithClasses(value = Entity.class, preCompile = MappedSuperclass.class) @IgnoreCompilationErrors void testInheritance() throws Exception { // need to work with the source file. Entity_.
SeparateCompilationUnitsTest
java
netty__netty
codec-compression/src/main/java/io/netty/handler/codec/compression/GzipOptions.java
{ "start": 822, "end": 887 }
class ____ an extension of {@link DeflateOptions} */ public final
is
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/DelegatingPeekingKeyValueIterator.java
{ "start": 1103, "end": 2674 }
class ____<K, V> implements KeyValueIterator<K, V>, PeekingKeyValueIterator<K, V> { private final KeyValueIterator<K, V> underlying; private final String storeName; private KeyValue<K, V> next; private volatile boolean open = true; public DelegatingPeekingKeyValueIterator(final String storeName, final KeyValueIterator<K, V> underlying) { this.storeName = storeName; this.underlying = underlying; } @Override public synchronized K peekNextKey() { if (!hasNext()) { throw new NoSuchElementException(); } return next.key; } @Override public synchronized void close() { underlying.close(); open = false; } @Override public synchronized boolean hasNext() { if (!open) { throw new IllegalStateException(String.format("Iterator for store %s has already been closed.", storeName)); } if (next != null) { return true; } if (!underlying.hasNext()) { return false; } next = underlying.next(); return true; } @Override public synchronized KeyValue<K, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } final KeyValue<K, V> result = next; next = null; return result; } @Override public KeyValue<K, V> peekNext() { if (!hasNext()) { throw new NoSuchElementException(); } return next; } }
DelegatingPeekingKeyValueIterator
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java
{ "start": 6376, "end": 6669 }
interface ____ extends MetadataCustom<ClusterCustom> {} /** * Project-level custom metadata that persists (via XContent) across restarts. * The deserialization method for each implementation must be registered with the {@link NamedXContentRegistry}. */ public
ClusterCustom
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToCartesianShapeSerializationTests.java
{ "start": 540, "end": 794 }
class ____ extends AbstractUnaryScalarSerializationTests<ToCartesianShape> { @Override protected ToCartesianShape create(Source source, Expression child) { return new ToCartesianShape(source, child); } }
ToCartesianShapeSerializationTests
java
spring-projects__spring-boot
module/spring-boot-health/src/test/java/org/springframework/boot/health/actuate/endpoint/HealthEndpointSupportTests.java
{ "start": 1462, "end": 1738 }
class ____ {@link HealthEndpointSupport} tests. * * @param <E> the endpoint type; * @param <H> the health type * @param <D> the descriptor type * @param <R> the registry type * @param <C> the contributor type * @author Phillip Webb * @author Madhura Bhave */ abstract
for
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/api/datastream/UnionSerializerTest.java
{ "start": 1362, "end": 3220 }
class ____ extends SerializerTestBase<TaggedUnion<Object, Object>> { public UnionSerializerTest() { super( new DeeplyEqualsChecker() .withCustomCheck( (o1, o2) -> o1 instanceof TaggedUnion && o2 instanceof TaggedUnion, (o1, o2, checker) -> { TaggedUnion union1 = (TaggedUnion) o1; TaggedUnion union2 = (TaggedUnion) o2; if (union1.isOne() && union2.isOne()) { return checker.deepEquals(union1.getOne(), union2.getOne()); } else if (union1.isTwo() && union2.isTwo()) { return checker.deepEquals(union1.getTwo(), union2.getTwo()); } else { return false; } })); } @Override protected TypeSerializer<TaggedUnion<Object, Object>> createSerializer() { return new UnionSerializer<>( new KryoSerializer<>(Object.class, new SerializerConfigImpl()), new KryoSerializer<>(Object.class, new SerializerConfigImpl())); } @Override protected int getLength() { return -1; } @Override @SuppressWarnings("unchecked") protected Class<TaggedUnion<Object, Object>> getTypeClass() { return (Class<TaggedUnion<Object, Object>>) (Class<?>) TaggedUnion.class; } @Override @SuppressWarnings("unchecked") protected TaggedUnion<Object, Object>[] getTestData() { return new TaggedUnion[] {TaggedUnion.one(1), TaggedUnion.two("A"), TaggedUnion.one("C")}; } }
UnionSerializerTest
java
google__guava
android/guava-tests/test/com/google/common/graph/StandardImmutableDirectedNetworkTest.java
{ "start": 1030, "end": 2937 }
class ____ extends AbstractStandardDirectedNetworkTest { @Parameters(name = "allowsSelfLoops={0}, allowsParallelEdges={1}, nodeOrder={2}, edgeOrder={3}") public static Collection<Object[]> parameters() { ElementOrder<?> naturalElementOrder = ElementOrder.sorted(Ordering.natural()); return Arrays.asList( new Object[][] { {false, false, ElementOrder.insertion(), ElementOrder.insertion()}, {true, false, ElementOrder.insertion(), ElementOrder.insertion()}, {false, false, naturalElementOrder, naturalElementOrder}, {true, true, ElementOrder.insertion(), ElementOrder.insertion()}, }); } private final boolean allowsSelfLoops; private final boolean allowsParallelEdges; private final ElementOrder<Integer> nodeOrder; private final ElementOrder<String> edgeOrder; private ImmutableNetwork.Builder<Integer, String> networkBuilder; public StandardImmutableDirectedNetworkTest( boolean allowsSelfLoops, boolean allowsParallelEdges, ElementOrder<Integer> nodeOrder, ElementOrder<String> edgeOrder) { this.allowsSelfLoops = allowsSelfLoops; this.allowsParallelEdges = allowsParallelEdges; this.nodeOrder = nodeOrder; this.edgeOrder = edgeOrder; } @Override Network<Integer, String> createGraph() { networkBuilder = NetworkBuilder.directed() .allowsSelfLoops(allowsSelfLoops) .allowsParallelEdges(allowsParallelEdges) .nodeOrder(nodeOrder) .edgeOrder(edgeOrder) .immutable(); return networkBuilder.build(); } @Override void addNode(Integer n) { networkBuilder.addNode(n); network = networkBuilder.build(); } @Override void addEdge(Integer n1, Integer n2, String e) { networkBuilder.addEdge(n1, n2, e); network = networkBuilder.build(); } }
StandardImmutableDirectedNetworkTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_castToBytes.java
{ "start": 150, "end": 609 }
class ____ extends TestCase { public void test_castToDate() throws Exception { Assert.assertArrayEquals(new byte[0], TypeUtils.castToBytes(new byte[0])); } public void test_castToDate_error() throws Exception { Exception error = null; try { TypeUtils.castToBytes(new int[0]); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } }
TypeUtilsTest_castToBytes
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/profile/UnlessBuildProfileStereotypeTest.java
{ "start": 3531, "end": 3652 }
class ____ implements MyService { } @InheritableTransitiveTestNever static abstract
TransitiveTestNeverMyService
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/RollingUpgradeInfo.java
{ "start": 3225, "end": 3928 }
class ____ { private final String blockPoolId; private final long startTime; private final long finalizeTime; private final boolean createdRollbackImages; public Bean(RollingUpgradeInfo f) { this.blockPoolId = f.getBlockPoolId(); this.startTime = f.startTime; this.finalizeTime = f.finalizeTime; this.createdRollbackImages = f.createdRollbackImages(); } public String getBlockPoolId() { return blockPoolId; } public long getStartTime() { return startTime; } public long getFinalizeTime() { return finalizeTime; } public boolean isCreatedRollbackImages() { return createdRollbackImages; } } }
Bean
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ParameterNameTest.java
{ "start": 6730, "end": 7130 }
class ____ { abstract void target(Object param); void test(Object arg) { target(/*note param = */ arg); } } """) .doTest(); } @Test public void namedParametersChecker_tolerateComment_withNoEquals() { testHelper .addSourceLines( "Test.java", """ abstract
Test
java
quarkusio__quarkus
integration-tests/gradle/src/test/java/io/quarkus/gradle/TestWithSidecarModule.java
{ "start": 216, "end": 607 }
class ____ extends QuarkusGradleWrapperTestBase { @Test public void test() throws Exception { final File projectDir = getProjectDir("test-with-sidecar-module"); final BuildResult build = runGradleWrapper(projectDir, "clean", ":my-module:test"); assertThat(BuildResult.isSuccessful(build.getTasks().get(":my-module:test"))).isTrue(); } }
TestWithSidecarModule
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/errors/TransactionExceptionHierarchyTest.java
{ "start": 1583, "end": 2742 }
class ____ check */ @ParameterizedTest @ValueSource(classes = { TimeoutException.class, NotEnoughReplicasException.class, CoordinatorLoadInProgressException.class, CorruptRecordException.class, NotEnoughReplicasAfterAppendException.class, ConcurrentTransactionsException.class }) void testRetriableExceptionHierarchy(Class<? extends Exception> exceptionClass) { assertTrue(RetriableException.class.isAssignableFrom(exceptionClass), exceptionClass.getSimpleName() + " should extend RetriableException"); assertFalse(RefreshRetriableException.class.isAssignableFrom(exceptionClass), exceptionClass.getSimpleName() + " should NOT extend RefreshRetriableException"); } /** * Verifies that RefreshRetriableException extends RetriableException. */ @Test void testRefreshRetriableException() { assertTrue(RetriableException.class.isAssignableFrom(RefreshRetriableException.class), "RefreshRetriableException should extend RetriableException"); } /** * Verifies that the given exception
to
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ShouldNotBeEmpty.java
{ "start": 956, "end": 2091 }
class ____ extends BasicErrorMessageFactory { private static final ShouldNotBeEmpty INSTANCE = new ShouldNotBeEmpty("%nExpecting actual not to be empty"); /** * Returns the singleton instance of this class. * @return the singleton instance of this class. */ public static ErrorMessageFactory shouldNotBeEmpty() { return INSTANCE; } /** * Creates a new <code>{@link ShouldNotBeEmpty}</code>. * @param actual the actual file in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldNotBeEmpty(File actual) { return new ShouldNotBeEmpty("%nExpecting file %s not to be empty", actual); } /** * Creates a new <code>{@link ShouldNotBeEmpty}</code>. * @param actual the actual path in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldNotBeEmpty(Path actual) { return new ShouldNotBeEmpty("%nExpecting path %s not to be empty", actual); } private ShouldNotBeEmpty(String format, Object... arguments) { super(format, arguments); } }
ShouldNotBeEmpty
java
netty__netty
codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java
{ "start": 21400, "end": 26918 }
class ____ implements StreamByteDistributor.Writer { private boolean inWritePendingBytes; private long totalPendingBytes; @Override public final void write(Http2Stream stream, int numBytes) { state(stream).writeAllocatedBytes(numBytes); } /** * Called when the writability of the underlying channel changes. * @throws Http2Exception If a write occurs and an exception happens in the write operation. */ void channelWritabilityChange() throws Http2Exception { } /** * Called when the state is cancelled. * @param state the state that was cancelled. */ void stateCancelled(FlowState state) { } /** * Set the initial window size for {@code state}. * @param state the state to change the initial window size for. * @param initialWindowSize the size of the window in bytes. */ void windowSize(FlowState state, int initialWindowSize) { state.windowSize(initialWindowSize); } /** * Increment the window size for a particular stream. * @param state the state associated with the stream whose window is being incremented. * @param delta The amount to increment by. * @throws Http2Exception If this operation overflows the window for {@code state}. */ void incrementWindowSize(FlowState state, int delta) throws Http2Exception { state.incrementStreamWindow(delta); } /** * Add a frame to be sent via flow control. * @param state The state associated with the stream which the {@code frame} is associated with. * @param frame the frame to enqueue. * @throws Http2Exception If a writability error occurs. */ void enqueueFrame(FlowState state, FlowControlled frame) throws Http2Exception { state.enqueueFrame(frame); } /** * Increment the total amount of pending bytes for all streams. When any stream's pending bytes changes * method should be called. * @param delta The amount to increment by. */ final void incrementPendingBytes(int delta) { totalPendingBytes += delta; // Notification of writibilty change should be delayed until the end of the top level event. // This is to ensure the flow controller is more consistent state before calling external listener methods. } /** * Determine if the stream associated with {@code state} is writable. * @param state The state which is associated with the stream to test writability for. * @return {@code true} if {@link FlowState#stream()} is writable. {@code false} otherwise. */ final boolean isWritable(FlowState state) { return isWritableConnection() && state.isWritable(); } final void writePendingBytes() throws Http2Exception { // Reentry is not permitted during the byte distribution process. It may lead to undesirable distribution of // bytes and even infinite loops. We protect against reentry and make sure each call has an opportunity to // cause a distribution to occur. This may be useful for example if the channel's writability changes from // Writable -> Not Writable (because we are writing) -> Writable (because the user flushed to make more room // in the channel outbound buffer). if (inWritePendingBytes) { return; } inWritePendingBytes = true; try { int bytesToWrite = writableBytes(); // Make sure we always write at least once, regardless if we have bytesToWrite or not. // This ensures that zero-length frames will always be written. for (;;) { if (!streamByteDistributor.distribute(bytesToWrite, this) || (bytesToWrite = writableBytes()) <= 0 || !isChannelWritable0()) { break; } } } finally { inWritePendingBytes = false; } } void initialWindowSize(int newWindowSize) throws Http2Exception { checkPositiveOrZero(newWindowSize, "newWindowSize"); final int delta = newWindowSize - initialWindowSize; initialWindowSize = newWindowSize; connection.forEachActiveStream(new Http2StreamVisitor() { @Override public boolean visit(Http2Stream stream) throws Http2Exception { state(stream).incrementStreamWindow(delta); return true; } }); if (delta > 0 && isChannelWritable()) { // The window size increased, send any pending frames for all streams. writePendingBytes(); } } final boolean isWritableConnection() { return connectionState.windowSize() - totalPendingBytes > 0 && isChannelWritable(); } } /** * Writability of a {@code stream} is calculated using the following: * <pre> * Connection Window - Total Queued Bytes > 0 && * Stream Window - Bytes Queued for Stream > 0 && * isChannelWritable() * </pre> */ private final
WritabilityMonitor
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4401RepositoryOrderForParentPomTest.java
{ "start": 1040, "end": 2057 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Verify that the implicit default repo (central) is tried after explicitly declared repos during parent POM * resolution. * * @throws Exception in case of failure */ @Test public void testit() throws Exception { File testDir = extractResources("/mng-4401"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.deleteArtifacts("org.apache.maven.its.mng4401"); verifier.filterFile("settings-template.xml", "settings.xml"); verifier.addCliArgument("-s"); verifier.addCliArgument("settings.xml"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyFilePresent("target/passed.txt"); verifier.verifyFileNotPresent("target/failed.txt"); } }
MavenITmng4401RepositoryOrderForParentPomTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/UnknownParameterException.java
{ "start": 420, "end": 558 }
class ____ extends HibernateException { public UnknownParameterException(String message) { super( message ); } }
UnknownParameterException
java
google__auto
value/src/it/gwtserializer/src/test/java/com/google/auto/value/client/GwtSerializerTest.java
{ "start": 4975, "end": 5197 }
interface ____ { Builder message(String message); Builder simple(SimpleWithBuilder simple); NestedWithBuilder build(); } } @AutoValue @GwtCompatible(serializable = true) abstract static
Builder
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/InstanceOfAssertFactoriesTest.java
{ "start": 37514, "end": 38196 }
class ____ { private final Object actual = new float[][] { { 0.0f, 1.0f }, { 2.0f, 3.0f } }; @Test void createAssert() { // WHEN Float2DArrayAssert result = FLOAT_2D_ARRAY.createAssert(actual); // THEN result.hasDimensions(2, 2); } @Test void createAssert_with_ValueProvider() { // GIVEN ValueProvider<?> valueProvider = mockThatDelegatesTo(type -> actual); // WHEN Float2DArrayAssert result = FLOAT_2D_ARRAY.createAssert(valueProvider); // THEN result.hasDimensions(2, 2); verify(valueProvider).apply(float[][].class); } } @Nested @TestInstance(PER_CLASS)
Float_2D_Array_Factory
java
spring-projects__spring-boot
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java
{ "start": 5187, "end": 6817 }
class ____ implements HeapDumper { private final Object diagnosticMXBean; private final Method dumpHeapMethod; @SuppressWarnings("unchecked") protected HotSpotDiagnosticMXBeanHeapDumper() { try { Class<?> diagnosticMXBeanClass = ClassUtils .resolveClassName("com.sun.management.HotSpotDiagnosticMXBean", null); this.diagnosticMXBean = ManagementFactory .getPlatformMXBean((Class<PlatformManagedObject>) diagnosticMXBeanClass); this.dumpHeapMethod = getDumpHeapMethod(diagnosticMXBeanClass); } catch (Throwable ex) { throw new HeapDumperUnavailableException("Unable to locate HotSpotDiagnosticMXBean", ex); } } private static Method getDumpHeapMethod(Class<?> clazz) { Method method = ReflectionUtils.findMethod(clazz, "dumpHeap", String.class, Boolean.TYPE); Assert.state(method != null, "'method' must not be null"); return method; } @Override public File dumpHeap(@Nullable Boolean live) throws IOException { File file = createTempFile(); ReflectionUtils.invokeMethod(this.dumpHeapMethod, this.diagnosticMXBean, file.getAbsolutePath(), (live != null) ? live : true); return file; } private File createTempFile() throws IOException { String date = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm").format(LocalDateTime.now()); File file = File.createTempFile("heap-" + date, ".hprof"); file.delete(); return file; } } /** * {@link HeapDumper} that uses * {@code openj9.lang.management.OpenJ9DiagnosticsMXBean}, available on OpenJ9, to * dump the heap to a file. */ private static final
HotSpotDiagnosticMXBeanHeapDumper
java
quarkusio__quarkus
integration-tests/opentelemetry-quartz/src/test/java/io/quarkus/it/opentelemetry/quartz/OpenTelemetryQuartzTest.java
{ "start": 777, "end": 4997 }
class ____ { private static long DURATION_IN_NANOSECONDS = 100_000_000; // Thread.sleep(100l) for each job @Test public void quartzSpanTest() { // ensure that scheduled job is called assertCounter("/scheduler/count", 1, Duration.ofSeconds(3)); // assert programmatically scheduled job is called assertCounter("/scheduler/count/manual", 1, Duration.ofSeconds(3)); // assert JobDefinition type scheduler assertCounter("/scheduler/count/job-definition", 1, Duration.ofSeconds(1)); // ------- SPAN ASSERTS ------- List<Map<String, Object>> spans = getSpans(); assertJobSpan(spans, "myCounter", DURATION_IN_NANOSECONDS); // identity assertJobSpan(spans, "myGroup.myManualJob", DURATION_IN_NANOSECONDS); // group + identity assertJobSpan(spans, "myJobDefinition", DURATION_IN_NANOSECONDS); // identity // errors assertErrorJobSpan(spans, "myFailedBasicScheduler", DURATION_IN_NANOSECONDS, "error occurred in myFailedBasicScheduler."); assertErrorJobSpan(spans, "myFailedGroup.myFailedManualJob", DURATION_IN_NANOSECONDS, "error occurred in myFailedManualJob."); assertErrorJobSpan(spans, "myFailedJobDefinition", DURATION_IN_NANOSECONDS, "error occurred in myFailedJobDefinition."); } private void assertCounter(String counterPath, int expectedCount, Duration timeout) { await().atMost(timeout) .pollInterval(Duration.ofMillis(500)) .until(() -> { Response response = given().when().get(counterPath); int code = response.statusCode(); if (code != 200) { return false; } String body = response.asString(); int count = Integer.valueOf(body); return count >= expectedCount; }); } private List<Map<String, Object>> getSpans() { return get("/export").body().as(new TypeRef<>() { }); } private void assertJobSpan(List<Map<String, Object>> spans, String expectedName, long expectedDuration) { assertNotNull(spans); assertFalse(spans.isEmpty()); Map<String, Object> span = spans.stream().filter(map -> map.get("name").equals(expectedName)).findFirst().orElse(null); assertNotNull(span, "Span with name '" + expectedName + "' not found."); assertEquals(SpanKind.INTERNAL.toString(), span.get("kind"), "Span with name '" + expectedName + "' is not internal."); long start = (long) span.get("startEpochNanos"); long end = (long) span.get("endEpochNanos"); long delta = (end - start); assertTrue(delta >= expectedDuration, "Duration of span with name '" + expectedName + "' is not longer than 100ms, actual duration: " + delta + " (ns)"); } private void assertErrorJobSpan(List<Map<String, Object>> spans, String expectedName, long expectedDuration, String expectedErrorMessage) { assertJobSpan(spans, expectedName, expectedDuration); Map<String, Object> span = spans.stream().filter(map -> map.get("name").equals(expectedName)).findFirst() .orElseThrow(AssertionError::new); // this assert should never be thrown, since we already checked it in `assertJobSpan` Map<String, Object> statusAttributes = (Map<String, Object>) span.get("status"); assertNotNull(statusAttributes, "Span with name '" + expectedName + "' is not an ERROR"); assertEquals(StatusCode.ERROR.toString(), statusAttributes.get("statusCode"), "Span with name '" + expectedName + "' is not an ERROR"); Map<String, Object> exception = (Map<String, Object>) ((List<Map<String, Object>>) span.get("events")).stream() .map(map -> map.get("exception")).findFirst().orElseThrow(AssertionError::new); assertTrue(((String) exception.get("message")).contains(expectedErrorMessage), "Span with name '" + expectedName + "' has wrong error message"); } }
OpenTelemetryQuartzTest
java
apache__flink
flink-clients/src/main/java/org/apache/flink/client/ClientUtils.java
{ "start": 2517, "end": 8968 }
enum ____ { ; private static final Logger LOG = LoggerFactory.getLogger(ClientUtils.class); public static URLClassLoader buildUserCodeClassLoader( List<URL> jars, List<URL> classpaths, ClassLoader parent, Configuration configuration) { URL[] urls = new URL[jars.size() + classpaths.size()]; for (int i = 0; i < jars.size(); i++) { urls[i] = jars.get(i); } for (int i = 0; i < classpaths.size(); i++) { urls[i + jars.size()] = classpaths.get(i); } return FlinkUserCodeClassLoaders.create(urls, parent, configuration); } public static void executeProgram( PipelineExecutorServiceLoader executorServiceLoader, Configuration configuration, PackagedProgram program, boolean enforceSingleJobExecution, boolean suppressSysout) throws ProgramInvocationException { checkNotNull(executorServiceLoader); final ClassLoader userCodeClassLoader = program.getUserCodeClassLoader(); final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(userCodeClassLoader); LOG.info( "Starting program (detached: {})", !configuration.get(DeploymentOptions.ATTACHED)); StreamContextEnvironment.setAsContext( executorServiceLoader, configuration, userCodeClassLoader, enforceSingleJobExecution, suppressSysout); // For DataStream v2. ExecutionContextEnvironment.setAsContext( executorServiceLoader, configuration, userCodeClassLoader); try { program.invokeInteractiveModeForExecution(); } finally { StreamContextEnvironment.unsetAsContext(); // For DataStream v2. ExecutionContextEnvironment.unsetAsContext(); } } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } /** * This method blocks until the job status is not INITIALIZING anymore. * * @param jobStatusSupplier supplier returning the job status. * @param jobResultSupplier supplier returning the job result. This will only be called if the * job reaches the FAILED state. * @throws JobInitializationException If the initialization failed */ public static void waitUntilJobInitializationFinished( SupplierWithException<JobStatus, Exception> jobStatusSupplier, SupplierWithException<JobResult, Exception> jobResultSupplier, ClassLoader userCodeClassloader) throws JobInitializationException { LOG.debug("Wait until job initialization is finished"); WaitStrategy waitStrategy = new ExponentialWaitStrategy(50, 2000); try { JobStatus status = jobStatusSupplier.get(); long attempt = 0; while (status == JobStatus.INITIALIZING) { Thread.sleep(waitStrategy.sleepTime(attempt++)); status = jobStatusSupplier.get(); } if (status == JobStatus.FAILED) { JobResult result = jobResultSupplier.get(); Optional<SerializedThrowable> throwable = result.getSerializedThrowable(); if (throwable.isPresent()) { Throwable t = throwable.get().deserializeError(userCodeClassloader); if (t instanceof JobInitializationException) { throw t; } } } } catch (JobInitializationException initializationException) { throw initializationException; } catch (Throwable throwable) { ExceptionUtils.checkInterrupted(throwable); throw new RuntimeException("Error while waiting for job to be initialized", throwable); } } /** * The client reports the heartbeat to the dispatcher for aliveness. * * @param jobClient The job client. * @param interval The heartbeat interval. * @param timeout The heartbeat timeout. * @return The ScheduledExecutorService which reports heartbeat periodically. */ public static ScheduledExecutorService reportHeartbeatPeriodically( JobClient jobClient, long interval, long timeout) { checkArgument( interval < timeout, "The client's heartbeat interval " + "should be less than the heartbeat timeout. Please adjust the param '" + ClientOptions.CLIENT_HEARTBEAT_INTERVAL + "' or '" + ClientOptions.CLIENT_HEARTBEAT_TIMEOUT + "'"); JobID jobID = jobClient.getJobID(); LOG.info("Begin to report client's heartbeat for the job {}.", jobID); ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleAtFixedRate( () -> { LOG.debug("Report client's heartbeat for the job {}.", jobID); jobClient.reportHeartbeat(System.currentTimeMillis() + timeout); }, interval, interval, TimeUnit.MILLISECONDS); return scheduledExecutor; } public static Collection<HttpHeader> readHeadersFromEnvironmentVariable(String envVarName) { List<HttpHeader> headers = new ArrayList<>(); String rawHeaders = System.getenv(envVarName); if (rawHeaders != null) { String[] lines = rawHeaders.split("\n"); for (String line : lines) { String[] keyValue = line.split(":", 2); if (keyValue.length == 2) { headers.add(new HttpHeader(keyValue[0], keyValue[1])); } else { LOG.info( "Skipped a malformed header {} from FLINK_REST_CLIENT_HEADERS env variable. Expecting newline-separated headers in format header_name:header_value.", line); } } } return headers; } }
ClientUtils
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/WildcardImportTest.java
{ "start": 6574, "end": 6671 }
class ____ { Map.Entry<String, String> e; C c; static
Test
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/builditem/TransformedClassesBuildItem.java
{ "start": 536, "end": 1486 }
class ____ extends SimpleBuildItem { private final Map<Path, Set<TransformedClass>> transformedClassesByJar; private final Map<Path, Set<String>> transformedFilesByJar; public TransformedClassesBuildItem(Map<Path, Set<TransformedClass>> transformedClassesByJar) { this.transformedClassesByJar = new HashMap<>(transformedClassesByJar); this.transformedFilesByJar = new HashMap<>(); for (Map.Entry<Path, Set<TransformedClass>> e : transformedClassesByJar.entrySet()) { transformedFilesByJar.put(e.getKey(), e.getValue().stream().map(TransformedClass::getFileName).collect(Collectors.toSet())); } } public Map<Path, Set<TransformedClass>> getTransformedClassesByJar() { return transformedClassesByJar; } public Map<Path, Set<String>> getTransformedFilesByJar() { return transformedFilesByJar; } public static
TransformedClassesBuildItem
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/authorization/OAuth2ClientRegistrationTests.java
{ "start": 7360, "end": 24083 }
class ____ { private static final String ISSUER = "https://example.com:8443/issuer1"; private static final String DEFAULT_TOKEN_ENDPOINT_URI = "/oauth2/token"; private static final String DEFAULT_OAUTH2_CLIENT_REGISTRATION_ENDPOINT_URI = "/oauth2/register"; private static final HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenHttpResponseConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); private static final HttpMessageConverter<OAuth2ClientRegistration> clientRegistrationHttpMessageConverter = new OAuth2ClientRegistrationHttpMessageConverter(); private static EmbeddedDatabase db; private static JWKSource<SecurityContext> jwkSource; public final SpringTestContext spring = new SpringTestContext(this); @Autowired private MockMvc mvc; @Autowired private JdbcOperations jdbcOperations; @Autowired private RegisteredClientRepository registeredClientRepository; private static AuthenticationConverter authenticationConverter; private static Consumer<List<AuthenticationConverter>> authenticationConvertersConsumer; private static AuthenticationProvider authenticationProvider; private static Consumer<List<AuthenticationProvider>> authenticationProvidersConsumer; private static AuthenticationSuccessHandler authenticationSuccessHandler; private static AuthenticationFailureHandler authenticationFailureHandler; private MockWebServer server; @BeforeAll public static void init() { JWKSet jwkSet = new JWKSet(TestJwks.DEFAULT_RSA_JWK); jwkSource = (jwkSelector, securityContext) -> jwkSelector.select(jwkSet); db = new EmbeddedDatabaseBuilder().generateUniqueName(true) .setType(EmbeddedDatabaseType.HSQL) .setScriptEncoding("UTF-8") .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql") .addScript( "org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql") .build(); authenticationConverter = mock(AuthenticationConverter.class); authenticationConvertersConsumer = mock(Consumer.class); authenticationProvider = mock(AuthenticationProvider.class); authenticationProvidersConsumer = mock(Consumer.class); authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); authenticationFailureHandler = mock(AuthenticationFailureHandler.class); } @BeforeEach public void setup() throws Exception { this.server = new MockWebServer(); this.server.start(); given(authenticationProvider.supports(OAuth2ClientRegistrationAuthenticationToken.class)).willReturn(true); } @AfterEach public void tearDown() throws Exception { this.server.shutdown(); this.jdbcOperations.update("truncate table oauth2_authorization"); this.jdbcOperations.update("truncate table oauth2_registered_client"); reset(authenticationConverter); reset(authenticationConvertersConsumer); reset(authenticationProvider); reset(authenticationProvidersConsumer); reset(authenticationSuccessHandler); reset(authenticationFailureHandler); } @AfterAll public static void destroy() { db.shutdown(); } @Test public void requestWhenClientRegistrationRequestAuthorizedThenClientRegistrationResponse() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); // @formatter:off OAuth2ClientRegistration clientRegistration = OAuth2ClientRegistration.builder() .clientName("client-name") .redirectUri("https://client.example.com") .grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()) .grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()) .scope("scope1") .scope("scope2") .build(); // @formatter:on OAuth2ClientRegistration clientRegistrationResponse = registerClient(clientRegistration); assertClientRegistrationResponse(clientRegistration, clientRegistrationResponse); } @Test public void requestWhenOpenClientRegistrationRequestThenClientRegistrationResponse() throws Exception { this.spring.register(OpenClientRegistrationConfiguration.class).autowire(); // @formatter:off OAuth2ClientRegistration clientRegistration = OAuth2ClientRegistration.builder() .clientName("client-name") .redirectUri("https://client.example.com") .grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()) .grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()) .scope("scope1") .scope("scope2") .build(); // @formatter:on MvcResult mvcResult = this.mvc .perform(post(ISSUER.concat(DEFAULT_OAUTH2_CLIENT_REGISTRATION_ENDPOINT_URI)) .contentType(MediaType.APPLICATION_JSON) .content(getClientRegistrationRequestContent(clientRegistration))) .andExpect(status().isCreated()) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andReturn(); OAuth2ClientRegistration clientRegistrationResponse = readClientRegistrationResponse(mvcResult.getResponse()); assertClientRegistrationResponse(clientRegistration, clientRegistrationResponse); } @Test public void requestWhenClientRegistrationEndpointCustomizedThenUsed() throws Exception { this.spring.register(CustomClientRegistrationConfiguration.class).autowire(); // @formatter:off OAuth2ClientRegistration clientRegistration = OAuth2ClientRegistration.builder() .clientName("client-name") .redirectUri("https://client.example.com") .grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()) .grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()) .scope("scope1") .scope("scope2") .build(); // @formatter:on willAnswer((invocation) -> { HttpServletResponse response = invocation.getArgument(1, HttpServletResponse.class); ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); httpResponse.setStatusCode(HttpStatus.CREATED); new OAuth2ClientRegistrationHttpMessageConverter().write(clientRegistration, null, httpResponse); return null; }).given(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), any()); registerClient(clientRegistration); verify(authenticationConverter).convert(any()); ArgumentCaptor<List<AuthenticationConverter>> authenticationConvertersCaptor = ArgumentCaptor .forClass(List.class); verify(authenticationConvertersConsumer).accept(authenticationConvertersCaptor.capture()); List<AuthenticationConverter> authenticationConverters = authenticationConvertersCaptor.getValue(); assertThat(authenticationConverters).hasSize(2) .allMatch((converter) -> converter == authenticationConverter || converter instanceof OAuth2ClientRegistrationAuthenticationConverter); verify(authenticationProvider).authenticate(any()); ArgumentCaptor<List<AuthenticationProvider>> authenticationProvidersCaptor = ArgumentCaptor .forClass(List.class); verify(authenticationProvidersConsumer).accept(authenticationProvidersCaptor.capture()); List<AuthenticationProvider> authenticationProviders = authenticationProvidersCaptor.getValue(); assertThat(authenticationProviders).hasSize(2) .allMatch((provider) -> provider == authenticationProvider || provider instanceof OAuth2ClientRegistrationAuthenticationProvider); verify(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), any()); verifyNoInteractions(authenticationFailureHandler); } @Test public void requestWhenClientRegistrationEndpointCustomizedWithAuthenticationFailureHandlerThenUsed() throws Exception { this.spring.register(CustomClientRegistrationConfiguration.class).autowire(); given(authenticationProvider.authenticate(any())).willThrow(new OAuth2AuthenticationException("error")); this.mvc.perform(post(ISSUER.concat(DEFAULT_OAUTH2_CLIENT_REGISTRATION_ENDPOINT_URI)).with(jwt())); verify(authenticationFailureHandler).onAuthenticationFailure(any(), any(), any()); verifyNoInteractions(authenticationSuccessHandler); } @Test public void requestWhenClientRegistersWithSecretThenClientAuthenticationSuccess() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); // @formatter:off OAuth2ClientRegistration clientRegistration = OAuth2ClientRegistration.builder() .clientName("client-name") .redirectUri("https://client.example.com") .grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()) .grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()) .scope("scope1") .scope("scope2") .build(); // @formatter:on OAuth2ClientRegistration clientRegistrationResponse = registerClient(clientRegistration); this.mvc .perform(post(ISSUER.concat(DEFAULT_TOKEN_ENDPOINT_URI)) .param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()) .param(OAuth2ParameterNames.SCOPE, "scope1") .with(httpBasic(clientRegistrationResponse.getClientId(), clientRegistrationResponse.getClientSecret()))) .andExpect(status().isOk()) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.scope").value("scope1")) .andReturn(); } @Test public void requestWhenClientRegistersWithCustomMetadataThenSavedToRegisteredClient() throws Exception { this.spring.register(CustomClientMetadataConfiguration.class).autowire(); // @formatter:off OAuth2ClientRegistration clientRegistration = OAuth2ClientRegistration.builder() .clientName("client-name") .redirectUri("https://client.example.com") .grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()) .grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()) .scope("scope1") .scope("scope2") .claim("custom-metadata-name-1", "value-1") .claim("custom-metadata-name-2", "value-2") .claim("non-registered-custom-metadata", "value-3") .build(); // @formatter:on OAuth2ClientRegistration clientRegistrationResponse = registerClient(clientRegistration); RegisteredClient registeredClient = this.registeredClientRepository .findByClientId(clientRegistrationResponse.getClientId()); assertClientRegistrationResponse(clientRegistration, clientRegistrationResponse); assertThat(clientRegistrationResponse.<String>getClaim("custom-metadata-name-1")).isEqualTo("value-1"); assertThat(clientRegistrationResponse.<String>getClaim("custom-metadata-name-2")).isEqualTo("value-2"); assertThat(clientRegistrationResponse.<String>getClaim("non-registered-custom-metadata")).isNull(); assertThat(registeredClient.getClientSettings().<String>getSetting("custom-metadata-name-1")) .isEqualTo("value-1"); assertThat(registeredClient.getClientSettings().<String>getSetting("custom-metadata-name-2")) .isEqualTo("value-2"); assertThat(registeredClient.getClientSettings().<String>getSetting("non-registered-custom-metadata")).isNull(); } @Test public void requestWhenClientRegistersWithSecretExpirationThenClientRegistrationResponse() throws Exception { this.spring.register(ClientSecretExpirationConfiguration.class).autowire(); // @formatter:off OAuth2ClientRegistration clientRegistration = OAuth2ClientRegistration.builder() .clientName("client-name") .redirectUri("https://client.example.com") .grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()) .grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()) .scope("scope1") .scope("scope2") .build(); // @formatter:on OAuth2ClientRegistration clientRegistrationResponse = registerClient(clientRegistration); Instant expectedSecretExpiryDate = Instant.now().plus(Duration.ofHours(24)); TemporalUnitWithinOffset allowedDelta = new TemporalUnitWithinOffset(1, ChronoUnit.MINUTES); // Returned response contains expiration date assertThat(clientRegistrationResponse.getClientSecretExpiresAt()).isNotNull() .isCloseTo(expectedSecretExpiryDate, allowedDelta); RegisteredClient registeredClient = this.registeredClientRepository .findByClientId(clientRegistrationResponse.getClientId()); // Persisted RegisteredClient contains expiration date assertThat(registeredClient).isNotNull(); assertThat(registeredClient.getClientSecretExpiresAt()).isNotNull() .isCloseTo(expectedSecretExpiryDate, allowedDelta); } private OAuth2ClientRegistration registerClient(OAuth2ClientRegistration clientRegistration) throws Exception { // ***** (1) Obtain the "initial" access token used for registering the client String clientRegistrationScope = "client.create"; // @formatter:off RegisteredClient clientRegistrar = RegisteredClient.withId("client-registrar-1") .clientId("client-registrar-1") .clientSecret("{noop}secret") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS) .scope(clientRegistrationScope) .build(); // @formatter:on this.registeredClientRepository.save(clientRegistrar); MvcResult mvcResult = this.mvc .perform(post(ISSUER.concat(DEFAULT_TOKEN_ENDPOINT_URI)) .param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()) .param(OAuth2ParameterNames.SCOPE, clientRegistrationScope) .with(httpBasic("client-registrar-1", "secret"))) .andExpect(status().isOk()) .andExpect(jsonPath("$.access_token").isNotEmpty()) .andExpect(jsonPath("$.scope").value(clientRegistrationScope)) .andReturn(); OAuth2AccessToken accessToken = readAccessTokenResponse(mvcResult.getResponse()).getAccessToken(); // ***** (2) Register the client HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setBearerAuth(accessToken.getTokenValue()); // Register the client mvcResult = this.mvc .perform(post(ISSUER.concat(DEFAULT_OAUTH2_CLIENT_REGISTRATION_ENDPOINT_URI)).headers(httpHeaders) .contentType(MediaType.APPLICATION_JSON) .content(getClientRegistrationRequestContent(clientRegistration))) .andExpect(status().isCreated()) .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))) .andReturn(); return readClientRegistrationResponse(mvcResult.getResponse()); } private static void assertClientRegistrationResponse(OAuth2ClientRegistration clientRegistrationRequest, OAuth2ClientRegistration clientRegistrationResponse) { assertThat(clientRegistrationResponse.getClientId()).isNotNull(); assertThat(clientRegistrationResponse.getClientIdIssuedAt()).isNotNull(); assertThat(clientRegistrationResponse.getClientSecret()).isNotNull(); assertThat(clientRegistrationResponse.getClientSecretExpiresAt()).isNull(); assertThat(clientRegistrationResponse.getClientName()).isEqualTo(clientRegistrationRequest.getClientName()); assertThat(clientRegistrationResponse.getRedirectUris()) .containsExactlyInAnyOrderElementsOf(clientRegistrationRequest.getRedirectUris()); assertThat(clientRegistrationResponse.getGrantTypes()) .containsExactlyInAnyOrderElementsOf(clientRegistrationRequest.getGrantTypes()); assertThat(clientRegistrationResponse.getResponseTypes()) .containsExactly(OAuth2AuthorizationResponseType.CODE.getValue()); assertThat(clientRegistrationResponse.getScopes()) .containsExactlyInAnyOrderElementsOf(clientRegistrationRequest.getScopes()); assertThat(clientRegistrationResponse.getTokenEndpointAuthenticationMethod()) .isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue()); } private static OAuth2AccessTokenResponse readAccessTokenResponse(MockHttpServletResponse response) throws Exception { MockClientHttpResponse httpResponse = new MockClientHttpResponse(response.getContentAsByteArray(), HttpStatus.valueOf(response.getStatus())); return accessTokenHttpResponseConverter.read(OAuth2AccessTokenResponse.class, httpResponse); } private static byte[] getClientRegistrationRequestContent(OAuth2ClientRegistration clientRegistration) throws Exception { MockHttpOutputMessage httpRequest = new MockHttpOutputMessage(); clientRegistrationHttpMessageConverter.write(clientRegistration, null, httpRequest); return httpRequest.getBodyAsBytes(); } private static OAuth2ClientRegistration readClientRegistrationResponse(MockHttpServletResponse response) throws Exception { MockClientHttpResponse httpResponse = new MockClientHttpResponse(response.getContentAsByteArray(), HttpStatus.valueOf(response.getStatus())); return clientRegistrationHttpMessageConverter.read(OAuth2ClientRegistration.class, httpResponse); } @EnableWebSecurity @Configuration(proxyBeanMethods = false) static
OAuth2ClientRegistrationTests
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/ChangelogFunction.java
{ "start": 4344, "end": 4698 }
interface ____ extends FunctionDefinition { /** * Returns the {@link ChangelogMode} of the PTF, taking into account the table arguments and the * planner's requirements. */ ChangelogMode getChangelogMode(ChangelogContext changelogContext); /** Context during changelog mode inference. */ @PublicEvolving
ChangelogFunction
java
netty__netty
buffer/src/main/java/io/netty/buffer/DefaultByteBufHolder.java
{ "start": 861, "end": 4354 }
class ____ implements ByteBufHolder { private final ByteBuf data; public DefaultByteBufHolder(ByteBuf data) { this.data = ObjectUtil.checkNotNull(data, "data"); } @Override public ByteBuf content() { return ByteBufUtil.ensureAccessible(data); } /** * {@inheritDoc} * <p> * This method calls {@code replace(content().copy())} by default. */ @Override public ByteBufHolder copy() { return replace(data.copy()); } /** * {@inheritDoc} * <p> * This method calls {@code replace(content().duplicate())} by default. */ @Override public ByteBufHolder duplicate() { return replace(data.duplicate()); } /** * {@inheritDoc} * <p> * This method calls {@code replace(content().retainedDuplicate())} by default. */ @Override public ByteBufHolder retainedDuplicate() { return replace(data.retainedDuplicate()); } /** * {@inheritDoc} * <p> * Override this method to return a new instance of this object whose content is set to the specified * {@code content}. The default implementation of {@link #copy()}, {@link #duplicate()} and * {@link #retainedDuplicate()} invokes this method to create a copy. */ @Override public ByteBufHolder replace(ByteBuf content) { return new DefaultByteBufHolder(content); } @Override public int refCnt() { return data.refCnt(); } @Override public ByteBufHolder retain() { data.retain(); return this; } @Override public ByteBufHolder retain(int increment) { data.retain(increment); return this; } @Override public ByteBufHolder touch() { data.touch(); return this; } @Override public ByteBufHolder touch(Object hint) { data.touch(hint); return this; } @Override public boolean release() { return data.release(); } @Override public boolean release(int decrement) { return data.release(decrement); } /** * Return {@link ByteBuf#toString()} without checking the reference count first. This is useful to implement * {@link #toString()}. */ protected final String contentToString() { return data.toString(); } @Override public String toString() { return StringUtil.simpleClassName(this) + '(' + contentToString() + ')'; } /** * This implementation of the {@code equals} operation is restricted to * work only with instances of the same class. The reason for that is that * Netty library already has a number of classes that extend {@link DefaultByteBufHolder} and * override {@code equals} method with an additional comparison logic and we * need the symmetric property of the {@code equals} operation to be preserved. * * @param o the reference object with which to compare. * @return {@code true} if this object is the same as the obj * argument; {@code false} otherwise. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o != null && getClass() == o.getClass()) { return data.equals(((DefaultByteBufHolder) o).data); } return false; } @Override public int hashCode() { return data.hashCode(); } }
DefaultByteBufHolder
java
quarkusio__quarkus
core/builder/src/main/java/io/quarkus/builder/json/JsonNumber.java
{ "start": 41, "end": 84 }
interface ____ extends JsonValue { }
JsonNumber
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/http/Saml2LogoutBeanDefinitionParserTests.java
{ "start": 22383, "end": 22940 }
class ____ implements RequestPostProcessor { @Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); for (Map.Entry<String, String[]> entries : request.getParameterMap().entrySet()) { builder.queryParam(entries.getKey(), UriUtils.encode(entries.getValue()[0], StandardCharsets.ISO_8859_1)); } request.setQueryString(builder.build(true).toUriString().substring(1)); return request; } } }
SamlQueryStringRequestPostProcessor
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/eventbus/VirtualThreadEventBusTest.java
{ "start": 696, "end": 1319 }
class ____ extends VertxTestBase { VertxInternal vertx; @Before public void setUp() throws Exception { super.setUp(); vertx = (VertxInternal) super.vertx; } @Test public void testEventBus() { Assume.assumeTrue(isVirtualThreadAvailable()); EventBus eb = vertx.eventBus(); eb.consumer("test-addr", msg -> { msg.reply(msg.body()); }); vertx.createVirtualThreadContext().runOnContext(v -> { Message<String> ret = eb.<String>request("test-addr", "test").await(); assertEquals("test", ret.body()); testComplete(); }); await(); } }
VirtualThreadEventBusTest
java
apache__dubbo
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java
{ "start": 1185, "end": 1752 }
class ____ implements TestService { private String name; @Override public String echo(String message) { return "[ECHO] " + message; } @Override public Model model(Model model) { return model; } @Override public String testPrimitive(boolean z, int i) { return null; } @Override public Model testEnum(TimeUnit timeUnit) { return null; } @Override public String testArray(String[] strArray, int[] intArray, Model[] modelArray) { return null; } }
DefaultTestService
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/doublearray/DoubleArrayAssert_hasSizeGreaterThanOrEqualTo_Test.java
{ "start": 806, "end": 1187 }
class ____ extends DoubleArrayAssertBaseTest { @Override protected DoubleArrayAssert invoke_api_method() { return assertions.hasSizeGreaterThanOrEqualTo(6); } @Override protected void verify_internal_effects() { verify(arrays).assertHasSizeGreaterThanOrEqualTo(getInfo(assertions), getActual(assertions), 6); } }
DoubleArrayAssert_hasSizeGreaterThanOrEqualTo_Test
java
quarkusio__quarkus
extensions/micrometer-opentelemetry/deployment/src/test/java/io/quarkus/micrometer/opentelemetry/deployment/common/InMemoryMetricExporter.java
{ "start": 1016, "end": 6650 }
class ____ implements MetricExporter { private final Queue<MetricData> finishedMetricItems = new ConcurrentLinkedQueue<>(); private final AggregationTemporality aggregationTemporality = AggregationTemporality.CUMULATIVE; private boolean isStopped = false; public MetricDataFilter metrics(final String name) { return new MetricDataFilter(this, name); } public MetricDataFilter get(final String name) { return new MetricDataFilter(this, name); } public MetricDataFilter find(final String name) { return new MetricDataFilter(this, name); } /* * ignore points with /export in the route */ private static boolean notExporterPointData(PointData pointData) { return pointData.getAttributes().asMap().entrySet().stream() .noneMatch(entry -> entry.getKey().getKey().equals("uri") && entry.getValue().toString().contains("/export")); } private static boolean isPathFound(String path, Attributes attributes) { if (path == null) { return true;// any match } Object value = attributes.asMap().get(AttributeKey.stringKey("uri")); if (value == null) { return false; } return value.toString().equals(path); } public MetricData getLastFinishedHistogramItem(String testSummary, int count) { Awaitility.await().atMost(5, SECONDS) .untilAsserted(() -> Assertions.assertEquals(count, getFinishedMetricItems(testSummary, null).size())); List<MetricData> metricData = getFinishedMetricItems(testSummary, null); return metricData.get(metricData.size() - 1);// get last added entry which will be the most recent } public void assertCountDataPointsAtLeast(final String name, final String target, final int count) { Awaitility.await().atMost(5, SECONDS) .untilAsserted(() -> Assertions.assertTrue(count < countMaxPoints(name, target))); } public void assertCountDataPointsAtLeastOrEqual(final String name, final String target, final int count) { Awaitility.await().atMost(5, SECONDS) .untilAsserted(() -> Assertions.assertTrue(count <= countMaxPoints(name, target))); } public void assertCountDataPointsAtLeastOrEqual(Supplier<MetricDataFilter> tag, int count) { Awaitility.await().atMost(50, SECONDS) .untilAsserted(() -> Assertions.assertTrue(count <= tag.get().lastReadingPointsSize())); } private Integer countMaxPoints(String name, String target) { List<MetricData> metricData = getFinishedMetricItems(name, target); if (metricData.isEmpty()) { return 0; } int size = metricData.get(metricData.size() - 1).getData().getPoints().size(); return size; } /** * Returns a {@code List} of the finished {@code Metric}s, represented by {@code MetricData}. * * @return a {@code List} of the finished {@code Metric}s. */ public List<MetricData> getFinishedMetricItems() { return Collections.unmodifiableList(new ArrayList<>(finishedMetricItems)); } public MetricData getFinishedMetricItem(String metricName) { List<MetricData> metricData = getFinishedMetricItems(metricName, null); if (metricData.isEmpty()) { return null; } return metricData.get(metricData.size() - 1);// get last added entry which will be the most recent } public List<MetricData> getFinishedMetricItems(final String name, final String target) { return Collections.unmodifiableList(new ArrayList<>( finishedMetricItems.stream() .filter(metricData -> metricData.getName().equals(name)) .filter(metricData -> metricData.getData().getPoints().stream() .anyMatch(point -> isPathFound(target, point.getAttributes()))) .collect(Collectors.toList()))); } /** * Clears the internal {@code List} of finished {@code Metric}s. * * <p> * Does not reset the state of this exporter if already shutdown. */ public void reset() { finishedMetricItems.clear(); } @Override public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { return aggregationTemporality; } /** * Exports the collection of {@code Metric}s into the inmemory queue. * * <p> * If this is called after {@code shutdown}, this will return {@code ResultCode.FAILURE}. */ @Override public CompletableResultCode export(Collection<MetricData> metrics) { if (isStopped) { return CompletableResultCode.ofFailure(); } finishedMetricItems.addAll(metrics); return CompletableResultCode.ofSuccess(); } /** * The InMemory exporter does not batch metrics, so this method will immediately return with * success. * * @return always Success */ @Override public CompletableResultCode flush() { return CompletableResultCode.ofSuccess(); } /** * Clears the internal {@code List} of finished {@code Metric}s. * * <p> * Any subsequent call to export() function on this MetricExporter, will return {@code * CompletableResultCode.ofFailure()} */ @Override public CompletableResultCode shutdown() { isStopped = true; finishedMetricItems.clear(); return CompletableResultCode.ofSuccess(); } }
InMemoryMetricExporter
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java
{ "start": 9764, "end": 10085 }
class ____ Graal is active. @SuppressWarnings("unchecked") Class<T> target = GraalImageCode.getCurrent().isDefined() && features.mockedType.isInterface() ? (Class<T>) Object.class : features.mockedType; // If we create a mock for an
when
java
resilience4j__resilience4j
resilience4j-reactor/src/main/java/io/github/resilience4j/reactor/bulkhead/operator/BulkheadSubscriber.java
{ "start": 1103, "end": 2662 }
class ____<T> extends AbstractSubscriber<T> { private final Bulkhead bulkhead; private final boolean singleProducer; private final AtomicBoolean eventWasEmitted = new AtomicBoolean(false); private final AtomicBoolean completedSignaled = new AtomicBoolean(false); BulkheadSubscriber(Bulkhead bulkhead, CoreSubscriber<? super T> downstreamSubscriber, boolean singleProducer) { super(downstreamSubscriber); this.bulkhead = requireNonNull(bulkhead); this.singleProducer = singleProducer; } @Override public void hookOnNext(T t) { if (!isDisposed()) { if (singleProducer && completedSignaled.compareAndSet(false, true)) { bulkhead.onComplete(); } eventWasEmitted.set(true); downstreamSubscriber.onNext(t); } } @Override public void hookOnCancel() { if (completedSignaled.compareAndSet(false, true)) { if (eventWasEmitted.get()) { bulkhead.onComplete(); } else { bulkhead.releasePermission(); } } } @Override public void hookOnError(Throwable t) { if (!completedSignaled.get()) { bulkhead.onComplete(); } downstreamSubscriber.onError(t); } @Override public void hookOnComplete() { if (completedSignaled.compareAndSet(false, true)) { bulkhead.onComplete(); } downstreamSubscriber.onComplete(); } }
BulkheadSubscriber
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/embeddable/EmbeddableInheritanceMappedSuperclassAndGenericsTest.java
{ "start": 5824, "end": 6179 }
class ____ { @Id private Long id; @Embedded private Range<Integer> range; public TestEntity() { } public TestEntity(Long id, Range<Integer> range) { this.id = id; this.range = range; } public Range<Integer> getRange() { return range; } public void setRange(Range<Integer> range) { this.range = range; } } }
TestEntity
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/main/java/org/apache/hadoop/yarn/server/timelineservice/reader/security/TimelineReaderWhitelistAuthorizationFilter.java
{ "start": 1738, "end": 4695 }
class ____ implements Filter { public static final String EMPTY_STRING = ""; private static final Logger LOG = LoggerFactory.getLogger(TimelineReaderWhitelistAuthorizationFilter.class); private boolean isWhitelistReadAuthEnabled = false; private AccessControlList allowedUsersAclList; private AccessControlList adminAclList; @Override public void destroy() { // NOTHING } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (isWhitelistReadAuthEnabled) { UserGroupInformation callerUGI = TimelineReaderWebServicesUtils .getUser(httpRequest); if (callerUGI == null) { String msg = "Unable to obtain user name, user not authenticated"; throw new AuthorizationException(msg); } if (!(adminAclList.isUserAllowed(callerUGI) || allowedUsersAclList.isUserAllowed(callerUGI))) { String userName = callerUGI.getShortUserName(); String msg = "User " + userName + " is not allowed to read TimelineService V2 data."; httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, msg); return; } } if (chain != null) { chain.doFilter(request, response); } } @Override public void init(FilterConfig conf) throws ServletException { String isWhitelistReadAuthEnabledStr = conf .getInitParameter(YarnConfiguration.TIMELINE_SERVICE_READ_AUTH_ENABLED); if (isWhitelistReadAuthEnabledStr == null) { isWhitelistReadAuthEnabled = YarnConfiguration.DEFAULT_TIMELINE_SERVICE_READ_AUTH_ENABLED; } else { isWhitelistReadAuthEnabled = Boolean.valueOf(isWhitelistReadAuthEnabledStr); } if (isWhitelistReadAuthEnabled) { String listAllowedUsers = conf.getInitParameter( YarnConfiguration.TIMELINE_SERVICE_READ_ALLOWED_USERS); if (StringUtils.isEmpty(listAllowedUsers)) { listAllowedUsers = YarnConfiguration.DEFAULT_TIMELINE_SERVICE_READ_ALLOWED_USERS; } LOG.info("listAllowedUsers={}", listAllowedUsers); allowedUsersAclList = new AccessControlList(listAllowedUsers); LOG.info("allowedUsersAclList={}", allowedUsersAclList.getUsers()); // also allow admins String adminAclListStr = conf.getInitParameter(YarnConfiguration.YARN_ADMIN_ACL); if (StringUtils.isEmpty(adminAclListStr)) { adminAclListStr = TimelineReaderWhitelistAuthorizationFilter.EMPTY_STRING; LOG.info("adminAclList not set, hence setting it to \"\""); } adminAclList = new AccessControlList(adminAclListStr); LOG.info("adminAclList={}", adminAclList.getUsers()); } } }
TimelineReaderWhitelistAuthorizationFilter
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopDoubleIntAggregator.java
{ "start": 1424, "end": 3149 }
class ____ { public static SingleState initSingle(BigArrays bigArrays, int limit, boolean ascending) { return new SingleState(bigArrays, limit, ascending); } public static void combine(SingleState state, double v, int outputValue) { state.add(v, outputValue); } public static void combineIntermediate(SingleState state, DoubleBlock values, IntBlock outputValues) { int start = values.getFirstValueIndex(0); int end = start + values.getValueCount(0); for (int i = start; i < end; i++) { combine(state, values.getDouble(i), outputValues.getInt(i)); } } public static Block evaluateFinal(SingleState state, DriverContext driverContext) { return state.toBlock(driverContext.blockFactory()); } public static GroupingState initGrouping(BigArrays bigArrays, int limit, boolean ascending) { return new GroupingState(bigArrays, limit, ascending); } public static void combine(GroupingState state, int groupId, double v, int outputValue) { state.add(groupId, v, outputValue); } public static void combineIntermediate(GroupingState state, int groupId, DoubleBlock values, IntBlock outputValues, int position) { int start = values.getFirstValueIndex(position); int end = start + values.getValueCount(position); for (int i = start; i < end; i++) { combine(state, groupId, values.getDouble(i), outputValues.getInt(i)); } } public static Block evaluateFinal(GroupingState state, IntVector selected, GroupingAggregatorEvaluationContext ctx) { return state.toBlock(ctx.blockFactory(), selected); } public static
TopDoubleIntAggregator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InvalidBlockTagTest.java
{ "start": 5716, "end": 5815 }
interface ____ { void foo(); } """) .doTest(); } }
Test
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/mixins/TestMixinSerForMethods.java
{ "start": 1605, "end": 1819 }
class ____ extends BaseClass { public LeafClass(String a, String b) { super(a, b); } @Override @JsonIgnore public String takeB() { return null; } } static
LeafClass
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateWithUseJdbcMetadataDefaultsSettingToFalseAndQuotedNameTest.java
{ "start": 1396, "end": 4744 }
class ____ { private File updateOutputFile; private File createOutputFile; private StandardServiceRegistry ssr; private MetadataImplementor metadata; public void setUp(String jdbcMetadataExtractorStrategy) throws IOException { createOutputFile = File.createTempFile( "create_script", ".sql" ); createOutputFile.deleteOnExit(); updateOutputFile = File.createTempFile( "update_script", ".sql" ); updateOutputFile.deleteOnExit(); ssr = ServiceRegistryUtil.serviceRegistryBuilder() .applySetting( "hibernate.temp.use_jdbc_metadata_defaults", "false" ) .applySetting( AvailableSettings.SHOW_SQL, "true" ) .applySetting( AvailableSettings.HBM2DDL_JDBC_METADATA_EXTRACTOR_STRATEGY, jdbcMetadataExtractorStrategy ) .build(); final MetadataSources metadataSources = new MetadataSources( ssr ); metadataSources.addAnnotatedClass( AnotherTestEntity.class ); metadata = (MetadataImplementor) metadataSources.buildMetadata(); metadata.orderColumns( false ); metadata.validate(); } @AfterEach public void tearDown() { new SchemaExport().setHaltOnError( true ) .setFormat( false ) .drop( EnumSet.of( TargetType.DATABASE ), metadata ); StandardServiceRegistryBuilder.destroy( ssr ); } @ParameterizedTest @EnumSource(JdbcMetadataAccessStrategy.class) public void testSchemaUpdateDoesNotTryToRecreateExistingTables(JdbcMetadataAccessStrategy strategy) throws Exception { setUp( strategy.toString() ); createSchema(); new SchemaUpdate().setHaltOnError( true ) .setOutputFile( updateOutputFile.getAbsolutePath() ) .setFormat( false ) .execute( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), metadata ); checkNoUpdateStatementHasBeenGenerated(); } private void checkNoUpdateStatementHasBeenGenerated() throws IOException { final String fileContent = new String( Files.readAllBytes( updateOutputFile.toPath() ) ); assertThat( "The update output file should be empty because the db schema had already been generated and the domain model was not modified", fileContent, is( "" ) ); } private void createSchema() throws Exception { new SchemaUpdate().setHaltOnError( true ) .setOutputFile( createOutputFile.getAbsolutePath() ) .execute( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), metadata ); new SchemaValidator().validate( metadata ); checkSchemaHasBeenGenerated(); } private void checkSchemaHasBeenGenerated() throws Exception { String fileContent = new String( Files.readAllBytes( createOutputFile.toPath() ) ); final Dialect dialect = metadata.getDatabase().getDialect(); Pattern fileContentPattern; if ( dialect.openQuote() == '[' ) { fileContentPattern = Pattern.compile( "create( (column|row))? table " + "\\[" + "another_test_entity" + "\\]" ); } else { fileContentPattern = Pattern.compile( "create( (column|row))? table " + dialect.openQuote() + "another_test_entity" + dialect .closeQuote() ); } Matcher fileContentMatcher = fileContentPattern.matcher( fileContent.toLowerCase() ); assertThat( "The schema has not been correctly generated, Script file : " + fileContent.toLowerCase(), fileContentMatcher.find(), is( true ) ); } @Entity(name = "`Another_Test_Entity`") public static
SchemaUpdateWithUseJdbcMetadataDefaultsSettingToFalseAndQuotedNameTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/PulsarEndpointBuilderFactory.java
{ "start": 55993, "end": 56290 }
interface ____ extends AdvancedPulsarEndpointConsumerBuilder, AdvancedPulsarEndpointProducerBuilder { default PulsarEndpointBuilder basic() { return (PulsarEndpointBuilder) this; } } public
AdvancedPulsarEndpointBuilder
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/IdentifierBuilder.java
{ "start": 1539, "end": 14783 }
class ____ extends AbstractBuilder { private static final String BLANK_INDEX_ERROR_MESSAGE = "Blank index specified in index pattern"; private static final String INVALID_ESQL_CHARS = Strings.INVALID_FILENAME_CHARS.replace("'*',", ""); @Override public String visitIdentifier(IdentifierContext ctx) { return ctx == null ? null : unquoteIdentifier(ctx.QUOTED_IDENTIFIER(), ctx.UNQUOTED_IDENTIFIER()); } protected static String unquoteIdentifier(TerminalNode quotedNode, TerminalNode unquotedNode) { String result; if (quotedNode != null) { result = unquoteIdString(quotedNode.getText()); } else { result = unquotedNode.getText(); } return result; } protected static String unquoteIdString(String quotedString) { return quotedString.substring(1, quotedString.length() - 1).replace("``", "`"); } protected static String quoteIdString(String unquotedString) { return "`" + unquotedString.replace("`", "``") + "`"; } @Override public String visitClusterString(EsqlBaseParser.ClusterStringContext ctx) { if (ctx == null) { return null; } else { return ctx.UNQUOTED_SOURCE().getText(); } } @Override public String visitIndexString(IndexStringContext ctx) { if (ctx.UNQUOTED_SOURCE() != null) { return ctx.UNQUOTED_SOURCE().getText(); } else { return unquote(ctx.QUOTED_STRING().getText()); } } @Override public String visitSelectorString(EsqlBaseParser.SelectorStringContext ctx) { if (ctx == null) { return null; } else { return ctx.UNQUOTED_SOURCE().getText(); } } public String visitIndexPattern(List<EsqlBaseParser.IndexPatternContext> ctx) { List<String> patterns = new ArrayList<>(ctx.size()); Holder<Boolean> hasSeenStar = new Holder<>(false); ctx.forEach(c -> { String indexPattern = c.unquotedIndexString() != null ? c.unquotedIndexString().getText() : visitIndexString(c.indexString()); String clusterString = visitClusterString(c.clusterString()); String selectorString = visitSelectorString(c.selectorString()); hasSeenStar.set(hasSeenStar.get() || indexPattern.contains(WILDCARD)); validate(clusterString, indexPattern, selectorString, c, hasSeenStar.get()); patterns.add(reassembleIndexName(clusterString, indexPattern, selectorString)); }); return Strings.collectionToDelimitedString(patterns, ","); } private static void throwInvalidIndexNameException(String indexPattern, String message, EsqlBaseParser.IndexPatternContext ctx) { var ie = new InvalidIndexNameException(indexPattern, message); throw new ParsingException(ie, source(ctx), ie.getMessage()); } private static void throwOnMixingSelectorWithCluster(String indexPattern, EsqlBaseParser.IndexPatternContext c) { throwInvalidIndexNameException(indexPattern, "Selectors are not yet supported on remote cluster patterns", c); } private static String reassembleIndexName(String clusterString, String indexPattern, String selectorString) { if (clusterString == null && selectorString == null) { return indexPattern; } StringBuilder expression = new StringBuilder(); if (clusterString != null) { expression.append(clusterString).append(REMOTE_CLUSTER_INDEX_SEPARATOR); } expression.append(indexPattern); if (selectorString != null) { expression.append(SELECTOR_SEPARATOR).append(selectorString); } return expression.toString(); } protected static void validateClusterString(String clusterString, EsqlBaseParser.IndexPatternContext ctx) { if (clusterString.indexOf(RemoteClusterService.REMOTE_CLUSTER_INDEX_SEPARATOR) != -1) { throw new ParsingException(source(ctx), "cluster string [{}] must not contain ':'", clusterString); } } /** * Takes the parsed constituent strings and validates them. * @param clusterString Name of the remote cluster. Can be null. * @param indexPattern Name of the index or pattern; can also have multiple patterns in case of quoting, * e.g. {@code FROM """index*,-index1"""}. * @param selectorString Selector string, i.e. "::data" or "::failures". Can be null. * @param ctx Index Pattern Context for generating error messages with offsets. * @param hasSeenStar If we've seen an asterisk so far. */ private static void validate( String clusterString, String indexPattern, String selectorString, EsqlBaseParser.IndexPatternContext ctx, boolean hasSeenStar ) { /* * At this point, only 3 formats are possible: * "index_pattern(s)", * remote:index_pattern, and, * index_pattern::selector_string. * * The grammar prohibits remote:"index_pattern(s)" or "index_pattern(s)"::selector_string as they're * partially quoted. So if either of cluster string or selector string are present, there's no need * to split the pattern by comma since comma requires partial quoting. */ String[] patterns; if (clusterString == null && selectorString == null) { // Pattern could be quoted or is singular like "index_name". patterns = indexPattern.split(",", -1); } else { // Either of cluster string or selector string is present. Pattern is unquoted. patterns = new String[] { indexPattern }; } patterns = Arrays.stream(patterns).map(String::strip).toArray(String[]::new); if (Arrays.stream(patterns).anyMatch(String::isBlank)) { throwInvalidIndexNameException(indexPattern, BLANK_INDEX_ERROR_MESSAGE, ctx); } // Edge case: happens when all the index names in a pattern are empty like "FROM ",,,,,"". if (patterns.length == 0) { throwInvalidIndexNameException(indexPattern, BLANK_INDEX_ERROR_MESSAGE, ctx); } else if (patterns.length == 1) { // Pattern is either an unquoted string or a quoted string with a single index (no comma sep). validateSingleIndexPattern(clusterString, patterns[0], selectorString, ctx, hasSeenStar); } else { /* * Presence of multiple patterns requires a comma and comma requires quoting. If quoting is present, * cluster string and selector string cannot be present; they need to be attached within the quoting. * So we attempt to extract them later. */ for (String pattern : patterns) { validateSingleIndexPattern(null, pattern, null, ctx, hasSeenStar); } } } /** * Validates the constituent strings. Will extract the cluster string and/or selector string from the index * name if clubbed together inside a quoted string. * * @param clusterString Name of the remote cluster. Can be null. * @param indexName Name of the index. * @param selectorString Selector string, i.e. "::data" or "::failures". Can be null. * @param ctx Index Pattern Context for generating error messages with offsets. * @param hasSeenStar If we've seen an asterisk so far. */ private static void validateSingleIndexPattern( String clusterString, String indexName, String selectorString, EsqlBaseParser.IndexPatternContext ctx, boolean hasSeenStar ) { indexName = indexName.strip(); /* * Precedence: * 1. Cannot mix cluster and selector strings. * 2. Cluster string must be valid. * 3. Index name must be valid. * 4. Selector string must be valid. * * Since cluster string and/or selector string can be clubbed with the index name, we must try to * manually extract them before we attempt to do #2, #3, and #4. */ // It is possible to specify a pattern like "remote_cluster:index_name". Try to extract such details from the index string. if (clusterString == null && selectorString == null) { try { var split = splitIndexName(indexName); clusterString = split[0]; indexName = split[1]; } catch (IllegalArgumentException e) { throw new ParsingException(e, source(ctx), e.getMessage()); } } // At the moment, selector strings for remote indices is not allowed. if (clusterString != null && selectorString != null) { throwOnMixingSelectorWithCluster(reassembleIndexName(clusterString, indexName, selectorString), ctx); } // Validation in the right precedence. if (clusterString != null) { clusterString = clusterString.strip(); validateClusterString(clusterString, ctx); } /* * It is possible for selector string to be attached to the index: "index_name::selector_string". * Try to extract the selector string. */ try { Tuple<String, String> splitPattern = IndexNameExpressionResolver.splitSelectorExpression(indexName); if (splitPattern.v2() != null) { // Cluster string too was clubbed with the index name like selector string. if (clusterString != null) { throwOnMixingSelectorWithCluster(reassembleIndexName(clusterString, splitPattern.v1(), splitPattern.v2()), ctx); } else { // We've seen a selectorString. Use it. selectorString = splitPattern.v2(); } } indexName = splitPattern.v1(); } catch (InvalidIndexNameException e) { throw new ParsingException(e, source(ctx), e.getMessage()); } resolveAndValidateIndex(indexName, ctx, hasSeenStar); if (selectorString != null) { selectorString = selectorString.strip(); try { // Ensures that the selector provided is one of the valid kinds. IndexNameExpressionResolver.SelectorResolver.validateIndexSelectorString(indexName, selectorString); } catch (InvalidIndexNameException e) { throw new ParsingException(e, source(ctx), e.getMessage()); } } } private static void resolveAndValidateIndex(String index, EsqlBaseParser.IndexPatternContext ctx, boolean hasSeenStar) { // If index name is blank without any replacements, it was likely blank right from the beginning and is invalid. if (index.isBlank()) { throwInvalidIndexNameException(index, BLANK_INDEX_ERROR_MESSAGE, ctx); } hasSeenStar = hasSeenStar || index.contains(WILDCARD); index = index.replace(WILDCARD, "").strip(); if (index.isBlank()) { return; } var hasExclusion = index.startsWith(EXCLUSION); index = removeExclusion(index); String tempName; try { // remove the exclusion outside of <>, from index names with DateMath expression, // e.g. -<-logstash-{now/d}> becomes <-logstash-{now/d}> before calling resolveDateMathExpression tempName = IndexNameExpressionResolver.resolveDateMathExpression(index); } catch (ElasticsearchParseException e) { // throws exception if the DateMath expression is invalid, resolveDateMathExpression does not complain about exclusions throw new ParsingException(e, source(ctx), e.getMessage()); } hasExclusion = tempName.startsWith(EXCLUSION) || hasExclusion; index = tempName.equals(index) ? index : removeExclusion(tempName); try { MetadataCreateIndexService.validateIndexOrAliasName(index, InvalidIndexNameException::new); } catch (InvalidIndexNameException e) { // ignore invalid index name if it has exclusions and there is an index with wildcard before it if (hasSeenStar && hasExclusion) { return; } /* * We only modify this particular message because it mentions '*' as an invalid char. * However, we do allow asterisk in the index patterns: wildcarded patterns. Let's not * mislead the user by mentioning this char in the error message. */ if (e.getMessage().contains("must not contain the following characters")) { throwInvalidIndexNameException(index, "must not contain the following characters " + INVALID_ESQL_CHARS, ctx); } throw new ParsingException(e, source(ctx), e.getMessage()); } } private static String removeExclusion(String indexPattern) { return indexPattern.charAt(0) == EXCLUSION.charAt(0) ? indexPattern.substring(1) : indexPattern; } }
IdentifierBuilder
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/CommandFactory.java
{ "start": 2571, "end": 3613 }
class ____ the command names * @param names one or more command names that will invoke this class */ public void addClass(Class<? extends Command> cmdClass, String ... names) { for (String name : names) classMap.put(name, cmdClass); } /** * Register the given object as handling the given list of command * names. Avoid calling this method and use * {@link #addClass(Class, String...)} whenever possible to avoid * startup overhead from excessive command object instantiations. This * method is intended only for handling nested non-static classes that * are re-usable. Namely -help/-usage. * @param cmdObject the object implementing the command names * @param names one or more command names that will invoke this class */ public void addObject(Command cmdObject, String ... names) { for (String name : names) { objectMap.put(name, cmdObject); classMap.put(name, null); // just so it shows up in the list of commands } } /** * Returns an instance of the
implementing
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/UndertowEndpointBuilderFactory.java
{ "start": 63792, "end": 65959 }
interface ____ { /** * Undertow (camel-undertow) * Expose HTTP and WebSocket endpoints and access external * HTTP/WebSocket servers. * * Category: http,networking * Since: 2.16 * Maven coordinates: org.apache.camel:camel-undertow * * @return the dsl builder for the headers' name. */ default UndertowHeaderNameBuilder undertow() { return UndertowHeaderNameBuilder.INSTANCE; } /** * Undertow (camel-undertow) * Expose HTTP and WebSocket endpoints and access external * HTTP/WebSocket servers. * * Category: http,networking * Since: 2.16 * Maven coordinates: org.apache.camel:camel-undertow * * Syntax: <code>undertow:httpURI</code> * * Path parameter: httpURI (required) * The url of the HTTP endpoint to use. * * @param path httpURI * @return the dsl builder */ default UndertowEndpointBuilder undertow(String path) { return UndertowEndpointBuilderFactory.endpointBuilder("undertow", path); } /** * Undertow (camel-undertow) * Expose HTTP and WebSocket endpoints and access external * HTTP/WebSocket servers. * * Category: http,networking * Since: 2.16 * Maven coordinates: org.apache.camel:camel-undertow * * Syntax: <code>undertow:httpURI</code> * * Path parameter: httpURI (required) * The url of the HTTP endpoint to use. * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path httpURI * @return the dsl builder */ default UndertowEndpointBuilder undertow(String componentName, String path) { return UndertowEndpointBuilderFactory.endpointBuilder(componentName, path); } } /** * The builder of headers' name for the Undertow component. */ public static
UndertowBuilders
java
apache__camel
components/camel-ai/camel-langchain4j-chat/src/main/java/org/apache/camel/component/langchain4j/chat/LangChain4jChatOperations.java
{ "start": 864, "end": 988 }
enum ____ { CHAT_SINGLE_MESSAGE, CHAT_SINGLE_MESSAGE_WITH_PROMPT, CHAT_MULTIPLE_MESSAGES }
LangChain4jChatOperations
java
elastic__elasticsearch
libs/x-content/impl/src/test/java/org/elasticsearch/xcontent/provider/json/ESUTF8StreamJsonParserTests.java
{ "start": 1410, "end": 16296 }
class ____ extends ESTestCase { private void testParseJson(String input, CheckedConsumer<ESUTF8StreamJsonParser, IOException> test) throws IOException { JsonFactory factory = new ESJsonFactoryBuilder().build(); assertThat(factory, Matchers.instanceOf(ESJsonFactory.class)); JsonParser parser = factory.createParser(StandardCharsets.UTF_8.encode(input).array()); assertThat(parser, Matchers.instanceOf(ESUTF8StreamJsonParser.class)); test.accept((ESUTF8StreamJsonParser) parser); } private void assertTextRef(XContentString.UTF8Bytes textRef, String expectedValue) { assertThat(textRef, Matchers.equalTo(new XContentString.UTF8Bytes(expectedValue.getBytes(StandardCharsets.UTF_8)))); } public void testGetValueAsText() throws IOException { testParseJson("{\"foo\": \"bar\"}", parser -> { assertThat(parser.nextToken(), Matchers.equalTo(JsonToken.START_OBJECT)); assertThat(parser.nextFieldName(), Matchers.equalTo("foo")); assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.VALUE_STRING)); var text = parser.getValueAsText(); assertThat(text, Matchers.notNullValue()); var bytes = text.bytes(); assertThat(bytes.offset(), Matchers.equalTo(9)); assertThat(bytes.offset() + bytes.length(), Matchers.equalTo(12)); assertTextRef(bytes, "bar"); assertThat(parser.getValueAsString(), Matchers.equalTo("bar")); assertThat(parser.getValueAsText(), Matchers.nullValue()); assertThat(parser.nextToken(), Matchers.equalTo(JsonToken.END_OBJECT)); }); testParseJson("{\"foo\": [\"bar\\\"baz\\\"\", \"foobar\"]}", parser -> { assertThat(parser.nextToken(), Matchers.equalTo(JsonToken.START_OBJECT)); assertThat(parser.nextFieldName(), Matchers.equalTo("foo")); assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.START_ARRAY)); assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.VALUE_STRING)); var firstText = parser.getValueAsText(); assertThat(firstText, Matchers.notNullValue()); assertTextRef(firstText.bytes(), "bar\"baz\""); // Retrieve the value for a second time to ensure the last value is available firstText = parser.getValueAsText(); assertThat(firstText, Matchers.notNullValue()); assertTextRef(firstText.bytes(), "bar\"baz\""); // Ensure values lastOptimisedValue is reset assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.VALUE_STRING)); var secondTest = parser.getValueAsText(); assertThat(secondTest, Matchers.notNullValue()); assertTextRef(secondTest.bytes(), "foobar"); secondTest = parser.getValueAsText(); assertThat(secondTest, Matchers.notNullValue()); assertTextRef(secondTest.bytes(), "foobar"); assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.END_ARRAY)); }); testParseJson("{\"foo\": \"b\\u00e5r\"}", parser -> { assertThat(parser.nextToken(), Matchers.equalTo(JsonToken.START_OBJECT)); assertThat(parser.nextFieldName(), Matchers.equalTo("foo")); assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.VALUE_STRING)); assertThat(parser.getValueAsText(), Matchers.nullValue()); assertThat(parser.getValueAsString(), Matchers.equalTo("bår")); }); testParseJson("{\"foo\": \"\uD83D\uDE0A\"}", parser -> { assertThat(parser.nextToken(), Matchers.equalTo(JsonToken.START_OBJECT)); assertThat(parser.nextFieldName(), Matchers.equalTo("foo")); assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.VALUE_STRING)); var text = parser.getValueAsText(); assertThat(text, Matchers.notNullValue()); var bytes = text.bytes(); assertTextRef(bytes, "\uD83D\uDE0A"); assertThat(text.stringLength(), Matchers.equalTo(2)); }); testParseJson("{\"foo\": \"bår\"}", parser -> { assertThat(parser.nextToken(), Matchers.equalTo(JsonToken.START_OBJECT)); assertThat(parser.nextFieldName(), Matchers.equalTo("foo")); assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.VALUE_STRING)); var text = parser.getValueAsText(); assertThat(text, Matchers.notNullValue()); var bytes = text.bytes(); assertThat(bytes.offset(), Matchers.equalTo(9)); assertThat(bytes.offset() + bytes.length(), Matchers.equalTo(13)); assertTextRef(bytes, "bår"); assertThat(parser.getValueAsString(), Matchers.equalTo("bår")); assertThat(parser.nextToken(), Matchers.equalTo(JsonToken.END_OBJECT)); }); testParseJson("{\"foo\": [\"lorem\", \"ipsum\", \"dolor\"]}", parser -> { assertThat(parser.nextToken(), Matchers.equalTo(JsonToken.START_OBJECT)); assertThat(parser.nextFieldName(), Matchers.equalTo("foo")); assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.START_ARRAY)); assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.VALUE_STRING)); { var textRef = parser.getValueAsText().bytes(); assertThat(textRef, Matchers.notNullValue()); assertThat(textRef.offset(), Matchers.equalTo(10)); assertThat(textRef.offset() + textRef.length(), Matchers.equalTo(15)); assertTextRef(textRef, "lorem"); } assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.VALUE_STRING)); { var textRef = parser.getValueAsText().bytes(); assertThat(textRef, Matchers.notNullValue()); assertThat(textRef.offset(), Matchers.equalTo(19)); assertThat(textRef.offset() + textRef.length(), Matchers.equalTo(24)); assertTextRef(textRef, "ipsum"); } assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.VALUE_STRING)); { var textRef = parser.getValueAsText().bytes(); assertThat(textRef, Matchers.notNullValue()); assertThat(textRef.offset(), Matchers.equalTo(28)); assertThat(textRef.offset() + textRef.length(), Matchers.equalTo(33)); assertTextRef(textRef, "dolor"); } assertThat(parser.nextToken(), Matchers.equalTo(JsonToken.END_ARRAY)); assertThat(parser.nextToken(), Matchers.equalTo(JsonToken.END_OBJECT)); }); } private record TestInput(String input, String result, boolean supportsOptimized) {} private static final TestInput[] ESCAPE_SEQUENCES = { new TestInput("\\b", "\b", false), new TestInput("\\t", "\t", false), new TestInput("\\n", "\n", false), new TestInput("\\f", "\f", false), new TestInput("\\r", "\r", false), new TestInput("\\\"", "\"", true), new TestInput("\\/", "/", true), new TestInput("\\\\", "\\", true) }; private int randomCodepointIncludeAscii() { while (true) { char val = Character.toChars(randomInt(0xFFFF))[0]; if (val >= Character.MIN_SURROGATE && val <= Character.MAX_SURROGATE) { continue; } return val; } } private int randomCodepointIncludeOutsideBMP(int remainingLength) { while (true) { int codePoint = randomInt(0x10FFFF); char[] val = Character.toChars(codePoint); // Don't include ascii if (val.length == 1 && val[0] <= 0x7F) { continue; } boolean surrogate = val[0] >= Character.MIN_SURROGATE && val[0] <= Character.MAX_SURROGATE; // Single surrogate is invalid if (val.length == 1 && surrogate) { continue; } // Not enough remaining space for a surrogate pair if (remainingLength < 2 && surrogate) { continue; } return codePoint; } } private TestInput buildRandomInput(int length) { StringBuilder input = new StringBuilder(length); StringBuilder result = new StringBuilder(length); boolean forceSupportOptimized = randomBoolean(); boolean doesSupportOptimized = true; for (int i = 0; i < length; ++i) { if (forceSupportOptimized == false && randomBoolean()) { switch (randomInt(9)) { case 0 -> { var escape = randomFrom(ESCAPE_SEQUENCES); input.append(escape.input()); result.append(escape.result()); doesSupportOptimized = doesSupportOptimized && escape.supportsOptimized(); } case 1 -> { int value = randomCodepointIncludeAscii(); input.append(String.format(Locale.ENGLISH, "\\u%04x", value)); result.append(Character.toChars(value)); doesSupportOptimized = false; } default -> { var remainingLength = length - i; var value = Character.toChars(randomCodepointIncludeOutsideBMP(remainingLength)); input.append(value); result.append(value); } } } else { var value = randomAlphanumericOfLength(1); input.append(value); result.append(value); } } return new TestInput(input.toString(), result.toString(), doesSupportOptimized); } public void testGetValueRandomized() throws IOException { StringBuilder inputBuilder = new StringBuilder(); inputBuilder.append('{'); final int numKeys = 128; String[] keys = new String[numKeys]; TestInput[] inputs = new TestInput[numKeys]; for (int i = 0; i < numKeys; i++) { String currKey = randomAlphanumericOfLength(6); var currVal = buildRandomInput(randomInt(512)); inputBuilder.append('"'); inputBuilder.append(currKey); inputBuilder.append("\":\""); inputBuilder.append(currVal.input()); inputBuilder.append('"'); if (i < numKeys - 1) { inputBuilder.append(','); } keys[i] = currKey; inputs[i] = currVal; } inputBuilder.append('}'); testParseJson(inputBuilder.toString(), parser -> { assertThat(parser.nextToken(), Matchers.equalTo(JsonToken.START_OBJECT)); for (int i = 0; i < numKeys; i++) { assertThat(parser.nextFieldName(), Matchers.equalTo(keys[i])); assertThat(parser.nextValue(), Matchers.equalTo(JsonToken.VALUE_STRING)); String currVal = inputs[i].result(); if (inputs[i].supportsOptimized()) { var text = parser.getValueAsText(); assertTextRef(text.bytes(), currVal); assertThat(text.stringLength(), Matchers.equalTo(currVal.length())); // Retrieve it a second time text = parser.getValueAsText(); assertThat(text, Matchers.notNullValue()); assertTextRef(text.bytes(), currVal); assertThat(text.stringLength(), Matchers.equalTo(currVal.length())); // Use getText() assertThat(parser.getText(), Matchers.equalTo(text.string())); // After retrieving it with getText() we do not use the optimised value anymore. assertThat(parser.getValueAsText(), Matchers.nullValue()); } else { assertThat(parser.getText(), Matchers.notNullValue()); assertThat(parser.getValueAsText(), Matchers.nullValue()); assertThat(parser.getValueAsString(), Matchers.equalTo(currVal)); // Retrieve it twice to ensure it works as expected assertThat(parser.getValueAsText(), Matchers.nullValue()); assertThat(parser.getValueAsString(), Matchers.equalTo(currVal)); } } }); } /** * This test compares the retrieval of an optimised text against the baseline. */ public void testOptimisedParser() throws Exception { for (int i = 0; i < 200; i++) { String json = randomJsonInput(randomIntBetween(1, 6)); try ( var baselineParser = XContentHelper.createParser( XContentParserConfiguration.EMPTY, new BytesArray(json), XContentType.JSON ); var optimisedParser = TestXContentParser.create(json) ) { var expected = baselineParser.mapOrdered(); var actual = optimisedParser.mapOrdered(); assertThat(expected, Matchers.equalTo(actual)); } } } private String randomJsonInput(int depth) { StringBuilder sb = new StringBuilder(); sb.append('{'); int numberOfFields = randomIntBetween(1, 10); for (int i = 0; i < numberOfFields; i++) { sb.append("\"k-").append(randomAlphanumericOfLength(10)).append("\":"); if (depth == 0 || randomBoolean()) { if (randomIntBetween(0, 9) == 0) { sb.append( IntStream.range(0, randomIntBetween(1, 10)) .mapToObj(ignored -> randomUTF8Value()) .collect(Collectors.joining(",", "[", "]")) ); } else { sb.append(randomUTF8Value()); } } else { sb.append(randomJsonInput(depth - 1)); } if (i < numberOfFields - 1) { sb.append(','); } } sb.append("}"); return sb.toString(); } private String randomUTF8Value() { return "\"" + buildRandomInput(randomIntBetween(10, 50)).input + "\""; } /** * This XContentParser introduces a random mix of getText() and getOptimisedText() * to simulate different access patterns for optimised fields. */ private static
ESUTF8StreamJsonParserTests
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/subjects/Subject.java
{ "start": 1227, "end": 3023 }
class ____<T> extends Observable<T> implements Observer<T> { /** * Returns true if the subject has any Observers. * <p>The method is thread-safe. * @return true if the subject has any Observers */ @CheckReturnValue public abstract boolean hasObservers(); /** * Returns true if the subject has reached a terminal state through an error event. * <p>The method is thread-safe. * @return true if the subject has reached a terminal state through an error event * @see #getThrowable() * @see #hasComplete() */ @CheckReturnValue public abstract boolean hasThrowable(); /** * Returns true if the subject has reached a terminal state through a complete event. * <p>The method is thread-safe. * @return true if the subject has reached a terminal state through a complete event * @see #hasThrowable() */ @CheckReturnValue public abstract boolean hasComplete(); /** * Returns the error that caused the Subject to terminate or null if the Subject * hasn't terminated yet. * <p>The method is thread-safe. * @return the error that caused the Subject to terminate or null if the Subject * hasn't terminated yet */ @Nullable @CheckReturnValue public abstract Throwable getThrowable(); /** * Wraps this Subject and serializes the calls to the onSubscribe, onNext, onError and * onComplete methods, making them thread-safe. * <p>The method is thread-safe. * @return the wrapped and serialized subject */ @NonNull @CheckReturnValue public final Subject<T> toSerialized() { if (this instanceof SerializedSubject) { return this; } return new SerializedSubject<>(this); } }
Subject
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/EqualTest_extract_oracle.java
{ "start": 254, "end": 1329 }
class ____ extends TestCase { public void test_exits() throws Exception { String sql = "EXTRACT(MONTH FROM x)"; String sql_c = "EXTRACT(MONTH FROM 7)"; SQLMethodInvokeExpr exprA, exprB, exprC; { OracleExprParser parser = new OracleExprParser(sql); exprA = (SQLMethodInvokeExpr) parser.expr(); } { OracleExprParser parser = new OracleExprParser(sql); exprB = (SQLMethodInvokeExpr) parser.expr(); } { OracleExprParser parser = new OracleExprParser(sql_c); exprC = (SQLMethodInvokeExpr) parser.expr(); } assertEquals(exprA, exprB); assertNotEquals(exprA, exprC); assertTrue(exprA.equals(exprA)); assertFalse(exprA.equals(new Object())); assertEquals(exprA.hashCode(), exprB.hashCode()); assertEquals(new SQLMethodInvokeExpr(), new SQLMethodInvokeExpr()); assertEquals(new SQLMethodInvokeExpr().hashCode(), new SQLMethodInvokeExpr().hashCode()); } }
EqualTest_extract_oracle
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/output/committer/manifest/impl/ManifestCommitterSupport.java
{ "start": 4681, "end": 12616 }
class ____ { private ManifestCommitterSupport() { } /** * Create an IOStatistics Store with the standard statistics * set up. * @return a store builder preconfigured with the standard stats. */ public static IOStatisticsStoreBuilder createIOStatisticsStore() { final IOStatisticsStoreBuilder store = iostatisticsStore(); store.withSampleTracking(COUNTER_STATISTICS); store.withDurationTracking(DURATION_STATISTICS); return store; } /** * If the object is an IOStatisticsSource, get and add * its IOStatistics. * @param o source object. */ public static void maybeAddIOStatistics(IOStatisticsAggregator ios, Object o) { if (o instanceof IOStatisticsSource) { ios.aggregate(((IOStatisticsSource) o).getIOStatistics()); } } /** * Build a Job UUID from the job conf (if it is * {@link ManifestCommitterConstants#SPARK_WRITE_UUID} * or the MR job ID. * @param conf job/task configuration * @param jobId job ID from YARN or spark. * @return (a job ID, source) */ public static Pair<String, String> buildJobUUID(Configuration conf, JobID jobId) { String jobUUID = conf.getTrimmed(SPARK_WRITE_UUID, ""); if (jobUUID.isEmpty()) { jobUUID = jobId.toString(); return Pair.of(jobUUID, JOB_ID_SOURCE_MAPREDUCE); } else { return Pair.of(jobUUID, SPARK_WRITE_UUID); } } /** * Get the location of pending job attempts. * @param out the base output directory. * @return the location of pending job attempts. */ public static Path getPendingJobAttemptsPath(Path out) { return new Path(out, PENDING_DIR_NAME); } /** * Get the Application Attempt Id for this job. * @param context the context to look in * @return the Application Attempt Id for a given job. */ public static int getAppAttemptId(JobContext context) { return getAppAttemptId(context.getConfiguration()); } /** * Get the Application Attempt Id for this job * by looking for {@link MRJobConfig#APPLICATION_ATTEMPT_ID} * in the configuration, falling back to 0 if unset. * For spark it will always be 0, for MR it will be set in the AM * to the {@code ApplicationAttemptId} the AM is launched with. * @param conf job configuration. * @return the Application Attempt Id for the job. */ public static int getAppAttemptId(Configuration conf) { return conf.getInt(MRJobConfig.APPLICATION_ATTEMPT_ID, INITIAL_APP_ATTEMPT_ID); } /** * Get the path in the job attempt dir for a manifest for a task. * @param manifestDir manifest directory * @param taskId taskID. * @return the final path to rename the manifest file to */ public static Path manifestPathForTask(Path manifestDir, String taskId) { return new Path(manifestDir, taskId + MANIFEST_SUFFIX); } /** * Get the path in the manifest subdir for the temp path to save a * task attempt's manifest before renaming it to the * path defined by {@link #manifestPathForTask(Path, String)}. * @param manifestDir manifest directory * @param taskAttemptId task attempt ID. * @return the path to save/load the manifest. */ public static Path manifestTempPathForTaskAttempt(Path manifestDir, String taskAttemptId) { return new Path(manifestDir, taskAttemptId + MANIFEST_SUFFIX + TMP_SUFFIX); } /** * Create a task attempt dir; stage config must be for a task attempt. * @param stageConfig state config. * @return a manifest with job and task attempt info set up. */ public static TaskManifest createTaskManifest(StageConfig stageConfig) { final TaskManifest manifest = new TaskManifest(); manifest.setTaskAttemptID(stageConfig.getTaskAttemptId()); manifest.setTaskID(stageConfig.getTaskId()); manifest.setJobId(stageConfig.getJobId()); manifest.setJobAttemptNumber(stageConfig.getJobAttemptNumber()); manifest.setTaskAttemptDir( stageConfig.getTaskAttemptDir().toUri().toString()); return manifest; } /** * Create success/outcome data. * @param stageConfig configuration. * @param stage * @return a _SUCCESS object with some diagnostics. */ public static ManifestSuccessData createManifestOutcome( StageConfig stageConfig, String stage) { final ManifestSuccessData outcome = new ManifestSuccessData(); outcome.setJobId(stageConfig.getJobId()); outcome.setJobIdSource(stageConfig.getJobIdSource()); outcome.setCommitter(MANIFEST_COMMITTER_CLASSNAME); // real timestamp outcome.setTimestamp(System.currentTimeMillis()); final ZonedDateTime now = ZonedDateTime.now(); outcome.setDate(now.toString()); outcome.setHostname(NetUtils.getLocalHostname()); // add some extra diagnostics which can still be parsed by older // builds of test applications. // Audit Span information can go in here too, in future. try { outcome.putDiagnostic(PRINCIPAL, UserGroupInformation.getCurrentUser().getShortUserName()); } catch (IOException ignored) { // don't know who we are? exclude from the diagnostics. } outcome.putDiagnostic(STAGE, stage); return outcome; } /** * Add heap information to IOStatisticSetters gauges, with a stage in front of every key. * @param ioStatisticsSetters map to update * @param stage stage */ public static void addHeapInformation(IOStatisticsSetters ioStatisticsSetters, String stage) { final long totalMemory = Runtime.getRuntime().totalMemory(); final long freeMemory = Runtime.getRuntime().freeMemory(); final String prefix = "stage."; ioStatisticsSetters.setGauge(prefix + stage + "." + TOTAL_MEMORY, totalMemory); ioStatisticsSetters.setGauge(prefix + stage + "." + FREE_MEMORY, freeMemory); ioStatisticsSetters.setGauge(prefix + stage + "." + HEAP_MEMORY, totalMemory - freeMemory); } /** * Create the filename for a report from the jobID. * @param jobId jobId * @return filename for a report. */ public static String createJobSummaryFilename(String jobId) { return String.format(SUMMARY_FILENAME_FORMAT, jobId); } /** * Get an etag from a FileStatus which MUST BE * an implementation of EtagSource and * whose etag MUST NOT BE null/empty. * @param status the status; may be null. * @return the etag or null if not provided */ public static String getEtag(FileStatus status) { if (status instanceof EtagSource) { return ((EtagSource) status).getEtag(); } else { return null; } } /** * Create the manifest store operations for the given FS. * This supports binding to custom filesystem handlers. * @param conf configuration. * @param filesystem fs. * @param path path under FS. * @return a bonded store operations. * @throws IOException on binding/init problems. */ public static ManifestStoreOperations createManifestStoreOperations( final Configuration conf, final FileSystem filesystem, final Path path) throws IOException { try { final Class<? extends ManifestStoreOperations> storeClass = conf.getClass( OPT_STORE_OPERATIONS_CLASS, ManifestStoreOperationsThroughFileSystem.class, ManifestStoreOperations.class); final ManifestStoreOperations operations = storeClass. getDeclaredConstructor().newInstance(); operations.bindToFileSystem(filesystem, path); return operations; } catch (Exception e) { throw new PathIOException(path.toString(), "Failed to create Store Operations from configuration option " + OPT_STORE_OPERATIONS_CLASS + ":" + e, e); } } /** * Logic to create directory names from job and attempt. * This is self-contained it so it can be used in tests * as well as in the committer. */ public static
ManifestCommitterSupport
java
apache__logging-log4j2
log4j-perf-test/src/main/java/org/apache/logging/log4j/ThrowVsReturnBenchmark.java
{ "start": 1267, "end": 2701 }
class ____ { private static final int SALT = ThreadLocalRandom.current().nextInt(); private static final RuntimeException EXCEPTION = new RuntimeException(); private static final int MAX_DEPTH = 5; @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public int withReturn(final Blackhole blackhole) { return withReturn(blackhole, 0); } private static int withReturn(final Blackhole blackhole, final int depth) { doWork(blackhole); return depth < MAX_DEPTH ? withReturn(blackhole, depth + 1) : blackhole.i1; } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public int withThrow(final Blackhole blackhole) { try { withThrow(blackhole, 0); } catch (final Exception error) { if (error == EXCEPTION) { return blackhole.i1; } } throw new IllegalStateException(); } private static void withThrow(final Blackhole blackhole, final int depth) { doWork(blackhole); if (depth < MAX_DEPTH) { withThrow(blackhole, depth + 1); } else { throw EXCEPTION; } } private static void doWork(final Blackhole blackhole) { for (int i = 0; i < 1_000; i++) { blackhole.consume((i << 10) + SALT); } } }
ThrowVsReturnBenchmark
java
netty__netty
common/src/main/java/io/netty/util/NetUtilSubstitutions.java
{ "start": 3474, "end": 3937 }
class ____ { static Collection<NetworkInterface> get() { // using https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom return NetUtilNetworkInterfacesLazyHolder.NETWORK_INTERFACES; } static void set(Collection<NetworkInterface> ignored) { // a no-op setter to avoid exceptions when NetUtil is initialized at run-time } } private static final
NetUtilNetworkInterfacesAccessor
java
apache__rocketmq
namesrv/src/test/java/org/apache/rocketmq/namesrv/routeinfo/RouteInfoManagerNewTest.java
{ "start": 2300, "end": 44618 }
class ____ { private RouteInfoManager routeInfoManager; private static final String DEFAULT_CLUSTER = "Default_Cluster"; private static final String DEFAULT_BROKER = "Default_Broker"; private static final String DEFAULT_ADDR_PREFIX = "127.0.0.1:"; private static final String DEFAULT_ADDR = DEFAULT_ADDR_PREFIX + "10911"; // Synced from RouteInfoManager private static final int BROKER_CHANNEL_EXPIRED_TIME = 1000 * 60 * 2; @Spy private static NamesrvConfig config = spy(new NamesrvConfig()); @Before public void setup() { config.setSupportActingMaster(true); routeInfoManager = new RouteInfoManager(config, null); routeInfoManager.start(); } @After public void tearDown() throws Exception { routeInfoManager.shutdown(); } @Test public void getAllClusterInfo() { registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic"); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker() .cluster("AnotherCluster") .name("AnotherBroker") .addr(DEFAULT_ADDR_PREFIX + 30911), "TestTopic1"); final byte[] content = routeInfoManager.getAllClusterInfo().encode(); final ClusterInfo clusterInfo = ClusterInfo.decode(content, ClusterInfo.class); assertThat(clusterInfo.retrieveAllClusterNames()).contains(DEFAULT_CLUSTER, "AnotherCluster"); assertThat(clusterInfo.getBrokerAddrTable().keySet()).contains(DEFAULT_BROKER, "AnotherBroker"); final List<String> addrList = Arrays.asList(clusterInfo.getBrokerAddrTable().get(DEFAULT_BROKER).getBrokerAddrs().get(0L), clusterInfo.getBrokerAddrTable().get("AnotherBroker").getBrokerAddrs().get(0L)); assertThat(addrList).contains(DEFAULT_ADDR, DEFAULT_ADDR_PREFIX + 30911); } @Test public void deleteTopic() { String testTopic = "TestTopic"; registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), testTopic); routeInfoManager.deleteTopic(testTopic); assertThat(routeInfoManager.pickupTopicRouteData(testTopic)).isNull(); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), testTopic); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker().cluster("AnotherCluster").name("AnotherBroker"), testTopic); assertThat(routeInfoManager.pickupTopicRouteData(testTopic).getBrokerDatas().size()).isEqualTo(2); routeInfoManager.deleteTopic(testTopic, DEFAULT_CLUSTER); assertThat(routeInfoManager.pickupTopicRouteData(testTopic).getBrokerDatas().size()).isEqualTo(1); assertThat(routeInfoManager.pickupTopicRouteData(testTopic).getBrokerDatas().get(0).getBrokerName()).isEqualTo("AnotherBroker"); } @Test public void getAllTopicList() { byte[] content = routeInfoManager.getAllTopicList().encode(); TopicList topicList = TopicList.decode(content, TopicList.class); assertThat(topicList.getTopicList()).isEmpty(); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic", "TestTopic1", "TestTopic2"); content = routeInfoManager.getAllTopicList().encode(); topicList = TopicList.decode(content, TopicList.class); assertThat(topicList.getTopicList()).contains("TestTopic", "TestTopic1", "TestTopic2"); } @Test public void registerBroker() { // Register master broker final RegisterBrokerResult masterResult = registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic"); assertThat(masterResult).isNotNull(); assertThat(masterResult.getHaServerAddr()).isNull(); assertThat(masterResult.getMasterAddr()).isNull(); // Register slave broker final BrokerBasicInfo slaveBroker = BrokerBasicInfo.defaultBroker() .id(1).addr(DEFAULT_ADDR_PREFIX + 30911).haAddr(DEFAULT_ADDR_PREFIX + 40911); final RegisterBrokerResult slaveResult = registerBrokerWithNormalTopic(slaveBroker, "TestTopic"); assertThat(slaveResult).isNotNull(); assertThat(slaveResult.getHaServerAddr()).isEqualTo(DEFAULT_ADDR_PREFIX + 20911); assertThat(slaveResult.getMasterAddr()).isEqualTo(DEFAULT_ADDR); } @Test public void unregisterBroker() { registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic", "TestTopic1", "TestTopic2"); routeInfoManager.unregisterBroker(DEFAULT_CLUSTER, DEFAULT_ADDR, DEFAULT_BROKER, 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic2")).isNull(); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic", "TestTopic1", "TestTopic2"); routeInfoManager.submitUnRegisterBrokerRequest(BrokerBasicInfo.defaultBroker().unRegisterRequest()); await().atMost(Duration.ofSeconds(5)).until(() -> routeInfoManager.blockedUnRegisterRequests() == 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic2")).isNull(); } @Test public void registerSlaveBroker() { registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()).containsKeys(0L); registerBrokerWithNormalTopic(BrokerBasicInfo.slaveBroker(), "TestTopic"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()).containsKeys(0L, 1L); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()) .containsValues(BrokerBasicInfo.defaultBroker().brokerAddr, BrokerBasicInfo.slaveBroker().brokerAddr); } @Test public void createNewTopic() { registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic"); registerBrokerWithNormalTopic(BrokerBasicInfo.slaveBroker(), "TestTopic"); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic", "TestTopic1"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1").getBrokerDatas().get(0).getBrokerAddrs()).containsKeys(0L, 1L); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1").getBrokerDatas().get(0).getBrokerAddrs()) .containsValues(BrokerBasicInfo.defaultBroker().brokerAddr, BrokerBasicInfo.slaveBroker().brokerAddr); } @Test public void switchBrokerRole() { final BrokerBasicInfo masterBroker = BrokerBasicInfo.defaultBroker().enableActingMaster(false); final BrokerBasicInfo slaveBroker = BrokerBasicInfo.slaveBroker().enableActingMaster(false); registerBrokerWithNormalTopic(masterBroker, "TestTopic"); registerBrokerWithNormalTopic(slaveBroker, "TestTopic"); // Master Down routeInfoManager.unregisterBroker(masterBroker.clusterName, masterBroker.brokerAddr, masterBroker.brokerName, 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()).containsOnlyKeys(1L); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()) .containsValues(slaveBroker.brokerAddr); // Switch slave to master slaveBroker.id(0).dataVersion.nextVersion(); registerBrokerWithNormalTopic(slaveBroker, "TestTopic"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()).containsOnlyKeys(0L); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()) .containsValues(slaveBroker.brokerAddr); // Old master switch to slave masterBroker.id(1).dataVersion.nextVersion(); registerBrokerWithNormalTopic(masterBroker, "TestTopic"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()).containsKeys(0L, 1L); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()) .containsValues(BrokerBasicInfo.defaultBroker().brokerAddr, BrokerBasicInfo.slaveBroker().brokerAddr); } @Test public void unRegisterSlaveBroker() { registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic"); final BrokerBasicInfo slaveBroker = BrokerBasicInfo.slaveBroker(); registerBrokerWithNormalTopic(slaveBroker, "TestTopic"); routeInfoManager.unregisterBroker(slaveBroker.clusterName, slaveBroker.brokerAddr, slaveBroker.brokerName, 1); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().size()).isEqualTo(1); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0) .getBrokerAddrs().get(0L)).isEqualTo(BrokerBasicInfo.defaultBroker().brokerAddr); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic"); registerBrokerWithNormalTopic(slaveBroker, "TestTopic"); routeInfoManager.submitUnRegisterBrokerRequest(slaveBroker.unRegisterRequest()); await().atMost(Duration.ofSeconds(5)).until(() -> routeInfoManager.blockedUnRegisterRequests() == 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().size()).isEqualTo(1); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0) .getBrokerAddrs().get(0L)).isEqualTo(BrokerBasicInfo.defaultBroker().brokerAddr); } @Test public void unRegisterMasterBroker() { final BrokerBasicInfo masterBroker = BrokerBasicInfo.defaultBroker(); masterBroker.enableActingMaster = true; registerBrokerWithNormalTopic(masterBroker, "TestTopic"); final BrokerBasicInfo slaveBroker = BrokerBasicInfo.slaveBroker(); registerBrokerWithNormalTopic(slaveBroker, "TestTopic"); routeInfoManager.unregisterBroker(masterBroker.clusterName, masterBroker.brokerAddr, masterBroker.brokerName, 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().size()).isEqualTo(1); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0) .getBrokerAddrs().get(0L)).isEqualTo(slaveBroker.brokerAddr); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getQueueDatas().size()).isEqualTo(1); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getQueueDatas().get(0).getPerm()).isEqualTo(PermName.PERM_READ); } @Test public void unRegisterMasterBrokerOldVersion() { final BrokerBasicInfo masterBroker = BrokerBasicInfo.defaultBroker(); masterBroker.enableActingMaster = false; registerBrokerWithNormalTopic(masterBroker, "TestTopic"); final BrokerBasicInfo slaveBroker = BrokerBasicInfo.slaveBroker(); slaveBroker.enableActingMaster = false; registerBrokerWithNormalTopic(slaveBroker, "TestTopic"); routeInfoManager.unregisterBroker(masterBroker.clusterName, masterBroker.brokerAddr, masterBroker.brokerName, 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().size()).isEqualTo(1); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0) .getBrokerAddrs().get(0L)).isNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getQueueDatas().size()).isEqualTo(1); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getQueueDatas().get(0).getPerm()).isEqualTo(PermName.PERM_READ | PermName.PERM_WRITE); } @Test public void submitMultiUnRegisterRequests() { final BrokerBasicInfo master1 = BrokerBasicInfo.defaultBroker(); final BrokerBasicInfo master2 = BrokerBasicInfo.defaultBroker().name(DEFAULT_BROKER + 1).addr(DEFAULT_ADDR + 9); registerBrokerWithNormalTopic(master1, "TestTopic1"); registerBrokerWithNormalTopic(master2, "TestTopic2"); routeInfoManager.submitUnRegisterBrokerRequest(master1.unRegisterRequest()); routeInfoManager.submitUnRegisterBrokerRequest(master2.unRegisterRequest()); await().atMost(Duration.ofSeconds(5)).until(() -> routeInfoManager.blockedUnRegisterRequests() == 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic2")).isNull(); } @Test public void isBrokerTopicConfigChanged() { registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic"); final DataVersion dataVersion = routeInfoManager.queryBrokerTopicConfig(DEFAULT_CLUSTER, DEFAULT_ADDR); assertThat(routeInfoManager.isBrokerTopicConfigChanged(DEFAULT_CLUSTER, DEFAULT_ADDR, dataVersion)).isFalse(); DataVersion newVersion = new DataVersion(); newVersion.setTimestamp(System.currentTimeMillis() + 1000); newVersion.setCounter(new AtomicLong(dataVersion.getCounter().get())); assertThat(routeInfoManager.isBrokerTopicConfigChanged(DEFAULT_CLUSTER, DEFAULT_ADDR, newVersion)).isTrue(); newVersion = new DataVersion(); newVersion.setTimestamp(dataVersion.getTimestamp()); newVersion.setCounter(new AtomicLong(dataVersion.getCounter().get() + 1)); assertThat(routeInfoManager.isBrokerTopicConfigChanged(DEFAULT_CLUSTER, DEFAULT_ADDR, newVersion)).isTrue(); } @Test public void isTopicConfigChanged() { final BrokerBasicInfo brokerInfo = BrokerBasicInfo.defaultBroker(); assertThat(routeInfoManager.isTopicConfigChanged(DEFAULT_CLUSTER, DEFAULT_ADDR, brokerInfo.dataVersion, DEFAULT_BROKER, "TestTopic")).isTrue(); registerBrokerWithNormalTopic(brokerInfo, "TestTopic"); assertThat(routeInfoManager.isTopicConfigChanged(DEFAULT_CLUSTER, DEFAULT_ADDR, brokerInfo.dataVersion, DEFAULT_BROKER, "TestTopic")).isFalse(); assertThat(routeInfoManager.isTopicConfigChanged(DEFAULT_CLUSTER, DEFAULT_ADDR, brokerInfo.dataVersion, DEFAULT_BROKER, "TestTopic1")).isTrue(); } @Test public void queryBrokerTopicConfig() { final BrokerBasicInfo basicInfo = BrokerBasicInfo.defaultBroker(); registerBrokerWithNormalTopic(basicInfo, "TestTopic"); final DataVersion dataVersion = routeInfoManager.queryBrokerTopicConfig(DEFAULT_CLUSTER, DEFAULT_ADDR); assertThat(basicInfo.dataVersion.equals(dataVersion)).isTrue(); } @Test public void wipeWritePermOfBrokerByLock() { registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getQueueDatas().get(0).getPerm()).isEqualTo(6); routeInfoManager.wipeWritePermOfBrokerByLock(DEFAULT_BROKER); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getQueueDatas().get(0).getPerm()).isEqualTo(4); } @Test public void pickupTopicRouteData() { String testTopic = "TestTopic"; registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), testTopic); TopicRouteData data = routeInfoManager.pickupTopicRouteData(testTopic); assertThat(data.getBrokerDatas().size()).isEqualTo(1); assertThat(data.getBrokerDatas().get(0).getBrokerName()).isEqualTo(DEFAULT_BROKER); assertThat(data.getBrokerDatas().get(0).getBrokerAddrs().get(0L)).isEqualTo(DEFAULT_ADDR); assertThat(data.getQueueDatas().size()).isEqualTo(1); assertThat(data.getQueueDatas().get(0).getBrokerName()).isEqualTo(DEFAULT_BROKER); assertThat(data.getQueueDatas().get(0).getReadQueueNums()).isEqualTo(8); assertThat(data.getQueueDatas().get(0).getWriteQueueNums()).isEqualTo(8); assertThat(data.getQueueDatas().get(0).getPerm()).isEqualTo(6); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker().name("AnotherBroker"), testTopic); data = routeInfoManager.pickupTopicRouteData(testTopic); assertThat(data.getBrokerDatas().size()).isEqualTo(2); assertThat(data.getQueueDatas().size()).isEqualTo(2); List<String> brokerList = Arrays.asList(data.getBrokerDatas().get(0).getBrokerName(), data.getBrokerDatas().get(1).getBrokerName()); assertThat(brokerList).contains(DEFAULT_BROKER, "AnotherBroker"); brokerList = Arrays.asList(data.getQueueDatas().get(0).getBrokerName(), data.getQueueDatas().get(1).getBrokerName()); assertThat(brokerList).contains(DEFAULT_BROKER, "AnotherBroker"); } @Test public void pickupTopicRouteDataWithSlave() { String testTopic = "TestTopic"; registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), testTopic); registerBrokerWithNormalTopic(BrokerBasicInfo.slaveBroker(), testTopic); TopicRouteData routeData = routeInfoManager.pickupTopicRouteData(testTopic); assertThat(routeData.getBrokerDatas().get(0).getBrokerAddrs()).hasSize(2); assertThat(PermName.isWriteable(routeData.getQueueDatas().get(0).getPerm())).isTrue(); routeInfoManager.unRegisterBroker(Sets.newHashSet(BrokerBasicInfo.defaultBroker().unRegisterRequest())); routeData = routeInfoManager.pickupTopicRouteData(testTopic); assertThat(routeData.getBrokerDatas().get(0).getBrokerAddrs()).hasSize(1); assertThat(PermName.isWriteable(routeData.getQueueDatas().get(0).getPerm())).isFalse(); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), testTopic); routeData = routeInfoManager.pickupTopicRouteData(testTopic); assertThat(routeData.getBrokerDatas().get(0).getBrokerAddrs()).hasSize(2); assertThat(PermName.isWriteable(routeData.getQueueDatas().get(0).getPerm())).isTrue(); } @Test public void scanNotActiveBroker() throws InterruptedException { registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic"); routeInfoManager.scanNotActiveBroker(); registerBrokerWithNormalTopicAndExpire(BrokerBasicInfo.defaultBroker(),"TestTopic"); Thread.sleep(30000); routeInfoManager.scanNotActiveBroker(); } @Test public void pickupPartitionOrderTopicRouteData() { String orderTopic = "PartitionOrderTopicTest"; // Case 1: Register global order topic with slave registerBrokerWithOrderTopic(BrokerBasicInfo.slaveBroker(), orderTopic); TopicRouteData orderRoute = routeInfoManager.pickupTopicRouteData(orderTopic); // Acting master check assertThat(orderRoute.getBrokerDatas().get(0).getBrokerAddrs()) .containsOnlyKeys(MixAll.MASTER_ID); assertThat(orderRoute.getBrokerDatas().get(0).getBrokerAddrs()) .containsValue(BrokerBasicInfo.slaveBroker().brokerAddr); assertThat(PermName.isWriteable(orderRoute.getQueueDatas().get(0).getPerm())).isFalse(); routeInfoManager.unRegisterBroker(Sets.newHashSet(BrokerBasicInfo.slaveBroker().unRegisterRequest())); // Case 2: Register global order topic with master and slave, then unregister master registerBrokerWithOrderTopic(BrokerBasicInfo.slaveBroker(), orderTopic); registerBrokerWithOrderTopic(BrokerBasicInfo.defaultBroker(), orderTopic); routeInfoManager.unRegisterBroker(Sets.newHashSet(BrokerBasicInfo.defaultBroker().unRegisterRequest())); orderRoute = routeInfoManager.pickupTopicRouteData(orderTopic); // Acting master check assertThat(orderRoute.getBrokerDatas().get(0).getBrokerAddrs()) .containsOnlyKeys(MixAll.MASTER_ID); assertThat(orderRoute.getBrokerDatas().get(0).getBrokerAddrs()) .containsValue(BrokerBasicInfo.slaveBroker().brokerAddr); assertThat(PermName.isWriteable(orderRoute.getQueueDatas().get(0).getPerm())).isFalse(); routeInfoManager.unRegisterBroker(Sets.newHashSet(BrokerBasicInfo.slaveBroker().unRegisterRequest())); // Case 3: Register two broker groups, only one group enable acting master registerBrokerWithOrderTopic(BrokerBasicInfo.slaveBroker(), orderTopic); registerBrokerWithOrderTopic(BrokerBasicInfo.defaultBroker(), orderTopic); final BrokerBasicInfo master1 = BrokerBasicInfo.defaultBroker().name(DEFAULT_BROKER + "_ANOTHER"); final BrokerBasicInfo slave1 = BrokerBasicInfo.slaveBroker().name(DEFAULT_BROKER + "_ANOTHER"); registerBrokerWithOrderTopic(master1, orderTopic); registerBrokerWithOrderTopic(slave1, orderTopic); orderRoute = routeInfoManager.pickupTopicRouteData(orderTopic); assertThat(orderRoute.getBrokerDatas()).hasSize(2); assertThat(orderRoute.getQueueDatas()).hasSize(2); routeInfoManager.unRegisterBroker(Sets.newHashSet(BrokerBasicInfo.defaultBroker().unRegisterRequest())); orderRoute = routeInfoManager.pickupTopicRouteData(orderTopic); assertThat(orderRoute.getBrokerDatas()).hasSize(2); assertThat(orderRoute.getQueueDatas()).hasSize(2); for (final BrokerData brokerData : orderRoute.getBrokerDatas()) { if (brokerData.getBrokerAddrs().size() == 1) { assertThat(brokerData.getBrokerAddrs()).containsOnlyKeys(MixAll.MASTER_ID); assertThat(brokerData.getBrokerAddrs()).containsValue(BrokerBasicInfo.slaveBroker().brokerAddr); } else if (brokerData.getBrokerAddrs().size() == 2) { assertThat(brokerData.getBrokerAddrs()).containsKeys(MixAll.MASTER_ID, (long) slave1.brokerId); assertThat(brokerData.getBrokerAddrs()).containsValues(master1.brokerAddr, slave1.brokerAddr); } else { throw new RuntimeException("Shouldn't reach here"); } } } @Test public void pickupGlobalOrderTopicRouteData() { String orderTopic = "GlobalOrderTopicTest"; // Case 1: Register global order topic with slave registerBrokerWithGlobalOrderTopic(BrokerBasicInfo.slaveBroker(), orderTopic); TopicRouteData orderRoute = routeInfoManager.pickupTopicRouteData(orderTopic); // Acting master check assertThat(orderRoute.getBrokerDatas().get(0).getBrokerAddrs()) .containsOnlyKeys(MixAll.MASTER_ID); assertThat(orderRoute.getBrokerDatas().get(0).getBrokerAddrs()) .containsValue(BrokerBasicInfo.slaveBroker().brokerAddr); assertThat(PermName.isWriteable(orderRoute.getQueueDatas().get(0).getPerm())).isFalse(); routeInfoManager.unRegisterBroker(Sets.newHashSet(BrokerBasicInfo.slaveBroker().unRegisterRequest())); // Case 2: Register global order topic with master and slave, then unregister master registerBrokerWithGlobalOrderTopic(BrokerBasicInfo.slaveBroker(), orderTopic); registerBrokerWithGlobalOrderTopic(BrokerBasicInfo.defaultBroker(), orderTopic); routeInfoManager.unRegisterBroker(Sets.newHashSet(BrokerBasicInfo.defaultBroker().unRegisterRequest())); // Acting master check assertThat(orderRoute.getBrokerDatas().get(0).getBrokerAddrs()) .containsOnlyKeys(MixAll.MASTER_ID); assertThat(orderRoute.getBrokerDatas().get(0).getBrokerAddrs()) .containsValue(BrokerBasicInfo.slaveBroker().brokerAddr); assertThat(PermName.isWriteable(orderRoute.getQueueDatas().get(0).getPerm())).isFalse(); } @Test public void registerOnlySlaveBroker() { final String testTopic = "TestTopic"; // Case 1: Only slave broker registerBrokerWithNormalTopic(BrokerBasicInfo.slaveBroker(), testTopic); assertThat(routeInfoManager.pickupTopicRouteData(testTopic)).isNotNull(); int topicPerm = routeInfoManager.pickupTopicRouteData(testTopic).getQueueDatas().get(0).getPerm(); assertThat(PermName.isWriteable(topicPerm)).isFalse(); routeInfoManager.unRegisterBroker(Sets.newHashSet(BrokerBasicInfo.slaveBroker().unRegisterRequest())); // Case 2: Register master, and slave, then unregister master, finally recover master registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), testTopic); registerBrokerWithNormalTopic(BrokerBasicInfo.slaveBroker(), testTopic); assertThat(routeInfoManager.pickupTopicRouteData(testTopic)).isNotNull(); topicPerm = routeInfoManager.pickupTopicRouteData(testTopic).getQueueDatas().get(0).getPerm(); assertThat(PermName.isWriteable(topicPerm)).isTrue(); routeInfoManager.unRegisterBroker(Sets.newHashSet(BrokerBasicInfo.defaultBroker().unRegisterRequest())); assertThat(routeInfoManager.pickupTopicRouteData(testTopic)).isNotNull(); topicPerm = routeInfoManager.pickupTopicRouteData(testTopic).getQueueDatas().get(0).getPerm(); assertThat(PermName.isWriteable(topicPerm)).isFalse(); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), testTopic); assertThat(routeInfoManager.pickupTopicRouteData(testTopic)).isNotNull(); topicPerm = routeInfoManager.pickupTopicRouteData(testTopic).getQueueDatas().get(0).getPerm(); assertThat(PermName.isWriteable(topicPerm)).isTrue(); } @Test public void onChannelDestroy() { Channel channel = mock(Channel.class); registerBroker(BrokerBasicInfo.defaultBroker(), channel, null, "TestTopic", "TestTopic1"); routeInfoManager.onChannelDestroy(channel); await().atMost(Duration.ofSeconds(5)).until(() -> routeInfoManager.blockedUnRegisterRequests() == 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNull(); final BrokerBasicInfo masterBroker = BrokerBasicInfo.defaultBroker().enableActingMaster(false); final BrokerBasicInfo slaveBroker = BrokerBasicInfo.slaveBroker().enableActingMaster(false); Channel masterChannel = mock(Channel.class); Channel slaveChannel = mock(Channel.class); registerBroker(masterBroker, masterChannel, null, "TestTopic"); registerBroker(slaveBroker, slaveChannel, null, "TestTopic"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()).containsKeys(0L, 1L); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()) .containsValues(masterBroker.brokerAddr, slaveBroker.brokerAddr); routeInfoManager.onChannelDestroy(masterChannel); await().atMost(Duration.ofSeconds(5)).until(() -> routeInfoManager.blockedUnRegisterRequests() == 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()).containsOnlyKeys(1L); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()) .containsValues(slaveBroker.brokerAddr); routeInfoManager.onChannelDestroy(slaveChannel); await().atMost(Duration.ofSeconds(5)).until(() -> routeInfoManager.blockedUnRegisterRequests() == 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNull(); } @Test public void onChannelDestroyByBrokerInfo() { registerBroker(BrokerBasicInfo.defaultBroker(), mock(Channel.class), null, "TestTopic", "TestTopic1"); BrokerAddrInfo brokerAddrInfo = new BrokerAddrInfo(DEFAULT_CLUSTER, DEFAULT_ADDR); routeInfoManager.onChannelDestroy(brokerAddrInfo); await().atMost(Duration.ofSeconds(5)).until(() -> routeInfoManager.blockedUnRegisterRequests() == 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNull(); } @Test public void switchBrokerRole_ChannelDestroy() { final BrokerBasicInfo masterBroker = BrokerBasicInfo.defaultBroker().enableActingMaster(false); final BrokerBasicInfo slaveBroker = BrokerBasicInfo.slaveBroker().enableActingMaster(false); Channel masterChannel = mock(Channel.class); Channel slaveChannel = mock(Channel.class); registerBroker(masterBroker, masterChannel, null, "TestTopic"); registerBroker(slaveBroker, slaveChannel, null, "TestTopic"); // Master Down routeInfoManager.onChannelDestroy(masterChannel); await().atMost(Duration.ofSeconds(5)).until(() -> routeInfoManager.blockedUnRegisterRequests() == 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()).containsOnlyKeys(1L); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()) .containsValues(slaveBroker.brokerAddr); // Switch slave to master slaveBroker.id(0).dataVersion.nextVersion(); registerBrokerWithNormalTopic(slaveBroker, "TestTopic"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()).containsOnlyKeys(0L); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()) .containsValues(slaveBroker.brokerAddr); // Old master switch to slave masterBroker.id(1).dataVersion.nextVersion(); registerBrokerWithNormalTopic(masterBroker, "TestTopic"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()).containsKeys(0L, 1L); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerAddrs()) .containsValues(BrokerBasicInfo.defaultBroker().brokerAddr, BrokerBasicInfo.slaveBroker().brokerAddr); } @Test public void keepTopicWithBrokerRegistration() { RegisterBrokerResult masterResult = registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic", "TestTopic1"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNotNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNotNull(); masterResult = registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic1"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNotNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNotNull(); } @Test public void deleteTopicWithBrokerRegistration() { config.setDeleteTopicWithBrokerRegistration(true); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic", "TestTopic1"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNotNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNotNull(); registerBrokerWithNormalTopic(BrokerBasicInfo.defaultBroker(), "TestTopic1"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNotNull(); } @Test public void deleteTopicWithBrokerRegistration2() { // Register two brokers and delete a specific one by one config.setDeleteTopicWithBrokerRegistration(true); final BrokerBasicInfo master1 = BrokerBasicInfo.defaultBroker(); final BrokerBasicInfo master2 = BrokerBasicInfo.defaultBroker().name(DEFAULT_BROKER + 1).addr(DEFAULT_ADDR + 9); registerBrokerWithNormalTopic(master1, "TestTopic", "TestTopic1"); registerBrokerWithNormalTopic(master2, "TestTopic", "TestTopic1"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas()).hasSize(2); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1").getBrokerDatas()).hasSize(2); registerBrokerWithNormalTopic(master1, "TestTopic1"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas()).hasSize(1); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic").getBrokerDatas().get(0).getBrokerName()) .isEqualTo(master2.brokerName); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1").getBrokerDatas()).hasSize(2); registerBrokerWithNormalTopic(master2, "TestTopic1"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1").getBrokerDatas()).hasSize(2); } @Test public void registerSingleTopicWithBrokerRegistration() { config.setDeleteTopicWithBrokerRegistration(true); final BrokerBasicInfo master1 = BrokerBasicInfo.defaultBroker(); registerSingleTopicWithBrokerName(master1.brokerName, "TestTopic"); // Single topic registration failed because there is no broker connection exists assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNull(); // Register broker with TestTopic first and then register single topic TestTopic1 registerBrokerWithNormalTopic(master1, "TestTopic"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNotNull(); registerSingleTopicWithBrokerName(master1.brokerName, "TestTopic1"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNotNull(); // Register the two topics to keep the route info registerBrokerWithNormalTopic(master1, "TestTopic", "TestTopic1"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNotNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNotNull(); // Cancel the TestTopic1 with broker registration registerBrokerWithNormalTopic(master1, "TestTopic"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNotNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNull(); // Add TestTopic1 and cancel all the topics with broker un-registration registerSingleTopicWithBrokerName(master1.brokerName, "TestTopic1"); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNotNull(); routeInfoManager.unregisterBroker(master1.clusterName, master1.brokerAddr, master1.brokerName, 0); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic")).isNull(); assertThat(routeInfoManager.pickupTopicRouteData("TestTopic1")).isNull(); } private RegisterBrokerResult registerBrokerWithNormalTopic(BrokerBasicInfo brokerInfo, String... topics) { ConcurrentHashMap<String, TopicConfig> topicConfigConcurrentHashMap = new ConcurrentHashMap<>(); TopicConfig baseTopic = new TopicConfig("baseTopic"); topicConfigConcurrentHashMap.put(baseTopic.getTopicName(), baseTopic); for (final String topic : topics) { TopicConfig topicConfig = new TopicConfig(); topicConfig.setWriteQueueNums(8); topicConfig.setTopicName(topic); topicConfig.setPerm(6); topicConfig.setReadQueueNums(8); topicConfig.setOrder(false); topicConfigConcurrentHashMap.put(topic, topicConfig); } return registerBroker(brokerInfo, mock(Channel.class), topicConfigConcurrentHashMap, topics); } private RegisterBrokerResult registerBrokerWithNormalTopicAndExpire(BrokerBasicInfo brokerInfo, String... topics) { ConcurrentHashMap<String, TopicConfig> topicConfigConcurrentHashMap = new ConcurrentHashMap<>(); TopicConfig baseTopic = new TopicConfig("baseTopic"); topicConfigConcurrentHashMap.put(baseTopic.getTopicName(), baseTopic); for (final String topic : topics) { TopicConfig topicConfig = new TopicConfig(); topicConfig.setWriteQueueNums(8); topicConfig.setTopicName(topic); topicConfig.setPerm(6); topicConfig.setReadQueueNums(8); topicConfig.setOrder(false); topicConfigConcurrentHashMap.put(topic, topicConfig); } return registerBrokerWithExpiredTime(brokerInfo, mock(Channel.class), topicConfigConcurrentHashMap, topics); } private RegisterBrokerResult registerBrokerWithOrderTopic(BrokerBasicInfo brokerBasicInfo, String... topics) { ConcurrentHashMap<String, TopicConfig> topicConfigConcurrentHashMap = new ConcurrentHashMap<>(); TopicConfig baseTopic = new TopicConfig("baseTopic"); baseTopic.setOrder(true); topicConfigConcurrentHashMap.put(baseTopic.getTopicName(), baseTopic); for (final String topic : topics) { TopicConfig topicConfig = new TopicConfig(); topicConfig.setWriteQueueNums(8); topicConfig.setTopicName(topic); topicConfig.setPerm(6); topicConfig.setReadQueueNums(8); topicConfig.setOrder(true); topicConfigConcurrentHashMap.put(topic, topicConfig); } return registerBroker(brokerBasicInfo, mock(Channel.class), topicConfigConcurrentHashMap, topics); } private RegisterBrokerResult registerBrokerWithGlobalOrderTopic(BrokerBasicInfo brokerBasicInfo, String... topics) { ConcurrentHashMap<String, TopicConfig> topicConfigConcurrentHashMap = new ConcurrentHashMap<>(); TopicConfig baseTopic = new TopicConfig("baseTopic", 1, 1); baseTopic.setOrder(true); topicConfigConcurrentHashMap.put(baseTopic.getTopicName(), baseTopic); for (final String topic : topics) { TopicConfig topicConfig = new TopicConfig(); topicConfig.setWriteQueueNums(1); topicConfig.setTopicName(topic); topicConfig.setPerm(6); topicConfig.setReadQueueNums(1); topicConfig.setOrder(true); topicConfigConcurrentHashMap.put(topic, topicConfig); } return registerBroker(brokerBasicInfo, mock(Channel.class), topicConfigConcurrentHashMap, topics); } private RegisterBrokerResult registerBroker(BrokerBasicInfo brokerInfo, Channel channel, ConcurrentMap<String, TopicConfig> topicConfigConcurrentHashMap, String... topics) { if (topicConfigConcurrentHashMap == null) { topicConfigConcurrentHashMap = new ConcurrentHashMap<>(); TopicConfig baseTopic = new TopicConfig("baseTopic"); topicConfigConcurrentHashMap.put(baseTopic.getTopicName(), baseTopic); for (final String topic : topics) { TopicConfig topicConfig = new TopicConfig(); topicConfig.setWriteQueueNums(8); topicConfig.setTopicName(topic); topicConfig.setPerm(6); topicConfig.setReadQueueNums(8); topicConfig.setOrder(false); topicConfigConcurrentHashMap.put(topic, topicConfig); } } TopicConfigSerializeWrapper topicConfigSerializeWrapper = new TopicConfigSerializeWrapper(); topicConfigSerializeWrapper.setDataVersion(brokerInfo.dataVersion); topicConfigSerializeWrapper.setTopicConfigTable(topicConfigConcurrentHashMap); return routeInfoManager.registerBroker( brokerInfo.clusterName, brokerInfo.brokerAddr, brokerInfo.brokerName, brokerInfo.brokerId, brokerInfo.haAddr, "", null, brokerInfo.enableActingMaster, topicConfigSerializeWrapper, new ArrayList<>(), channel); } private RegisterBrokerResult registerBrokerWithExpiredTime(BrokerBasicInfo brokerInfo, Channel channel, ConcurrentMap<String, TopicConfig> topicConfigConcurrentHashMap, String... topics) { if (topicConfigConcurrentHashMap == null) { topicConfigConcurrentHashMap = new ConcurrentHashMap<>(); TopicConfig baseTopic = new TopicConfig("baseTopic"); topicConfigConcurrentHashMap.put(baseTopic.getTopicName(), baseTopic); for (final String topic : topics) { TopicConfig topicConfig = new TopicConfig(); topicConfig.setWriteQueueNums(8); topicConfig.setTopicName(topic); topicConfig.setPerm(6); topicConfig.setReadQueueNums(8); topicConfig.setOrder(false); topicConfigConcurrentHashMap.put(topic, topicConfig); } } TopicConfigSerializeWrapper topicConfigSerializeWrapper = new TopicConfigSerializeWrapper(); topicConfigSerializeWrapper.setDataVersion(brokerInfo.dataVersion); topicConfigSerializeWrapper.setTopicConfigTable(topicConfigConcurrentHashMap); return routeInfoManager.registerBroker( brokerInfo.clusterName, brokerInfo.brokerAddr, brokerInfo.brokerName, brokerInfo.brokerId, brokerInfo.haAddr, "", 30000L, brokerInfo.enableActingMaster, topicConfigSerializeWrapper, new ArrayList<>(), channel); } private void registerSingleTopicWithBrokerName(String brokerName, String... topics) { for (final String topic : topics) { QueueData queueData = new QueueData(); queueData.setBrokerName(brokerName); queueData.setReadQueueNums(8); queueData.setWriteQueueNums(8); queueData.setPerm(6); routeInfoManager.registerTopic(topic, Collections.singletonList(queueData)); } } static
RouteInfoManagerNewTest
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/encoded/ClientWithQueryParamAndEncodedTest.java
{ "start": 3920, "end": 4071 }
interface ____ { @Encoded @GET String call(@QueryParam("subQuery") String subQuery); } public
SubClientWithEncodedInMethod
java
apache__camel
core/camel-management-api/src/main/java/org/apache/camel/api/management/NotificationSenderAware.java
{ "start": 882, "end": 944 }
class ____ get a {@link NotificationSender} injected */ public
to
java
netty__netty
codec-base/src/test/java/io/netty/handler/codec/frame/LengthFieldBasedFrameDecoderTest.java
{ "start": 1262, "end": 2936 }
class ____ { @Test public void testFailSlowTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new LengthFieldBasedFrameDecoder(5, 0, 4, 0, 4, false)); for (int i = 0; i < 2; i ++) { assertFalse(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0, 0, 2 }))); try { assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0 }))); fail(DecoderException.class.getSimpleName() + " must be raised."); } catch (TooLongFrameException e) { // Expected } ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0, 0, 1, 'A' })); ByteBuf buf = ch.readInbound(); assertEquals("A", buf.toString(CharsetUtil.ISO_8859_1)); buf.release(); } } @Test public void testFailFastTooLongFrameRecovery() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new LengthFieldBasedFrameDecoder(5, 0, 4, 0, 4)); for (int i = 0; i < 2; i ++) { try { assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0, 0, 2 }))); fail(DecoderException.class.getSimpleName() + " must be raised."); } catch (TooLongFrameException e) { // Expected } ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0, 0, 0, 0, 1, 'A' })); ByteBuf buf = ch.readInbound(); assertEquals("A", buf.toString(CharsetUtil.ISO_8859_1)); buf.release(); } } }
LengthFieldBasedFrameDecoderTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/mutationquery/MutationQueriesWhereTest.java
{ "start": 5317, "end": 5817 }
class ____ { @Id private Long id; @Column private boolean deleted; private String name; @ManyToMany @JoinTable( name = "users_roles", joinColumns = @JoinColumn( name = "user_id" ), inverseJoinColumns = @JoinColumn( name = "role_id" ) ) private List<RoleEntity> roles; } @Entity( name = "DiscriminatorBase" ) @Inheritance( strategy = InheritanceType.SINGLE_TABLE ) @DiscriminatorColumn( name = "disc_col" ) @SQLRestriction( "deleted = false" ) public static
UserEntity
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/deletedetached/DeleteDetachedJpaComplianceTest.java
{ "start": 2590, "end": 2814 }
class ____ { long regionId; long restaurantId; public RestaurantPK() { } public RestaurantPK(long regionId, long restaurantId) { this.regionId = regionId; this.restaurantId = restaurantId; } } }
RestaurantPK
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/job/metrics/DoubleAccumulator.java
{ "start": 5820, "end": 6402 }
class ____ implements DoubleAccumulator { public static final String NAME = "sum"; private double value; private DoubleSum(double init) { value = init; } @Override public void add(double value) { this.value += value; } @Override public double getValue() { return value; } @Override public String getName() { return NAME; } } /** {@link DoubleAccumulator} that returns the average over all values. */ final
DoubleSum
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/WallVisitorUtilsLargeOrTest.java
{ "start": 176, "end": 556 }
class ____ extends TestCase { public void test_largeOr() throws Exception { StringBuilder buf = new StringBuilder(); buf.append("ID = 1"); for (int i = 2; i <= 1000 * 10; ++i) { buf.append(" OR ID = " + i); } assertEquals(null, WallVisitorUtils.getValue(SQLUtils.toSQLExpr(buf.toString()))); } }
WallVisitorUtilsLargeOrTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/spi/UniqueConstraintCollector.java
{ "start": 340, "end": 492 }
interface ____ extends Annotation { UniqueConstraint[] uniqueConstraints(); void uniqueConstraints(UniqueConstraint[] value); }
UniqueConstraintCollector
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/DoublesBaseTest.java
{ "start": 1195, "end": 2060 }
class ____ { protected static final WritableAssertionInfo INFO = someInfo(); protected Failures failures; protected Doubles doubles; protected ComparatorBasedComparisonStrategy absValueComparisonStrategy; protected Doubles doublesWithAbsValueComparisonStrategy; @BeforeEach public void setUp() { failures = spy(Failures.instance()); doubles = new Doubles(); doubles.setFailures(failures); absValueComparisonStrategy = new ComparatorBasedComparisonStrategy(new AbsValueComparator<Double>()); doublesWithAbsValueComparisonStrategy = new Doubles(absValueComparisonStrategy); doublesWithAbsValueComparisonStrategy.failures = failures; } protected Double NaN() { return doubles.NaN(); } protected Double absDiff(Double actual, Double other) { return Doubles.instance().absDiff(actual, other); } }
DoublesBaseTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/VersionId.java
{ "start": 582, "end": 1401 }
interface ____<T extends VersionId<T>> extends Comparable<T> { /** * The version id this object represents */ int id(); default boolean after(T version) { return version.id() < id(); } default boolean onOrAfter(T version) { return version.id() <= id(); } default boolean before(T version) { return version.id() > id(); } default boolean onOrBefore(T version) { return version.id() >= id(); } default boolean between(T lowerInclusive, T upperExclusive) { if (upperExclusive.onOrBefore(lowerInclusive)) throw new IllegalArgumentException(); return onOrAfter(lowerInclusive) && before(upperExclusive); } @Override default int compareTo(T o) { return Integer.compare(id(), o.id()); } }
VersionId
java
apache__hadoop
hadoop-cloud-storage-project/hadoop-tos/src/test/java/org/apache/hadoop/fs/tosfs/object/tos/TestTOSRetryPolicy.java
{ "start": 2559, "end": 8394 }
class ____ { private final String retryKey = "retryKey.txt"; private TOSV2 tosClient; private DelegationClient client; @BeforeAll public static void before() { assumeTrue(TestEnv.checkTestEnabled()); } @BeforeEach public void setUp() { client = createRetryableDelegationClient(); tosClient = mock(TOSV2.class); client.setClient(tosClient); } @AfterEach public void tearDown() throws IOException { tosClient.close(); client.close(); } private DelegationClient createRetryableDelegationClient() { Configuration conf = new Configuration(); conf.set(ConfKeys.FS_OBJECT_STORAGE_ENDPOINT.key(TOS_SCHEME), "https://tos-cn-beijing.ivolces.com"); conf.set(TosKeys.FS_TOS_CREDENTIALS_PROVIDER, SimpleCredentialsProvider.NAME); conf.setBoolean(TosKeys.FS_TOS_DISABLE_CLIENT_CACHE, true); conf.set(TosKeys.FS_TOS_ACCESS_KEY_ID, "ACCESS_KEY"); conf.set(TosKeys.FS_TOS_SECRET_ACCESS_KEY, "SECRET_KEY"); return new DelegationClientBuilder().bucket("test").conf(conf).build(); } @Test public void testShouldThrowExceptionAfterRunOut5RetryTimesIfNoRetryConfigSet() throws IOException { TOS storage = (TOS) ObjectStorageFactory.create(TOS_SCHEME, TestUtility.bucket(), new Configuration()); storage.setClient(client); client.setMaxRetryTimes(5); PutObjectOutput response = mock(PutObjectOutput.class); InputStreamProvider streamProvider = mock(InputStreamProvider.class); when(tosClient.putObject(any())).thenThrow( new TosServerException(HttpStatus.INTERNAL_SERVER_ERROR), new TosServerException(HttpStatus.TOO_MANY_REQUESTS), new TosException(new SocketException("fake msg")), new TosException(new UnknownHostException("fake msg")), new TosException(new SSLException("fake msg")), new TosException(new InterruptedException("fake msg")), new TosException(new InterruptedException("fake msg"))).thenReturn(response); // after run out retry times, should throw exception RuntimeException exception = assertThrows(RuntimeException.class, () -> storage.put(retryKey, streamProvider, 0)); assertTrue(exception instanceof TosException); assertTrue(exception.getCause() instanceof SSLException); // the newStream method of stream provider should be called 5 times verify(streamProvider, times(5)).newStream(); storage.close(); } @Test public void testShouldReturnResultAfterRetry8TimesIfConfigured10TimesRetry() throws IOException { TOS storage = (TOS) ObjectStorageFactory.create(TOS_SCHEME, TestUtility.bucket(), new Configuration()); DelegationClient delegationClient = createRetryableDelegationClient(); delegationClient.setClient(tosClient); delegationClient.setMaxRetryTimes(10); storage.setClient(delegationClient); UploadPartV2Output response = new UploadPartV2Output().setPartNumber(1).setEtag("etag"); InputStream in = mock(InputStream.class); InputStreamProvider streamProvider = mock(InputStreamProvider.class); when(streamProvider.newStream()).thenReturn(in); when(tosClient.uploadPart(any())).thenThrow( new TosServerException(HttpStatus.INTERNAL_SERVER_ERROR), new TosServerException(HttpStatus.TOO_MANY_REQUESTS), new TosException(new SocketException("fake msg")), new TosException(new UnknownHostException("fake msg")), new TosException(new SSLException("fake msg")), new TosException(new InterruptedException("fake msg")), new TosException(new InterruptedException("fake msg"))).thenReturn(response); // after run out retry times, should throw exception Part part = storage.uploadPart(retryKey, "uploadId", 1, streamProvider, 0); assertEquals(1, part.num()); assertEquals("etag", part.eTag()); // the newStream method of stream provider should be called 8 times verify(streamProvider, times(8)).newStream(); storage.close(); } @Test public void testShouldReturnResultIfRetry3TimesSucceed() throws IOException { TOS storage = (TOS) ObjectStorageFactory.create(TOS_SCHEME, TestUtility.bucket(), new Configuration()); storage.setClient(client); PutObjectOutput response = mock(PutObjectOutput.class); InputStreamProvider streamProvider = mock(InputStreamProvider.class); RequestInfo requestInfo = mock(RequestInfo.class); Map<String, String> header = new HashMap<>(); when(response.getRequestInfo()).thenReturn(requestInfo); when(requestInfo.getHeader()).thenReturn(header); when(tosClient.putObject(any())).thenThrow( new TosServerException(HttpStatus.INTERNAL_SERVER_ERROR), new TosServerException(HttpStatus.TOO_MANY_REQUESTS)).thenReturn(response); storage.put(retryKey, streamProvider, 0); // the newStream method of stream provider should be called 3 times verify(streamProvider, times(3)).newStream(); storage.close(); } @Test public void testShouldNotRetryIfThrowUnRetryException() throws IOException { TOS storage = (TOS) ObjectStorageFactory.create(TOS_SCHEME, TestUtility.bucket(), new Configuration()); storage.setClient(client); InputStreamProvider streamProvider = mock(InputStreamProvider.class); when(tosClient.putObject(any())).thenThrow( new TosException(new NullPointerException("fake msg."))); RuntimeException exception = assertThrows(RuntimeException.class, () -> storage.put(retryKey, streamProvider, 0)); assertTrue(exception instanceof TosException); assertTrue(exception.getCause() instanceof NullPointerException); // the newStream method of stream provider should be only called once. verify(streamProvider, times(1)).newStream(); storage.close(); } }
TestTOSRetryPolicy
java
quarkusio__quarkus
integration-tests/hibernate-orm-envers/src/main/java/io/quarkus/it/envers/Project.java
{ "start": 418, "end": 817 }
class ____ { private Long id; private String name; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "projectSeq") public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Project
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/junit/jupiter/CustomSoftAssertionsExtensionIntegrationTest.java
{ "start": 4295, "end": 4373 }
class ____ extends AbstractCustomSoftAssertionsExample { } } }
InnerExample
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/topn/ResultBuilderForExponentialHistogram.java
{ "start": 586, "end": 1824 }
class ____ implements ResultBuilder { private final ExponentialHistogramBlockBuilder builder; private final ReusableTopNEncoderInput reusableInput = new ReusableTopNEncoderInput(); ResultBuilderForExponentialHistogram(BlockFactory blockFactory, int positions) { this.builder = blockFactory.newExponentialHistogramBlockBuilder(positions); } @Override public void decodeKey(BytesRef keys) { throw new AssertionError("ExponentialHistogramBlock can't be a key"); } @Override public void decodeValue(BytesRef values) { int count = TopNEncoder.DEFAULT_UNSORTABLE.decodeVInt(values); if (count == 0) { builder.appendNull(); return; } assert count == 1 : "ExponentialHistogramBlock does not support multi values"; reusableInput.inputValues = values; builder.deserializeAndAppend(reusableInput); } @Override public Block build() { return builder.build(); } @Override public String toString() { return "ResultBuilderForExponentialHistogram"; } @Override public void close() { builder.close(); } private static final
ResultBuilderForExponentialHistogram
java
FasterXML__jackson-core
src/main/java/tools/jackson/core/base/ParserBase.java
{ "start": 607, "end": 794 }
class ____ by many (but not all) Jackson {@link JsonParser} * implementations. Contains most common things that are independent * of actual underlying input source. */ public abstract
used
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/introspect/CustomAnnotationIntrospector1756Test.java
{ "start": 2006, "end": 3031 }
class ____ extends NopAnnotationIntrospector { @Override public String findImplicitPropertyName(MapperConfig<?> config, final AnnotatedMember member) { // Constructor parameter if (member instanceof AnnotatedParameter) { final Field1756 field = member.getAnnotation(Field1756.class); if (field == null) { return null; } return field.value(); } // Getter if (member instanceof AnnotatedMethod) { return member.getName(); } return null; } @Override public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated a) { final AnnotatedConstructor ctor = (AnnotatedConstructor) a; if ((ctor.getParameterCount() > 0) && (ctor.getParameter(0).getAnnotation(Field1756.class) != null)) { return JsonCreator.Mode.PROPERTIES; } return null; } } public static
FoobarAnnotationIntrospector
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/DatabaseTimestampsColumnTest.java
{ "start": 1173, "end": 1978 }
class ____ { @Id @GeneratedValue private Long id; @NaturalId(mutable = true) private String name; @Column(nullable = false) @Timestamp private Date creationDate; @Column(nullable = true) @Timestamp(EventType.UPDATE) private Date editionDate; @Column(nullable = false, name="version") @Timestamp({ EventType.INSERT, EventType.UPDATE }) private Date timestamp; public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreationDate() { return creationDate; } public Date getEditionDate() { return editionDate; } public Date getTimestamp() { return timestamp; } } @ValueGenerationType(generatedBy = TimestampValueGeneration.class) @Retention(RetentionPolicy.RUNTIME) public @
Person
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/runtime/AbstractGenericTypeComparatorTest.java
{ "start": 10006, "end": 11201 }
class ____ implements Comparable<Book> { private long bookId; private String title; private long authorId; public Book() {} public Book(long bookId, String title, long authorId) { this.bookId = bookId; this.title = title; this.authorId = authorId; } @Override public boolean equals(Object obj) { if (obj.getClass() == Book.class) { Book other = (Book) obj; return other.bookId == this.bookId && other.authorId == this.authorId && this.title.equals(other.title); } else { return false; } } @Override public int compareTo(Book o) { int cmp = (this.bookId < o.bookId ? -1 : (this.bookId == o.bookId ? 0 : 1)); if (cmp != 0) { return cmp; } cmp = title.compareTo(o.title); if (cmp != 0) { return cmp; } return (this.authorId < o.authorId ? -1 : (this.authorId == o.authorId ? 0 : 1)); } } public static
Book
java
elastic__elasticsearch
modules/lang-painless/src/test/java/org/elasticsearch/painless/FactoryTests.java
{ "start": 12077, "end": 19642 }
interface ____ { FactoryTestConverterScript newInstance(Map<String, Object> params); } public static final ScriptContext<FactoryTestConverterScript.Factory> CONTEXT = new ScriptContext<>( "test", FactoryTestConverterScript.Factory.class ); public static long[] convertFromInt(int i) { return new long[] { i }; } public static long[] convertFromString(String s) { return new long[] { Long.parseLong(s) }; } public static long[] convertFromList(List<?> l) { long[] converted = new long[l.size()]; for (int i = 0; i < l.size(); i++) { Object o = l.get(i); if (o instanceof Long) { converted[i] = (Long) o; } else if (o instanceof Integer) { converted[i] = (Integer) o; } else if (o instanceof String) { converted[i] = Long.parseLong((String) o); } } return converted; } public static long[] convertFromDef(Object def) { if (def instanceof String) { return convertFromString((String) def); } else if (def instanceof Integer) { return convertFromInt(((Integer) def).intValue()); } else if (def instanceof List) { return convertFromList((List) def); } else { return (long[]) def; } // throw new ClassCastException("Cannot convert [" + def + "] to long[]"); } } public void testConverterFactory() { FactoryTestConverterScript.Factory factory = scriptEngine.compile( "converter_test", "return test;", FactoryTestConverterScript.CONTEXT, Collections.emptyMap() ); FactoryTestConverterScript script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 2 }, script.execute(2)); script = factory.newInstance(Collections.singletonMap("test", 3)); assertArrayEquals(new long[] { 3 }, script.execute(3)); factory = scriptEngine.compile("converter_test", "return test + 1;", FactoryTestConverterScript.CONTEXT, Collections.emptyMap()); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 1001 }, script.execute(1000)); factory = scriptEngine.compile("converter_test", "return '100';", FactoryTestConverterScript.CONTEXT, Collections.emptyMap()); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 100 }, script.execute(1000)); factory = scriptEngine.compile( "converter_test", "long[] a = new long[]{test, 123}; return a;", FactoryTestConverterScript.CONTEXT, Collections.emptyMap() ); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 1000, 123 }, script.execute(1000)); factory = scriptEngine.compile("converter_test", "return [test, 123];", FactoryTestConverterScript.CONTEXT, Collections.emptyMap()); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 1000, 123 }, script.execute(1000)); factory = scriptEngine.compile( "converter_test", "ArrayList a = new ArrayList(); a.add(test); a.add(456); a.add('789'); return a;", FactoryTestConverterScript.CONTEXT, Collections.emptyMap() ); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 123, 456, 789 }, script.execute(123)); // autoreturn, no converter factory = scriptEngine.compile("converter_test", "new long[]{test}", FactoryTestConverterScript.CONTEXT, Collections.emptyMap()); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 123 }, script.execute(123)); // autoreturn, converter factory = scriptEngine.compile("converter_test", "test", FactoryTestConverterScript.CONTEXT, Collections.emptyMap()); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 456 }, script.execute(456)); factory = scriptEngine.compile("converter_test", "'1001'", FactoryTestConverterScript.CONTEXT, Collections.emptyMap()); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 1001 }, script.execute(456)); // def tests factory = scriptEngine.compile( "converter_test", "def a = new long[]{test, 123}; return a;", FactoryTestConverterScript.CONTEXT, Collections.emptyMap() ); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 1000, 123 }, script.execute(1000)); factory = scriptEngine.compile( "converter_test", "def l = [test, 123]; l;", FactoryTestConverterScript.CONTEXT, Collections.emptyMap() ); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 1000, 123 }, script.execute(1000)); factory = scriptEngine.compile( "converter_test", "def a = new ArrayList(); a.add(test); a.add(456); a.add('789'); return a;", FactoryTestConverterScript.CONTEXT, Collections.emptyMap() ); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 123, 456, 789 }, script.execute(123)); // autoreturn, no converter factory = scriptEngine.compile( "converter_test", "def a = new long[]{test}; a;", FactoryTestConverterScript.CONTEXT, Collections.emptyMap() ); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 123 }, script.execute(123)); // autoreturn, converter factory = scriptEngine.compile("converter_test", "def a = '1001'; a", FactoryTestConverterScript.CONTEXT, Collections.emptyMap()); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 1001 }, script.execute(456)); factory = scriptEngine.compile("converter_test", "int x = 1", FactoryTestConverterScript.CONTEXT, Collections.emptyMap()); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(null, script.execute(123)); factory = scriptEngine.compile( "converter_test", "short x = 1; return x", FactoryTestConverterScript.CONTEXT, Collections.emptyMap() ); script = factory.newInstance(Collections.singletonMap("test", 2)); assertArrayEquals(new long[] { 1 }, script.execute(123)); ClassCastException cce = expectScriptThrows( ClassCastException.class, () -> scriptEngine.compile("converter_test", "return true;", FactoryTestConverterScript.CONTEXT, Collections.emptyMap()) ); assertEquals(cce.getMessage(), "Cannot cast from [boolean] to [long[]]."); } public abstract static
Factory
java
elastic__elasticsearch
test/test-clusters/src/main/java/org/elasticsearch/test/cluster/local/AbstractLocalClusterFactory.java
{ "start": 2883, "end": 4712 }
class ____<S extends LocalClusterSpec, H extends LocalClusterHandle> implements LocalClusterFactory<S, H> { private static final Logger LOGGER = LogManager.getLogger(AbstractLocalClusterFactory.class); private static final Duration NODE_UP_TIMEOUT = Duration.ofMinutes(6); private static final Map<Pair<Version, DistributionType>, DistributionDescriptor> TEST_DISTRIBUTIONS = new ConcurrentHashMap<>(); private static final String TESTS_CLUSTER_MODULES_PATH_SYSPROP = "tests.cluster.modules.path"; private static final String TESTS_CLUSTER_PLUGINS_PATH_SYSPROP = "tests.cluster.plugins.path"; private static final String TESTS_CLUSTER_FIPS_JAR_PATH_SYSPROP = "tests.cluster.fips.jars.path"; private static final String TESTS_CLUSTER_DEBUG_ENABLED_SYSPROP = "tests.cluster.debug.enabled"; private static final String ENABLE_DEBUG_JVM_ARGS = "-agentlib:jdwp=transport=dt_socket,server=n,suspend=y,address="; private static final String ENTITLEMENT_POLICY_YAML = "entitlement-policy.yaml"; private static final String PLUGIN_DESCRIPTOR_PROPERTIES = "plugin-descriptor.properties"; public static final String FIRST_DISTRO_WITH_JDK_21 = "8.11.0"; private final DistributionResolver distributionResolver; public AbstractLocalClusterFactory(DistributionResolver distributionResolver) { this.distributionResolver = distributionResolver; } @Override public H create(S spec) { Path baseWorkingDir; try { baseWorkingDir = Files.createTempDirectory(spec.getName()); } catch (IOException e) { throw new UncheckedIOException(e); } return createHandle(baseWorkingDir, spec); } protected abstract H createHandle(Path baseWorkingDir, S spec); public static
AbstractLocalClusterFactory
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/xml/BeanNameGenerationTests.java
{ "start": 1075, "end": 2396 }
class ____ { private DefaultListableBeanFactory beanFactory; @BeforeEach void setUp() { this.beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); reader.loadBeanDefinitions(new ClassPathResource("beanNameGeneration.xml", getClass())); } @Test void naming() { String className = GeneratedNameBean.class.getName(); String targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "0"; GeneratedNameBean topLevel1 = (GeneratedNameBean) beanFactory.getBean(targetName); assertThat(topLevel1).isNotNull(); targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "1"; GeneratedNameBean topLevel2 = (GeneratedNameBean) beanFactory.getBean(targetName); assertThat(topLevel2).isNotNull(); GeneratedNameBean child1 = topLevel1.getChild(); assertThat(child1.getBeanName()).isNotNull(); assertThat(child1.getBeanName()).startsWith(className); GeneratedNameBean child2 = topLevel2.getChild(); assertThat(child2.getBeanName()).isNotNull(); assertThat(child2.getBeanName()).startsWith(className); assertThat(child1.getBeanName()).isNotEqualTo(child2.getBeanName()); } }
BeanNameGenerationTests
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/net/DatagramSocketManager.java
{ "start": 4110, "end": 4909 }
class ____ implements ManagerFactory<DatagramSocketManager, FactoryData> { @Override public DatagramSocketManager createManager(final String name, final FactoryData data) { InetAddress inetAddress; try { inetAddress = InetAddress.getByName(data.host); } catch (final UnknownHostException ex) { LOGGER.error("Could not find address of " + data.host, ex); return null; } final OutputStream os = new DatagramOutputStream(data.host, data.port, data.layout.getHeader(), data.layout.getFooter()); return new DatagramSocketManager(name, os, inetAddress, data.host, data.port, data.layout, data.bufferSize); } } }
DatagramSocketManagerFactory
java
apache__camel
components/camel-jackson/src/test/java/org/apache/camel/component/jackson/converter/JacksonConversionsSimpleTest.java
{ "start": 1347, "end": 3109 }
class ____ extends CamelTestSupport { @Override public boolean isUseRouteBuilder() { return false; } @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); // enable jackson type converter by setting this property on // CamelContext context.getGlobalOptions().put(JacksonConstants.ENABLE_TYPE_CONVERTER, "true"); return context; } @Test public void shouldNotConvertMapToString() { Exchange exchange = new DefaultExchange(context); Map<String, String> body = new HashMap<>(); Object convertedObject = context.getTypeConverter().convertTo(String.class, exchange, body); // will do a toString which is an empty map assertEquals(body.toString(), convertedObject); } @Test public void shouldNotConvertMapToNumber() { Exchange exchange = new DefaultExchange(context); Object convertedObject = context.getTypeConverter().convertTo(Long.class, exchange, new HashMap<String, String>()); assertNull(convertedObject); } @Test public void shouldNotConvertMapToPrimitive() { Exchange exchange = new DefaultExchange(context); Object convertedObject = context.getTypeConverter().convertTo(long.class, exchange, new HashMap<String, String>()); assertNull(convertedObject); } @Test public void shouldNotConvertStringToEnum() { Exchange exchange = new DefaultExchange(context); Object convertedObject = context.getTypeConverter().convertTo(ExchangePattern.class, exchange, "InOnly"); assertEquals(ExchangePattern.InOnly, convertedObject); } }
JacksonConversionsSimpleTest
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/mapreduce/MockJob.java
{ "start": 1495, "end": 3612 }
class ____ extends Job { private static final Logger LOG = LoggerFactory.getLogger(MockJob.class); public static final String NAME = "mock"; private final ClientProtocol mockClient; private static int jobIdCounter; private static String trackerId = Long.toString(System.currentTimeMillis()); private Credentials submittedCredentials; public MockJob(final JobConf conf, final String jobName) throws IOException, InterruptedException { super(conf); setJobName(jobName); mockClient = mock(ClientProtocol.class); init(); } public void init() throws IOException, InterruptedException { when(mockClient.submitJob(any(JobID.class), any(String.class), any(Credentials.class))) .thenAnswer(invocation -> { final Object[] args = invocation.getArguments(); String name = (String) args[1]; LOG.info("Submitted Job {}", name); submittedCredentials = (Credentials) args[2]; final JobStatus status = new JobStatus(); status.setState(JobStatus.State.RUNNING); status.setSchedulingInfo(NAME); status.setTrackingUrl("http://localhost:8080/"); return status; }); when(mockClient.getNewJobID()) .thenReturn( new JobID(trackerId, jobIdCounter++)); when(mockClient.getQueueAdmins(any(String.class))) .thenReturn( new AccessControlList(AccessControlList.WILDCARD_ACL_VALUE)); } @Override public boolean isSuccessful() throws IOException { return true; } /** Only for mocking via unit tests. */ @InterfaceAudience.Private JobSubmitter getJobSubmitter(FileSystem fs, ClientProtocol submitClient) throws IOException { return new JobSubmitter(fs, mockClient); } @Override synchronized void connect() throws IOException, InterruptedException, ClassNotFoundException { super.connect(); } public Credentials getSubmittedCredentials() { return submittedCredentials; } @Override synchronized void updateStatus() throws IOException { // no-op } }
MockJob
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/SessionAttributesHandler.java
{ "start": 1114, "end": 1367 }
class ____ assist {@link ModelInitializer} with managing model * attributes in the {@link WebSession} based on model attribute names and types * declared va {@link SessionAttributes @SessionAttributes}. * * @author Rossen Stoyanchev * @since 5.0 */
to
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/buildextension/injectionPoints/InjectionPointTransformerTest.java
{ "start": 2466, "end": 2717 }
class ____ { @Produces @MyQualifier @Dependent String producedString = "foo"; @Produces @Dependent String producedStringNoQualifier = "bar"; } @ApplicationScoped static
SimpleProducer
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/package-info.java
{ "start": 5380, "end": 6397 }
class ____ is used (by default, or specified by name=value parameter in the Metrics annotation) as the metrics record name for which a set of metrics are to be reported. For example, you could have a record named "CacheStat" for reporting a number of statistics relating to the usage of some cache in your application.</dd> <dt><em>&#064;Metric</em></dt> <dd>The {@link org.apache.hadoop.metrics2.annotation.Metric} annotation identifies a particular metric, which in this case, is the result of the method call getMyMetric of the "gauge" (default) type, which means it can vary in both directions, compared with a "counter" type, which can only increase or stay the same. The name of the metric is "MyMetric" (inferred from getMyMetric method name by default.) The 42 here is the value of the metric which can be substituted with any valid java expressions. </dd> </dl> <p>Note, the {@link org.apache.hadoop.metrics2.MetricsSource}
name
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java
{ "start": 9062, "end": 9111 }
class ____ implements MockitoListener {} }
MyListener
java
google__error-prone
check_api/src/test/java/com/google/errorprone/util/testdata/TargetTypeTest.java
{ "start": 16332, "end": 16372 }
interface ____<T> { void foo(); }
A
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/EmbeddableInheritanceHierarchyOrderTest.java
{ "start": 4773, "end": 5157 }
class ____ { @Id private Long id; @Embedded private Animal pet; public Owner() { } public Owner(Long id, Animal pet) { this.id = id; this.pet = pet; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Animal getPet() { return pet; } public void setPet(Animal pet) { this.pet = pet; } } }
Owner
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/parallel/ParallelInvalid.java
{ "start": 896, "end": 1386 }
class ____ extends ParallelFlowable<Object> { @Override public void subscribe(Subscriber<? super Object>[] subscribers) { TestException ex = new TestException(); for (Subscriber<? super Object> s : subscribers) { EmptySubscription.error(ex, s); s.onError(ex); s.onNext(0); s.onComplete(); s.onComplete(); } } @Override public int parallelism() { return 4; } }
ParallelInvalid
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GoogleCloudStorageEndpointBuilderFactory.java
{ "start": 1648, "end": 3727 }
interface ____ extends EndpointConsumerBuilder { default AdvancedGoogleCloudStorageEndpointConsumerBuilder advanced() { return (AdvancedGoogleCloudStorageEndpointConsumerBuilder) this; } /** * Setting the autocreation of the bucket bucketName. * * The option is a: <code>boolean</code> type. * * Default: true * Group: common * * @param autoCreateBucket the value to set * @return the dsl builder */ default GoogleCloudStorageEndpointConsumerBuilder autoCreateBucket(boolean autoCreateBucket) { doSetProperty("autoCreateBucket", autoCreateBucket); return this; } /** * Setting the autocreation of the bucket bucketName. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: common * * @param autoCreateBucket the value to set * @return the dsl builder */ default GoogleCloudStorageEndpointConsumerBuilder autoCreateBucket(String autoCreateBucket) { doSetProperty("autoCreateBucket", autoCreateBucket); return this; } /** * The Service account key that can be used as credentials for the * Storage client. It can be loaded by default from classpath, but you * can prefix with classpath:, file:, or http: to load the resource from * different systems. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param serviceAccountKey the value to set * @return the dsl builder */ default GoogleCloudStorageEndpointConsumerBuilder serviceAccountKey(String serviceAccountKey) { doSetProperty("serviceAccountKey", serviceAccountKey); return this; } /** * The Cloud Storage
GoogleCloudStorageEndpointConsumerBuilder
java
quarkusio__quarkus
integration-tests/gradle/src/test/java/io/quarkus/gradle/JavaPlatformWithEagerResolutionTest.java
{ "start": 243, "end": 829 }
class ____ extends QuarkusGradleWrapperTestBase { @Test public void shouldImportConditionalDependency() throws IOException, URISyntaxException, InterruptedException { final File projectDir = getProjectDir("java-platform-with-eager-resolution-project"); runGradleWrapper(projectDir, "clean", ":quarkusBuild"); final File buildDir = new File(projectDir, "build"); final Path quarkusOutput = buildDir.toPath().resolve("quarkus-app"); assertThat(quarkusOutput.resolve("quarkus-run.jar")).exists(); } }
JavaPlatformWithEagerResolutionTest
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/BeanFactory.java
{ "start": 10907, "end": 12125 }
interface ____ superclass * @return an instance of the single bean matching the required type * @throws NoSuchBeanDefinitionException if no bean of the given type was found * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found * @throws BeansException if the bean could not be created * @since 3.0 * @see ListableBeanFactory */ <T> T getBean(Class<T> requiredType) throws BeansException; /** * Return an instance, which may be shared or independent, of the specified bean. * <p>Allows for specifying explicit constructor arguments / factory method arguments, * overriding the specified default arguments (if any) in the bean definition. * Note that the provided arguments need to match a specific candidate constructor / * factory method in the order of declared parameters. * <p>This method goes into {@link ListableBeanFactory} by-type lookup territory * but may also be translated into a conventional by-name lookup based on the name * of the given type. For more extensive retrieval operations across sets of beans, * use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}. * @param requiredType type the bean must match; can be an
or
java
apache__spark
sql/core/src/test/gen-java/org/apache/spark/sql/execution/datasources/parquet/test/avro/AvroNonNullableArrays.java
{ "start": 4305, "end": 8591 }
class ____ extends org.apache.avro.specific.SpecificRecordBuilderBase<AvroNonNullableArrays> implements org.apache.avro.data.RecordBuilder<AvroNonNullableArrays> { private java.util.List<java.lang.String> strings_column; private java.util.List<java.lang.Integer> maybe_ints_column; /** Creates a new Builder */ private Builder() { super(org.apache.spark.sql.execution.datasources.parquet.test.avro.AvroNonNullableArrays.SCHEMA$); } /** Creates a Builder by copying an existing Builder */ private Builder(org.apache.spark.sql.execution.datasources.parquet.test.avro.AvroNonNullableArrays.Builder other) { super(other); if (isValidValue(fields()[0], other.strings_column)) { this.strings_column = data().deepCopy(fields()[0].schema(), other.strings_column); fieldSetFlags()[0] = true; } if (isValidValue(fields()[1], other.maybe_ints_column)) { this.maybe_ints_column = data().deepCopy(fields()[1].schema(), other.maybe_ints_column); fieldSetFlags()[1] = true; } } /** Creates a Builder by copying an existing AvroNonNullableArrays instance */ private Builder(org.apache.spark.sql.execution.datasources.parquet.test.avro.AvroNonNullableArrays other) { super(org.apache.spark.sql.execution.datasources.parquet.test.avro.AvroNonNullableArrays.SCHEMA$); if (isValidValue(fields()[0], other.strings_column)) { this.strings_column = data().deepCopy(fields()[0].schema(), other.strings_column); fieldSetFlags()[0] = true; } if (isValidValue(fields()[1], other.maybe_ints_column)) { this.maybe_ints_column = data().deepCopy(fields()[1].schema(), other.maybe_ints_column); fieldSetFlags()[1] = true; } } /** Gets the value of the 'strings_column' field */ public java.util.List<java.lang.String> getStringsColumn() { return strings_column; } /** Sets the value of the 'strings_column' field */ public org.apache.spark.sql.execution.datasources.parquet.test.avro.AvroNonNullableArrays.Builder setStringsColumn(java.util.List<java.lang.String> value) { validate(fields()[0], value); this.strings_column = value; fieldSetFlags()[0] = true; return this; } /** Checks whether the 'strings_column' field has been set */ public boolean hasStringsColumn() { return fieldSetFlags()[0]; } /** Clears the value of the 'strings_column' field */ public org.apache.spark.sql.execution.datasources.parquet.test.avro.AvroNonNullableArrays.Builder clearStringsColumn() { strings_column = null; fieldSetFlags()[0] = false; return this; } /** Gets the value of the 'maybe_ints_column' field */ public java.util.List<java.lang.Integer> getMaybeIntsColumn() { return maybe_ints_column; } /** Sets the value of the 'maybe_ints_column' field */ public org.apache.spark.sql.execution.datasources.parquet.test.avro.AvroNonNullableArrays.Builder setMaybeIntsColumn(java.util.List<java.lang.Integer> value) { validate(fields()[1], value); this.maybe_ints_column = value; fieldSetFlags()[1] = true; return this; } /** Checks whether the 'maybe_ints_column' field has been set */ public boolean hasMaybeIntsColumn() { return fieldSetFlags()[1]; } /** Clears the value of the 'maybe_ints_column' field */ public org.apache.spark.sql.execution.datasources.parquet.test.avro.AvroNonNullableArrays.Builder clearMaybeIntsColumn() { maybe_ints_column = null; fieldSetFlags()[1] = false; return this; } @Override @SuppressWarnings(value="unchecked") public AvroNonNullableArrays build() { try { AvroNonNullableArrays record = new AvroNonNullableArrays(); record.strings_column = fieldSetFlags()[0] ? this.strings_column : (java.util.List<java.lang.String>) defaultValue(fields()[0]); record.maybe_ints_column = fieldSetFlags()[1] ? this.maybe_ints_column : (java.util.List<java.lang.Integer>) defaultValue(fields()[1]); return record; } catch (Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } } } }
Builder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DefaultCharsetTest.java
{ "start": 8687, "end": 9098 }
class ____ { void f(String s, File f) throws Exception { Files.newWriter(new File(s), UTF_8); Files.newWriter(f, UTF_8); } } """) .doTest(); } @Test public void androidReader() { refactoringTest() .addInputLines( "in/Test.java", """ import java.io.*;
Test
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_yanpei2.java
{ "start": 177, "end": 613 }
class ____ extends TestCase { public void test_for_sepcial_chars() throws Exception { String text = "{\"answerAllow\":true,\"atUsers\":[],\"desc\":\"测试账号\\n测试账号\"}"; JSONObject obj = JSON.parseObject(text); Assert.assertEquals(true, obj.get("answerAllow"));; Assert.assertEquals(0, obj.getJSONArray("atUsers").size());; Assert.assertEquals("测试账号\n测试账号", obj.get("desc"));; } }
Bug_for_yanpei2
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/secondarytable/SecondaryTableDynamicUpateTest.java
{ "start": 3189, "end": 4183 }
class ____ { @Id private Long id; @Column(name = "TEST_COL") private String testCol; @Column(name = "TESTCOL1", table = "SECOND_TABLE_TEST") private String testCol1; @Column(name = "TESTCOL2", table = "SECOND_TABLE_TEST") private String testCol2; public TestEntity() { } public TestEntity(Long id, String testCol, String testCol1, String testCol2) { this.id = id; this.testCol = testCol; this.testCol1 = testCol1; this.testCol2 = testCol2; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTestCol() { return testCol; } public void setTestCol(String testCol) { this.testCol = testCol; } public String getTestCol1() { return testCol1; } public void setTestCol1(String testCol1) { this.testCol1 = testCol1; } public String getTestCol2() { return testCol2; } public void setTestCol2(String testCol2) { this.testCol2 = testCol2; } } }
TestEntity