language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | spring-projects__spring-boot | module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java | {
"start": 17533,
"end": 17773
} | class ____ extends Foo {
private @Nullable List<String> list;
public @Nullable List<String> getList() {
return this.list;
}
public void setList(@Nullable List<String> list) {
this.list = list;
}
}
public static | ListHolder |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertySourcesDeducerTests.java | {
"start": 4647,
"end": 5044
} | class ____ {
@Bean
static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer1() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer2() {
return new PropertySourcesPlaceholderConfigurer();
}
}
private static | MultiplePropertySourcesPlaceholderConfigurerConfiguration |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/superbuilder/Car.java | {
"start": 1267,
"end": 1537
} | class ____ extends CarBuilder<Car, CarBuilderImpl> {
private CarBuilderImpl() {
}
protected CarBuilderImpl self() {
return this;
}
public Car build() {
return new Car( this );
}
}
}
| CarBuilderImpl |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncDeadLetterChannelTest.java | {
"start": 1139,
"end": 2174
} | class ____ extends ContextTestSupport {
@Override
public boolean isUseRouteBuilder() {
return false;
}
@Test
public void testAsyncErrorHandlerWait() throws Exception {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
errorHandler(deadLetterChannel("mock:dead").maximumRedeliveries(2).redeliveryDelay(0).logStackTrace(false));
from("direct:in").threads(2).to("mock:foo").process(new Processor() {
public void process(Exchange exchange) throws Exception {
throw new Exception("Forced exception by unit test");
}
});
}
});
context.start();
getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:dead").expectedMessageCount(1);
template.requestBody("direct:in", "Hello World");
assertMockEndpointsSatisfied();
}
}
| AsyncDeadLetterChannelTest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestReduceFetchFromPartialMem.java | {
"start": 6203,
"end": 8854
} | class ____
implements Reducer<Text,Text,Text,Text> {
private static int nMaps;
private static final Text vb = new Text();
static {
byte[] v = new byte[4096];
Arrays.fill(v, (byte)'V');
vb.set(v);
}
private int nRec = 0;
private int nKey = -1;
private int aKey = -1;
private int bKey = -1;
private final Text kb = new Text();
private final Formatter fmt = new Formatter(new StringBuilder(25));
@Override
public void configure(JobConf conf) {
nMaps = conf.getNumMapTasks();
((StringBuilder)fmt.out()).append(keyfmt);
}
@Override
public void reduce(Text key, Iterator<Text> values,
OutputCollector<Text,Text> out, Reporter reporter)
throws IOException {
int vc = 0;
final int vlen;
final int preRec = nRec;
final int vcCheck, recCheck;
((StringBuilder)fmt.out()).setLength(keylen);
if (25 == key.getLength()) {
// tagged record
recCheck = 1; // expect only 1 record
switch ((char)key.getBytes()[0]) {
case 'A':
vlen = getValLen(++aKey, nMaps) - 128;
vcCheck = aKey; // expect eq id
break;
case 'B':
vlen = getValLen(++bKey, nMaps);
vcCheck = bKey; // expect eq id
break;
default:
vlen = vcCheck = -1;
fail("Unexpected tag on record: " + ((char)key.getBytes()[24]));
}
kb.set((char)key.getBytes()[0] + fmt.format(tagfmt,vcCheck).toString());
} else {
kb.set(fmt.format(tagfmt, ++nKey).toString());
vlen = 1000;
recCheck = nMaps; // expect 1 rec per map
vcCheck = (nMaps * (nMaps - 1)) >>> 1; // expect eq sum(id)
}
assertEquals(kb, key);
while (values.hasNext()) {
final Text val = values.next();
// increment vc by map ID assoc w/ val
vc += val.getBytes()[0];
// verify that all the fixed characters 'V' match
assertEquals(0, WritableComparator.compareBytes(
vb.getBytes(), 1, vlen - 1,
val.getBytes(), 1, val.getLength() - 1));
out.collect(key, val);
++nRec;
}
assertEquals(recCheck, nRec - preRec, "Bad rec count for " + key);
assertEquals(vcCheck, vc, "Bad rec group for " + key);
}
@Override
public void close() throws IOException {
assertEquals(4095, nKey);
assertEquals(nMaps - 1, aKey);
assertEquals(nMaps - 1, bKey);
assertEquals(nMaps * (4096 + 2), nRec, "Bad record count");
}
}
public static | MBValidate |
java | apache__rocketmq | client/src/main/java/org/apache/rocketmq/client/consumer/PopCallback.java | {
"start": 894,
"end": 1009
} | interface ____ {
void onSuccess(final PopResult popResult);
void onException(final Throwable e);
}
| PopCallback |
java | quarkusio__quarkus | extensions/hibernate-reactive/deployment/src/test/java/io/quarkus/hibernate/reactive/config/ConfigActiveFalseStaticInjectionTest.java | {
"start": 2166,
"end": 2393
} | class ____ {
@Inject
Mutiny.SessionFactory sessionFactory;
public Uni<MyEntity> useHibernate() {
return sessionFactory.withTransaction(s -> s.find(MyEntity.class, 1L));
}
}
}
| MyBean |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_1148/Entity.java | {
"start": 843,
"end": 1044
} | class ____ {
//CHECKSTYLE:OFF
public NestedDto client;
//CHECKSTYLE:ON
ClientDto(NestedDto client) {
this.client = client;
}
}
static | ClientDto |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceMismatchStrategyTest.java | {
"start": 3906,
"end": 4399
} | class ____ {
@Id
@GeneratedValue(generator = "hilo_sequence_generator")
@GenericGenerator(name = "hilo_sequence_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = {
@Parameter(name = "sequence_name", value = sequenceName),
@Parameter(name = "initial_value", value = "1"),
@Parameter(name = "increment_size", value = "10"),
@Parameter(name = "optimizer", value = "hilo")
})
private Long id;
private String aString;
}
}
| TestEntity |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/loader/internal/SimpleNaturalIdLoadAccessImpl.java | {
"start": 987,
"end": 4325
} | class ____<T>
extends BaseNaturalIdLoadAccessImpl<T>
implements SimpleNaturalIdLoadAccess<T> {
private final boolean hasSimpleNaturalId;
public SimpleNaturalIdLoadAccessImpl(LoadAccessContext context, EntityMappingType entityDescriptor) {
super( context, entityDescriptor );
hasSimpleNaturalId = entityDescriptor.getNaturalIdMapping() instanceof SimpleNaturalIdMapping;
}
@Override
public LockOptions getLockOptions() {
return super.getLockOptions();
}
@Override
public boolean isSynchronizationEnabled() {
return super.isSynchronizationEnabled();
}
@Override
public SimpleNaturalIdLoadAccess<T> with(LockMode lockMode, PessimisticLockScope lockScope) {
//noinspection unchecked
return (SimpleNaturalIdLoadAccess<T>) super.with( lockMode, lockScope );
}
@Override
public SimpleNaturalIdLoadAccess<T> with(Timeout timeout) {
//noinspection unchecked
return (SimpleNaturalIdLoadAccess<T>) super.with( timeout );
}
@Override
public final SimpleNaturalIdLoadAccessImpl<T> with(LockOptions lockOptions) {
return (SimpleNaturalIdLoadAccessImpl<T>) super.with( lockOptions );
}
@Override
public SimpleNaturalIdLoadAccessImpl<T> setSynchronizationEnabled(boolean synchronizationEnabled) {
super.synchronizationEnabled( synchronizationEnabled );
return this;
}
@Override
public T getReference(Object naturalIdValue) {
verifySimplicity( naturalIdValue );
return doGetReference( entityPersister().getNaturalIdMapping().normalizeInput( naturalIdValue) );
}
@Override
public T load(Object naturalIdValue) {
verifySimplicity( naturalIdValue );
return doLoad( entityPersister().getNaturalIdMapping().normalizeInput( naturalIdValue) );
}
/**
* Verify that the given natural id is "simple".
* <p>
* We allow compound natural id "simple" loading if all the values are passed as an array,
* list, or map. We assume an array is properly ordered following the attribute ordering.
* For lists, just like arrays, we assume the user has ordered them properly; for maps,
* the key is expected to be the attribute name.
*/
private void verifySimplicity(Object naturalIdValue) {
assert naturalIdValue != null;
if ( !hasSimpleNaturalId
&& !naturalIdValue.getClass().isArray()
&& !(naturalIdValue instanceof List)
&& !(naturalIdValue instanceof Map) ) {
throw new HibernateException(
String.format(
Locale.ROOT,
"Cannot interpret natural id value [%s] as compound natural id of entity '%s'",
naturalIdValue,
entityPersister().getEntityName()
)
);
}
}
@Override
public Optional<T> loadOptional(Object naturalIdValue) {
return Optional.ofNullable( load( naturalIdValue ) );
}
@Override
public SimpleNaturalIdLoadAccess<T> with(EntityGraph<T> graph, GraphSemantic semantic) {
super.with( graph, semantic );
return this;
}
@Override
public SimpleNaturalIdLoadAccess<T> withLoadGraph(EntityGraph<T> graph) {
return SimpleNaturalIdLoadAccess.super.withLoadGraph(graph);
}
@Override
public SimpleNaturalIdLoadAccess<T> enableFetchProfile(String profileName) {
super.enableFetchProfile( profileName );
return this;
}
@Override
public SimpleNaturalIdLoadAccess<T> disableFetchProfile(String profileName) {
super.enableFetchProfile( profileName );
return this;
}
}
| SimpleNaturalIdLoadAccessImpl |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/script/BucketAggregationSelectorScript.java | {
"start": 1294,
"end": 1403
} | interface ____ {
BucketAggregationSelectorScript newInstance(Map<String, Object> params);
}
}
| Factory |
java | google__error-prone | core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java | {
"start": 72992,
"end": 73124
} | class ____ {}
""")
.addSourceLines(
"ClassContainingRawType.java", //
" | InAllCompilationUnits |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/datanode/DiskBalancerWorkStatus.java | {
"start": 4898,
"end": 5241
} | enum ____ {
NO_PLAN(0),
PLAN_UNDER_PROGRESS(1),
PLAN_DONE(2),
PLAN_CANCELLED(3);
private int result;
private Result(int result) {
this.result = result;
}
/**
* Get int value of result.
*
* @return int
*/
public int getIntResult() {
return result;
}
}
/**
* A | Result |
java | google__guava | android/guava/src/com/google/common/base/Function.java | {
"start": 932,
"end": 1182
} | class ____ common functions and related utilities.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/FunctionalExplained">the use of {@code Function}</a>.
*
* <h3>For Java 8+ users</h3>
*
* <p>This | provides |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/TaskExecutorToJobManagerHeartbeatPayload.java | {
"start": 993,
"end": 2351
} | class ____ implements Serializable {
private static final long serialVersionUID = 525146950563585444L;
private final AccumulatorReport accumulatorReport;
private final ExecutionDeploymentReport executionDeploymentReport;
public TaskExecutorToJobManagerHeartbeatPayload(
AccumulatorReport accumulatorReport,
ExecutionDeploymentReport executionDeploymentReport) {
this.accumulatorReport = accumulatorReport;
this.executionDeploymentReport = executionDeploymentReport;
}
public AccumulatorReport getAccumulatorReport() {
return accumulatorReport;
}
public ExecutionDeploymentReport getExecutionDeploymentReport() {
return executionDeploymentReport;
}
public static TaskExecutorToJobManagerHeartbeatPayload empty() {
return new TaskExecutorToJobManagerHeartbeatPayload(
new AccumulatorReport(Collections.emptyList()),
new ExecutionDeploymentReport(Collections.emptySet()));
}
@Override
public String toString() {
return "TaskExectorToJobManagerHeartbeatPayload{"
+ "accumulatorReport="
+ accumulatorReport
+ ", executionDeploymentReport="
+ executionDeploymentReport
+ '}';
}
}
| TaskExecutorToJobManagerHeartbeatPayload |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/dataview/StateDataViewStore.java | {
"start": 1034,
"end": 1141
} | interface ____ methods for registering {@link StateDataView} with a managed store. */
@Internal
public | contains |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_1900/Issue1945.java | {
"start": 276,
"end": 652
} | class ____ extends TestCase {
public void test_0() throws Exception {
B b = new B();
b.clazz = new Class[]{String.class};
b.aInstance = new HashMap();
b.aInstance.put("test", "test");
String s = JSON.toJSONString(b, WriteClassName);
System.out.println(s);
B a1 = JSON.parseObject(s, B.class);
}
static | Issue1945 |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java | {
"start": 1702,
"end": 9851
} | class ____ {
private final ImportAutoConfigurationImportSelector importSelector = new TestImportAutoConfigurationImportSelector();
private final ConfigurableListableBeanFactory beanFactory = new DefaultListableBeanFactory();
private final MockEnvironment environment = new MockEnvironment();
@BeforeEach
void setup() {
this.importSelector.setBeanFactory(this.beanFactory);
this.importSelector.setEnvironment(this.environment);
this.importSelector.setResourceLoader(new DefaultResourceLoader());
this.importSelector.setBeanClassLoader(Thread.currentThread().getContextClassLoader());
}
@Test
void importsAreSelected() throws Exception {
AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportImported.class);
String[] imports = this.importSelector.selectImports(annotationMetadata);
assertThat(imports).containsExactly(ImportedAutoConfiguration.class.getName());
}
@Test
void importsAreSelectedUsingClassesAttribute() throws Exception {
AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportImportedUsingClassesAttribute.class);
String[] imports = this.importSelector.selectImports(annotationMetadata);
assertThat(imports).containsExactly(ImportedAutoConfiguration.class.getName());
}
@Test
@WithResource(
name = "META-INF/spring/org.springframework.boot.autoconfigure.ImportAutoConfigurationImportSelectorTests$FromImportsFile.imports",
content = """
org.springframework.boot.autoconfigure.ImportAutoConfigurationImportSelectorTests$ImportedAutoConfiguration
org.springframework.boot.autoconfigure.missing.MissingAutoConfiguration
""")
void importsAreSelectedFromImportsFile() throws Exception {
AnnotationMetadata annotationMetadata = getAnnotationMetadata(FromImportsFile.class);
String[] imports = this.importSelector.selectImports(annotationMetadata);
assertThat(imports).containsExactly(
"org.springframework.boot.autoconfigure.ImportAutoConfigurationImportSelectorTests$ImportedAutoConfiguration",
"org.springframework.boot.autoconfigure.missing.MissingAutoConfiguration");
}
@Test
@WithResource(
name = "META-INF/spring/org.springframework.boot.autoconfigure.ImportAutoConfigurationImportSelectorTests$FromImportsFile.imports",
content = """
optional:org.springframework.boot.autoconfigure.ImportAutoConfigurationImportSelectorTests$ImportedAutoConfiguration
optional:org.springframework.boot.autoconfigure.missing.MissingAutoConfiguration
org.springframework.boot.autoconfigure.ImportAutoConfigurationImportSelectorTests$AnotherImportedAutoConfiguration
""")
void importsSelectedFromImportsFileIgnoreMissingOptionalClasses() throws Exception {
AnnotationMetadata annotationMetadata = getAnnotationMetadata(FromImportsFile.class);
String[] imports = this.importSelector.selectImports(annotationMetadata);
assertThat(imports).containsExactly(
"org.springframework.boot.autoconfigure.ImportAutoConfigurationImportSelectorTests$ImportedAutoConfiguration",
"org.springframework.boot.autoconfigure.ImportAutoConfigurationImportSelectorTests$AnotherImportedAutoConfiguration");
}
@Test
void propertyExclusionsAreApplied() throws IOException {
this.environment.setProperty("spring.autoconfigure.exclude", ImportedAutoConfiguration.class.getName());
AnnotationMetadata annotationMetadata = getAnnotationMetadata(MultipleImports.class);
String[] imports = this.importSelector.selectImports(annotationMetadata);
assertThat(imports).containsExactly(AnotherImportedAutoConfiguration.class.getName());
}
@Test
void multipleImportsAreFound() throws Exception {
AnnotationMetadata annotationMetadata = getAnnotationMetadata(MultipleImports.class);
String[] imports = this.importSelector.selectImports(annotationMetadata);
assertThat(imports).containsOnly(ImportedAutoConfiguration.class.getName(),
AnotherImportedAutoConfiguration.class.getName());
}
@Test
void selfAnnotatingAnnotationDoesNotCauseStackOverflow() throws IOException {
AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportWithSelfAnnotatingAnnotation.class);
String[] imports = this.importSelector.selectImports(annotationMetadata);
assertThat(imports).containsOnly(AnotherImportedAutoConfiguration.class.getName());
}
@Test
void exclusionsAreApplied() throws Exception {
AnnotationMetadata annotationMetadata = getAnnotationMetadata(MultipleImportsWithExclusion.class);
String[] imports = this.importSelector.selectImports(annotationMetadata);
assertThat(imports).containsOnly(ImportedAutoConfiguration.class.getName());
}
@Test
void exclusionsWithoutImport() throws Exception {
AnnotationMetadata annotationMetadata = getAnnotationMetadata(ExclusionWithoutImport.class);
String[] imports = this.importSelector.selectImports(annotationMetadata);
assertThat(imports).containsOnly(ImportedAutoConfiguration.class.getName());
}
@Test
void exclusionsAliasesAreApplied() throws Exception {
AnnotationMetadata annotationMetadata = getAnnotationMetadata(ImportWithSelfAnnotatingAnnotationExclude.class);
String[] imports = this.importSelector.selectImports(annotationMetadata);
assertThat(imports).isEmpty();
}
@Test
void determineImportsWhenUsingMetaWithoutClassesShouldBeEqual() throws Exception {
Set<Object> set1 = this.importSelector
.determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedOne.class));
Set<Object> set2 = this.importSelector
.determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class));
assertThat(set1).isEqualTo(set2);
assertThat(set1).hasSameHashCodeAs(set2);
}
@Test
void determineImportsWhenUsingNonMetaWithoutClassesShouldBeSame() throws Exception {
Set<Object> set1 = this.importSelector
.determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedOne.class));
Set<Object> set2 = this.importSelector
.determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedTwo.class));
assertThat(set1).isEqualTo(set2);
}
@Test
void determineImportsWhenUsingNonMetaWithClassesShouldBeSame() throws Exception {
Set<Object> set1 = this.importSelector
.determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsOne.class));
Set<Object> set2 = this.importSelector
.determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsTwo.class));
assertThat(set1).isEqualTo(set2);
}
@Test
void determineImportsWhenUsingMetaExcludeWithoutClassesShouldBeEqual() throws Exception {
Set<Object> set1 = this.importSelector
.determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class));
Set<Object> set2 = this.importSelector
.determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedTwo.class));
assertThat(set1).isEqualTo(set2);
assertThat(set1).hasSameHashCodeAs(set2);
}
@Test
void determineImportsWhenUsingMetaDifferentExcludeWithoutClassesShouldBeDifferent() throws Exception {
Set<Object> set1 = this.importSelector
.determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class));
Set<Object> set2 = this.importSelector
.determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class));
assertThat(set1).isNotEqualTo(set2);
}
@Test
void determineImportsShouldNotSetPackageImport() throws Exception {
Class<?> packageImportsClass = ClassUtils
.resolveClassName("org.springframework.boot.autoconfigure.AutoConfigurationPackages.PackageImports", null);
Set<Object> selectedImports = this.importSelector
.determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class));
for (Object selectedImport : selectedImports) {
assertThat(selectedImport).isNotInstanceOf(packageImportsClass);
}
}
private AnnotationMetadata getAnnotationMetadata(Class<?> source) throws IOException {
return new SimpleMetadataReaderFactory().getMetadataReader(source.getName()).getAnnotationMetadata();
}
@ImportAutoConfiguration(ImportedAutoConfiguration.class)
static | ImportAutoConfigurationImportSelectorTests |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/factories/TableFactoryHarness.java | {
"start": 3827,
"end": 4281
} | class ____ extends TableFactoryHarness.ScanSourceBase
* implements SupportsLimitPushDown {
* private final SharedReference<List<Long>> appliedLimits;
*
* CustomSource(SharedReference<List<Long>> appliedLimits) {
* this.appliedLimits = appliedLimits;
* }
*
* public void applyLimit(long limit) {
* appliedLimits.get().add(limit);
* }
* }
* }
* }</pre>
*/
public | CustomSource |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/fetch/FetchPhase.java | {
"start": 5249,
"end": 20482
} | class ____ implements SourceProvider {
Source source;
@Override
public Source getSource(LeafReaderContext ctx, int doc) {
return source;
}
}
private SearchHits buildSearchHits(
SearchContext context,
int[] docIdsToLoad,
Profiler profiler,
RankDocShardInfo rankDocs,
IntConsumer memoryChecker
) {
var lookup = context.getSearchExecutionContext().getMappingLookup();
// Optionally remove sparse and dense vector fields early to:
// - Reduce the in-memory size of the source
// - Speed up retrieval of the synthetic source
// Note: These vectors will no longer be accessible via _source for any sub-fetch processors,
// but they are typically accessed through doc values instead (e.g: re-scorer).
var res = maybeExcludeVectorFields(
context.getSearchExecutionContext().getMappingLookup(),
context.getSearchExecutionContext().getIndexSettings(),
context.fetchSourceContext(),
context.fetchFieldsContext()
);
if (context.fetchSourceContext() != res.v1()) {
context.fetchSourceContext(res.v1());
}
if (lookup.inferenceFields().isEmpty() == false && shouldExcludeInferenceFieldsFromSource(context.fetchSourceContext()) == false) {
// Rehydrate the inference fields into the {@code _source} because they were explicitly requested.
var oldFetchFieldsContext = context.fetchFieldsContext();
var newFetchFieldsContext = new FetchFieldsContext(new ArrayList<>());
if (oldFetchFieldsContext != null) {
newFetchFieldsContext.fields().addAll(oldFetchFieldsContext.fields());
}
newFetchFieldsContext.fields().add(new FieldAndFormat(InferenceMetadataFieldsMapper.NAME, null));
context.fetchFieldsContext(newFetchFieldsContext);
}
SourceLoader sourceLoader = context.newSourceLoader(res.v2());
FetchContext fetchContext = new FetchContext(context, sourceLoader);
PreloadedSourceProvider sourceProvider = new PreloadedSourceProvider();
PreloadedFieldLookupProvider fieldLookupProvider = new PreloadedFieldLookupProvider();
// The following relies on the fact that we fetch sequentially one segment after another, from a single thread
// This needs to be revised once we add concurrency to the fetch phase, and needs a work-around for situations
// where we run fetch as part of the query phase, where inter-segment concurrency is leveraged.
// One problem is the global setLookupProviders call against the shared execution context.
// Another problem is that the above provider implementations are not thread-safe
context.getSearchExecutionContext().setLookupProviders(sourceProvider, ctx -> fieldLookupProvider);
List<FetchSubPhaseProcessor> processors = getProcessors(context.shardTarget(), fetchContext, profiler);
StoredFieldsSpec storedFieldsSpec = StoredFieldsSpec.build(processors, FetchSubPhaseProcessor::storedFieldsSpec);
storedFieldsSpec = storedFieldsSpec.merge(new StoredFieldsSpec(false, false, sourceLoader.requiredStoredFields()));
// Ideally the required stored fields would be provided as constructor argument a few lines above, but that requires moving
// the getProcessors call to before the setLookupProviders call, which causes weird issues in InnerHitsPhase.
// setLookupProviders resets the SearchLookup used throughout the rest of the fetch phase, which StoredValueFetchers rely on
// to retrieve stored fields, and InnerHitsPhase is the last sub-fetch phase and re-runs the entire fetch phase.
fieldLookupProvider.setPreloadedStoredFieldNames(storedFieldsSpec.requiredStoredFields());
StoredFieldLoader storedFieldLoader = profiler.storedFields(StoredFieldLoader.fromSpec(storedFieldsSpec));
IdLoader idLoader = context.newIdLoader();
boolean requiresSource = storedFieldsSpec.requiresSource();
final int[] locallyAccumulatedBytes = new int[1];
NestedDocuments nestedDocuments = context.getSearchExecutionContext().getNestedDocuments();
FetchPhaseDocsIterator docsIterator = new FetchPhaseDocsIterator() {
LeafReaderContext ctx;
LeafNestedDocuments leafNestedDocuments;
LeafStoredFieldLoader leafStoredFieldLoader;
SourceLoader.Leaf leafSourceLoader;
IdLoader.Leaf leafIdLoader;
IntConsumer memChecker = memoryChecker != null ? memoryChecker : bytes -> {
locallyAccumulatedBytes[0] += bytes;
if (context.checkCircuitBreaker(locallyAccumulatedBytes[0], "fetch source")) {
addRequestBreakerBytes(locallyAccumulatedBytes[0]);
locallyAccumulatedBytes[0] = 0;
}
};
@Override
protected void setNextReader(LeafReaderContext ctx, int[] docsInLeaf) throws IOException {
Timer timer = profiler.startNextReader();
try {
this.ctx = ctx;
this.leafNestedDocuments = nestedDocuments.getLeafNestedDocuments(ctx);
this.leafStoredFieldLoader = storedFieldLoader.getLoader(ctx, docsInLeaf);
this.leafSourceLoader = sourceLoader.leaf(ctx.reader(), docsInLeaf);
this.leafIdLoader = idLoader.leaf(leafStoredFieldLoader, ctx.reader(), docsInLeaf);
fieldLookupProvider.setNextReader(ctx);
for (FetchSubPhaseProcessor processor : processors) {
processor.setNextReader(ctx);
}
} finally {
if (timer != null) {
timer.stop();
}
}
}
@Override
protected SearchHit nextDoc(int doc) throws IOException {
if (context.isCancelled()) {
throw new TaskCancelledException("cancelled");
}
HitContext hit = prepareHitContext(
context,
requiresSource,
profiler,
leafNestedDocuments,
leafStoredFieldLoader,
doc,
ctx,
leafSourceLoader,
leafIdLoader,
rankDocs == null ? null : rankDocs.get(doc)
);
boolean success = false;
try {
sourceProvider.source = hit.source();
fieldLookupProvider.setPreloadedStoredFieldValues(hit.hit().getId(), hit.loadedFields());
for (FetchSubPhaseProcessor processor : processors) {
processor.process(hit);
}
BytesReference sourceRef = hit.hit().getSourceRef();
if (sourceRef != null) {
// This is an empirical value that seems to work well.
// Deserializing a large source would also mean serializing it to HTTP response later on, so x2 seems reasonable
memChecker.accept(sourceRef.length() * 2);
}
success = true;
return hit.hit();
} finally {
if (success == false) {
hit.hit().decRef();
}
}
}
};
try {
SearchHit[] hits = docsIterator.iterate(
context.shardTarget(),
context.searcher().getIndexReader(),
docIdsToLoad,
context.request().allowPartialSearchResults(),
context.queryResult()
);
if (context.isCancelled()) {
for (SearchHit hit : hits) {
// release all hits that would otherwise become owned and eventually released by SearchHits below
hit.decRef();
}
throw new TaskCancelledException("cancelled");
}
TotalHits totalHits = context.getTotalHits();
return new SearchHits(hits, totalHits, context.getMaxScore());
} finally {
long bytes = docsIterator.getRequestBreakerBytes();
if (bytes > 0L) {
context.circuitBreaker().addWithoutBreaking(-bytes);
}
}
}
List<FetchSubPhaseProcessor> getProcessors(SearchShardTarget target, FetchContext context, Profiler profiler) {
try {
List<FetchSubPhaseProcessor> processors = new ArrayList<>();
for (FetchSubPhase fsp : fetchSubPhases) {
FetchSubPhaseProcessor processor = fsp.getProcessor(context);
if (processor != null) {
processors.add(profiler.profile(fsp.getClass().getSimpleName(), "", processor));
}
}
return processors;
} catch (Exception e) {
throw new FetchPhaseExecutionException(target, "Error building fetch sub-phases", e);
}
}
private static HitContext prepareHitContext(
SearchContext context,
boolean requiresSource,
Profiler profiler,
LeafNestedDocuments nestedDocuments,
LeafStoredFieldLoader leafStoredFieldLoader,
int docId,
LeafReaderContext subReaderContext,
SourceLoader.Leaf sourceLoader,
IdLoader.Leaf idLoader,
RankDoc rankDoc
) throws IOException {
if (nestedDocuments.advance(docId - subReaderContext.docBase) == null) {
return prepareNonNestedHitContext(
requiresSource,
profiler,
leafStoredFieldLoader,
docId,
subReaderContext,
sourceLoader,
idLoader,
rankDoc
);
} else {
return prepareNestedHitContext(
context,
requiresSource,
profiler,
docId,
nestedDocuments,
subReaderContext,
leafStoredFieldLoader,
rankDoc
);
}
}
/**
* Resets the provided {@link HitContext} with information on the current
* document. This includes the following:
* - Adding an initial {@link SearchHit} instance.
* - Loading the document source and setting it on {@link HitContext#source()}. This
* allows fetch subphases that use the hit context to access the preloaded source.
*/
private static HitContext prepareNonNestedHitContext(
boolean requiresSource,
Profiler profiler,
LeafStoredFieldLoader leafStoredFieldLoader,
int docId,
LeafReaderContext subReaderContext,
SourceLoader.Leaf sourceLoader,
IdLoader.Leaf idLoader,
RankDoc rankDoc
) throws IOException {
int subDocId = docId - subReaderContext.docBase;
leafStoredFieldLoader.advanceTo(subDocId);
String id = idLoader.getId(subDocId);
if (id == null) {
SearchHit hit = new SearchHit(docId);
// TODO: can we use real pooled buffers here as well?
Source source = Source.lazy(lazyStoredSourceLoader(profiler, subReaderContext, subDocId));
return new HitContext(hit, subReaderContext, subDocId, Map.of(), source, rankDoc);
} else {
SearchHit hit = new SearchHit(docId, id);
Source source;
if (requiresSource) {
Timer timer = profiler.startLoadingSource();
try {
source = sourceLoader.source(leafStoredFieldLoader, subDocId);
} finally {
if (timer != null) {
timer.stop();
}
}
} else {
source = Source.lazy(lazyStoredSourceLoader(profiler, subReaderContext, subDocId));
}
return new HitContext(hit, subReaderContext, subDocId, leafStoredFieldLoader.storedFields(), source, rankDoc);
}
}
private static Supplier<Source> lazyStoredSourceLoader(Profiler profiler, LeafReaderContext ctx, int doc) {
return () -> {
StoredFieldLoader rootLoader = profiler.storedFields(StoredFieldLoader.create(true, Collections.emptySet()));
try {
LeafStoredFieldLoader leafRootLoader = rootLoader.getLoader(ctx, null);
leafRootLoader.advanceTo(doc);
return Source.fromBytes(leafRootLoader.source());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
/**
* Resets the provided {@link HitContext} with information on the current
* nested document. This includes the following:
* - Adding an initial {@link SearchHit} instance.
* - Loading the document source, filtering it based on the nested document ID, then
* setting it on {@link HitContext#source()}. This allows fetch subphases that
* use the hit context to access the preloaded source.
*/
private static HitContext prepareNestedHitContext(
SearchContext context,
boolean requiresSource,
Profiler profiler,
int topDocId,
LeafNestedDocuments nestedInfo,
LeafReaderContext subReaderContext,
LeafStoredFieldLoader childFieldLoader,
RankDoc rankDoc
) throws IOException {
String rootId;
Source rootSource = Source.empty(XContentType.JSON);
if (context instanceof InnerHitsContext.InnerHitSubContext innerHitsContext) {
rootId = innerHitsContext.getRootId();
if (requiresSource) {
rootSource = innerHitsContext.getRootLookup();
}
} else {
StoredFieldLoader rootLoader = profiler.storedFields(StoredFieldLoader.create(requiresSource, Collections.emptySet()));
LeafStoredFieldLoader leafRootLoader = rootLoader.getLoader(subReaderContext, null);
leafRootLoader.advanceTo(nestedInfo.rootDoc());
rootId = leafRootLoader.id();
if (requiresSource) {
if (leafRootLoader.source() != null) {
rootSource = Source.fromBytes(leafRootLoader.source());
}
}
}
childFieldLoader.advanceTo(nestedInfo.doc());
SearchHit.NestedIdentity nestedIdentity = nestedInfo.nestedIdentity();
assert nestedIdentity != null;
Source nestedSource = nestedIdentity.extractSource(rootSource);
SearchHit nestedHit = new SearchHit(topDocId, rootId, nestedIdentity);
return new HitContext(nestedHit, subReaderContext, nestedInfo.doc(), childFieldLoader.storedFields(), nestedSource, rankDoc);
}
| PreloadedSourceProvider |
java | apache__flink | flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/TestingFlinkKubeClient.java | {
"start": 16286,
"end": 17472
} | class ____ extends KubernetesConfigMap {
private final String name;
private final Map<String, String> data;
private final Map<String, String> labels;
private final Map<String, String> annotations;
private final String resourceVersion = "1";
public MockKubernetesConfigMap(String name) {
super(null);
this.name = name;
this.data = new HashMap<>();
this.labels = new HashMap<>();
this.annotations = new HashMap<>();
}
@Override
public String getName() {
return this.name;
}
@Override
public Map<String, String> getData() {
return this.data;
}
@Override
public Map<String, String> getAnnotations() {
return annotations;
}
@Override
public Map<String, String> getLabels() {
return this.labels;
}
@Override
public String getResourceVersion() {
return this.resourceVersion;
}
}
/** Testing implementation of {@link KubernetesLeaderElector}. */
public static | MockKubernetesConfigMap |
java | quarkusio__quarkus | extensions/quartz/deployment/src/test/java/io/quarkus/quartz/test/InjectJobTest.java | {
"start": 1838,
"end": 2001
} | class ____ {
@Inject
CountDownLatch latch;
public void execute() {
latch.countDown();
}
}
public static | Service |
java | quarkusio__quarkus | extensions/panache/hibernate-reactive-rest-data-panache/deployment/src/test/java/io/quarkus/hibernate/reactive/rest/data/panache/deployment/entity/PanacheEntityResourceGetMethodTest.java | {
"start": 441,
"end": 1747
} | class ____ extends AbstractGetMethodTest {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(Collection.class, CollectionsResource.class, AbstractEntity.class, AbstractItem.class,
Item.class, ItemsResource.class,
EmptyListItem.class, EmptyListItemsResource.class)
.addAsResource("application.properties")
.addAsResource("import.sql"));
@Test
void shouldCopyAdditionalMethodsAsResources() {
given().accept("application/json")
.when().get("/collections/name/full collection")
.then().statusCode(200)
.and().body("id", is("full"))
.and().body("name", is("full collection"));
}
@Test
void shouldAdditionalMethodsSupportHal() {
given().accept("application/hal+json")
.when().get("/collections/name/full collection")
.then().statusCode(200)
.and().body("id", is("full"))
.and().body("name", is("full collection"))
.and().body("_links.addByName.href", containsString("/name/full"));
}
}
| PanacheEntityResourceGetMethodTest |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/result/method/SyncHandlerMethodArgumentResolver.java | {
"start": 1133,
"end": 1963
} | interface ____ extends HandlerMethodArgumentResolver {
/**
* {@inheritDoc}
* <p>By default this simply delegates to {@link #resolveArgumentValue} for
* synchronous resolution.
*/
@Override
default Mono<Object> resolveArgument(
MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {
return Mono.justOrEmpty(resolveArgumentValue(parameter, bindingContext, exchange));
}
/**
* Resolve the value for the method parameter synchronously.
* @param parameter the method parameter
* @param bindingContext the binding context to use
* @param exchange the current exchange
* @return the resolved value, if any
*/
@Nullable Object resolveArgumentValue(
MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange);
}
| SyncHandlerMethodArgumentResolver |
java | spring-projects__spring-boot | buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/PullPolicy.java | {
"start": 768,
"end": 1016
} | enum ____ {
/**
* Always pull the image from the registry.
*/
ALWAYS,
/**
* Never pull the image from the registry.
*/
NEVER,
/**
* Pull the image from the registry only if it does not exist locally.
*/
IF_NOT_PRESENT
}
| PullPolicy |
java | quarkusio__quarkus | integration-tests/grpc-stork-response-time/src/test/java/io/quarkus/grpc/examples/stork/GrpcStorkResponseTimeCollectionIT.java | {
"start": 119,
"end": 208
} | class ____ extends GrpcStorkResponseTimeCollectionTest {
}
| GrpcStorkResponseTimeCollectionIT |
java | micronaut-projects__micronaut-core | management/src/main/java/io/micronaut/management/endpoint/loggers/LoggersEndpoint.java | {
"start": 1625,
"end": 4541
} | class ____ {
/**
* Endpoint name.
*/
public static final String NAME = "loggers";
/**
* Endpoint configuration prefix.
*/
public static final String PREFIX = EndpointConfiguration.PREFIX + "." + NAME;
/**
* Endpoint default enabled.
*/
public static final boolean DEFAULT_ENABLED = false;
/**
* Endpoint default sensitivity.
*/
public static final boolean DEFAULT_SENSITIVE = false;
private final ManagedLoggingSystem loggingSystem;
private final LoggersManager<Map<String, Object>> loggersManager;
private boolean writeSensitive = true;
/**
* @param loggingSystem the {@link io.micronaut.logging.LoggingSystem}
* @param loggersManager the {@link LoggersManager}
*/
public LoggersEndpoint(ManagedLoggingSystem loggingSystem,
LoggersManager<Map<String, Object>> loggersManager) {
this.loggingSystem = loggingSystem;
this.loggersManager = loggersManager;
}
/**
* @return the loggers as a {@link Mono}
*/
@Read
@SingleResult
public Publisher<Map<String, Object>> loggers() {
return Mono.from(loggersManager.getLoggers(loggingSystem));
}
/**
* @param name The name of the logger to find
* @return the {@link io.micronaut.logging.LogLevel} (both configured and effective) of the named logger
*/
@Read
@SingleResult
public Publisher<Map<String, Object>> logger(@NotBlank @Selector String name) {
return Mono.from(loggersManager.getLogger(loggingSystem, name));
}
/**
* @param name The name of the logger to configure
* @param configuredLevel The {@link io.micronaut.logging.LogLevel} to set on the named logger
*/
@Write
@Sensitive(property = "write-sensitive")
public void setLogLevel(@NotBlank @Selector String name,
io.micronaut.logging.@Nullable LogLevel configuredLevel) {
try {
loggersManager.setLogLevel(loggingSystem, name,
configuredLevel != null ? configuredLevel : io.micronaut.logging.LogLevel.NOT_SPECIFIED);
} catch (IllegalArgumentException ex) {
throw new UnsatisfiedArgumentException(
Argument.of(io.micronaut.logging.LogLevel.class, "configuredLevel"),
"Invalid log level specified: " + configuredLevel
);
}
}
/**
* @return True if modifications require authentication
*/
public boolean isWriteSensitive() {
return writeSensitive;
}
/**
* Determines whether modifications to the log level should
* require authentication. Default value (true).
*
* @param writeSensitive The write sensitivity option.
*/
public void setWriteSensitive(boolean writeSensitive) {
this.writeSensitive = writeSensitive;
}
}
| LoggersEndpoint |
java | redisson__redisson | redisson/src/main/java/org/redisson/config/ConfigSupport.java | {
"start": 20661,
"end": 22264
} | class ____ extends Constructor {
private final ClassLoader classLoader;
private final ConstructMapWithClass mapWithClassConstructor;
JSONCustomConstructor(ClassLoader classLoader, LoaderOptions loaderOptions, boolean useCaseInsensitive) {
super(loaderOptions);
this.classLoader = classLoader;
this.setPropertyUtils(new CustomPropertyUtils(useCaseInsensitive));
this.mapWithClassConstructor = new ConstructMapWithClass();
this.yamlConstructors.put(Tag.MAP, mapWithClassConstructor);
}
@Override
protected Class<?> getClassForName(String name) throws ClassNotFoundException {
if (classLoader != null) {
return Class.forName(name, true, classLoader);
}
return super.getClassForName(name);
}
@Override
protected org.yaml.snakeyaml.constructor.Construct getConstructor(Node node) {
if (node.getTag() == Tag.MAP) {
return new org.yaml.snakeyaml.constructor.Construct() {
@Override
public Object construct(Node node) {
return mapWithClassConstructor.construct(node);
}
@Override
public void construct2ndStep(Node node, Object object) {
mapWithClassConstructor.construct2ndStep(node, object);
}
};
}
return super.getConstructor(node);
}
private final | JSONCustomConstructor |
java | quarkusio__quarkus | integration-tests/hibernate-orm-data/src/test/java/io/quarkus/it/hibernate/processor/data/HibernateOrmDataInGraalIT.java | {
"start": 134,
"end": 200
} | class ____ extends HibernateOrmDataTest {
}
| HibernateOrmDataInGraalIT |
java | apache__maven | compat/maven-compat/src/test/java/org/apache/maven/artifact/deployer/ArtifactDeployerTest.java | {
"start": 1545,
"end": 2923
} | class ____ extends AbstractArtifactComponentTestCase {
@Inject
private ArtifactDeployer artifactDeployer;
@Inject
private SessionScope sessionScope;
protected String component() {
return "deployer";
}
@Test
void testArtifactInstallation() throws Exception {
sessionScope.enter();
try {
sessionScope.seed(MavenSession.class, mock(MavenSession.class));
String artifactBasedir = new File(getBasedir(), "src/test/resources/artifact-install").getAbsolutePath();
Artifact artifact = createArtifact("artifact", "1.0");
File file = new File(artifactBasedir, "artifact-1.0.jar");
assertEquals("dummy", new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8).trim());
artifactDeployer.deploy(file, artifact, remoteRepository(), localRepository());
ArtifactRepository remoteRepository = remoteRepository();
File deployedFile = new File(remoteRepository.getBasedir(), remoteRepository.pathOf(artifact));
assertTrue(deployedFile.exists(), "Expected " + deployedFile + ".exists() to return true");
assertEquals("dummy", new String(Files.readAllBytes(deployedFile.toPath()), StandardCharsets.UTF_8).trim());
} finally {
sessionScope.exit();
}
}
}
| ArtifactDeployerTest |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/expression/BeanFactoryResolver.java | {
"start": 1125,
"end": 1823
} | class ____ implements BeanResolver {
private final BeanFactory beanFactory;
/**
* Create a new {@code BeanFactoryResolver} for the given factory.
* @param beanFactory the {@code BeanFactory} to resolve bean names against
*/
public BeanFactoryResolver(BeanFactory beanFactory) {
Assert.notNull(beanFactory, "BeanFactory must not be null");
this.beanFactory = beanFactory;
}
@Override
public Object resolve(EvaluationContext context, String beanName) throws AccessException {
try {
return this.beanFactory.getBean(beanName);
}
catch (BeansException ex) {
throw new AccessException("Could not resolve bean reference against BeanFactory", ex);
}
}
}
| BeanFactoryResolver |
java | apache__avro | lang/java/tools/src/test/compiler/output/OptionalGettersAllFieldsTest.java | {
"start": 9177,
"end": 19103
} | class ____ extends org.apache.avro.specific.SpecificRecordBuilderBase<OptionalGettersAllFieldsTest>
implements org.apache.avro.data.RecordBuilder<OptionalGettersAllFieldsTest> {
private java.lang.CharSequence name;
private java.lang.CharSequence nullable_name;
private java.lang.Object favorite_number;
private java.lang.Integer nullable_favorite_number;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(avro.examples.baseball.OptionalGettersAllFieldsTest.Builder other) {
super(other);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.nullable_name)) {
this.nullable_name = data().deepCopy(fields()[1].schema(), other.nullable_name);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
if (isValidValue(fields()[2], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[2].schema(), other.favorite_number);
fieldSetFlags()[2] = other.fieldSetFlags()[2];
}
if (isValidValue(fields()[3], other.nullable_favorite_number)) {
this.nullable_favorite_number = data().deepCopy(fields()[3].schema(), other.nullable_favorite_number);
fieldSetFlags()[3] = other.fieldSetFlags()[3];
}
}
/**
* Creates a Builder by copying an existing OptionalGettersAllFieldsTest instance
* @param other The existing instance to copy.
*/
private Builder(avro.examples.baseball.OptionalGettersAllFieldsTest other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.nullable_name)) {
this.nullable_name = data().deepCopy(fields()[1].schema(), other.nullable_name);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[2].schema(), other.favorite_number);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.nullable_favorite_number)) {
this.nullable_favorite_number = data().deepCopy(fields()[3].schema(), other.nullable_favorite_number);
fieldSetFlags()[3] = true;
}
}
/**
* Gets the value of the 'name' field.
* @return The value.
*/
public java.lang.CharSequence getName() {
return name;
}
/**
* Sets the value of the 'name' field.
* @param value The value of 'name'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder setName(java.lang.CharSequence value) {
validate(fields()[0], value);
this.name = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'name' field has been set.
* @return True if the 'name' field has been set, false otherwise.
*/
public boolean hasName() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'name' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder clearName() {
name = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'nullable_name' field.
* @return The value.
*/
public java.lang.CharSequence getNullableName() {
return nullable_name;
}
/**
* Sets the value of the 'nullable_name' field.
* @param value The value of 'nullable_name'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder setNullableName(java.lang.CharSequence value) {
validate(fields()[1], value);
this.nullable_name = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'nullable_name' field has been set.
* @return True if the 'nullable_name' field has been set, false otherwise.
*/
public boolean hasNullableName() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'nullable_name' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder clearNullableName() {
nullable_name = null;
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'favorite_number' field.
* @return The value.
*/
public java.lang.Object getFavoriteNumber() {
return favorite_number;
}
/**
* Sets the value of the 'favorite_number' field.
* @param value The value of 'favorite_number'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder setFavoriteNumber(java.lang.Object value) {
validate(fields()[2], value);
this.favorite_number = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'favorite_number' field has been set.
* @return True if the 'favorite_number' field has been set, false otherwise.
*/
public boolean hasFavoriteNumber() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'favorite_number' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder clearFavoriteNumber() {
favorite_number = null;
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'nullable_favorite_number' field.
* @return The value.
*/
public java.lang.Integer getNullableFavoriteNumber() {
return nullable_favorite_number;
}
/**
* Sets the value of the 'nullable_favorite_number' field.
* @param value The value of 'nullable_favorite_number'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder setNullableFavoriteNumber(java.lang.Integer value) {
validate(fields()[3], value);
this.nullable_favorite_number = value;
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'nullable_favorite_number' field has been set.
* @return True if the 'nullable_favorite_number' field has been set, false otherwise.
*/
public boolean hasNullableFavoriteNumber() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'nullable_favorite_number' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder clearNullableFavoriteNumber() {
nullable_favorite_number = null;
fieldSetFlags()[3] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public OptionalGettersAllFieldsTest build() {
try {
OptionalGettersAllFieldsTest record = new OptionalGettersAllFieldsTest();
record.name = fieldSetFlags()[0] ? this.name : (java.lang.CharSequence) defaultValue(fields()[0]);
record.nullable_name = fieldSetFlags()[1] ? this.nullable_name : (java.lang.CharSequence) defaultValue(fields()[1]);
record.favorite_number = fieldSetFlags()[2] ? this.favorite_number : defaultValue(fields()[2]);
record.nullable_favorite_number = fieldSetFlags()[3] ? this.nullable_favorite_number : (java.lang.Integer) defaultValue(fields()[3]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<OptionalGettersAllFieldsTest>
WRITER$ = (org.apache.avro.io.DatumWriter<OptionalGettersAllFieldsTest>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<OptionalGettersAllFieldsTest>
READER$ = (org.apache.avro.io.DatumReader<OptionalGettersAllFieldsTest>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
@Override
public int hashCode() {
int result = 1;
result = 31 * result + (this.name == null ? 0 : this.name.hashCode());
result = 31 * result + (this.nullable_name == null ? 0 : this.nullable_name.hashCode());
result = 31 * result + (this.favorite_number == null ? 0 : this.favorite_number.hashCode());
result = 31 * result + (this.nullable_favorite_number == null ? 0 : this.nullable_favorite_number.hashCode());
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof OptionalGettersAllFieldsTest)) {
return false;
}
OptionalGettersAllFieldsTest other = (OptionalGettersAllFieldsTest) o;
if (Utf8.compareSequences(this.name, other.name) != 0) {
return false;
}
if (Utf8.compareSequences(this.nullable_name, other.nullable_name) != 0) {
return false;
}
if (!java.util.Objects.equals(this.favorite_number, other.favorite_number)) {
return false;
}
if (!java.util.Objects.equals(this.nullable_favorite_number, other.nullable_favorite_number)) {
return false;
}
return true;
}
}
| Builder |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/StartContainerRequestPBImpl.java | {
"start": 1738,
"end": 5402
} | class ____ extends StartContainerRequest {
StartContainerRequestProto proto = StartContainerRequestProto.getDefaultInstance();
StartContainerRequestProto.Builder builder = null;
boolean viaProto = false;
private ContainerLaunchContext containerLaunchContext = null;
private Token containerToken = null;
public StartContainerRequestPBImpl() {
builder = StartContainerRequestProto.newBuilder();
}
public StartContainerRequestPBImpl(StartContainerRequestProto proto) {
this.proto = proto;
viaProto = true;
}
public StartContainerRequestProto getProto() {
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
@Override
public int hashCode() {
return getProto().hashCode();
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other.getClass().isAssignableFrom(this.getClass())) {
return this.getProto().equals(this.getClass().cast(other).getProto());
}
return false;
}
@Override
public String toString() {
return TextFormat.shortDebugString(getProto());
}
private void mergeLocalToBuilder() {
if (this.containerLaunchContext != null) {
builder.setContainerLaunchContext(convertToProtoFormat(this.containerLaunchContext));
}
if(this.containerToken != null) {
builder.setContainerToken(convertToProtoFormat(this.containerToken));
}
}
private void mergeLocalToProto() {
if (viaProto)
maybeInitBuilder();
mergeLocalToBuilder();
proto = builder.build();
viaProto = true;
}
private void maybeInitBuilder() {
if (viaProto || builder == null) {
builder = StartContainerRequestProto.newBuilder(proto);
}
viaProto = false;
}
@Override
public ContainerLaunchContext getContainerLaunchContext() {
StartContainerRequestProtoOrBuilder p = viaProto ? proto : builder;
if (this.containerLaunchContext != null) {
return this.containerLaunchContext;
}
if (!p.hasContainerLaunchContext()) {
return null;
}
this.containerLaunchContext = convertFromProtoFormat(p.getContainerLaunchContext());
return this.containerLaunchContext;
}
@Override
public void setContainerLaunchContext(ContainerLaunchContext containerLaunchContext) {
maybeInitBuilder();
if (containerLaunchContext == null)
builder.clearContainerLaunchContext();
this.containerLaunchContext = containerLaunchContext;
}
@Override
public Token getContainerToken() {
StartContainerRequestProtoOrBuilder p = viaProto ? proto : builder;
if (this.containerToken != null) {
return this.containerToken;
}
if (!p.hasContainerToken()) {
return null;
}
this.containerToken = convertFromProtoFormat(p.getContainerToken());
return this.containerToken;
}
@Override
public void setContainerToken(Token containerToken) {
maybeInitBuilder();
if(containerToken == null) {
builder.clearContainerToken();
}
this.containerToken = containerToken;
}
private ContainerLaunchContextPBImpl convertFromProtoFormat(ContainerLaunchContextProto p) {
return new ContainerLaunchContextPBImpl(p);
}
private ContainerLaunchContextProto convertToProtoFormat(ContainerLaunchContext t) {
return ((ContainerLaunchContextPBImpl)t).getProto();
}
private TokenPBImpl convertFromProtoFormat(TokenProto containerProto) {
return new TokenPBImpl(containerProto);
}
private TokenProto convertToProtoFormat(Token container) {
return ((TokenPBImpl)container).getProto();
}
}
| StartContainerRequestPBImpl |
java | google__dagger | dagger-compiler/main/java/dagger/internal/codegen/writing/PrivateMethodRequestRepresentation.java | {
"start": 5187,
"end": 5390
} | interface ____ {
PrivateMethodRequestRepresentation create(
BindingRequest request,
ContributionBinding binding,
RequestRepresentation wrappedRequestRepresentation);
}
}
| Factory |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/common/AbstractAucRoc.java | {
"start": 8582,
"end": 10866
} | class ____ implements Comparable<AucRocPoint>, ToXContentObject, Writeable {
private static final String TPR = "tpr";
private static final String FPR = "fpr";
private static final String THRESHOLD = "threshold";
final double tpr;
final double fpr;
final double threshold;
public AucRocPoint(double tpr, double fpr, double threshold) {
this.tpr = tpr;
this.fpr = fpr;
this.threshold = threshold;
}
private AucRocPoint(StreamInput in) throws IOException {
this.tpr = in.readDouble();
this.fpr = in.readDouble();
this.threshold = in.readDouble();
}
@Override
public int compareTo(AucRocPoint o) {
return Comparator.comparingDouble((AucRocPoint p) -> p.threshold)
.reversed()
.thenComparing(p -> p.fpr)
.thenComparing(p -> p.tpr)
.compare(this, o);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeDouble(tpr);
out.writeDouble(fpr);
out.writeDouble(threshold);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(TPR, tpr);
builder.field(FPR, fpr);
builder.field(THRESHOLD, threshold);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AucRocPoint that = (AucRocPoint) o;
return tpr == that.tpr && fpr == that.fpr && threshold == that.threshold;
}
@Override
public int hashCode() {
return Objects.hash(tpr, fpr, threshold);
}
@Override
public String toString() {
return Strings.toString(this);
}
}
private static double interpolate(double x, double x1, double y1, double x2, double y2) {
return y1 + (x - x1) * (y2 - y1) / (x2 - x1);
}
public static | AucRocPoint |
java | apache__camel | core/camel-util/src/test/java/org/apache/camel/util/StringHelperTest.java | {
"start": 7393,
"end": 23186
} | class ____ {
@Test
void testDashToCamelCaseWithNull() {
assertThat(dashToCamelCase(null)).isNull();
}
@Test
void testDashToCamelCaseWithEmptyValue() {
assertThat(dashToCamelCase("")).isEmpty();
}
@Test
void testDashToCamelCaseWithNoDash() {
assertThat(dashToCamelCase("a")).isEqualTo("a");
}
@Test
void testDashToCamelCaseWithOneDash() {
assertThat(dashToCamelCase("a-b")).isEqualTo("aB");
}
@Test
void testDashToCamelCaseWithSeveralDashes() {
assertThat(dashToCamelCase("a-bb-cc-dd")).isEqualTo("aBbCcDd");
}
@Test
void testDashToCamelCaseWithEndDash() {
assertThat(dashToCamelCase("a-")).isEqualTo("a");
}
@Test
void testDashToCamelCaseWithEndDashes() {
assertThat(dashToCamelCase("a----")).isEqualTo("a");
}
@Test
void testDashToCamelCaseWithSeceralDashesGrouped() {
assertThat(dashToCamelCase("a--b")).isEqualTo("aB");
}
}
@Test
public void testSplitWords() {
String[] arr = splitWords("apiName/methodName");
assertEquals(2, arr.length);
assertEquals("apiName", arr[0]);
assertEquals("methodName", arr[1]);
arr = splitWords("hello");
assertEquals(1, arr.length);
assertEquals("hello", arr[0]);
}
@Test
public void testReplaceFirst() {
assertEquals("jms:queue:bar", replaceFirst("jms:queue:bar", "foo", "bar"));
assertEquals("jms:queue:bar", replaceFirst("jms:queue:foo", "foo", "bar"));
assertEquals("jms:queue:bar?blah=123", replaceFirst("jms:queue:foo?blah=123", "foo", "bar"));
assertEquals("jms:queue:bar?blah=foo", replaceFirst("jms:queue:foo?blah=foo", "foo", "bar"));
}
@Test
public void testRemoveLeadingAndEndingQuotes() {
assertEquals("abc", removeLeadingAndEndingQuotes("'abc'"));
assertEquals("abc", removeLeadingAndEndingQuotes("\"abc\""));
assertEquals("a'b'c", removeLeadingAndEndingQuotes("a'b'c"));
assertEquals("'b'c", removeLeadingAndEndingQuotes("'b'c"));
assertEquals("", removeLeadingAndEndingQuotes("''"));
assertEquals("'", removeLeadingAndEndingQuotes("'"));
}
@Test
public void testRemoveLeadingAndEndingQuotesWithSpaces() {
assertNull(StringHelper.removeLeadingAndEndingQuotes(null));
assertEquals(" ", StringHelper.removeLeadingAndEndingQuotes(" "));
assertEquals("Hello World", StringHelper.removeLeadingAndEndingQuotes("Hello World"));
assertEquals("Hello World", StringHelper.removeLeadingAndEndingQuotes("'Hello World'"));
assertEquals("Hello World", StringHelper.removeLeadingAndEndingQuotes("\"Hello World\""));
assertEquals("Hello 'Camel'", StringHelper.removeLeadingAndEndingQuotes("Hello 'Camel'"));
}
@Test
public void testSplitOnCharacterAsList() {
List<String> list = splitOnCharacterAsList("foo", ',', 1);
assertEquals(1, list.size());
assertEquals("foo", list.get(0));
list = splitOnCharacterAsList("foo,bar", ',', 2);
assertEquals(2, list.size());
assertEquals("foo", list.get(0));
assertEquals("bar", list.get(1));
list = splitOnCharacterAsList("foo,bar,", ',', 3);
assertEquals(2, list.size());
assertEquals("foo", list.get(0));
assertEquals("bar", list.get(1));
list = splitOnCharacterAsList(",foo,bar", ',', 3);
assertEquals(2, list.size());
assertEquals("foo", list.get(0));
assertEquals("bar", list.get(1));
list = splitOnCharacterAsList(",foo,bar,", ',', 4);
assertEquals(2, list.size());
assertEquals("foo", list.get(0));
assertEquals("bar", list.get(1));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append(i);
sb.append(",");
}
String value = sb.toString();
int count = StringHelper.countChar(value, ',') + 1;
list = splitOnCharacterAsList(value, ',', count);
assertEquals(100, list.size());
assertEquals("0", list.get(0));
assertEquals("50", list.get(50));
assertEquals("99", list.get(99));
}
@Test
public void testSplitOnCharacterAsIterator() {
Iterator<String> it = splitOnCharacterAsIterator("foo", ',', 1);
assertEquals("foo", it.next());
assertFalse(it.hasNext());
it = splitOnCharacterAsIterator("foo,bar", ',', 2);
assertEquals("foo", it.next());
assertEquals("bar", it.next());
assertFalse(it.hasNext());
it = splitOnCharacterAsIterator("foo,bar,", ',', 3);
assertEquals("foo", it.next());
assertEquals("bar", it.next());
assertFalse(it.hasNext());
it = splitOnCharacterAsIterator(",foo,bar", ',', 3);
assertEquals("foo", it.next());
assertEquals("bar", it.next());
assertFalse(it.hasNext());
it = splitOnCharacterAsIterator(",foo,bar,", ',', 4);
assertEquals("foo", it.next());
assertEquals("bar", it.next());
assertFalse(it.hasNext());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append(i);
sb.append(",");
}
String value = sb.toString();
int count = StringHelper.countChar(value, ',') + 1;
it = splitOnCharacterAsIterator(value, ',', count);
for (int i = 0; i < 100; i++) {
assertEquals(Integer.toString(i), it.next());
}
assertFalse(it.hasNext());
}
@Test
public void testPad() {
assertEquals(" ", StringHelper.padString(1));
assertEquals(" ", StringHelper.padString(2));
assertEquals(" ", StringHelper.padString(3));
assertEquals(" ", StringHelper.padString(3, 1));
assertEquals(" ", StringHelper.padString(1, 1));
assertEquals("", StringHelper.padString(0));
assertEquals("", StringHelper.padString(0, 2));
}
@Test
public void testFillChars() {
assertEquals("", StringHelper.fillChars('-', 0));
assertEquals("==", StringHelper.fillChars('=', 2));
assertEquals("----", StringHelper.fillChars('-', 4));
assertEquals("..........", StringHelper.fillChars('.', 10));
}
@Test
public void testSimpleSanitized() {
String out = StringHelper.sanitize("hello");
assertEquals(-1, out.indexOf(':'), "Should not contain : ");
assertEquals(-1, out.indexOf('.'), "Should not contain . ");
}
@Test
public void testNotFileFriendlySimpleSanitized() {
String out = StringHelper.sanitize("c:\\helloworld");
assertEquals(-1, out.indexOf(':'), "Should not contain : ");
assertEquals(-1, out.indexOf('.'), "Should not contain . ");
}
@Test
public void testSimpleCRLF() {
String out = StringHelper.removeCRLF("hello");
assertEquals("hello", out);
boolean b6 = !out.contains("\r");
assertTrue(b6, "Should not contain : ");
boolean b5 = !out.contains("\n");
assertTrue(b5, "Should not contain : ");
out = StringHelper.removeCRLF("hello\r\n");
assertEquals("hello", out);
boolean b4 = !out.contains("\r");
assertTrue(b4, "Should not contain : ");
boolean b3 = !out.contains("\n");
assertTrue(b3, "Should not contain : ");
out = StringHelper.removeCRLF("\r\nhe\r\nllo\n");
assertEquals("hello", out);
boolean b2 = !out.contains("\r");
assertTrue(b2, "Should not contain : ");
boolean b1 = !out.contains("\n");
assertTrue(b1, "Should not contain : ");
out = StringHelper.removeCRLF("hello" + System.lineSeparator());
assertEquals("hello", out);
boolean b = !out.contains(System.lineSeparator());
assertTrue(b, "Should not contain : ");
}
@Test
public void testCountChar() {
assertEquals(0, StringHelper.countChar("Hello World", 'x'));
assertEquals(1, StringHelper.countChar("Hello World", 'e'));
assertEquals(3, StringHelper.countChar("Hello World", 'l'));
assertEquals(1, StringHelper.countChar("Hello World", ' '));
assertEquals(0, StringHelper.countChar("", ' '));
assertEquals(0, StringHelper.countChar(null, ' '));
}
@Test
public void testRemoveQuotes() {
assertEquals("Hello World", StringHelper.removeQuotes("Hello World"));
assertEquals("", StringHelper.removeQuotes(""));
assertNull(StringHelper.removeQuotes(null));
assertEquals(" ", StringHelper.removeQuotes(" "));
assertEquals("foo", StringHelper.removeQuotes("'foo'"));
assertEquals("foo", StringHelper.removeQuotes("'foo"));
assertEquals("foo", StringHelper.removeQuotes("foo'"));
assertEquals("foo", StringHelper.removeQuotes("\"foo\""));
assertEquals("foo", StringHelper.removeQuotes("\"foo"));
assertEquals("foo", StringHelper.removeQuotes("foo\""));
assertEquals("foo", StringHelper.removeQuotes("'foo\""));
}
@Test
public void testHasUpper() {
assertFalse(StringHelper.hasUpperCase(null));
assertFalse(StringHelper.hasUpperCase(""));
assertFalse(StringHelper.hasUpperCase(" "));
assertFalse(StringHelper.hasUpperCase("com.foo"));
assertFalse(StringHelper.hasUpperCase("com.foo.123"));
assertTrue(StringHelper.hasUpperCase("com.foo.MyClass"));
assertTrue(StringHelper.hasUpperCase("com.foo.My"));
// Note, this is not a FQN
assertTrue(StringHelper.hasUpperCase("com.foo.subA"));
}
@Test
public void testIsClassName() {
assertFalse(StringHelper.isClassName(null));
assertFalse(StringHelper.isClassName(""));
assertFalse(StringHelper.isClassName(" "));
assertFalse(StringHelper.isClassName("com.foo"));
assertFalse(StringHelper.isClassName("com.foo.123"));
assertTrue(StringHelper.isClassName("com.foo.MyClass"));
assertTrue(StringHelper.isClassName("com.foo.My"));
// Note, this is not a FQN
assertFalse(StringHelper.isClassName("com.foo.subA"));
}
@Test
public void testHasStartToken() {
assertFalse(StringHelper.hasStartToken(null, null));
assertFalse(StringHelper.hasStartToken(null, "simple"));
assertFalse(StringHelper.hasStartToken("", null));
assertFalse(StringHelper.hasStartToken("", "simple"));
assertFalse(StringHelper.hasStartToken("Hello World", null));
assertFalse(StringHelper.hasStartToken("Hello World", "simple"));
assertFalse(StringHelper.hasStartToken("${body}", null));
assertTrue(StringHelper.hasStartToken("${body}", "simple"));
assertTrue(StringHelper.hasStartToken("$simple{body}", "simple"));
assertFalse(StringHelper.hasStartToken("${body}", null));
assertFalse(StringHelper.hasStartToken("${body}", "foo"));
// $foo{ is valid because its foo language
assertTrue(StringHelper.hasStartToken("$foo{body}", "foo"));
}
@Test
public void testIsQuoted() {
assertFalse(StringHelper.isQuoted(null));
assertFalse(StringHelper.isQuoted(""));
assertFalse(StringHelper.isQuoted(" "));
assertFalse(StringHelper.isQuoted("abc"));
assertFalse(StringHelper.isQuoted("abc'"));
assertFalse(StringHelper.isQuoted("\"abc'"));
assertFalse(StringHelper.isQuoted("abc\""));
assertFalse(StringHelper.isQuoted("'abc\""));
assertFalse(StringHelper.isQuoted("\"abc'"));
assertFalse(StringHelper.isQuoted("abc'def'"));
assertFalse(StringHelper.isQuoted("abc'def'ghi"));
assertFalse(StringHelper.isQuoted("'def'ghi"));
assertTrue(StringHelper.isQuoted("'abc'"));
assertTrue(StringHelper.isQuoted("\"abc\""));
}
@Test
public void testRemoveInitialCharacters() {
assertEquals("foo", StringHelper.removeStartingCharacters("foo", '/'));
assertEquals("foo", StringHelper.removeStartingCharacters("/foo", '/'));
assertEquals("foo", StringHelper.removeStartingCharacters("//foo", '/'));
}
@Test
public void testBefore() {
assertEquals("Hello ", StringHelper.before("Hello World", "World"));
assertEquals("Hello ", StringHelper.before("Hello World Again", "World"));
assertNull(StringHelper.before("Hello Again", "Foo"));
assertTrue(StringHelper.before("mykey:ignore", ":", "mykey"::equals).orElse(false));
assertFalse(StringHelper.before("ignore:ignore", ":", "mykey"::equals).orElse(false));
assertEquals("", StringHelper.before("Hello World", "Test", ""));
assertNull(StringHelper.before("Hello World", "Test", (String) null));
assertEquals("a:b", StringHelper.beforeLast("a:b:c", ":"));
assertEquals("", StringHelper.beforeLast("a:b:c", "_", ""));
}
@Test
public void testAfter() {
assertEquals(" World", StringHelper.after("Hello World", "Hello"));
assertEquals(" World Again", StringHelper.after("Hello World Again", "Hello"));
assertNull(StringHelper.after("Hello Again", "Foo"));
assertTrue(StringHelper.after("ignore:mykey", ":", "mykey"::equals).orElse(false));
assertFalse(StringHelper.after("ignore:ignore", ":", "mykey"::equals).orElse(false));
assertEquals("", StringHelper.after("Hello World", "Test", ""));
assertNull(StringHelper.after("Hello World", "Test", (String) null));
assertEquals("c", StringHelper.afterLast("a:b:c", ":"));
assertEquals("", StringHelper.afterLast("a:b:c", "_", ""));
}
@Test
public void testBetween() {
assertEquals("foo bar", StringHelper.between("Hello 'foo bar' how are you", "'", "'"));
assertEquals("foo bar", StringHelper.between("Hello ${foo bar} how are you", "${", "}"));
assertNull(StringHelper.between("Hello ${foo bar} how are you", "'", "'"));
assertTrue(StringHelper.between("begin:mykey:end", "begin:", ":end", "mykey"::equals).orElse(false));
assertFalse(StringHelper.between("begin:ignore:end", "begin:", ":end", "mykey"::equals).orElse(false));
}
@Test
public void testBetweenOuterPair() {
assertEquals("bar(baz)123", StringHelper.betweenOuterPair("foo(bar(baz)123)", '(', ')'));
assertNull(StringHelper.betweenOuterPair("foo(bar(baz)123))", '(', ')'));
assertNull(StringHelper.betweenOuterPair("foo(bar(baz123", '(', ')'));
assertNull(StringHelper.betweenOuterPair("foo)bar)baz123", '(', ')'));
assertEquals("bar", StringHelper.betweenOuterPair("foo(bar)baz123", '(', ')'));
assertEquals("'bar', 'baz()123', 123", StringHelper.betweenOuterPair("foo('bar', 'baz()123', 123)", '(', ')'));
assertTrue(StringHelper.betweenOuterPair("foo(bar)baz123", '(', ')', "bar"::equals).orElse(false));
assertFalse(StringHelper.betweenOuterPair("foo[bar)baz123", '(', ')', "bar"::equals).orElse(false));
}
@Test
public void testIsJavaIdentifier() {
assertTrue(StringHelper.isJavaIdentifier("foo"));
assertFalse(StringHelper.isJavaIdentifier("foo.bar"));
assertFalse(StringHelper.isJavaIdentifier(""));
assertFalse(StringHelper.isJavaIdentifier(null));
}
@Test
public void testNormalizeClassName() {
assertEquals("my.package-info", StringHelper.normalizeClassName("my.package-info"), "Should get the right | DashToCamelCase |
java | grpc__grpc-java | binder/src/main/java/io/grpc/binder/internal/LeakSafeOneWayBinder.java | {
"start": 1294,
"end": 1484
} | class ____ leaked.
* Once detached, this binder returns false from any future transactions (and pings).
*
* <p>Since two-way transactions block the calling thread on a remote process, this | is |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java | {
"start": 2653,
"end": 2719
} | class ____ {
}
@ConditionalOnProperty("b")
static | HasPropertyA |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/unidirectional/OneToOneEagerDerivedIdFetchModeSelectTest.java | {
"start": 1147,
"end": 3121
} | class ____ {
private Foo foo;
@Test
@JiraKey(value = "HHH-14390")
public void testQuery(SessionFactoryScope scope) {
scope.inTransaction( session -> {
Bar newBar = (Bar) session.createQuery( "SELECT b FROM Bar b WHERE b.foo.id = :id" )
.setParameter( "id", foo.getId() )
.uniqueResult();
assertNotNull( newBar );
assertNotNull( newBar.getFoo() );
assertEquals( foo.getId(), newBar.getFoo().getId() );
assertEquals( "Some details", newBar.getDetails() );
} );
}
@Test
@JiraKey(value = "HHH-14390")
public void testQueryById(SessionFactoryScope scope) {
scope.inTransaction( session -> {
Bar newBar = (Bar) session.createQuery( "SELECT b FROM Bar b WHERE b.foo = :foo" )
.setParameter( "foo", foo )
.uniqueResult();
assertNotNull( newBar );
assertNotNull( newBar.getFoo() );
assertEquals( foo.getId(), newBar.getFoo().getId() );
assertEquals( "Some details", newBar.getDetails() );
} );
}
@Test
@JiraKey(value = "HHH-14390")
public void testFindByPrimaryKey(SessionFactoryScope scope) {
scope.inTransaction( session -> {
Bar newBar = session.find( Bar.class, foo.getId() );
assertNotNull( newBar );
assertNotNull( newBar.getFoo() );
assertEquals( foo.getId(), newBar.getFoo().getId() );
assertEquals( "Some details", newBar.getDetails() );
} );
}
@BeforeEach
public void setupData(SessionFactoryScope scope) {
this.foo = scope.fromTransaction( session -> {
Foo foo = new Foo();
session.persist( foo );
Bar bar = new Bar();
bar.setFoo( foo );
bar.setDetails( "Some details" );
session.persist( bar );
session.flush();
assertNotNull( foo.getId() );
assertEquals( foo.getId(), bar.getFoo().getId() );
return foo;
} );
}
@AfterEach
public void cleanupData(SessionFactoryScope scope) {
this.foo = null;
scope.getSessionFactory().getSchemaManager().truncate();
}
@Entity(name = "Foo")
public static | OneToOneEagerDerivedIdFetchModeSelectTest |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/origin/JarUriTests.java | {
"start": 827,
"end": 2077
} | class ____ {
@Test
void describeBootInfClassesUri() {
JarUri uri = JarUri.from("jar:file:/home/user/project/target/project-0.0.1-SNAPSHOT.jar"
+ "!/BOOT-INF/classes!/application.properties");
assertThat(uri).isNotNull();
assertThat(uri.getDescription()).isEqualTo("project-0.0.1-SNAPSHOT.jar");
}
@Test
void describeBootInfLibUri() {
JarUri uri = JarUri.from("jar:file:/home/user/project/target/project-0.0.1-SNAPSHOT.jar"
+ "!/BOOT-INF/lib/nested.jar!/application.properties");
assertThat(uri).isNotNull();
assertThat(uri.getDescription()).isEqualTo("project-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/nested.jar");
}
@Test
void describeRegularJar() {
JarUri uri = JarUri
.from("jar:file:/home/user/project/target/project-0.0.1-SNAPSHOT.jar!/application.properties");
assertThat(uri).isNotNull();
assertThat(uri.getDescription()).isEqualTo("project-0.0.1-SNAPSHOT.jar");
}
@Test
void getDescriptionMergedWithExisting() {
JarUri uri = JarUri.from("jar:file:/project-0.0.1-SNAPSHOT.jar!/application.properties");
assertThat(uri).isNotNull();
assertThat(uri.getDescription("classpath: [application.properties]"))
.isEqualTo("classpath: [application.properties] from project-0.0.1-SNAPSHOT.jar");
}
}
| JarUriTests |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/search/action/AsyncSearchResponse.java | {
"start": 1358,
"end": 9762
} | class ____ extends ActionResponse implements ChunkedToXContentObject, AsyncResponse<AsyncSearchResponse> {
@Nullable
private final String id;
@Nullable
private final SearchResponse searchResponse;
@Nullable
private final Exception error;
private final boolean isRunning;
private final boolean isPartial;
private final long startTimeMillis;
private final long expirationTimeMillis;
private final RefCounted refCounted = LeakTracker.wrap(new AbstractRefCounted() {
@Override
protected void closeInternal() {
if (searchResponse != null) {
searchResponse.decRef();
}
}
});
/**
* Creates an {@link AsyncSearchResponse} with meta-information only (not-modified).
*/
public AsyncSearchResponse(String id, boolean isPartial, boolean isRunning, long startTimeMillis, long expirationTimeMillis) {
this(id, null, null, isPartial, isRunning, startTimeMillis, expirationTimeMillis);
}
/**
* Creates a new {@link AsyncSearchResponse}
*
* @param id The id of the search for further retrieval, <code>null</code> if not stored.
* @param searchResponse The actual search response.
* @param error The error if the search failed, <code>null</code> if the search is running
* or has completed without failure.
* @param isPartial Whether the <code>searchResponse</code> contains partial results.
* @param isRunning Whether the search is running in the cluster.
* @param startTimeMillis The start date of the search in milliseconds since epoch.
*/
public AsyncSearchResponse(
String id,
SearchResponse searchResponse,
Exception error,
boolean isPartial,
boolean isRunning,
long startTimeMillis,
long expirationTimeMillis
) {
this.id = id;
this.error = error;
if (searchResponse != null) {
searchResponse.mustIncRef();
}
this.searchResponse = searchResponse;
this.isPartial = isPartial;
this.isRunning = isRunning;
this.startTimeMillis = startTimeMillis;
this.expirationTimeMillis = expirationTimeMillis;
}
public AsyncSearchResponse(StreamInput in) throws IOException {
this.id = in.readOptionalString();
this.error = in.readBoolean() ? in.readException() : null;
this.searchResponse = in.readOptionalWriteable(SearchResponse::new);
this.isPartial = in.readBoolean();
this.isRunning = in.readBoolean();
this.startTimeMillis = in.readLong();
this.expirationTimeMillis = in.readLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeOptionalString(id);
if (error != null) {
out.writeBoolean(true);
out.writeException(error);
} else {
out.writeBoolean(false);
}
out.writeOptionalWriteable(searchResponse);
out.writeBoolean(isPartial);
out.writeBoolean(isRunning);
out.writeLong(startTimeMillis);
out.writeLong(expirationTimeMillis);
}
@Override
public void incRef() {
refCounted.incRef();
}
@Override
public boolean tryIncRef() {
return refCounted.tryIncRef();
}
@Override
public boolean decRef() {
return refCounted.decRef();
}
@Override
public boolean hasReferences() {
return refCounted.hasReferences();
}
public AsyncSearchResponse clone(String searchId) {
return new AsyncSearchResponse(searchId, searchResponse, error, isPartial, isRunning, startTimeMillis, expirationTimeMillis);
}
/**
* Returns the id of the async search request or null if the response is not stored in the cluster.
*/
@Nullable
public String getId() {
return id;
}
/**
* Returns the current {@link SearchResponse} or <code>null</code> if not available.
*
* See {@link #isPartial()} to determine whether the response contains partial or complete
* results.
*/
public SearchResponse getSearchResponse() {
return searchResponse;
}
/**
* Returns the failure reason or null if the query is running or has completed normally.
*/
public Exception getFailure() {
return error;
}
/**
* Returns <code>true</code> if the {@link SearchResponse} contains partial
* results computed from a subset of the total shards.
*/
public boolean isPartial() {
return isPartial;
}
/**
* Whether the search is still running in the cluster.
*
* A value of <code>false</code> indicates that the response is final
* even if {@link #isPartial()} returns <code>true</code>. In such case,
* the partial response represents the status of the search before a
* non-recoverable failure.
*/
public boolean isRunning() {
return isRunning;
}
/**
* When this response was created as a timestamp in milliseconds since epoch.
*/
public long getStartTime() {
return startTimeMillis;
}
/**
* When this response will expired as a timestamp in milliseconds since epoch.
*/
@Override
public long getExpirationTime() {
return expirationTimeMillis;
}
/**
* @return completion time in millis if the search is finished running.
* Otherwise it will return null;
*/
public Long getCompletionTime() {
if (searchResponse == null || isRunning) {
return null;
} else {
return getStartTime() + searchResponse.getTook().millis();
}
}
@Override
public AsyncSearchResponse withExpirationTime(long expirationTime) {
return new AsyncSearchResponse(id, searchResponse, error, isPartial, isRunning, startTimeMillis, expirationTime);
}
public RestStatus status() {
if (searchResponse == null || isPartial) {
// shard failures are not considered fatal for partial results so
// we return OK until we get the final response even if we don't have
// a single successful shard.
return error != null ? ExceptionsHelper.status(ExceptionsHelper.unwrapCause(error)) : OK;
} else {
return searchResponse.status();
}
}
@Override
public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params params) {
return Iterators.concat(ChunkedToXContentHelper.chunk((builder, p) -> {
builder.startObject();
if (id != null) {
builder.field("id", id);
}
builder.field("is_partial", isPartial);
builder.field("is_running", isRunning);
builder.timestampFieldsFromUnixEpochMillis("start_time_in_millis", "start_time", startTimeMillis);
builder.timestampFieldsFromUnixEpochMillis("expiration_time_in_millis", "expiration_time", expirationTimeMillis);
if (searchResponse != null) {
if (isRunning == false) {
TimeValue took = searchResponse.getTook();
builder.timestampFieldsFromUnixEpochMillis(
"completion_time_in_millis",
"completion_time",
startTimeMillis + took.millis()
);
}
builder.field("response");
}
return builder;
}),
searchResponse == null ? Collections.emptyIterator() : searchResponse.toXContentChunked(params),
ChunkedToXContentHelper.chunk((builder, p) -> {
if (error != null) {
builder.startObject("error");
ElasticsearchException.generateThrowableXContent(builder, params, error);
builder.endObject();
}
builder.endObject();
return builder;
})
);
}
@Override
public AsyncSearchResponse convertToFailure(Exception exc) {
exc.setStackTrace(new StackTraceElement[0]); // we don't need to store stack traces
return new AsyncSearchResponse(id, null, exc, isPartial, false, startTimeMillis, expirationTimeMillis);
}
}
| AsyncSearchResponse |
java | dropwizard__dropwizard | dropwizard-util/src/main/java/io/dropwizard/util/Generics.java | {
"start": 262,
"end": 394
} | class ____ parameters.
* @see <a href="http://gafter.blogspot.com/2006/12/super-type-tokens.html">Super Type Tokens</a>
*/
public | type |
java | google__guava | android/guava/src/com/google/common/util/concurrent/MoreExecutors.java | {
"start": 11058,
"end": 12882
} | class ____ {
final ExecutorService getExitingExecutorService(
ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
useDaemonThreadFactory(executor);
ExecutorService service = unconfigurableExecutorService(executor);
addDelayedShutdownHook(executor, terminationTimeout, timeUnit);
return service;
}
final ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) {
return getExitingExecutorService(executor, 120, TimeUnit.SECONDS);
}
final ScheduledExecutorService getExitingScheduledExecutorService(
ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
useDaemonThreadFactory(executor);
ScheduledExecutorService service = unconfigurableScheduledExecutorService(executor);
addDelayedShutdownHook(executor, terminationTimeout, timeUnit);
return service;
}
final ScheduledExecutorService getExitingScheduledExecutorService(
ScheduledThreadPoolExecutor executor) {
return getExitingScheduledExecutorService(executor, 120, TimeUnit.SECONDS);
}
final void addDelayedShutdownHook(
ExecutorService service, long terminationTimeout, TimeUnit timeUnit) {
checkNotNull(service);
checkNotNull(timeUnit);
addShutdownHook(
newThread(
"DelayedShutdownHook-for-" + service,
() -> {
service.shutdown();
try {
// We'd like to log progress and failures that may arise in the
// following code, but unfortunately the behavior of logging
// is undefined in shutdown hooks.
// This is because the logging code installs a shutdown hook of its
// own. See Cleaner | Application |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/cfg/MapperConfigBase.java | {
"start": 15878,
"end": 25397
} | class ____ (or custom scheme).
*/
@Override
public final SubtypeResolver getSubtypeResolver() {
return _subtypeResolver;
}
@Override
public final JavaType constructType(Class<?> cls) {
return _typeFactory.constructType(cls);
}
@Override
public final JavaType constructType(TypeReference<?> valueTypeRef) {
return _typeFactory.constructType(valueTypeRef.getType());
}
/*
/**********************************************************************
/* Simple Feature access
/**********************************************************************
*/
@Override
public final boolean isEnabled(DatatypeFeature feature) {
return _datatypeFeatures.isEnabled(feature);
}
@Override
public final DatatypeFeatures getDatatypeFeatures() {
return _datatypeFeatures;
}
/*
/**********************************************************************
/* Simple config property access
/**********************************************************************
*/
public final PropertyName getFullRootName() {
return _rootName;
}
@Override
public final Class<?> getActiveView() {
return _view;
}
@Override
public final ContextAttributes getAttributes() {
return _attributes;
}
/*
/**********************************************************************
/* Configuration access; default/overrides
/**********************************************************************
*/
@Override
public final ConfigOverride getConfigOverride(Class<?> type) {
ConfigOverride override = _configOverrides.findOverride(type);
return (override == null) ? EMPTY_OVERRIDE : override;
}
@Override
public final ConfigOverride findConfigOverride(Class<?> type) {
return _configOverrides.findOverride(type);
}
@Override
public final JsonInclude.Value getDefaultPropertyInclusion() {
return _configOverrides.getDefaultInclusion();
}
@Override
public final JsonInclude.Value getDefaultPropertyInclusion(Class<?> baseType) {
JsonInclude.Value v = getConfigOverride(baseType).getInclude();
JsonInclude.Value def = getDefaultPropertyInclusion();
if (def == null) {
return v;
}
return def.withOverrides(v);
}
@Override
public final JsonInclude.Value getDefaultInclusion(Class<?> baseType,
Class<?> propertyType) {
JsonInclude.Value v = getConfigOverride(propertyType).getIncludeAsProperty();
JsonInclude.Value def = getDefaultPropertyInclusion(baseType);
if (def == null) {
return v;
}
return def.withOverrides(v);
}
@Override
public final JsonFormat.Value getDefaultPropertyFormat(Class<?> type) {
return _configOverrides.findFormatDefaults(type);
}
@Override
public final JsonIgnoreProperties.Value getDefaultPropertyIgnorals(Class<?> type) {
ConfigOverride overrides = _configOverrides.findOverride(type);
if (overrides != null) {
JsonIgnoreProperties.Value v = overrides.getIgnorals();
if (v != null) {
return v;
}
}
// 01-May-2015, tatu: Could return `Value.empty()` but for now `null`
// seems simpler as callers can avoid processing.
return null;
}
@Override
public final JsonIgnoreProperties.Value getDefaultPropertyIgnorals(Class<?> baseType,
AnnotatedClass actualClass)
{
AnnotationIntrospector intr = getAnnotationIntrospector();
JsonIgnoreProperties.Value base = (intr == null) ? null
: intr.findPropertyIgnoralByName(this, actualClass);
JsonIgnoreProperties.Value overrides = getDefaultPropertyIgnorals(baseType);
return JsonIgnoreProperties.Value.merge(base, overrides);
}
@Override
public final JsonIncludeProperties.Value getDefaultPropertyInclusions(Class<?> baseType,
AnnotatedClass actualClass)
{
AnnotationIntrospector intr = getAnnotationIntrospector();
return (intr == null) ? null : intr.findPropertyInclusionByName(this, actualClass);
}
@Override
public final VisibilityChecker getDefaultVisibilityChecker()
{
return _configOverrides.getDefaultVisibility();
}
@Override
public final VisibilityChecker getDefaultVisibilityChecker(Class<?> baseType,
AnnotatedClass actualClass)
{
// 14-Apr-2021, tatu: [databind#3117] JDK types should be limited
// to "public-only" regardless of settings for other types
VisibilityChecker vc;
if (ClassUtil.isJDKClass(baseType)) {
vc = VisibilityChecker.allPublicInstance();
} else if (ClassUtil.isRecordType(baseType)) {
// 15-Jan-2023, tatu: [databind#3724] Records require slightly different defaults
vc = _configOverrides.getDefaultRecordVisibility();
} else {
vc = getDefaultVisibilityChecker();
}
AnnotationIntrospector intr = getAnnotationIntrospector();
if (intr != null) {
vc = intr.findAutoDetectVisibility(this, actualClass, vc);
}
ConfigOverride overrides = _configOverrides.findOverride(baseType);
if (overrides != null) {
vc = vc.withOverrides(overrides.getVisibility()); // ok to pass null
}
return vc;
}
@Override
public final JsonSetter.Value getDefaultNullHandling() {
return _configOverrides.getDefaultNullHandling();
}
@Override
public Boolean getDefaultMergeable() {
return _configOverrides.getDefaultMergeable();
}
@Override
public Boolean getDefaultMergeable(Class<?> baseType) {
Boolean b;
ConfigOverride cfg = _configOverrides.findOverride(baseType);
if (cfg != null) {
b = cfg.getMergeable();
if (b != null) {
return b;
}
}
return _configOverrides.getDefaultMergeable();
}
/*
/**********************************************************************
/* Other config access
/**********************************************************************
*/
@Override
public PropertyName findRootName(DatabindContext ctxt, JavaType rootType) {
if (_rootName != null) {
return _rootName;
}
return _rootNames.findRootName(ctxt, rootType);
}
@Override
public PropertyName findRootName(DatabindContext ctxt, Class<?> rawRootType) {
if (_rootName != null) {
return _rootName;
}
return _rootNames.findRootName(ctxt, rawRootType);
}
/*
/**********************************************************************
/* MixInResolver impl:
/**********************************************************************
*/
/**
* Method that will check if there are "mix-in" classes (with mix-in
* annotations) for given class
*/
@Override
public final Class<?> findMixInClassFor(Class<?> cls) {
return _mixIns.findMixInClassFor(cls);
}
@Override
public boolean hasMixIns() {
return _mixIns.hasMixIns();
}
// Not really relevant here (should not get called)
@Override
public MixInResolver snapshot() {
throw new UnsupportedOperationException();
}
/**
* Test-only method -- does not reflect possibly open-ended set that external
* mix-in resolver might provide.
*/
public final int mixInCount() {
return _mixIns.localSize();
}
/*
/**********************************************************************
/* Helper methods for implementations
/**********************************************************************
*/
@SuppressWarnings("unchecked")
protected Converter<Object,Object> _createConverter(Annotated annotated,
Object converterDef)
{
if (converterDef == null) {
return null;
}
if (converterDef instanceof Converter<?,?>) {
return (Converter<Object,Object>) converterDef;
}
if (!(converterDef instanceof Class)) {
throw new IllegalStateException("`AnnotationIntrospector` returned `Converter` definition of type "
+ClassUtil.classNameOf(converterDef)+"; expected type `Converter` or `Class<Converter>` instead");
}
Class<?> converterClass = (Class<?>)converterDef;
// there are some known "no class" markers to consider too:
if (converterClass == Converter.None.class || ClassUtil.isBogusClass(converterClass)) {
return null;
}
if (!Converter.class.isAssignableFrom(converterClass)) {
throw new IllegalStateException("AnnotationIntrospector returned `Class<"
+ClassUtil.classNameOf(converterClass)+"`>; expected `Class<Converter>`");
}
HandlerInstantiator hi = getHandlerInstantiator();
Converter<?,?> conv = (hi == null) ? null : hi.converterInstance(this, annotated, converterClass);
if (conv == null) {
conv = (Converter<?,?>) ClassUtil.createInstance(converterClass,
canOverrideAccessModifiers());
}
return (Converter<Object,Object>) conv;
}
}
| name |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/ast/MemberElement.java | {
"start": 1121,
"end": 1558
} | interface ____ extends Element {
/**
* @return The declaring type of the element.
*/
ClassElement getDeclaringType();
/**
* The owing type is the type that owns this element. This can differ from {@link #getDeclaringType()}
* in the case of inheritance since this method will return the subclass that owners the inherited member,
* whilst {@link #getDeclaringType()} will return the super | MemberElement |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/starrocks/ast/StarRocksObject.java | {
"start": 234,
"end": 509
} | interface ____ extends SQLObject {
void accept0(StarRocksASTVisitor v);
@Override
default void accept(SQLASTVisitor visitor) {
if (visitor instanceof StarRocksASTVisitor) {
accept0((StarRocksASTVisitor) visitor);
}
}
}
| StarRocksObject |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/output/GeoCoordinatesListOutputUnitTests.java | {
"start": 356,
"end": 940
} | class ____ {
private GeoCoordinatesListOutput<?, ?> sut = new GeoCoordinatesListOutput<>(StringCodec.UTF8);
@Test
void setIntegerShouldFail() {
assertThatThrownBy(() -> sut.set(123L)).isInstanceOf(UnsupportedOperationException.class);
}
@Test
void commandOutputCorrectlyDecoded() {
sut.multi(2);
sut.set(ByteBuffer.wrap("1.234".getBytes()));
sut.set(ByteBuffer.wrap("4.567".getBytes()));
sut.multi(-1);
assertThat(sut.get()).contains(new GeoCoordinates(1.234, 4.567));
}
}
| GeoCoordinatesListOutputUnitTests |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/support/DirtiesContextTestExecutionListenerTests.java | {
"start": 17817,
"end": 17917
} | class ____ {
void test() {
}
}
@NestedTestConfiguration(INHERIT)
| ConfigOverriddenByDefault |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/GenericTypeResolverTests.java | {
"start": 10743,
"end": 10811
} | class ____<T> implements MyInterfaceType<T> {
}
public | MyAbstractType |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/masterslave/MasterSlaveIntegrationTests.java | {
"start": 1069,
"end": 5953
} | class ____ extends AbstractRedisClientTest {
private RedisURI upstreamURI = RedisURI.Builder.redis(host, TestSettings.port(3)).withPassword(passwd)
.withClientName("my-client").withDatabase(5).build();
private StatefulRedisMasterSlaveConnection<String, String> connection;
private RedisURI upstream;
private RedisURI replica;
private RedisCommands<String, String> connection1;
private RedisCommands<String, String> connection2;
@BeforeEach
void before() throws Exception {
RedisURI node1 = RedisURI.Builder.redis(host, TestSettings.port(3)).withDatabase(2).build();
RedisURI node2 = RedisURI.Builder.redis(host, TestSettings.port(4)).withDatabase(2).build();
this.connection1 = client.connect(node1).sync();
this.connection2 = client.connect(node2).sync();
RedisInstance node1Instance = RoleParser.parse(this.connection1.role());
RedisInstance node2Instance = RoleParser.parse(this.connection2.role());
if (node1Instance.getRole().isUpstream() && node2Instance.getRole().isReplica()) {
upstream = node1;
replica = node2;
} else if (node2Instance.getRole().isUpstream() && node1Instance.getRole().isReplica()) {
upstream = node2;
replica = node1;
} else {
assumeTrue(false,
String.format("Cannot run the test because I don't have a distinct master and replica but %s and %s",
node1Instance, node2Instance));
}
WithPassword.enableAuthentication(this.connection1);
this.connection1.auth(passwd);
this.connection1.configSet("masterauth", passwd.toString());
WithPassword.enableAuthentication(this.connection2);
this.connection2.auth(passwd);
this.connection2.configSet("masterauth", passwd.toString());
connection = MasterSlave.connect(client, StringCodec.UTF8, upstreamURI);
connection.setReadFrom(ReadFrom.REPLICA);
}
@AfterEach
void after() {
if (connection1 != null) {
WithPassword.disableAuthentication(connection1);
connection1.configRewrite();
connection1.getStatefulConnection().close();
}
if (connection2 != null) {
WithPassword.disableAuthentication(connection2);
connection2.configRewrite();
connection2.getStatefulConnection().close();
}
if (connection != null) {
connection.close();
}
}
@Test
void testMasterSlaveReadFromMaster() {
connection.setReadFrom(ReadFrom.UPSTREAM);
String server = connection.sync().info("server");
Pattern pattern = Pattern.compile("tcp_port:(\\d+)");
Matcher matcher = pattern.matcher(server);
assertThat(matcher.find()).isTrue();
assertThat(matcher.group(1)).isEqualTo("" + upstream.getPort());
}
@Test
void testMasterSlaveReadFromSlave() {
String server = connection.sync().info("server");
Pattern pattern = Pattern.compile("tcp_port:(\\d+)");
Matcher matcher = pattern.matcher(server);
assertThat(matcher.find()).isTrue();
assertThat(matcher.group(1)).isEqualTo("" + replica.getPort());
assertThat(connection.getReadFrom()).isEqualTo(ReadFrom.REPLICA);
}
@Test
void testMasterSlaveReadWrite() {
RedisCommands<String, String> redisCommands = connection.sync();
redisCommands.set(key, value);
redisCommands.waitForReplication(1, 100);
assertThat(redisCommands.get(key)).isEqualTo(value);
}
@Test
void testConnectToSlave() {
connection.close();
RedisURI slaveUri = RedisURI.Builder.redis(host, TestSettings.port(4)).withPassword(passwd).build();
connection = MasterSlave.connect(client, StringCodec.UTF8, slaveUri);
RedisCommands<String, String> sync = connection.sync();
sync.set(key, value);
}
@Test
void noSlaveForRead() {
connection.setReadFrom(new ReadFrom() {
@Override
public List<RedisNodeDescription> select(Nodes nodes) {
return Collections.emptyList();
}
});
assertThatThrownBy(() -> slaveCall(connection)).isInstanceOf(RedisException.class);
}
@Test
void masterSlaveConnectionShouldSetClientName() {
assertThat(connection.sync().clientGetname()).isEqualTo(upstreamURI.getClientName());
connection.sync().quit();
assertThat(connection.sync().clientGetname()).isEqualTo(upstreamURI.getClientName());
connection.close();
}
static String slaveCall(StatefulRedisMasterReplicaConnection<String, String> connection) {
return connection.sync().info("replication");
}
}
| MasterSlaveIntegrationTests |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/search/DfsQueryPhase.java | {
"start": 2389,
"end": 13372
} | class ____ extends SearchPhase {
public static final String NAME = "dfs_query";
private final SearchPhaseResults<SearchPhaseResult> queryResult;
private final Client client;
private final AbstractSearchAsyncAction<?> context;
private final SearchProgressListener progressListener;
private long phaseStartTimeInNanos;
DfsQueryPhase(SearchPhaseResults<SearchPhaseResult> queryResult, Client client, AbstractSearchAsyncAction<?> context) {
super(NAME);
this.progressListener = context.getTask().getProgressListener();
this.queryResult = queryResult;
this.client = client;
this.context = context;
}
// protected for testing
protected SearchPhase nextPhase(AggregatedDfs dfs) {
return SearchQueryThenFetchAsyncAction.nextPhase(client, context, queryResult, dfs);
}
@SuppressWarnings("unchecked")
@Override
protected void run() {
phaseStartTimeInNanos = System.nanoTime();
List<DfsSearchResult> searchResults = (List<DfsSearchResult>) context.results.getAtomicArray().asList();
AggregatedDfs dfs = aggregateDfs(searchResults);
// TODO we can potentially also consume the actual per shard results from the initial phase here in the aggregateDfs
// to free up memory early
final CountedCollector<SearchPhaseResult> counter = new CountedCollector<>(
queryResult,
searchResults.size(),
() -> onFinish(dfs),
context
);
List<DfsKnnResults> knnResults = mergeKnnResults(context.getRequest(), searchResults);
for (final DfsSearchResult dfsResult : searchResults) {
final SearchShardTarget shardTarget = dfsResult.getSearchShardTarget();
final int shardIndex = dfsResult.getShardIndex();
QuerySearchRequest querySearchRequest = new QuerySearchRequest(
context.getOriginalIndices(shardIndex),
dfsResult.getContextId(),
rewriteShardSearchRequest(knnResults, dfsResult.getShardSearchRequest()),
dfs
);
final Transport.Connection connection;
try {
connection = context.getConnection(shardTarget.getClusterAlias(), shardTarget.getNodeId());
} catch (Exception e) {
shardFailure(e, querySearchRequest, shardIndex, shardTarget, counter);
continue;
}
context.getSearchTransport()
.sendExecuteQuery(connection, querySearchRequest, context.getTask(), new SearchActionListener<>(shardTarget, shardIndex) {
@Override
protected void innerOnResponse(QuerySearchResult response) {
try {
response.setSearchProfileDfsPhaseResult(dfsResult.searchProfileDfsPhaseResult());
counter.onResult(response);
} catch (Exception e) {
context.onPhaseFailure(NAME, "", e);
}
}
@Override
public void onFailure(Exception exception) {
try {
shardFailure(exception, querySearchRequest, shardIndex, shardTarget, counter);
} finally {
if (context.isPartOfPointInTime(querySearchRequest.contextId()) == false) {
// the query might not have been executed at all (for example because thread pool rejected
// execution) and the search context that was created in dfs phase might not be released.
// release it again to be in the safe side
context.sendReleaseSearchContext(querySearchRequest.contextId(), connection);
}
}
}
});
}
}
private void onFinish(AggregatedDfs dfs) {
context.getSearchResponseMetrics()
.recordSearchPhaseDuration(getName(), System.nanoTime() - phaseStartTimeInNanos, context.getSearchRequestAttributes());
context.executeNextPhase(NAME, () -> nextPhase(dfs));
}
private void shardFailure(
Exception exception,
QuerySearchRequest querySearchRequest,
int shardIndex,
SearchShardTarget shardTarget,
CountedCollector<SearchPhaseResult> counter
) {
context.getLogger().debug(() -> "[" + querySearchRequest.contextId() + "] Failed to execute query phase", exception);
progressListener.notifyQueryFailure(shardIndex, shardTarget, exception);
counter.onFailure(shardIndex, shardTarget, exception);
}
// package private for testing
ShardSearchRequest rewriteShardSearchRequest(List<DfsKnnResults> knnResults, ShardSearchRequest request) {
SearchSourceBuilder source = request.source();
if (source == null || source.knnSearch().isEmpty()) {
return request;
}
List<SubSearchSourceBuilder> subSearchSourceBuilders = new ArrayList<>(source.subSearches());
int i = 0;
for (DfsKnnResults dfsKnnResults : knnResults) {
List<ScoreDoc> scoreDocs = new ArrayList<>();
for (ScoreDoc scoreDoc : dfsKnnResults.scoreDocs()) {
if (scoreDoc.shardIndex == request.shardRequestIndex()) {
scoreDocs.add(scoreDoc);
}
}
scoreDocs.sort(Comparator.comparingInt(scoreDoc -> scoreDoc.doc));
String nestedPath = dfsKnnResults.getNestedPath();
QueryBuilder query = new KnnScoreDocQueryBuilder(
scoreDocs.toArray(Lucene.EMPTY_SCORE_DOCS),
source.knnSearch().get(i).getField(),
source.knnSearch().get(i).getQueryVector(),
source.knnSearch().get(i).getSimilarity(),
source.knnSearch().get(i).getFilterQueries()
).boost(source.knnSearch().get(i).boost()).queryName(source.knnSearch().get(i).queryName());
if (nestedPath != null) {
query = new NestedQueryBuilder(nestedPath, query, ScoreMode.Max).innerHit(source.knnSearch().get(i).innerHit());
}
subSearchSourceBuilders.add(new SubSearchSourceBuilder(query));
i++;
}
source = source.shallowCopy().subSearches(subSearchSourceBuilders).knnSearch(List.of());
request.source(source);
return request;
}
private static List<DfsKnnResults> mergeKnnResults(SearchRequest request, List<DfsSearchResult> dfsSearchResults) {
if (request.hasKnnSearch() == false) {
return null;
}
SearchSourceBuilder source = request.source();
List<List<TopDocs>> topDocsLists = new ArrayList<>(source.knnSearch().size());
List<SetOnce<String>> nestedPath = new ArrayList<>(source.knnSearch().size());
for (int i = 0; i < source.knnSearch().size(); i++) {
topDocsLists.add(new ArrayList<>());
nestedPath.add(new SetOnce<>());
}
for (DfsSearchResult dfsSearchResult : dfsSearchResults) {
if (dfsSearchResult.knnResults() != null) {
for (int i = 0; i < dfsSearchResult.knnResults().size(); i++) {
DfsKnnResults knnResults = dfsSearchResult.knnResults().get(i);
ScoreDoc[] scoreDocs = knnResults.scoreDocs();
TotalHits totalHits = new TotalHits(scoreDocs.length, TotalHits.Relation.EQUAL_TO);
TopDocs shardTopDocs = new TopDocs(totalHits, scoreDocs);
SearchPhaseController.setShardIndex(shardTopDocs, dfsSearchResult.getShardIndex());
topDocsLists.get(i).add(shardTopDocs);
nestedPath.get(i).trySet(knnResults.getNestedPath());
}
}
}
List<DfsKnnResults> mergedResults = new ArrayList<>(source.knnSearch().size());
for (int i = 0; i < source.knnSearch().size(); i++) {
TopDocs mergedTopDocs = TopDocs.merge(source.knnSearch().get(i).k(), topDocsLists.get(i).toArray(new TopDocs[0]));
mergedResults.add(new DfsKnnResults(nestedPath.get(i).get(), mergedTopDocs.scoreDocs));
}
return mergedResults;
}
private static AggregatedDfs aggregateDfs(Collection<DfsSearchResult> results) {
Map<Term, TermStatistics> termStatistics = new HashMap<>();
Map<String, CollectionStatistics> fieldStatistics = new HashMap<>();
long aggMaxDoc = 0;
for (DfsSearchResult lEntry : results) {
final Term[] terms = lEntry.terms();
final TermStatistics[] stats = lEntry.termStatistics();
assert terms.length == stats.length;
for (int i = 0; i < terms.length; i++) {
assert terms[i] != null;
if (stats[i] == null) {
continue;
}
TermStatistics existing = termStatistics.get(terms[i]);
if (existing != null) {
assert terms[i].bytes().equals(existing.term());
termStatistics.put(
terms[i],
new TermStatistics(
existing.term(),
existing.docFreq() + stats[i].docFreq(),
existing.totalTermFreq() + stats[i].totalTermFreq()
)
);
} else {
termStatistics.put(terms[i], stats[i]);
}
}
assert lEntry.fieldStatistics().containsKey(null) == false;
for (var entry : lEntry.fieldStatistics().entrySet()) {
String key = entry.getKey();
CollectionStatistics value = entry.getValue();
if (value == null) {
continue;
}
assert key != null;
CollectionStatistics existing = fieldStatistics.get(key);
if (existing != null) {
CollectionStatistics merged = new CollectionStatistics(
key,
existing.maxDoc() + value.maxDoc(),
existing.docCount() + value.docCount(),
existing.sumTotalTermFreq() + value.sumTotalTermFreq(),
existing.sumDocFreq() + value.sumDocFreq()
);
fieldStatistics.put(key, merged);
} else {
fieldStatistics.put(key, value);
}
}
aggMaxDoc += lEntry.maxDoc();
}
return new AggregatedDfs(termStatistics, fieldStatistics, aggMaxDoc);
}
}
| DfsQueryPhase |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/transport/InboundPipelineTests.java | {
"start": 1756,
"end": 16182
} | class ____ extends ESTestCase {
private static final int BYTE_THRESHOLD = 128 * 1024;
private final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
private final BytesRefRecycler recycler = new BytesRefRecycler(new MockPageCacheRecycler(Settings.EMPTY));
public void testPipelineHandling() throws IOException {
final List<Tuple<MessageData, Exception>> expected = new ArrayList<>();
final List<Tuple<MessageData, Exception>> actual = new ArrayList<>();
final List<ReleasableBytesReference> toRelease = new ArrayList<>();
final BiConsumer<TcpChannel, InboundMessage> messageHandler = (c, m) -> {
try (m) {
final Header header = m.getHeader();
final MessageData actualData;
final TransportVersion version = header.getVersion();
final boolean isRequest = header.isRequest();
final long requestId = header.getRequestId();
final Compression.Scheme compressionScheme = header.getCompressionScheme();
if (header.isCompressed()) {
assertNotNull(compressionScheme);
} else {
assertNull(compressionScheme);
}
if (m.isShortCircuit()) {
actualData = new MessageData(version, requestId, isRequest, compressionScheme, header.getActionName(), null);
} else if (isRequest) {
final TestRequest request = new TestRequest(m.openOrGetStreamInput());
actualData = new MessageData(version, requestId, isRequest, compressionScheme, header.getActionName(), request.value);
} else {
final TestResponse response = new TestResponse(m.openOrGetStreamInput());
actualData = new MessageData(version, requestId, isRequest, compressionScheme, null, response.value);
}
actual.add(new Tuple<>(actualData, m.getException()));
} catch (IOException e) {
throw new AssertionError(e);
}
};
final StatsTracker statsTracker = new StatsTracker();
final LongSupplier millisSupplier = () -> TimeValue.nsecToMSec(System.nanoTime());
final InboundDecoder decoder = new InboundDecoder(recycler);
final String breakThisAction = "break_this_action";
final String actionName = "actionName";
final Predicate<String> canTripBreaker = breakThisAction::equals;
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
circuitBreaker.startBreaking();
final InboundAggregator aggregator = new InboundAggregator(() -> circuitBreaker, canTripBreaker);
final InboundPipeline pipeline = new InboundPipeline(statsTracker, millisSupplier, decoder, aggregator, messageHandler);
final FakeTcpChannel channel = new FakeTcpChannel();
final int iterations = randomIntBetween(100, 500);
long totalMessages = 0;
long bytesReceived = 0;
for (int i = 0; i < iterations; ++i) {
actual.clear();
expected.clear();
toRelease.clear();
try (RecyclerBytesStreamOutput streamOutput = new RecyclerBytesStreamOutput(recycler)) {
while (streamOutput.size() < BYTE_THRESHOLD) {
final TransportVersion version = randomFrom(TransportVersion.current(), TransportVersion.minimumCompatible());
final String value = randomRealisticUnicodeOfCodepointLength(randomIntBetween(200, 400));
final boolean isRequest = randomBoolean();
Compression.Scheme compressionScheme = getCompressionScheme();
final long requestId = totalMessages++;
final MessageData messageData;
Exception expectedExceptionClass = null;
BytesReference message;
try (RecyclerBytesStreamOutput temporaryOutput = new RecyclerBytesStreamOutput(recycler)) {
if (isRequest) {
if (rarely()) {
messageData = new MessageData(version, requestId, true, compressionScheme, breakThisAction, null);
message = OutboundHandler.serialize(
OutboundHandler.MessageDirection.REQUEST,
breakThisAction,
requestId,
false,
version,
compressionScheme,
new TestRequest(value),
threadContext,
temporaryOutput
);
expectedExceptionClass = new CircuitBreakingException("", CircuitBreaker.Durability.PERMANENT);
} else {
messageData = new MessageData(version, requestId, true, compressionScheme, actionName, value);
message = OutboundHandler.serialize(
OutboundHandler.MessageDirection.REQUEST,
actionName,
requestId,
false,
version,
compressionScheme,
new TestRequest(value),
threadContext,
temporaryOutput
);
}
} else {
messageData = new MessageData(version, requestId, false, compressionScheme, null, value);
message = OutboundHandler.serialize(
OutboundHandler.MessageDirection.RESPONSE,
actionName,
requestId,
false,
version,
compressionScheme,
new TestResponse(value),
threadContext,
temporaryOutput
);
}
expected.add(new Tuple<>(messageData, expectedExceptionClass));
message.writeTo(streamOutput);
}
}
final BytesReference networkBytes = streamOutput.bytes();
int currentOffset = 0;
while (currentOffset != networkBytes.length()) {
final int remainingBytes = networkBytes.length() - currentOffset;
final int bytesToRead = Math.min(randomIntBetween(1, 32 * 1024), remainingBytes);
final BytesReference slice = networkBytes.slice(currentOffset, bytesToRead);
ReleasableBytesReference reference = new ReleasableBytesReference(slice, () -> {});
toRelease.add(reference);
bytesReceived += reference.length();
pipeline.handleBytes(channel, reference);
currentOffset += bytesToRead;
}
final int messages = expected.size();
for (int j = 0; j < messages; ++j) {
final Tuple<MessageData, Exception> expectedTuple = expected.get(j);
final Tuple<MessageData, Exception> actualTuple = actual.get(j);
final MessageData expectedMessageData = expectedTuple.v1();
final MessageData actualMessageData = actualTuple.v1();
assertEquals(expectedMessageData.requestId, actualMessageData.requestId);
assertEquals(expectedMessageData.isRequest, actualMessageData.isRequest);
assertEquals(expectedMessageData.compressionScheme, actualMessageData.compressionScheme);
assertEquals(expectedMessageData.actionName, actualMessageData.actionName);
assertEquals(expectedMessageData.value, actualMessageData.value);
if (expectedTuple.v2() != null) {
assertNotNull(actualTuple.v2());
assertThat(actualTuple.v2(), instanceOf(expectedTuple.v2().getClass()));
}
}
for (ReleasableBytesReference released : toRelease) {
assertFalse(released.hasReferences());
}
}
assertEquals(bytesReceived, statsTracker.getBytesRead());
assertEquals(totalMessages, statsTracker.getMessagesReceived());
}
}
private static Compression.Scheme getCompressionScheme() {
return randomFrom((Compression.Scheme) null, Compression.Scheme.DEFLATE, Compression.Scheme.LZ4);
}
public void testDecodeExceptionIsPropagated() throws IOException {
BiConsumer<TcpChannel, InboundMessage> messageHandler = (c, m) -> m.close();
final StatsTracker statsTracker = new StatsTracker();
final LongSupplier millisSupplier = () -> TimeValue.nsecToMSec(System.nanoTime());
final InboundDecoder decoder = new InboundDecoder(recycler);
final Supplier<CircuitBreaker> breaker = () -> new NoopCircuitBreaker("test");
final InboundAggregator aggregator = new InboundAggregator(breaker, (Predicate<String>) action -> true);
final InboundPipeline pipeline = new InboundPipeline(statsTracker, millisSupplier, decoder, aggregator, messageHandler);
try (RecyclerBytesStreamOutput streamOutput = new RecyclerBytesStreamOutput(recycler)) {
String actionName = "actionName";
final TransportVersion invalidVersion = TransportVersionUtils.getPreviousVersion(TransportVersion.minimumCompatible());
final String value = randomAlphaOfLength(1000);
final boolean isRequest = randomBoolean();
final long requestId = randomNonNegativeLong();
final BytesReference message = OutboundHandler.serialize(
isRequest ? OutboundHandler.MessageDirection.REQUEST : OutboundHandler.MessageDirection.RESPONSE,
actionName,
requestId,
false,
invalidVersion,
null,
isRequest ? new TestRequest(value) : new TestResponse(value),
threadContext,
streamOutput
);
try (ReleasableBytesReference releasable = ReleasableBytesReference.wrap(message)) {
expectThrows(IllegalStateException.class, () -> pipeline.handleBytes(new FakeTcpChannel(), releasable));
}
// Pipeline cannot be reused after uncaught exception
final IllegalStateException ise = expectThrows(
IllegalStateException.class,
() -> pipeline.handleBytes(new FakeTcpChannel(), ReleasableBytesReference.wrap(BytesArray.EMPTY))
);
assertEquals("Pipeline state corrupted by uncaught exception", ise.getMessage());
}
}
public void testEnsureBodyIsNotPrematurelyReleased() throws IOException {
BiConsumer<TcpChannel, InboundMessage> messageHandler = (c, m) -> m.close();
final StatsTracker statsTracker = new StatsTracker();
final LongSupplier millisSupplier = () -> TimeValue.nsecToMSec(System.nanoTime());
final InboundDecoder decoder = new InboundDecoder(recycler);
final Supplier<CircuitBreaker> breaker = () -> new NoopCircuitBreaker("test");
final InboundAggregator aggregator = new InboundAggregator(breaker, (Predicate<String>) action -> true);
final InboundPipeline pipeline = new InboundPipeline(statsTracker, millisSupplier, decoder, aggregator, messageHandler);
try (RecyclerBytesStreamOutput streamOutput = new RecyclerBytesStreamOutput(recycler)) {
String actionName = "actionName";
final TransportVersion version = TransportVersion.current();
final String value = randomAlphaOfLength(1000);
final boolean isRequest = randomBoolean();
final long requestId = randomNonNegativeLong();
final BytesReference reference = OutboundHandler.serialize(
isRequest ? OutboundHandler.MessageDirection.REQUEST : OutboundHandler.MessageDirection.RESPONSE,
actionName,
requestId,
false,
version,
null,
isRequest ? new TestRequest(value) : new TestResponse(value),
threadContext,
streamOutput
);
final int variableHeaderSize = reference.getInt(TcpHeader.HEADER_SIZE - 4);
final int totalHeaderSize = TcpHeader.HEADER_SIZE + variableHeaderSize;
final AtomicBoolean bodyReleased = new AtomicBoolean(false);
for (int i = 0; i < totalHeaderSize - 1; ++i) {
try (ReleasableBytesReference slice = ReleasableBytesReference.wrap(reference.slice(i, 1))) {
pipeline.handleBytes(new FakeTcpChannel(), slice);
}
}
final Releasable releasable = () -> bodyReleased.set(true);
final int from = totalHeaderSize - 1;
final BytesReference partHeaderPartBody = reference.slice(from, reference.length() - from - 1);
pipeline.handleBytes(new FakeTcpChannel(), new ReleasableBytesReference(partHeaderPartBody, releasable));
assertFalse(bodyReleased.get());
pipeline.handleBytes(
new FakeTcpChannel(),
new ReleasableBytesReference(reference.slice(reference.length() - 1, 1), releasable)
);
assertTrue(bodyReleased.get());
}
}
private record MessageData(
TransportVersion version,
long requestId,
boolean isRequest,
Compression.Scheme compressionScheme,
String actionName,
String value
) {}
}
| InboundPipelineTests |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/indices/mapping/put/PutMappingRequestBuilder.java | {
"start": 1005,
"end": 2812
} | class ____ extends AcknowledgedRequestBuilder<
PutMappingRequest,
AcknowledgedResponse,
PutMappingRequestBuilder> {
public PutMappingRequestBuilder(ElasticsearchClient client) {
super(client, TransportPutMappingAction.TYPE, new PutMappingRequest());
}
public PutMappingRequestBuilder setIndices(String... indices) {
request.indices(indices);
return this;
}
public PutMappingRequestBuilder setConcreteIndex(Index index) {
request.setConcreteIndex(index);
return this;
}
/**
* Specifies what type of requested indices to ignore and wildcard indices expressions.
* <p>
* For example indices that don't exist.
*/
public PutMappingRequestBuilder setIndicesOptions(IndicesOptions options) {
request.indicesOptions(options);
return this;
}
/**
* The mapping source definition.
*/
public PutMappingRequestBuilder setSource(XContentBuilder mappingBuilder) {
request.source(mappingBuilder);
return this;
}
/**
* The mapping source definition.
*/
public PutMappingRequestBuilder setSource(Map<String, ?> mappingSource) {
request.source(mappingSource);
return this;
}
/**
* The mapping source definition.
*/
public PutMappingRequestBuilder setSource(String mappingSource, XContentType xContentType) {
request.source(mappingSource, xContentType);
return this;
}
/**
* A specialized simplified mapping source method, takes the form of simple properties definition:
* ("field1", "type=string,store=true").
*/
public PutMappingRequestBuilder setSource(String... source) {
request.source(source);
return this;
}
}
| PutMappingRequestBuilder |
java | apache__logging-log4j2 | log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/message/ThrowableConsumingMessageFactory.java | {
"start": 1809,
"end": 7114
} | class ____ implements MessageFactory2 {
private Message newParameterizedMessage(final Object throwable, final String pattern, final Object... args) {
return new ParameterizedMessage(pattern, args, (Throwable) throwable);
}
@Override
public Message newMessage(final Object message) {
return new ObjectMessage(message);
}
@Override
public Message newMessage(final String message) {
return new SimpleMessage(message);
}
@Override
public Message newMessage(final String message, final Object... params) {
if (params != null && params.length > 0) {
final Object lastArg = params[params.length - 1];
return lastArg instanceof Throwable
? newParameterizedMessage(lastArg, message, Arrays.copyOf(params, params.length - 1))
: newParameterizedMessage(null, message, params);
}
return new SimpleMessage(message);
}
@Override
public Message newMessage(final CharSequence charSequence) {
return new SimpleMessage(charSequence);
}
@Override
public Message newMessage(final String message, final Object p0) {
return p0 instanceof Throwable
? newParameterizedMessage(p0, message)
: newParameterizedMessage(null, message, p0);
}
@Override
public Message newMessage(final String message, final Object p0, final Object p1) {
return p1 instanceof Throwable
? newParameterizedMessage(p1, message, p0)
: newParameterizedMessage(null, message, p0, p1);
}
@Override
public Message newMessage(final String message, final Object p0, final Object p1, final Object p2) {
return p2 instanceof Throwable
? newParameterizedMessage(p2, message, p0, p1)
: newParameterizedMessage(null, message, p0, p1, p2);
}
@Override
public Message newMessage(
final String message, final Object p0, final Object p1, final Object p2, final Object p3) {
return p3 instanceof Throwable
? newParameterizedMessage(p3, message, p0, p1, p2)
: newParameterizedMessage(null, message, p0, p1, p2, p3);
}
@Override
public Message newMessage(
final String message, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4) {
return p4 instanceof Throwable
? newParameterizedMessage(p4, message, p0, p1, p2, p3)
: newParameterizedMessage(null, message, p0, p1, p2, p3, p4);
}
@Override
public Message newMessage(
final String message,
final Object p0,
final Object p1,
final Object p2,
final Object p3,
final Object p4,
final Object p5) {
return p5 instanceof Throwable
? newParameterizedMessage(p5, message, p0, p1, p2, p3, p4)
: newParameterizedMessage(null, message, p0, p1, p2, p3, p4, p5);
}
@Override
public Message newMessage(
final String message,
final Object p0,
final Object p1,
final Object p2,
final Object p3,
final Object p4,
final Object p5,
final Object p6) {
return p6 instanceof Throwable
? newParameterizedMessage(p6, message, p0, p1, p2, p3, p4, p5)
: newParameterizedMessage(null, message, p0, p1, p2, p3, p4, p5, p6);
}
@Override
public Message newMessage(
final String message,
final Object p0,
final Object p1,
final Object p2,
final Object p3,
final Object p4,
final Object p5,
final Object p6,
final Object p7) {
return p7 instanceof Throwable
? newParameterizedMessage(p7, message, p0, p1, p2, p3, p4, p5, p6)
: newParameterizedMessage(null, message, p0, p1, p2, p3, p4, p5, p6, p7);
}
@Override
public Message newMessage(
final String message,
final Object p0,
final Object p1,
final Object p2,
final Object p3,
final Object p4,
final Object p5,
final Object p6,
final Object p7,
final Object p8) {
return p8 instanceof Throwable
? newParameterizedMessage(p8, message, p0, p1, p2, p3, p4, p5, p6, p7)
: newParameterizedMessage(null, message, p0, p1, p2, p3, p4, p5, p6, p7, p8);
}
@Override
public Message newMessage(
final String message,
final Object p0,
final Object p1,
final Object p2,
final Object p3,
final Object p4,
final Object p5,
final Object p6,
final Object p7,
final Object p8,
final Object p9) {
return p9 instanceof Throwable
? newParameterizedMessage(p9, message, p0, p1, p2, p3, p4, p5, p6, p7, p8)
: newParameterizedMessage(null, message, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
}
}
| ThrowableConsumingMessageFactory |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/stream/JSONReaderTest_5.java | {
"start": 370,
"end": 1140
} | class ____ extends TestCase {
public void test_read() throws Exception {
final int COUNT = 1000 * 10;
StringBuilder buf = new StringBuilder();
buf.append('[');
for (int i = 0; i < COUNT; ++i) {
if (i != 0) {
buf.append(',');
}
buf.append("{\"id\":").append(i).append('}');
}
buf.append(']');
JSONReader reader = new JSONReader(new StringReader(buf.toString()));
reader.startArray();
Map map = new HashMap();
int count = 0;
for (;;) {
if (reader.hasNext()) {
reader.startObject();
String key = reader.readString();
Long value = reader.readLong();
reader.endObject();
count++;
} else {
break;
}
}
assertEquals(COUNT, count);
reader.endArray();
reader.close();
}
}
| JSONReaderTest_5 |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/time/NearbyCallers.java | {
"start": 8244,
"end": 8896
} | class ____, then _only_ scan the other class-level
// fields
ImmutableList.Builder<Tree> treesToScan = ImmutableList.builder();
for (Tree member : classTree.getMembers()) {
if (member instanceof VariableTree variableTree) {
ExpressionTree expressionTree = variableTree.getInitializer();
if (expressionTree != null) {
treesToScan.add(expressionTree);
}
}
}
return treesToScan.build();
}
default -> {
// continue searching up the tree
}
}
}
return ImmutableList.of();
}
}
| tree |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java | {
"start": 20801,
"end": 22001
} | class ____ {@code null}, or the field could not be found.
* @throws IllegalArgumentException
* if the field name is {@code null}, blank or empty, or is not {@code static}.
* @throws IllegalAccessException
* if the field is not accessible.
* @throws SecurityException if an underlying accessible object's method denies the request.
* @see SecurityManager#checkPermission
*/
public static Object readStaticField(final Class<?> cls, final String fieldName) throws IllegalAccessException {
return readStaticField(cls, fieldName, false);
}
/**
* Reads the named {@code static} {@link Field}. Superclasses will be considered.
*
* @param cls
* the {@link Class} to reflect, must not be {@code null}.
* @param fieldName
* the field name to obtain.
* @param forceAccess
* whether to break scope restrictions using the
* {@link AccessibleObject#setAccessible(boolean)} method. {@code false} will only
* match {@code public} fields.
* @return the Field object.
* @throws NullPointerException
* if the | is |
java | quarkusio__quarkus | integration-tests/gradle/src/test/java/io/quarkus/gradle/devmode/KotlinMultiplatformModuleDevModeTest.java | {
"start": 102,
"end": 531
} | class ____ extends QuarkusDevGradleTestBase {
@Override
protected String projectDirectoryName() {
return "kotlin-multiplatform-module";
}
@Override
protected void testDevMode() throws Exception {
assertThat(getHttpResponse("/hello/kmp")).contains("hi from KMP");
assertThat(getHttpResponse("/hello/jvm")).contains("hi from JVM-only sources");
}
}
| KotlinMultiplatformModuleDevModeTest |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/node/JsonNodeFactoryTest.java | {
"start": 564,
"end": 3384
} | class ____ extends JsonNodeFactory {
private static final long serialVersionUID = 1L;
@Override
public ObjectNode objectNode() {
return new ObjectNode(this, new TreeMap<String, JsonNode>());
}
}
@Test
public void testSimpleCreation()
{
JsonNodeFactory f = MAPPER.getNodeFactory();
JsonNode n;
n = f.numberNode((byte) 4);
assertTrue(n.isInt());
assertEquals(4, n.intValue());
assertTrue(f.numberNode((Byte) null).isNull());
assertTrue(f.numberNode((Short) null).isNull());
assertTrue(f.numberNode((Integer) null).isNull());
assertTrue(f.numberNode((Long) null).isNull());
assertTrue(f.numberNode((Float) null).isNull());
assertTrue(f.numberNode((Double) null).isNull());
assertTrue(f.numberNode((BigDecimal) null).isNull());
assertTrue(f.numberNode((BigInteger) null).isNull());
assertTrue(f.missingNode().isMissingNode());
}
// 09-Sep-2020, tatu: Let's try something more useful: auto-sorting
// Tree Model!
@Test
public void testSortingObjectNode() throws Exception
{
final String SIMPLE_INPUT = "{\"b\":2,\"a\":1}";
// First, by default, ordering retained:
assertEquals(SIMPLE_INPUT,
MAPPER.writeValueAsString(MAPPER.readTree(SIMPLE_INPUT)));
// But can change easily
ObjectMapper mapper = JsonMapper.builder()
.nodeFactory(new SortingNodeFactory())
.build();
JsonNode sort = mapper.readTree(SIMPLE_INPUT);
assertEquals("{\"a\":1,\"b\":2}", MAPPER.writeValueAsString(sort));
final String BIGGER_INPUT = a2q("['x',{'b':1,'c':true,'a':3},false]");
final String BIGGER_OUTPUT = a2q("['x',{'a':3,'b':1,'c':true},false]");
assertEquals(BIGGER_OUTPUT,
MAPPER.writeValueAsString(mapper.readTree(BIGGER_INPUT)));
}
// 06-Nov-2022, tatu: Wasn't being tested, oddly enough
@Test
public void testBigDecimalNormalization() throws Exception
{
final BigDecimal NON_NORMALIZED = new BigDecimal("12.5000");
final BigDecimal NORMALIZED = NON_NORMALIZED.stripTrailingZeros();
// By default, 2.x WILL normalize but 3.x WON'T
JsonNode n1 = MAPPER.readTree(String.valueOf(NON_NORMALIZED));
assertEquals(NON_NORMALIZED, n1.decimalValue());
// But can change
ObjectMapper normMapper = JsonMapper.builder()
.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
.enable(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES)
.build();
JsonNode n3 = normMapper.readTree(String.valueOf(NON_NORMALIZED));
assertEquals(NORMALIZED, n3.decimalValue());
}
}
| SortingNodeFactory |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/naming/NamingMaintainFactory.java | {
"start": 1021,
"end": 2485
} | class ____ {
/**
* create a new maintain service.
*
* @param serverList server list
* @return new maintain service
* @throws NacosException nacos exception
*/
public static NamingMaintainService createMaintainService(String serverList) throws NacosException {
try {
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingMaintainService");
Constructor constructor = driverImplClass.getConstructor(String.class);
return (NamingMaintainService) constructor.newInstance(serverList);
} catch (Throwable e) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, e);
}
}
/**
* create a new maintain service.
*
* @param properties properties
* @return new maintain service
* @throws NacosException nacos exception
*/
public static NamingMaintainService createMaintainService(Properties properties) throws NacosException {
try {
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingMaintainService");
Constructor constructor = driverImplClass.getConstructor(Properties.class);
return (NamingMaintainService) constructor.newInstance(properties);
} catch (Throwable e) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, e);
}
}
}
| NamingMaintainFactory |
java | google__auto | common/src/main/java/com/google/auto/common/Overrides.java | {
"start": 9761,
"end": 12187
} | interface ____ we don't know what it is so we say no.
TypeElement overriderType = MoreElements.asType(overrider.getEnclosingElement());
return in.getKind().isInterface()
&& typeUtils.isSubtype(
typeUtils.erasure(overriderType.asType()),
typeUtils.erasure(overriddenType.asType()));
}
}
private boolean isSubsignature(
ExecutableElement overrider, ExecutableElement overridden, TypeElement in) {
DeclaredType inType = MoreTypes.asDeclared(in.asType());
try {
ExecutableType overriderExecutable =
MoreTypes.asExecutable(typeUtils.asMemberOf(inType, overrider));
ExecutableType overriddenExecutable =
MoreTypes.asExecutable(typeUtils.asMemberOf(inType, overridden));
return typeUtils.isSubsignature(overriderExecutable, overriddenExecutable);
} catch (IllegalArgumentException e) {
// This might mean that at least one of the methods is not in fact declared in or inherited
// by `in` (in which case we should indeed return false); or it might mean that we are
// tickling an Eclipse bug such as https://bugs.eclipse.org/bugs/show_bug.cgi?id=499026
// (in which case we fall back on explicit code to find the parameters).
int nParams = overrider.getParameters().size();
if (overridden.getParameters().size() != nParams) {
return false;
}
List<TypeMirror> overriderParams = erasedParameterTypes(overrider, in);
List<TypeMirror> overriddenParams = erasedParameterTypes(overridden, in);
if (overriderParams == null || overriddenParams == null) {
// This probably means that one or other of the methods is not in `in`.
return false;
}
for (int i = 0; i < nParams; i++) {
if (!typeUtils.isSameType(overriderParams.get(i), overriddenParams.get(i))) {
// If the erasures of the parameters don't correspond, return false. We erase so we
// don't get any confusion about different type variables not comparing equal.
return false;
}
}
return true;
}
}
/**
* Returns the list of erased parameter types of the given method as they appear in the given
* type. For example, if the method is {@code add(E)} from {@code List<E>} and we ask how it
* appears in {@code | then |
java | elastic__elasticsearch | test/test-clusters/src/main/java/org/elasticsearch/test/cluster/util/ArchivePatcher.java | {
"start": 1027,
"end": 3175
} | class ____ {
private final Path original;
private final Path target;
private final Map<String, Function<? super String, ? extends InputStream>> overrides = new HashMap<>();
public ArchivePatcher(Path original, Path target) {
this.original = original;
this.target = target;
}
public void override(String filename, Function<? super String, ? extends InputStream> override) {
this.overrides.put(filename, override);
}
public Path patch() {
try (
ZipFile input = new ZipFile(original.toFile());
ZipOutputStream output = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target.toFile())))
) {
Enumeration<? extends ZipEntry> entries = input.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
output.putNextEntry(entry);
if (overrides.containsKey(entry.getName())) {
Function<? super String, ? extends InputStream> override = overrides.remove(entry.getName());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(input.getInputStream(entry)))) {
String content = reader.lines().collect(Collectors.joining(System.lineSeparator()));
override.apply(content).transferTo(output);
}
} else {
input.getInputStream(entry).transferTo(output);
}
output.closeEntry();
}
for (Map.Entry<String, Function<? super String, ? extends InputStream>> override : overrides.entrySet()) {
ZipEntry entry = new ZipEntry(override.getKey());
output.putNextEntry(entry);
override.getValue().apply("").transferTo(output);
output.closeEntry();
}
output.flush();
output.finish();
} catch (IOException e) {
throw new UncheckedIOException("Failed to patch archive", e);
}
return target;
}
}
| ArchivePatcher |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/collection/OrderColumnListTest.java | {
"start": 3563,
"end": 4507
} | class ____ {
@Id
private Integer id;
@ElementCollection
@OrderColumn
private List<String> children = new ArrayList<String>();
Parent() {
}
Parent(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getChildren() {
return children;
}
public void setChildren(List<String> children) {
this.children = children;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Parent parent = (Parent) o;
return id != null ? id.equals( parent.id ) : parent.id == null;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
@Override
public String toString() {
return "Parent{" +
"id=" + id +
", children=" + children +
'}';
}
}
}
| Parent |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/threadpool/ThreadPoolStats.java | {
"start": 5954,
"end": 6575
} | class ____ {
static final String THREAD_POOL = "thread_pool";
static final String THREADS = "threads";
static final String QUEUE = "queue";
static final String ACTIVE = "active";
static final String REJECTED = "rejected";
static final String LARGEST = "largest";
static final String COMPLETED = "completed";
}
@Override
public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params params) {
return ChunkedToXContentHelper.object(Fields.THREAD_POOL, Iterators.flatMap(stats.iterator(), s -> s.toXContentChunked(params)));
}
}
| Fields |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/scripting/xmltags/SetSqlNode.java | {
"start": 839,
"end": 1095
} | class ____ extends TrimSqlNode {
private static final List<String> COMMA = Collections.singletonList(",");
public SetSqlNode(Configuration configuration, SqlNode contents) {
super(configuration, contents, "SET", COMMA, null, COMMA);
}
}
| SetSqlNode |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/IAM2EndpointBuilderFactory.java | {
"start": 1417,
"end": 1572
} | interface ____ {
/**
* Builder for endpoint for the AWS Identity and Access Management (IAM) component.
*/
public | IAM2EndpointBuilderFactory |
java | google__guava | android/guava-tests/test/com/google/common/cache/RemovalNotificationTest.java | {
"start": 859,
"end": 1335
} | class ____ extends TestCase {
public void testEquals() {
new EqualsTester()
.addEqualityGroup(
RemovalNotification.create("one", 1, RemovalCause.EXPLICIT),
RemovalNotification.create("one", 1, RemovalCause.REPLACED))
.addEqualityGroup(RemovalNotification.create("1", 1, RemovalCause.EXPLICIT))
.addEqualityGroup(RemovalNotification.create("one", 2, RemovalCause.EXPLICIT))
.testEquals();
}
}
| RemovalNotificationTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/benckmark/sql/MySqlPerfMain_visitor.java | {
"start": 1044,
"end": 2629
} | class ____ {
public static void main(String[] args) throws Exception {
System.out.println(System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version"));
List<String> arguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
System.out.println(arguments);
String sql = "SELECT ID, NAME, AGE FROM USER WHERE ID = ?";
for (int i = 0; i < 5; ++i) {
perfMySql(sql);
}
}
static long perfMySql(String sql) {
long startYGC = TestUtils.getYoungGC();
long startYGCTime = TestUtils.getYoungGCTime();
long startFGC = TestUtils.getFullGC();
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
long startMillis = System.currentTimeMillis();
for (int i = 0; i < 1000 * 1000 * 1; ++i) {
execMySql(statementList);
}
long millis = System.currentTimeMillis() - startMillis;
long ygc = TestUtils.getYoungGC() - startYGC;
long ygct = TestUtils.getYoungGCTime() - startYGCTime;
long fgc = TestUtils.getFullGC() - startFGC;
System.out.println("MySql\t" + millis + ", ygc " + ygc + ", ygct " + ygct + ", fgc " + fgc);
return millis;
}
static void execMySql(List<SQLStatement> statementList) {
MySqlASTVisitor visitor = new MySqlSchemaStatVisitor();
for (SQLStatement statement : statementList) {
statement.accept(visitor);
}
}
}
| MySqlPerfMain_visitor |
java | quarkusio__quarkus | extensions/hibernate-search-standalone-elasticsearch/runtime/src/main/java/io/quarkus/hibernate/search/standalone/elasticsearch/runtime/HibernateSearchStandaloneRuntimeConfig.java | {
"start": 5652,
"end": 9704
} | interface ____ {
// @formatter:off
/**
* The schema management strategy, controlling how indexes and their schema
* are created, updated, validated or dropped on startup and shutdown.
*
* Available values:
*
* [cols=2]
* !===
* h!Strategy
* h!Definition
*
* !none
* !Do nothing: assume that indexes already exist and that their schema matches Hibernate Search's expectations.
*
* !validate
* !Validate that indexes exist and that their schema matches Hibernate Search's expectations.
*
* If it does not, throw an exception, but make no attempt to fix the problem.
*
* !create
* !For indexes that do not exist, create them along with their schema.
*
* For indexes that already exist, do nothing: assume that their schema matches Hibernate Search's expectations.
*
* !create-or-validate (**default** unless using Dev Services)
* !For indexes that do not exist, create them along with their schema.
*
* For indexes that already exist, validate that their schema matches Hibernate Search's expectations.
*
* If it does not, throw an exception, but make no attempt to fix the problem.
*
* !create-or-update
* !For indexes that do not exist, create them along with their schema.
*
* For indexes that already exist, validate that their schema matches Hibernate Search's expectations;
* if it does not match expectations, try to update it.
*
* **This strategy is unfit for production environments**,
* due to several important limitations,
* but can be useful when developing.
*
* !drop-and-create
* !For indexes that do not exist, create them along with their schema.
*
* For indexes that already exist, drop them, then create them along with their schema.
*
* !drop-and-create-and-drop (**default** when using Dev Services)
* !For indexes that do not exist, create them along with their schema.
*
* For indexes that already exist, drop them, then create them along with their schema.
*
* Also, drop indexes and their schema on shutdown.
* !===
*
* See link:{hibernate-search-docs-url}#schema-management-strategy[this section of the reference documentation]
* for more information.
*
* @asciidoclet
*/
// @formatter:on
@WithDefault("create-or-validate")
@ConfigDocDefault("drop-and-create-and-drop when using Dev Services; create-or-validate otherwise")
SchemaManagementStrategyName strategy();
}
static String extensionPropertyKey(String radical) {
StringBuilder keyBuilder = new StringBuilder("quarkus.hibernate-search-standalone.");
keyBuilder.append(radical);
return keyBuilder.toString();
}
static String mapperPropertyKey(String radical) {
return "quarkus.hibernate-search-standalone." + radical;
}
static List<String> mapperPropertyKeys(String radical) {
return List.of(mapperPropertyKey(radical));
}
static String backendPropertyKey(String backendName, String indexName, String radical) {
StringBuilder keyBuilder = new StringBuilder("quarkus.hibernate-search-standalone.");
keyBuilder.append("elasticsearch.");
if (backendName != null) {
keyBuilder.append("\"").append(backendName).append("\".");
}
if (indexName != null) {
keyBuilder.append("indexes.\"").append(indexName).append("\".");
}
keyBuilder.append(radical);
return keyBuilder.toString();
}
static List<String> defaultBackendPropertyKeys(String radical) {
return mapperPropertyKeys("elasticsearch." + radical);
}
}
| SchemaManagementConfig |
java | quarkusio__quarkus | core/runtime/src/main/java/io/quarkus/runtime/ObjectSubstitution.java | {
"start": 39,
"end": 161
} | interface ____ can be used to substitute a non-bytecode serializable class
* with a replacement.
*
* Instances of this | that |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/util/ExceptionCollector.java | {
"start": 3966,
"end": 4115
} | interface ____ can be used to implement
* any generic block of code that potentially throws a {@link Throwable}.
*
* <p>The {@code Executable} | that |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableRenameConstraint.java | {
"start": 812,
"end": 1685
} | class ____ extends SQLObjectImpl implements SQLAlterTableItem {
private SQLName constraint;
private SQLName to;
public SQLAlterTableRenameConstraint() {
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, constraint);
acceptChild(visitor, to);
}
visitor.endVisit(this);
}
public SQLName getConstraint() {
return constraint;
}
public void setConstraint(SQLName constraint) {
if (constraint != null) {
constraint.setParent(this);
}
this.constraint = constraint;
}
public SQLName getTo() {
return to;
}
public void setTo(SQLName to) {
if (to != null) {
to.setParent(this);
}
this.to = to;
}
}
| SQLAlterTableRenameConstraint |
java | apache__camel | components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/processor/AbstractRestProcessor.java | {
"start": 29168,
"end": 29796
} | class ____
setResponseClass(exchange);
exchange.setProperty(RESPONSE_CLASS_PREFIX, "QueryRecords");
restClient.queryMore(nextRecordsUrl, determineHeaders(exchange), processWithResponseCallback(exchange, callback));
}
private void processQueryAll(final Exchange exchange, final AsyncCallback callback) throws SalesforceException {
final String sObjectQuery = getParameter(SOBJECT_QUERY, exchange, USE_BODY, NOT_OPTIONAL);
final boolean streamQueryResults = getParameter(STREAM_QUERY_RESULT, exchange, IGNORE_BODY, IS_OPTIONAL, Boolean.class);
// use custom response | property |
java | apache__dubbo | dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/PathParamArgumentResolver.java | {
"start": 1808,
"end": 3270
} | class ____ implements AnnotationBaseArgumentResolver<Annotation> {
@Override
public Class<Annotation> accept() {
return Annotations.PathParam.type();
}
@Override
public NamedValueMeta getNamedValueMeta(ParameterMeta parameter, AnnotationMeta<Annotation> annotation) {
return new NamedValueMeta(annotation.getValue(), true).setParamType(ParamType.PathVariable);
}
@Override
public Object resolve(
ParameterMeta parameter,
AnnotationMeta<Annotation> annotation,
HttpRequest request,
HttpResponse response) {
Map<String, String> variableMap = request.attribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
String name = annotation.getValue();
if (StringUtils.isEmpty(name)) {
name = parameter.getRequiredName();
}
if (variableMap == null) {
if (Helper.isRequired(parameter)) {
throw new RestParameterException(Messages.ARGUMENT_VALUE_MISSING, name, parameter.getType());
}
return null;
}
String value = variableMap.get(name);
if (value == null) {
return null;
}
int index = value.indexOf(';');
if (index != -1) {
value = value.substring(0, index);
}
return parameter.isAnnotated(Annotations.Encoded) ? value : RequestUtils.decodeURL(value);
}
}
| PathParamArgumentResolver |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/dynamic/BindingUtils.java | {
"start": 1434,
"end": 1585
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(BindingUtils.class);
private BindingUtils() {}
/**
* Load a | BindingUtils |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/ConfigurationMethod.java | {
"start": 915,
"end": 982
} | class ____.
*
* @author Chris Beams
* @since 3.1
*/
abstract | method |
java | quarkusio__quarkus | extensions/arc/deployment/src/test/java/io/quarkus/arc/test/profile/IfBuildProfileAllAnyTest.java | {
"start": 2119,
"end": 2302
} | interface ____ {
String profile();
}
// Not active, the "dev" profile is not active
@ApplicationScoped
@IfBuildProfile("dev")
public static | IfBuildProfileBean |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/slack/SentMessages.java | {
"start": 1024,
"end": 2303
} | class ____ implements ToXContentObject, Iterable<SentMessages.SentMessage> {
private static final ParseField ACCOUNT = new ParseField("account");
private static final ParseField SENT_MESSAGES = new ParseField("sent_messages");
private String accountName;
private List<SentMessage> messages;
public SentMessages(String accountName, List<SentMessage> messages) {
this.accountName = accountName;
this.messages = messages;
}
public String getAccountName() {
return accountName;
}
@Override
public Iterator<SentMessage> iterator() {
return messages.iterator();
}
public int count() {
return messages.size();
}
public List<SentMessage> asList() {
return Collections.unmodifiableList(messages);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(ACCOUNT.getPreferredName(), accountName);
builder.startArray(SENT_MESSAGES.getPreferredName());
for (SentMessage message : messages) {
message.toXContent(builder, params);
}
builder.endArray();
return builder.endObject();
}
public static | SentMessages |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/DefaultExchange.java | {
"start": 1198,
"end": 2726
} | class ____ extends AbstractExchange {
private final Clock timeInfo;
DefaultExchange(CamelContext context, EnumMap<ExchangePropertyKey, Object> internalProperties,
Map<String, Object> properties) {
super(context, internalProperties, properties);
this.timeInfo = new MonotonicClock();
}
public DefaultExchange(CamelContext context) {
super(context);
this.timeInfo = new MonotonicClock();
}
public DefaultExchange(CamelContext context, ExchangePattern pattern) {
super(context, pattern);
this.timeInfo = new MonotonicClock();
}
public DefaultExchange(Exchange parent) {
super(parent);
this.timeInfo = parent.getClock();
}
DefaultExchange(AbstractExchange parent) {
super(parent);
this.timeInfo = parent.getClock();
}
@Override
public Clock getClock() {
return timeInfo;
}
@Override
AbstractExchange newCopy() {
return new DefaultExchange(this);
}
public static DefaultExchange newFromEndpoint(Endpoint fromEndpoint) {
return newFromEndpoint(fromEndpoint, fromEndpoint.getExchangePattern());
}
public static DefaultExchange newFromEndpoint(Endpoint fromEndpoint, ExchangePattern exchangePattern) {
DefaultExchange exchange = new DefaultExchange(fromEndpoint.getCamelContext(), exchangePattern);
exchange.getExchangeExtension().setFromEndpoint(fromEndpoint);
return exchange;
}
}
| DefaultExchange |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/internal/tls/SslContextProvider.java | {
"start": 1170,
"end": 12129
} | class ____ {
private static final List<String> VALID_PROTOCOLS = List.of("TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3", "SSLv2Hello", "DTLSv1.2", "DTLSv1.0");
private static int idx(boolean useAlpn) {
return useAlpn ? 0 : 1;
}
private final boolean useWorkerPool;
private final Supplier<SslContextFactory> provider;
private final Set<String> enabledProtocols;
private final List<CRL> crls;
private final ClientAuth clientAuth;
private final Set<String> enabledCipherSuites;
private final List<String> applicationProtocols;
private final String endpointIdentificationAlgorithm;
private final KeyManagerFactory keyManagerFactory;
private final TrustManagerFactory trustManagerFactory;
private final Function<String, KeyManagerFactory> keyManagerFactoryMapper;
private final Function<String, TrustManager[]> trustManagerMapper;
private final SslContext[] sslContexts = new SslContext[2];
private final Map<String, SslContext>[] sslContextMaps = new Map[]{
new ConcurrentHashMap<>(), new ConcurrentHashMap<>()
};
public SslContextProvider(boolean useWorkerPool,
ClientAuth clientAuth,
String endpointIdentificationAlgorithm,
List<String> applicationProtocols,
Set<String> enabledCipherSuites,
Set<String> enabledProtocols,
KeyManagerFactory keyManagerFactory,
Function<String, KeyManagerFactory> keyManagerFactoryMapper,
TrustManagerFactory trustManagerFactory,
Function<String, TrustManager[]> trustManagerMapper,
List<CRL> crls,
Supplier<SslContextFactory> provider) {
// Filter the list of enabled protocols
enabledProtocols = new HashSet<>(enabledProtocols);
enabledProtocols.retainAll(VALID_PROTOCOLS);
this.useWorkerPool = useWorkerPool;
this.provider = provider;
this.clientAuth = clientAuth;
this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm;
this.applicationProtocols = applicationProtocols;
this.enabledCipherSuites = enabledCipherSuites;
this.enabledProtocols = enabledProtocols;
this.keyManagerFactory = keyManagerFactory;
this.trustManagerFactory = trustManagerFactory;
this.keyManagerFactoryMapper = keyManagerFactoryMapper;
this.trustManagerMapper = trustManagerMapper;
this.crls = crls;
}
public boolean useWorkerPool() {
return useWorkerPool;
}
public int sniEntrySize() {
return sslContextMaps[0].size() + sslContextMaps[1].size();
}
public SslContext createContext(boolean server,
KeyManagerFactory keyManagerFactory,
TrustManager[] trustManagers,
String serverName,
boolean useAlpn) {
if (keyManagerFactory == null) {
keyManagerFactory = defaultKeyManagerFactory();
}
if (trustManagers == null) {
trustManagers = defaultTrustManagers();
}
if (server) {
return createServerContext(keyManagerFactory, trustManagers, serverName, useAlpn);
} else {
return createClientContext(keyManagerFactory, trustManagers, serverName, useAlpn);
}
}
public SslContext sslClientContext(String serverName, boolean useAlpn) {
try {
return sslContext(serverName, useAlpn, false);
} catch (Exception e) {
throw new VertxException(e);
}
}
public SslContext sslContext(String serverName, boolean useAlpn, boolean server) throws Exception {
int idx = idx(useAlpn);
if (serverName != null) {
KeyManagerFactory kmf = resolveKeyManagerFactory(serverName);
TrustManager[] trustManagers = resolveTrustManagers(serverName);
if (kmf != null || trustManagers != null || !server) {
return sslContextMaps[idx].computeIfAbsent(serverName, s -> createContext(server, kmf, trustManagers, s, useAlpn));
}
}
if (sslContexts[idx] == null) {
SslContext context = createContext(server, null, null, serverName, useAlpn);
sslContexts[idx] = context;
}
return sslContexts[idx];
}
public SslContext sslServerContext(boolean useAlpn) {
try {
return sslContext(null, useAlpn, true);
} catch (Exception e) {
throw new VertxException(e);
}
}
/**
*
* @param useAlpn
* @return
*/
public Mapping<? super String, ? extends SslContext> serverNameMapping(boolean useAlpn) {
return (Mapping<String, SslContext>) serverName -> {
try {
return sslContext(serverName, useAlpn, true);
} catch (Exception e) {
// Log this
return null;
}
};
}
/**
* Server name {@link AsyncMapping} for {@link SniHandler}, mapping happens on a Vert.x worker thread.
*
* @return the {@link AsyncMapping}
*/
public AsyncMapping<? super String, ? extends SslContext> serverNameAsyncMapping(Executor workerPool, boolean useAlpn) {
return (AsyncMapping<String, SslContext>) (serverName, promise) -> {
workerPool.execute(() -> {
SslContext sslContext;
try {
sslContext = sslContext(serverName, useAlpn, true);
} catch (Exception e) {
promise.setFailure(e);
return;
}
promise.setSuccess(sslContext);
});
return promise;
};
}
public SslContext createContext(boolean server, boolean useAlpn) {
return createContext(server, defaultKeyManagerFactory(), defaultTrustManagers(), null, useAlpn);
}
public SslContext createClientContext(
KeyManagerFactory keyManagerFactory,
TrustManager[] trustManagers,
String serverName,
boolean useAlpn) {
try {
SslContextFactory factory = provider.get()
.useAlpn(useAlpn)
.forClient(serverName, endpointIdentificationAlgorithm)
.enabledProtocols(enabledProtocols)
.enabledCipherSuites(enabledCipherSuites)
.applicationProtocols(applicationProtocols);
if (keyManagerFactory != null) {
factory.keyMananagerFactory(keyManagerFactory);
}
if (trustManagers != null) {
TrustManagerFactory tmf = buildVertxTrustManagerFactory(trustManagers);
factory.trustManagerFactory(tmf);
}
return factory.create();
} catch (Exception e) {
throw new VertxException(e);
}
}
public SslContext createServerContext(KeyManagerFactory keyManagerFactory,
TrustManager[] trustManagers,
String serverName,
boolean useAlpn) {
try {
SslContextFactory factory = provider.get()
.useAlpn(useAlpn)
.forServer(SslContextManager.CLIENT_AUTH_MAPPING.get(clientAuth))
.enabledProtocols(enabledProtocols)
.enabledCipherSuites(enabledCipherSuites)
.applicationProtocols(applicationProtocols);
if (keyManagerFactory != null) {
factory.keyMananagerFactory(keyManagerFactory);
}
if (trustManagers != null) {
TrustManagerFactory tmf = buildVertxTrustManagerFactory(trustManagers);
factory.trustManagerFactory(tmf);
}
return factory.create();
} catch (Exception e) {
throw new VertxException(e);
}
}
public TrustManager[] defaultTrustManagers() {
return trustManagerFactory != null ? trustManagerFactory.getTrustManagers() : null;
}
public TrustManagerFactory defaultTrustManagerFactory() {
return trustManagerFactory;
}
public KeyManagerFactory defaultKeyManagerFactory() {
return keyManagerFactory;
}
/**
* Resolve the {@link KeyManagerFactory} for the {@code serverName}, when a factory cannot be resolved, {@code null} is returned.
* <br/>
* This can block and should be executed on the appropriate thread.
*
* @param serverName the server name
* @return the factory
* @throws Exception anything that would prevent loading the factory
*/
public KeyManagerFactory resolveKeyManagerFactory(String serverName) throws Exception {
if (keyManagerFactoryMapper != null) {
return keyManagerFactoryMapper.apply(serverName);
}
return null;
}
/**
* Resolve the {@link TrustManager}[] for the {@code serverName}, when managers cannot be resolved, {@code null} is returned.
* <br/>
* This can block and should be executed on the appropriate thread.
*
* @param serverName the server name
* @return the managers
* @throws Exception anything that would prevent loading the managers
*/
public TrustManager[] resolveTrustManagers(String serverName) throws Exception {
if (trustManagerMapper != null) {
return trustManagerMapper.apply(serverName);
}
return null;
}
private VertxTrustManagerFactory buildVertxTrustManagerFactory(TrustManager[] mgrs) {
if (crls != null && crls.size() > 0) {
mgrs = createUntrustRevokedCertTrustManager(mgrs, crls);
}
return new VertxTrustManagerFactory(mgrs);
}
/*
Proxy the specified trust managers with an implementation checking first the provided certificates
against the Certificate Revocation List (crl) before delegating to the original trust managers.
*/
private static TrustManager[] createUntrustRevokedCertTrustManager(TrustManager[] trustMgrs, List<CRL> crls) {
trustMgrs = trustMgrs.clone();
for (int i = 0;i < trustMgrs.length;i++) {
TrustManager trustMgr = trustMgrs[i];
if (trustMgr instanceof X509TrustManager) {
X509TrustManager x509TrustManager = (X509TrustManager) trustMgr;
trustMgrs[i] = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
checkRevoked(x509Certificates);
x509TrustManager.checkClientTrusted(x509Certificates, s);
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
checkRevoked(x509Certificates);
x509TrustManager.checkServerTrusted(x509Certificates, s);
}
private void checkRevoked(X509Certificate[] x509Certificates) throws CertificateException {
for (X509Certificate cert : x509Certificates) {
for (CRL crl : crls) {
if (crl.isRevoked(cert)) {
throw new CertificateException("Certificate revoked");
}
}
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return x509TrustManager.getAcceptedIssuers();
}
};
}
}
return trustMgrs;
}
}
| SslContextProvider |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkStrategyWithTimestampAssigner.java | {
"start": 993,
"end": 2021
} | class ____<T> implements WatermarkStrategy<T> {
private static final long serialVersionUID = 1L;
private final WatermarkStrategy<T> baseStrategy;
private final TimestampAssignerSupplier<T> timestampAssigner;
WatermarkStrategyWithTimestampAssigner(
WatermarkStrategy<T> baseStrategy, TimestampAssignerSupplier<T> timestampAssigner) {
this.baseStrategy = baseStrategy;
this.timestampAssigner = timestampAssigner;
}
@Override
public TimestampAssigner<T> createTimestampAssigner(TimestampAssignerSupplier.Context context) {
return timestampAssigner.createTimestampAssigner(context);
}
@Override
public WatermarkGenerator<T> createWatermarkGenerator(
WatermarkGeneratorSupplier.Context context) {
return baseStrategy.createWatermarkGenerator(context);
}
@Override
public WatermarkAlignmentParams getAlignmentParameters() {
return baseStrategy.getAlignmentParameters();
}
}
| WatermarkStrategyWithTimestampAssigner |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_1300/Issue1310.java | {
"start": 212,
"end": 572
} | class ____ extends TestCase {
public void test_trim() throws Exception {
Model model = new Model();
model.value = " a ";
assertEquals("{\"value\":\"a\"}", JSON.toJSONString(model));
Model model2 = JSON.parseObject("{\"value\":\" a \"}", Model.class);
assertEquals("a", model2.value);
}
public static | Issue1310 |
java | apache__camel | components/camel-avro-rpc/camel-avro-rpc-component/src/main/java/org/apache/camel/component/avro/AvroComponent.java | {
"start": 1258,
"end": 4626
} | class ____ extends DefaultComponent {
private final ConcurrentMap<String, AvroListener> listenerRegistry = new ConcurrentHashMap<>();
@Metadata(label = "advanced")
private AvroConfiguration configuration;
public AvroComponent() {
}
public AvroComponent(CamelContext context) {
super(context);
}
/**
* A factory method allowing derived components to create a new endpoint from the given URI, remaining path and
* optional parameters
*
* @param uri the full URI of the endpoint
* @param remaining the remaining part of the URI without the query parameters or component prefix
* @param parameters the optional parameters passed in
* @return a newly created endpoint or null if the endpoint cannot be created based on the inputs
*/
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
AvroConfiguration config;
if (configuration != null) {
config = configuration.copy();
} else {
config = new AvroConfiguration();
}
URI endpointUri = new URI(URISupport.normalizeUri(remaining));
config.parseURI(endpointUri);
Endpoint answer;
if (AvroConstants.AVRO_NETTY_TRANSPORT.equals(endpointUri.getScheme())) {
answer = new AvroNettyEndpoint(remaining, this, config);
} else if (AvroConstants.AVRO_HTTP_TRANSPORT.equals(endpointUri.getScheme())) {
answer = new AvroHttpEndpoint(remaining, this, config);
} else {
throw new IllegalArgumentException("Unknown avro scheme. Should use either netty or http.");
}
setProperties(answer, parameters);
return answer;
}
/**
* Registers new responder with uri as a key. Registers consumer in responder. In case if responder is already
* registered by this uri, then register consumer.
*
* @param uri URI of the endpoint without message name
* @param messageName message name
* @param consumer consumer that will be registered in providers` registry
* @throws Exception
*/
public void register(String uri, String messageName, AvroConsumer consumer) throws Exception {
AvroListener listener = listenerRegistry.get(uri);
if (listener == null) {
listener = new AvroListener(consumer.getEndpoint());
listenerRegistry.put(uri, listener);
}
listener.register(messageName, consumer);
}
/**
* Calls unregister of consumer by the appropriate message name. In case if all consumers are unregistered, then it
* removes responder from the registry.
*
* @param uri URI of the endpoint without message name
* @param messageName message name
*/
public void unregister(String uri, String messageName) {
if (listenerRegistry.get(uri).unregister(messageName)) {
listenerRegistry.remove(uri);
}
}
public AvroConfiguration getConfiguration() {
return configuration;
}
/**
* To use a shared {@link AvroConfiguration} to configure options once
*/
public void setConfiguration(AvroConfiguration configuration) {
this.configuration = configuration;
}
}
| AvroComponent |
java | quarkusio__quarkus | extensions/reactive-streams-operators/mutiny-reactive-streams-operators/deployment/src/test/java/io/quarkus/mutiny/reactive/operators/deployment/ReactiveStreamsOperatorsHotReloadTest.java | {
"start": 279,
"end": 934
} | class ____ {
@RegisterExtension
static final QuarkusDevModeTest test = new QuarkusDevModeTest()
.withApplicationRoot((jar) -> jar
.addClasses(io.quarkus.mutiny.reactive.operators.deployment.MyTestResource.class));
@Test
public void testHotReload() {
String resp = RestAssured.get("/test").asString();
Assertions.assertTrue(resp.startsWith("5"));
test.modifySourceFile(MyTestResource.class, s -> s.replace(".limit(2)", ".limit(10)"));
resp = RestAssured.get("/test").asString();
Assertions.assertTrue(resp.startsWith("9"));
}
}
| ReactiveStreamsOperatorsHotReloadTest |
java | apache__flink | flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/SavepointWriterTest.java | {
"start": 1411,
"end": 2789
} | class ____ {
@Test
void testCustomStateBackend() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
Configuration configuration = new Configuration();
configuration.set(
StateBackendOptions.STATE_BACKEND,
CustomStateBackendFactory.class.getCanonicalName());
configuration.set(ExecutionOptions.RUNTIME_MODE, RuntimeExecutionMode.BATCH);
assertThatThrownBy(
() ->
StateBackendLoader.fromApplicationOrConfigOrDefault(
null,
new Configuration(),
configuration,
ClassLoader.getSystemClassLoader(),
null))
.isInstanceOf(CustomStateBackendFactory.ExpectedException.class);
}
@Test
void testCantCreateSavepointFromNothing() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
assertThatThrownBy(() -> SavepointWriter.newSavepoint(env, 128).write("file:///tmp/path"))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("at least one operator to be created");
}
}
| SavepointWriterTest |
java | mapstruct__mapstruct | core/src/main/java/org/mapstruct/SubclassMapping.java | {
"start": 816,
"end": 2415
} | interface ____ {
* @SubclassMapping (target = TargetSubclass.class, source = SourceSubclass.class)
* TargetParent mapParent(SourceParent parent);
*
* TargetSubclass mapSubclass(SourceSubclass subInstant);
* }
* </code></pre>
* Below follow examples of the implementation for the mapParent method.
* <strong>Example 1:</strong> For parents that cannot be created. (e.g. abstract classes or interfaces)
* <pre><code class='java'>
* // generates
* @Override
* public TargetParent mapParent(SourceParent parent) {
* if (parent instanceof SourceSubclass) {
* return mapSubclass( (SourceSubclass) parent );
* }
* else {
* throw new IllegalArgumentException("Not all subclasses are supported for this mapping. Missing for "
* + parent.getClass());
* }
* }
* </code></pre>
* <strong>Example 2:</strong> For parents that can be created. (e.g. normal classes or interfaces with
* @Mapper( uses = ObjectFactory.class ) )
* <pre><code class='java'>
* // generates
* @Override
* public TargetParent mapParent(SourceParent parent) {
* TargetParent targetParent1;
* if (parent instanceof SourceSubclass) {
* targetParent1 = mapSubclass( (SourceSubclass) parent );
* }
* else {
* targetParent1 = new TargetParent();
* // ...
* }
* }
* </code></pre>
*
* @author Ben Zegveld
* @since 1.5
*/
@Repeatable(value = SubclassMappings.class)
@Retention(RetentionPolicy.CLASS)
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Experimental
public @ | MyMapper |
java | apache__camel | components/camel-mllp/src/test/java/org/apache/camel/test/stub/tcp/SocketStub.java | {
"start": 994,
"end": 4909
} | class ____ extends Socket {
public boolean connected = true;
public boolean inputShutdown;
public boolean outputShutdown;
public boolean closed;
public int receiveBufferSize = 1024;
public int sendBufferSize = 1024;
public int timeout = 1000;
public boolean linger;
public int lingerTimeout = 1024;
public SocketInputStreamStub inputStreamStub = new SocketInputStreamStub();
public SocketOutputStreamStub outputStreamStub = new SocketOutputStreamStub();
public boolean returnNullInputStream;
public boolean returnNullOutputStream;
public boolean throwExceptionOnClose;
public boolean throwExceptionOnShutdownInput;
public boolean throwExceptionOnShutdownOutput;
@Override
public InputStream getInputStream() throws IOException {
if (returnNullInputStream) {
return null;
}
if (isClosed()) {
throw new SocketException("Socket is closed");
}
if (!isConnected()) {
throw new SocketException("Socket is not connected");
}
if (isOutputShutdown()) {
throw new SocketException("Socket output is shutdown");
}
if (inputStreamStub == null) {
throw new IOException("Faking getInputStream failure");
}
return inputStreamStub;
}
@Override
public OutputStream getOutputStream() throws IOException {
if (returnNullOutputStream) {
return null;
}
if (isClosed()) {
throw new SocketException("Socket is closed");
}
if (!isConnected()) {
throw new SocketException("Socket is not connected");
}
if (isOutputShutdown()) {
throw new SocketException("Socket output is shutdown");
}
if (outputStreamStub == null) {
throw new IOException("Faking getOutputStream failure");
}
return outputStreamStub;
}
@Override
public void setSoLinger(boolean on, int linger) {
this.linger = on;
this.lingerTimeout = linger;
}
@Override
public int getSoLinger() {
if (linger) {
return lingerTimeout;
}
return -1;
}
@Override
public boolean isConnected() {
return connected;
}
@Override
public boolean isInputShutdown() {
return inputShutdown;
}
@Override
public boolean isOutputShutdown() {
return outputShutdown;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public void shutdownInput() throws IOException {
inputShutdown = true;
if (throwExceptionOnShutdownInput) {
throw new IOException("Faking a shutdownInput failure");
}
}
@Override
public void shutdownOutput() throws IOException {
outputShutdown = true;
if (throwExceptionOnShutdownOutput) {
throw new IOException("Faking a shutdownOutput failure");
}
}
@Override
public synchronized void close() throws IOException {
closed = true;
if (throwExceptionOnClose) {
throw new IOException("Faking a close failure");
}
}
@Override
public synchronized int getReceiveBufferSize() {
return receiveBufferSize;
}
@Override
public synchronized void setReceiveBufferSize(int size) {
this.receiveBufferSize = size;
}
@Override
public synchronized int getSendBufferSize() {
return sendBufferSize;
}
@Override
public synchronized void setSendBufferSize(int size) {
this.sendBufferSize = size;
}
@Override
public synchronized int getSoTimeout() {
return timeout;
}
@Override
public synchronized void setSoTimeout(int timeout) {
this.timeout = timeout;
}
}
| SocketStub |
java | micronaut-projects__micronaut-core | jackson-core/src/main/java/io/micronaut/jackson/core/env/EnvJsonPropertySourceLoader.java | {
"start": 1227,
"end": 3101
} | class ____ extends JsonPropertySourceLoader {
/**
* Position for the system property source loader in the chain.
*/
public static final int POSITION = SystemPropertiesPropertySource.POSITION + 50;
private static final String SPRING_APPLICATION_JSON = "SPRING_APPLICATION_JSON";
private static final String MICRONAUT_APPLICATION_JSON = "MICRONAUT_APPLICATION_JSON";
public EnvJsonPropertySourceLoader() {
}
public EnvJsonPropertySourceLoader(boolean logEnabled) {
super(logEnabled);
}
@Override
public int getOrder() {
return POSITION;
}
@Override
protected Optional<InputStream> readInput(ResourceLoader resourceLoader, String fileName) {
if (fileName.equals("application.json")) {
return getEnvValueAsStream();
}
return Optional.empty();
}
/**
* @return The JSON as input stream stored in the environment variables
* {@code SPRING_APPLICATION_JSON} or {@code MICRONAUT_APPLICATION_JSON}.
*/
protected Optional<InputStream> getEnvValueAsStream() {
String v = getEnvValue();
if (v != null) {
String encoding = CachedEnvironment.getProperty("file.encoding");
var charset = encoding != null ? Charset.forName(encoding) : StandardCharsets.UTF_8;
return Optional.of(new ByteArrayInputStream(v.getBytes(charset)));
}
return Optional.empty();
}
/**
* @return The JSON stored in the environment variables
* {@code SPRING_APPLICATION_JSON} or {@code MICRONAUT_APPLICATION_JSON}.
*/
protected String getEnvValue() {
String v = CachedEnvironment.getenv(SPRING_APPLICATION_JSON);
if (v == null) {
v = CachedEnvironment.getenv(MICRONAUT_APPLICATION_JSON);
}
return v;
}
}
| EnvJsonPropertySourceLoader |
java | apache__camel | components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/AddressEndpointConfiguration.java | {
"start": 1965,
"end": 4522
} | class ____ extends TwilioConfiguration {
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "creator")})
private String city;
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "creator")})
private String customerName;
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "creator")})
private String isoCountry;
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "creator"), @ApiMethod(methodName = "deleter"), @ApiMethod(methodName = "fetcher"), @ApiMethod(methodName = "reader"), @ApiMethod(methodName = "updater")})
private String pathAccountSid;
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "deleter"), @ApiMethod(methodName = "fetcher"), @ApiMethod(methodName = "updater")})
private String pathSid;
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "creator")})
private String postalCode;
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "creator")})
private String region;
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "creator")})
private String street;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getIsoCountry() {
return isoCountry;
}
public void setIsoCountry(String isoCountry) {
this.isoCountry = isoCountry;
}
public String getPathAccountSid() {
return pathAccountSid;
}
public void setPathAccountSid(String pathAccountSid) {
this.pathAccountSid = pathAccountSid;
}
public String getPathSid() {
return pathSid;
}
public void setPathSid(String pathSid) {
this.pathSid = pathSid;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
| AddressEndpointConfiguration |
java | apache__avro | lang/java/ipc/src/test/java/org/apache/avro/TestProtocolParsing.java | {
"start": 1019,
"end": 3443
} | class ____ {
public static Protocol getSimpleProtocol() throws IOException {
File file = new File("../../../share/test/schemas/simple.avpr");
return Protocol.parse(file);
}
@Test
void parsing() throws IOException {
Protocol protocol = getSimpleProtocol();
assertEquals(protocol.getDoc(), "Protocol used for testing.");
assertEquals(6, protocol.getMessages().size());
assertEquals("Pretend you're in a cave!", protocol.getMessages().get("echo").getDoc());
}
private static Message parseMessage(String message) throws Exception {
return Protocol.parse("{\"protocol\": \"org.foo.Bar\"," + "\"types\": []," + "\"messages\": {" + message + "}}")
.getMessages().values().iterator().next();
}
@Test
void oneWay() throws Exception {
Message m;
// permit one-way messages w/ null response
m = parseMessage("\"ack\": {" + "\"request\": []," + "\"response\": \"null\"," + "\"one-way\": true}");
assertTrue(m.isOneWay());
// permit one-way messages w/o response
m = parseMessage("\"ack\": {" + "\"request\": []," + "\"one-way\": true}");
assertTrue(m.isOneWay());
}
@Test
void oneWayResponse() throws Exception {
assertThrows(SchemaParseException.class, () -> {
// prohibit one-way messages with a non-null response type
parseMessage("\"ack\": {" + "\"request\": [\"string\"]," + "\"response\": \"string\"," + "\"one-way\": true}");
});
}
@Test
void oneWayError() throws Exception {
assertThrows(SchemaParseException.class, () -> {
// prohibit one-way messages with errors
parseMessage("\"ack\": {" + "\"request\": [\"string\"]," + "\"errors\": []," + "\"one-way\": true}");
});
}
@Test
void messageFieldAliases() throws IOException {
Protocol protocol = getSimpleProtocol();
final Message msg = protocol.getMessages().get("hello");
assertNotNull(msg);
final Schema.Field field = msg.getRequest().getField("greeting");
assertNotNull(field);
assertTrue(field.aliases().contains("salute"));
}
@Test
void messageCustomProperties() throws IOException {
Protocol protocol = getSimpleProtocol();
final Message msg = protocol.getMessages().get("hello");
assertNotNull(msg);
final Schema.Field field = msg.getRequest().getField("greeting");
assertNotNull(field);
assertEquals("customValue", field.getProp("customProp"));
}
}
| TestProtocolParsing |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/event/JobEventManager.java | {
"start": 1170,
"end": 3472
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(JobEventManager.class);
private final JobEventStore jobEventStore;
private boolean replaying = false;
private boolean running = false;
public JobEventManager(JobEventStore store) {
this.jobEventStore = checkNotNull(store);
}
/** Start the job event manager. */
public void start() throws Exception {
if (!running) {
jobEventStore.start();
running = true;
}
}
/**
* Stop the job event manager.
*
* <p>NOTE: This method maybe invoked multiply times.
*/
public void stop(boolean clear) {
if (running) {
jobEventStore.stop(clear);
running = false;
}
}
/**
* Write a job event asynchronously.
*
* @param event The job event that will be recorded.
* @param cutBlock whether start a new event block after write this event.
*/
public void writeEvent(JobEvent event, boolean cutBlock) {
checkState(running);
jobEventStore.writeEvent(event, cutBlock);
}
/**
* Replay all job events that have been record.
*
* @param replayHandler handler which will process the job event.
* @return <code>true</code> if replay successfully, <code>false</code> otherwise.
*/
public boolean replay(JobEventReplayHandler replayHandler) {
checkState(running);
try {
replaying = true;
replayHandler.startReplay();
JobEvent event;
while ((event = jobEventStore.readEvent()) != null) {
replayHandler.replayOneEvent(event);
}
replayHandler.finalizeReplay();
} catch (Throwable throwable) {
LOG.warn("Replay job event failed.", throwable);
return false;
} finally {
replaying = false;
}
return true;
}
/**
* Returns whether the store is empty.
*
* @return false if the store contains any job events, true otherwise.
*/
public boolean hasJobEvents() throws Exception {
return !jobEventStore.isEmpty();
}
@VisibleForTesting
boolean isRunning() {
return running;
}
}
| JobEventManager |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/plugins/PluginsServiceTests.java | {
"start": 31273,
"end": 32544
} | interface ____ be removed in a future release."
);
} finally {
closePluginLoaders(pluginService);
}
}
public void testDeprecatedPluginMethod() throws Exception {
final Path home = createTempDir();
final Settings settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), home).build();
final Path plugins = home.resolve("plugins");
final Path plugin = plugins.resolve("deprecated-plugin");
Files.createDirectories(plugin);
PluginTestUtil.writeSimplePluginDescriptor(plugin, "deprecated-plugin", "p.DeprecatedPlugin");
Path jar = plugin.resolve("impl.jar");
JarUtils.createJarWithEntries(jar, Map.of("p/DeprecatedPlugin.class", InMemoryJavaCompiler.compile("p.DeprecatedPlugin", """
package p;
import org.elasticsearch.cluster.routing.allocation.allocator.ShardsAllocator;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugins.ClusterPlugin;
import org.elasticsearch.plugins.Plugin;
import java.util.Map;
import java.util.function.Supplier;
public | will |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/aot/AotContextLoaderTests.java | {
"start": 1208,
"end": 3411
} | class ____ {
/**
* Verifies that a legacy {@link AotContextLoader} which only overrides
* {@link AotContextLoader#loadContextForAotProcessing(MergedContextConfiguration)
* is still supported.
*/
@Test // gh-34513
@SuppressWarnings("removal")
void legacyAotContextLoader() throws Exception {
// Prerequisites
assertDeclaringClasses(LegacyAotContextLoader.class, LegacyAotContextLoader.class, AotContextLoader.class);
AotContextLoader loader = spy(new LegacyAotContextLoader());
MergedContextConfiguration mergedConfig = new MergedContextConfiguration(getClass(), null, null, null, loader);
loader.loadContextForAotProcessing(mergedConfig, new RuntimeHints());
then(loader).should().loadContextForAotProcessing(mergedConfig);
}
/**
* Verifies that a modern {@link AotContextLoader} which only overrides
* {@link AotContextLoader#loadContextForAotProcessing(MergedContextConfiguration, RuntimeHints)
* is supported.
*/
@Test // gh-34513
@SuppressWarnings("removal")
void runtimeHintsAwareAotContextLoader() throws Exception {
// Prerequisites
assertDeclaringClasses(RuntimeHintsAwareAotContextLoader.class, AotContextLoader.class, RuntimeHintsAwareAotContextLoader.class);
AotContextLoader loader = spy(new RuntimeHintsAwareAotContextLoader());
MergedContextConfiguration mergedConfig = new MergedContextConfiguration(getClass(), null, null, null, loader);
loader.loadContextForAotProcessing(mergedConfig, new RuntimeHints());
then(loader).should(never()).loadContextForAotProcessing(mergedConfig);
}
private static void assertDeclaringClasses(Class<? extends AotContextLoader> loaderClass,
Class<?> declaringClassForLegacyMethod, Class<?> declaringClassForNewMethod) throws Exception {
Method legacyMethod = loaderClass.getMethod("loadContextForAotProcessing", MergedContextConfiguration.class);
Method newMethod = loaderClass.getMethod("loadContextForAotProcessing", MergedContextConfiguration.class, RuntimeHints.class);
assertThat(legacyMethod.getDeclaringClass()).isEqualTo(declaringClassForLegacyMethod);
assertThat(newMethod.getDeclaringClass()).isEqualTo(declaringClassForNewMethod);
}
private static | AotContextLoaderTests |
java | quarkusio__quarkus | extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/engineconfigurations/resolver/CustomResolversTest.java | {
"start": 1677,
"end": 2004
} | class ____ implements NamespaceResolver {
@Override
public CompletionStage<Object> resolve(EvalContext context) {
return CompletableFuture.completedStage("foo");
}
@Override
public String getNamespace() {
return "custom";
}
}
}
| CustomNamespaceResolver |
java | quarkusio__quarkus | extensions/oidc/runtime/src/main/java/io/quarkus/oidc/OidcTenantConfig.java | {
"start": 103957,
"end": 113645
} | enum ____ {
APPLE,
DISCORD,
FACEBOOK,
GITHUB,
GOOGLE,
LINKEDIN,
MASTODON,
MICROSOFT,
SLACK,
SPOTIFY,
STRAVA,
TWITCH,
TWITTER,
// New name for Twitter
X
}
/**
* @deprecated use the {@link #provider()} method instead
*/
@Deprecated(since = "3.18", forRemoval = true)
public Optional<Provider> getProvider() {
return provider;
}
/**
* @deprecated build this config with the {@link OidcTenantConfigBuilder} builder
*/
@Deprecated(since = "3.18", forRemoval = true)
public void setProvider(Provider provider) {
this.provider = Optional.of(provider);
}
/**
* @deprecated use the {@link #applicationType()} method instead
*/
@Deprecated(since = "3.18", forRemoval = true)
public Optional<ApplicationType> getApplicationType() {
return applicationType;
}
/**
* @deprecated build this config with the {@link OidcTenantConfigBuilder} builder
*/
@Deprecated(since = "3.18", forRemoval = true)
public void setApplicationType(ApplicationType type) {
this.applicationType = Optional.of(type);
}
/**
* @deprecated use the {@link #allowTokenIntrospectionCache()} method instead
*/
@Deprecated(since = "3.18", forRemoval = true)
public boolean isAllowTokenIntrospectionCache() {
return allowTokenIntrospectionCache();
}
/**
* @deprecated build this config with the {@link OidcTenantConfigBuilder} builder
*/
@Deprecated(since = "3.18", forRemoval = true)
public void setAllowTokenIntrospectionCache(boolean allowTokenIntrospectionCache) {
this.allowTokenIntrospectionCache = allowTokenIntrospectionCache;
}
/**
* @deprecated use the {@link #allowUserInfoCache()} method instead
*/
@Deprecated(since = "3.18", forRemoval = true)
public boolean isAllowUserInfoCache() {
return allowUserInfoCache();
}
/**
* @deprecated build this config with the {@link OidcTenantConfigBuilder} builder
*/
@Deprecated(since = "3.18", forRemoval = true)
public void setAllowUserInfoCache(boolean allowUserInfoCache) {
this.allowUserInfoCache = allowUserInfoCache;
}
/**
* @deprecated use the {@link #cacheUserInfoInIdtoken()} method instead
*/
@Deprecated(since = "3.18", forRemoval = true)
public Optional<Boolean> isCacheUserInfoInIdtoken() {
return cacheUserInfoInIdtoken();
}
/**
* @deprecated build this config with the {@link OidcTenantConfigBuilder} builder
*/
@Deprecated(since = "3.18", forRemoval = true)
public void setCacheUserInfoInIdtoken(boolean cacheUserInfoInIdtoken) {
this.cacheUserInfoInIdtoken = Optional.of(cacheUserInfoInIdtoken);
}
/**
* @deprecated use the {@link #introspectionCredentials()} method instead
*/
@Deprecated(since = "3.18", forRemoval = true)
public IntrospectionCredentials getIntrospectionCredentials() {
return introspectionCredentials;
}
/**
* @deprecated build this config with the {@link OidcTenantConfigBuilder} builder
*/
@Deprecated(since = "3.18", forRemoval = true)
public void setIntrospectionCredentials(IntrospectionCredentials introspectionCredentials) {
this.introspectionCredentials = introspectionCredentials;
}
/**
* @deprecated use the {@link #codeGrant()} method instead
*/
@Deprecated(since = "3.18", forRemoval = true)
public CodeGrant getCodeGrant() {
return codeGrant;
}
/**
* @deprecated build this config with the {@link OidcTenantConfigBuilder} builder
*/
@Deprecated(since = "3.18", forRemoval = true)
public void setCodeGrant(CodeGrant codeGrant) {
this.codeGrant = codeGrant;
}
/**
* @deprecated use the {@link #certificateChain()} method instead
*/
@Deprecated(since = "3.18", forRemoval = true)
public CertificateChain getCertificateChain() {
return certificateChain;
}
/**
* @deprecated build this config with the {@link OidcTenantConfigBuilder} builder
*/
@Deprecated(since = "3.18", forRemoval = true)
public void setCertificateChain(CertificateChain certificateChain) {
this.certificateChain = certificateChain;
}
@Override
public Optional<String> tenantId() {
return tenantId;
}
@Override
public boolean tenantEnabled() {
return tenantEnabled;
}
@Override
public Optional<io.quarkus.oidc.runtime.OidcTenantConfig.ApplicationType> applicationType() {
return applicationType.map(Enum::toString).map(io.quarkus.oidc.runtime.OidcTenantConfig.ApplicationType::valueOf);
}
@Override
public Optional<String> authorizationPath() {
return authorizationPath;
}
@Override
public Optional<String> userInfoPath() {
return userInfoPath;
}
@Override
public Optional<String> introspectionPath() {
return introspectionPath;
}
@Override
public Optional<String> jwksPath() {
return jwksPath;
}
@Override
public Optional<String> endSessionPath() {
return endSessionPath;
}
@Override
public Optional<List<String>> tenantPaths() {
return tenantPaths;
}
@Override
public Optional<String> publicKey() {
return publicKey;
}
@Override
public io.quarkus.oidc.runtime.OidcTenantConfig.IntrospectionCredentials introspectionCredentials() {
return introspectionCredentials;
}
@Override
public io.quarkus.oidc.runtime.OidcTenantConfig.Roles roles() {
return roles;
}
@Override
public io.quarkus.oidc.runtime.OidcTenantConfig.Token token() {
return token;
}
@Override
public io.quarkus.oidc.runtime.OidcTenantConfig.Logout logout() {
return logout;
}
@Override
public io.quarkus.oidc.runtime.OidcTenantConfig.ResourceMetadata resourceMetadata() {
return resourceMetadata;
}
@Override
public io.quarkus.oidc.runtime.OidcTenantConfig.CertificateChain certificateChain() {
return certificateChain;
}
@Override
public io.quarkus.oidc.runtime.OidcTenantConfig.Authentication authentication() {
return authentication;
}
@Override
public io.quarkus.oidc.runtime.OidcTenantConfig.CodeGrant codeGrant() {
return codeGrant;
}
@Override
public io.quarkus.oidc.runtime.OidcTenantConfig.TokenStateManager tokenStateManager() {
return tokenStateManager;
}
@Override
public boolean allowTokenIntrospectionCache() {
return allowTokenIntrospectionCache;
}
@Override
public boolean allowUserInfoCache() {
return allowUserInfoCache;
}
@Override
public Optional<Boolean> cacheUserInfoInIdtoken() {
return cacheUserInfoInIdtoken;
}
@Override
public io.quarkus.oidc.runtime.OidcTenantConfig.Jwks jwks() {
return jwks;
}
@Override
public Optional<io.quarkus.oidc.runtime.OidcTenantConfig.Provider> provider() {
return provider.map(Enum::toString).map(io.quarkus.oidc.runtime.OidcTenantConfig.Provider::valueOf);
}
/**
* Creates {@link OidcTenantConfigBuilder} builder populated with documented default values.
*
* @return OidcTenantConfigBuilder builder
*/
public static OidcTenantConfigBuilder builder() {
return new OidcTenantConfigBuilder();
}
/**
* Creates {@link OidcTenantConfigBuilder} builder from the existing {@link io.quarkus.oidc.runtime.OidcTenantConfig}
*
* @param mapping existing io.quarkus.oidc.runtime.OidcTenantConfig
*/
public static OidcTenantConfigBuilder builder(io.quarkus.oidc.runtime.OidcTenantConfig mapping) {
return new OidcTenantConfigBuilder(mapping);
}
/**
* Creates {@link OidcTenantConfig} from the {@code mapping}. This method is more efficient than
* the {@link #builder()} method if you don't need to modify the {@code mapping}.
*
* @param mapping existing io.quarkus.oidc.runtime.OidcTenantConfig
* @return OidcTenantConfig
*/
public static OidcTenantConfig of(io.quarkus.oidc.runtime.OidcTenantConfig mapping) {
return new OidcTenantConfig(mapping);
}
/**
* Creates {@link OidcTenantConfigBuilder} builder populated with documented default values and the provided base URL.
*
* @param authServerUrl {@link #authServerUrl()}
* @return OidcTenantConfigBuilder builder
*/
public static OidcTenantConfigBuilder authServerUrl(String authServerUrl) {
return builder().authServerUrl(authServerUrl);
}
/**
* Creates {@link OidcTenantConfigBuilder} builder populated with documented default values and the provided client
* registration path.
*
* @param registrationPath {@link #registrationPath()}
* @return OidcTenantConfigBuilder builder
*/
public static OidcTenantConfigBuilder registrationPath(String registrationPath) {
return builder().registrationPath(registrationPath);
}
/**
* Creates {@link OidcTenantConfigBuilder} builder populated with documented default values and the provided token path.
*
* @param tokenPath {@link #tokenPath()}
* @return OidcTenantConfigBuilder builder
*/
public static OidcTenantConfigBuilder tokenPath(String tokenPath) {
return builder().tokenPath(tokenPath);
}
}
| Provider |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/struct/POJOAsArrayWithAnyGetter4961Test.java | {
"start": 529,
"end": 744
} | class ____ {
public BeanWithAnyGetter value;
}
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
@JsonPropertyOrder({ "firstProperty", "secondProperties", "forthProperty" })
static | WrapperForAnyGetter |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java | {
"start": 117709,
"end": 117936
} | interface ____ {
Stepped setThreeAndBuild(double x);
}
public static StepOne<String> builder() {
return new AutoValue_AutoValueTest_Stepped.Builder();
}
@AutoValue.Builder
abstract static | StepThree |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/coordination/stateless/AtomicRegisterPreVoteCollector.java | {
"start": 877,
"end": 1852
} | class ____ extends PreVoteCollector {
private static final Logger logger = LogManager.getLogger(AtomicRegisterPreVoteCollector.class);
private final StoreHeartbeatService heartbeatService;
private final Runnable startElection;
public AtomicRegisterPreVoteCollector(StoreHeartbeatService heartbeatService, Runnable startElection) {
this.heartbeatService = heartbeatService;
this.startElection = startElection;
}
@Override
public Releasable start(ClusterState clusterState, Iterable<DiscoveryNode> broadcastNodes) {
final var shouldRun = new AtomicBoolean(true);
heartbeatService.checkLeaderHeartbeatAndRun(() -> {
if (shouldRun.getAndSet(false)) {
startElection.run();
}
}, heartbeat -> logger.info("skipping election since there is a recent heartbeat[{}] from the leader", heartbeat));
return () -> shouldRun.set(false);
}
}
| AtomicRegisterPreVoteCollector |
java | quarkusio__quarkus | extensions/panache/mongodb-panache-common/deployment/src/test/java/io/quarkus/mongodb/panache/common/MongoDatabaseResolverTest.java | {
"start": 7704,
"end": 7873
} | class ____ {
@BsonId
public Long id;
public String firstname;
public String lastname;
}
@ApplicationScoped
private static | Person |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryMethodReferenceTest.java | {
"start": 5842,
"end": 6242
} | class ____ {
void a(Converter<Integer, String> fn) {
// BUG: Diagnostic contains: b(fn)
b(fn::convert);
}
void b(Function<Integer, String> fn) {}
}
""")
.doTest();
}
@Test
public void ignoreSuper() {
helper
.addSourceLines(
"S.java",
"""
| Test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.