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
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/TestInternalTimerService.java
|
{
"start": 1225,
"end": 5508
}
|
class ____<K, N> implements InternalTimerService<N> {
private long currentProcessingTime = Long.MIN_VALUE;
private long currentWatermark = Long.MIN_VALUE;
private final KeyContext keyContext;
/** Processing time timers that are currently in-flight. */
private final PriorityQueue<Timer<K, N>> processingTimeTimersQueue;
private final Set<Timer<K, N>> processingTimeTimers;
/** Current waiting watermark callbacks. */
private final Set<Timer<K, N>> watermarkTimers;
private final PriorityQueue<Timer<K, N>> watermarkTimersQueue;
public TestInternalTimerService(KeyContext keyContext) {
this.keyContext = keyContext;
watermarkTimers = new HashSet<>();
watermarkTimersQueue = new PriorityQueue<>(100);
processingTimeTimers = new HashSet<>();
processingTimeTimersQueue = new PriorityQueue<>(100);
}
@Override
public long currentProcessingTime() {
return currentProcessingTime;
}
@Override
public long currentWatermark() {
return currentWatermark;
}
@Override
public void initializeWatermark(long watermark) {
this.currentWatermark = watermark;
}
@Override
public void registerProcessingTimeTimer(N namespace, long time) {
@SuppressWarnings("unchecked")
Timer<K, N> timer = new Timer<>(time, (K) keyContext.getCurrentKey(), namespace);
// make sure we only put one timer per key into the queue
if (processingTimeTimers.add(timer)) {
processingTimeTimersQueue.add(timer);
}
}
@Override
public void registerEventTimeTimer(N namespace, long time) {
@SuppressWarnings("unchecked")
Timer<K, N> timer = new Timer<>(time, (K) keyContext.getCurrentKey(), namespace);
if (watermarkTimers.add(timer)) {
watermarkTimersQueue.add(timer);
}
}
@Override
public void deleteProcessingTimeTimer(N namespace, long time) {
@SuppressWarnings("unchecked")
Timer<K, N> timer = new Timer<>(time, (K) keyContext.getCurrentKey(), namespace);
if (processingTimeTimers.remove(timer)) {
processingTimeTimersQueue.remove(timer);
}
}
@Override
public void deleteEventTimeTimer(N namespace, long time) {
@SuppressWarnings("unchecked")
Timer<K, N> timer = new Timer<>(time, (K) keyContext.getCurrentKey(), namespace);
if (watermarkTimers.remove(timer)) {
watermarkTimersQueue.remove(timer);
}
}
@Override
public void forEachEventTimeTimer(BiConsumerWithException<N, Long, Exception> consumer)
throws Exception {
for (Timer<K, N> timer : watermarkTimers) {
keyContext.setCurrentKey(timer.getKey());
consumer.accept(timer.getNamespace(), timer.getTimestamp());
}
}
@Override
public void forEachProcessingTimeTimer(BiConsumerWithException<N, Long, Exception> consumer)
throws Exception {
for (Timer<K, N> timer : processingTimeTimers) {
keyContext.setCurrentKey(timer.getKey());
consumer.accept(timer.getNamespace(), timer.getTimestamp());
}
}
public Collection<Timer<K, N>> advanceProcessingTime(long time) throws Exception {
List<Timer<K, N>> result = new ArrayList<>();
Timer<K, N> timer = processingTimeTimersQueue.peek();
while (timer != null && timer.timestamp <= time) {
processingTimeTimers.remove(timer);
processingTimeTimersQueue.remove();
result.add(timer);
timer = processingTimeTimersQueue.peek();
}
currentProcessingTime = time;
return result;
}
public Collection<Timer<K, N>> advanceWatermark(long time) throws Exception {
List<Timer<K, N>> result = new ArrayList<>();
Timer<K, N> timer = watermarkTimersQueue.peek();
while (timer != null && timer.timestamp <= time) {
watermarkTimers.remove(timer);
watermarkTimersQueue.remove();
result.add(timer);
timer = watermarkTimersQueue.peek();
}
currentWatermark = time;
return result;
}
/** Internal
|
TestInternalTimerService
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/index/mapper/MappingLookupTests.java
|
{
"start": 1452,
"end": 9225
}
|
class ____ extends ESTestCase {
private static MappingLookup createMappingLookup(
List<FieldMapper> fieldMappers,
List<ObjectMapper> objectMappers,
List<RuntimeField> runtimeFields
) {
RootObjectMapper.Builder builder = new RootObjectMapper.Builder("_doc", ObjectMapper.Defaults.SUBOBJECTS);
Map<String, RuntimeField> runtimeFieldTypes = runtimeFields.stream().collect(Collectors.toMap(RuntimeField::name, r -> r));
builder.addRuntimeFields(runtimeFieldTypes);
Mapping mapping = new Mapping(
builder.build(MapperBuilderContext.root(false, false)),
new MetadataFieldMapper[0],
Collections.emptyMap()
);
return MappingLookup.fromMappers(mapping, fieldMappers, objectMappers);
}
public void testOnlyRuntimeField() {
MappingLookup mappingLookup = createMappingLookup(
emptyList(),
emptyList(),
Collections.singletonList(new TestRuntimeField("test", "type"))
);
assertEquals(0, size(mappingLookup.fieldMappers()));
assertEquals(0, mappingLookup.objectMappers().size());
assertNull(mappingLookup.getMapper("test"));
assertThat(mappingLookup.fieldTypesLookup().get("test"), instanceOf(TestRuntimeField.TestRuntimeFieldType.class));
}
public void testRuntimeFieldLeafOverride() {
MockFieldMapper fieldMapper = new MockFieldMapper("test");
MappingLookup mappingLookup = createMappingLookup(
Collections.singletonList(fieldMapper),
emptyList(),
Collections.singletonList(new TestRuntimeField("test", "type"))
);
assertThat(mappingLookup.getMapper("test"), instanceOf(MockFieldMapper.class));
assertEquals(1, size(mappingLookup.fieldMappers()));
assertEquals(0, mappingLookup.objectMappers().size());
assertThat(mappingLookup.fieldTypesLookup().get("test"), instanceOf(TestRuntimeField.TestRuntimeFieldType.class));
}
public void testSubfieldOverride() {
MockFieldMapper fieldMapper = new MockFieldMapper("object.subfield");
ObjectMapper objectMapper = new ObjectMapper(
"object",
"object",
Explicit.EXPLICIT_TRUE,
ObjectMapper.Defaults.SUBOBJECTS,
Optional.empty(),
ObjectMapper.Dynamic.TRUE,
Collections.singletonMap("object.subfield", fieldMapper)
);
MappingLookup mappingLookup = createMappingLookup(
Collections.singletonList(fieldMapper),
Collections.singletonList(objectMapper),
Collections.singletonList(new TestRuntimeField("object.subfield", "type"))
);
assertThat(mappingLookup.getMapper("object.subfield"), instanceOf(MockFieldMapper.class));
assertEquals(1, size(mappingLookup.fieldMappers()));
assertEquals(1, mappingLookup.objectMappers().size());
assertThat(mappingLookup.fieldTypesLookup().get("object.subfield"), instanceOf(TestRuntimeField.TestRuntimeFieldType.class));
}
public void testAnalyzers() throws IOException {
FakeFieldType fieldType1 = new FakeFieldType("field1");
FieldMapper fieldMapper1 = new FakeFieldMapper(fieldType1, "index1");
FakeFieldType fieldType2 = new FakeFieldType("field2");
FieldMapper fieldMapper2 = new FakeFieldMapper(fieldType2, "index2");
MappingLookup mappingLookup = createMappingLookup(Arrays.asList(fieldMapper1, fieldMapper2), emptyList(), emptyList());
assertAnalyzes(mappingLookup.indexAnalyzer("field1", f -> null), "field1", "index1");
assertAnalyzes(mappingLookup.indexAnalyzer("field2", f -> null), "field2", "index2");
expectThrows(
IllegalArgumentException.class,
() -> mappingLookup.indexAnalyzer("field3", f -> { throw new IllegalArgumentException(); }).tokenStream("field3", "blah")
);
}
public void testEmptyMappingLookup() {
MappingLookup mappingLookup = MappingLookup.EMPTY;
assertEquals("{\"_doc\":{}}", Strings.toString(mappingLookup.getMapping()));
assertFalse(mappingLookup.hasMappings());
assertNull(mappingLookup.getMapping().getMeta());
assertEquals(0, mappingLookup.getMapping().getMetadataMappersMap().size());
assertFalse(mappingLookup.fieldMappers().iterator().hasNext());
assertEquals(0, mappingLookup.getMatchingFieldNames("*").size());
}
public void testValidateDoesNotShadow() {
FakeFieldType dim = new FakeFieldType("dim") {
@Override
public boolean isDimension() {
return true;
}
};
FieldMapper dimMapper = new FakeFieldMapper(dim, "index1");
MetricType metricType = randomFrom(MetricType.values());
FakeFieldType metric = new FakeFieldType("metric") {
@Override
public MetricType getMetricType() {
return metricType;
}
};
FieldMapper metricMapper = new FakeFieldMapper(metric, "index1");
FakeFieldType plain = new FakeFieldType("plain");
FieldMapper plainMapper = new FakeFieldMapper(plain, "index1");
MappingLookup mappingLookup = createMappingLookup(List.of(dimMapper, metricMapper, plainMapper), emptyList(), emptyList());
mappingLookup.validateDoesNotShadow("not_mapped");
Exception e = expectThrows(MapperParsingException.class, () -> mappingLookup.validateDoesNotShadow("dim"));
assertThat(e.getMessage(), equalTo("Field [dim] attempted to shadow a time_series_dimension"));
e = expectThrows(MapperParsingException.class, () -> mappingLookup.validateDoesNotShadow("metric"));
assertThat(e.getMessage(), equalTo("Field [metric] attempted to shadow a time_series_metric"));
mappingLookup.validateDoesNotShadow("plain");
}
public void testShadowingOnConstruction() {
FakeFieldType dim = new FakeFieldType("dim") {
@Override
public boolean isDimension() {
return true;
}
};
FieldMapper dimMapper = new FakeFieldMapper(dim, "index1");
MetricType metricType = randomFrom(MetricType.values());
FakeFieldType metric = new FakeFieldType("metric") {
@Override
public MetricType getMetricType() {
return metricType;
}
};
FieldMapper metricMapper = new FakeFieldMapper(metric, "index1");
boolean shadowDim = randomBoolean();
TestRuntimeField shadowing = new TestRuntimeField(shadowDim ? "dim" : "metric", "keyword");
Exception e = expectThrows(
MapperParsingException.class,
() -> createMappingLookup(List.of(dimMapper, metricMapper), emptyList(), List.of(shadowing))
);
assertThat(
e.getMessage(),
equalTo(
shadowDim
? "Field [dim] attempted to shadow a time_series_dimension"
: "Field [metric] attempted to shadow a time_series_metric"
)
);
}
private void assertAnalyzes(Analyzer analyzer, String field, String output) throws IOException {
try (TokenStream tok = analyzer.tokenStream(field, new StringReader(""))) {
CharTermAttribute term = tok.addAttribute(CharTermAttribute.class);
assertTrue(tok.incrementToken());
assertEquals(output, term.toString());
}
}
private static int size(Iterable<?> iterable) {
int count = 0;
for (Object obj : iterable) {
count++;
}
return count;
}
private static
|
MappingLookupTests
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/context/annotation/TestBeanNameGenerator.java
|
{
"start": 851,
"end": 1127
}
|
class ____ extends AnnotationBeanNameGenerator {
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
String beanName = super.generateBeanName(definition, registry);
return "testing." + beanName;
}
}
|
TestBeanNameGenerator
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/joinorder/JoinOrderTest.java
|
{
"start": 1686,
"end": 1815
}
|
class ____ {
@Id @GeneratedValue Long id;
}
@Entity(name = "TaskEventLog")
@Table(name = "vin_task_event_log")
public
|
Vineyard
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/dataframe/MappingsMergerTests.java
|
{
"start": 970,
"end": 13505
}
|
class ____ extends ESTestCase {
public void testMergeMappings_GivenIndicesWithIdenticalProperties() {
Map<String, Object> index1Mappings = Map.of("properties", Map.of("field_1", "field_1_mappings", "field_2", "field_2_mappings"));
MappingMetadata index1MappingMetadata = new MappingMetadata("_doc", index1Mappings);
Map<String, Object> index2Mappings = Map.of("properties", Map.of("field_1", "field_1_mappings", "field_2", "field_2_mappings"));
MappingMetadata index2MappingMetadata = new MappingMetadata("_doc", index2Mappings);
Map<String, MappingMetadata> mappings = Map.of("index_1", index1MappingMetadata, "index_2", index2MappingMetadata);
GetMappingsResponse getMappingsResponse = new GetMappingsResponse(mappings);
MappingMetadata mergedMappings = MappingsMerger.mergeMappings(newSource(), getMappingsResponse);
Map<String, Object> expectedMappings = new HashMap<>();
expectedMappings.put("dynamic", false);
expectedMappings.put("properties", index1Mappings.get("properties"));
assertThat(mergedMappings.getSourceAsMap(), equalTo(expectedMappings));
}
public void testMergeMappings_GivenPropertyFieldWithDifferentMapping() {
Map<String, Object> index1Mappings = Map.of("properties", Map.of("field_1", "field_1_mappings"));
MappingMetadata index1MappingMetadata = new MappingMetadata("_doc", index1Mappings);
Map<String, Object> index2Mappings = Map.of("properties", Map.of("field_1", "different_field_1_mappings"));
MappingMetadata index2MappingMetadata = new MappingMetadata("_doc", index2Mappings);
Map<String, MappingMetadata> mappings = Map.of("index_1", index1MappingMetadata, "index_2", index2MappingMetadata);
GetMappingsResponse getMappingsResponse = new GetMappingsResponse(mappings);
ElasticsearchStatusException e = expectThrows(
ElasticsearchStatusException.class,
() -> MappingsMerger.mergeMappings(newSource(), getMappingsResponse)
);
assertThat(e.status(), equalTo(RestStatus.BAD_REQUEST));
assertThat(e.getMessage(), containsString("cannot merge [properties] mappings because of differences for field [field_1]; "));
assertThat(e.getMessage(), containsString("mapped as [different_field_1_mappings] in index [index_2]"));
assertThat(e.getMessage(), containsString("mapped as [field_1_mappings] in index [index_1]"));
}
public void testMergeMappings_GivenIndicesWithDifferentPropertiesButNoConflicts() {
Map<String, Object> index1Mappings = Map.of("properties", Map.of("field_1", "field_1_mappings", "field_2", "field_2_mappings"));
MappingMetadata index1MappingMetadata = new MappingMetadata("_doc", index1Mappings);
Map<String, Object> index2Mappings = Map.of("properties", Map.of("field_1", "field_1_mappings", "field_3", "field_3_mappings"));
MappingMetadata index2MappingMetadata = new MappingMetadata("_doc", index2Mappings);
Map<String, MappingMetadata> mappings = Map.of("index_1", index1MappingMetadata, "index_2", index2MappingMetadata);
GetMappingsResponse getMappingsResponse = new GetMappingsResponse(mappings);
MappingMetadata mergedMappings = MappingsMerger.mergeMappings(newSource(), getMappingsResponse);
Map<String, Object> mappingsAsMap = mergedMappings.getSourceAsMap();
assertThat(mappingsAsMap.keySet(), containsInAnyOrder("dynamic", "properties"));
assertThat(mappingsAsMap.get("dynamic"), equalTo(false));
@SuppressWarnings("unchecked")
Map<String, Object> fieldMappings = (Map<String, Object>) mappingsAsMap.get("properties");
assertThat(fieldMappings.keySet(), containsInAnyOrder("field_1", "field_2", "field_3"));
assertThat(fieldMappings.get("field_1"), equalTo("field_1_mappings"));
assertThat(fieldMappings.get("field_2"), equalTo("field_2_mappings"));
assertThat(fieldMappings.get("field_3"), equalTo("field_3_mappings"));
}
public void testMergeMappings_GivenIndicesWithIdenticalRuntimeFields() {
Map<String, Object> index1Mappings = Map.of("runtime", Map.of("field_1", "field_1_mappings", "field_2", "field_2_mappings"));
MappingMetadata index1MappingMetadata = new MappingMetadata("_doc", index1Mappings);
Map<String, Object> index2Mappings = Map.of("runtime", Map.of("field_1", "field_1_mappings", "field_2", "field_2_mappings"));
MappingMetadata index2MappingMetadata = new MappingMetadata("_doc", index2Mappings);
Map<String, MappingMetadata> mappings = Map.of("index_1", index1MappingMetadata, "index_2", index2MappingMetadata);
GetMappingsResponse getMappingsResponse = new GetMappingsResponse(mappings);
MappingMetadata mergedMappings = MappingsMerger.mergeMappings(newSource(), getMappingsResponse);
Map<String, Object> expectedMappings = new HashMap<>();
expectedMappings.put("dynamic", false);
expectedMappings.put("runtime", index1Mappings.get("runtime"));
assertThat(mergedMappings.getSourceAsMap(), equalTo(expectedMappings));
}
public void testMergeMappings_GivenRuntimeFieldWithDifferentMapping() {
Map<String, Object> index1Mappings = Map.of("runtime", Map.of("field_1", "field_1_mappings"));
MappingMetadata index1MappingMetadata = new MappingMetadata("_doc", index1Mappings);
Map<String, Object> index2Mappings = Map.of("runtime", Map.of("field_1", "different_field_1_mappings"));
MappingMetadata index2MappingMetadata = new MappingMetadata("_doc", index2Mappings);
Map<String, MappingMetadata> mappings = Map.of("index_1", index1MappingMetadata, "index_2", index2MappingMetadata);
GetMappingsResponse getMappingsResponse = new GetMappingsResponse(mappings);
ElasticsearchStatusException e = expectThrows(
ElasticsearchStatusException.class,
() -> MappingsMerger.mergeMappings(newSource(), getMappingsResponse)
);
assertThat(e.status(), equalTo(RestStatus.BAD_REQUEST));
assertThat(e.getMessage(), containsString("cannot merge [runtime] mappings because of differences for field [field_1]; "));
assertThat(e.getMessage(), containsString("mapped as [different_field_1_mappings] in index [index_2]"));
assertThat(e.getMessage(), containsString("mapped as [field_1_mappings] in index [index_1]"));
}
public void testMergeMappings_GivenIndicesWithDifferentRuntimeFieldsButNoConflicts() {
Map<String, Object> index1Mappings = Map.of("runtime", Map.of("field_1", "field_1_mappings", "field_2", "field_2_mappings"));
MappingMetadata index1MappingMetadata = new MappingMetadata("_doc", index1Mappings);
Map<String, Object> index2Mappings = Map.of("runtime", Map.of("field_1", "field_1_mappings", "field_3", "field_3_mappings"));
MappingMetadata index2MappingMetadata = new MappingMetadata("_doc", index2Mappings);
Map<String, MappingMetadata> mappings = Map.of("index_1", index1MappingMetadata, "index_2", index2MappingMetadata);
GetMappingsResponse getMappingsResponse = new GetMappingsResponse(mappings);
MappingMetadata mergedMappings = MappingsMerger.mergeMappings(newSource(), getMappingsResponse);
Map<String, Object> mappingsAsMap = mergedMappings.getSourceAsMap();
assertThat(mappingsAsMap.keySet(), containsInAnyOrder("dynamic", "runtime"));
assertThat(mappingsAsMap.get("dynamic"), is(false));
@SuppressWarnings("unchecked")
Map<String, Object> fieldMappings = (Map<String, Object>) mappingsAsMap.get("runtime");
assertThat(fieldMappings.keySet(), containsInAnyOrder("field_1", "field_2", "field_3"));
assertThat(fieldMappings.get("field_1"), equalTo("field_1_mappings"));
assertThat(fieldMappings.get("field_2"), equalTo("field_2_mappings"));
assertThat(fieldMappings.get("field_3"), equalTo("field_3_mappings"));
}
public void testMergeMappings_GivenPropertyAndRuntimeFields() {
Map<String, Object> index1Mappings = new HashMap<>();
{
Map<String, Object> index1Properties = new HashMap<>();
index1Properties.put("p_1", "p_1_mappings");
Map<String, Object> index1Runtime = new HashMap<>();
index1Runtime.put("r_1", "r_1_mappings");
index1Mappings.put("properties", index1Properties);
index1Mappings.put("runtime", index1Runtime);
}
MappingMetadata index1MappingMetadata = new MappingMetadata("_doc", index1Mappings);
Map<String, Object> index2Mappings = new HashMap<>();
{
Map<String, Object> index2Properties = new HashMap<>();
index2Properties.put("p_2", "p_2_mappings");
Map<String, Object> index2Runtime = new HashMap<>();
index2Runtime.put("r_2", "r_2_mappings");
index2Runtime.put("p_1", "p_1_different_mappings"); // It is ok to have conflicting runtime/property mappings
index2Mappings.put("properties", index2Properties);
index2Mappings.put("runtime", index2Runtime);
}
MappingMetadata index2MappingMetadata = new MappingMetadata("_doc", index2Mappings);
Map<String, MappingMetadata> mappings = Map.of("index_1", index1MappingMetadata, "index_2", index2MappingMetadata);
GetMappingsResponse getMappingsResponse = new GetMappingsResponse(mappings);
MappingMetadata mergedMappings = MappingsMerger.mergeMappings(newSource(), getMappingsResponse);
Map<String, Object> mappingsAsMap = mergedMappings.getSourceAsMap();
assertThat(mappingsAsMap.keySet(), containsInAnyOrder("dynamic", "properties", "runtime"));
assertThat(mappingsAsMap.get("dynamic"), is(false));
@SuppressWarnings("unchecked")
Map<String, Object> mergedProperties = (Map<String, Object>) mappingsAsMap.get("properties");
assertThat(mergedProperties.keySet(), containsInAnyOrder("p_1", "p_2"));
assertThat(mergedProperties.get("p_1"), equalTo("p_1_mappings"));
assertThat(mergedProperties.get("p_2"), equalTo("p_2_mappings"));
@SuppressWarnings("unchecked")
Map<String, Object> mergedRuntime = (Map<String, Object>) mappingsAsMap.get("runtime");
assertThat(mergedRuntime.keySet(), containsInAnyOrder("r_1", "r_2", "p_1"));
assertThat(mergedRuntime.get("r_1"), equalTo("r_1_mappings"));
assertThat(mergedRuntime.get("r_2"), equalTo("r_2_mappings"));
assertThat(mergedRuntime.get("p_1"), equalTo("p_1_different_mappings"));
}
public void testMergeMappings_GivenSourceFiltering() {
Map<String, Object> properties = Map.of("field_1", "field_1_mappings", "field_2", "field_2_mappings");
Map<String, Object> runtime = Map.of("runtime_field_1", "runtime_field_1_mappings", "runtime_field_2", "runtime_field_2_mappings");
Map<String, Object> indexMappings = new HashMap<>();
indexMappings.put("properties", properties);
indexMappings.put("runtime", runtime);
MappingMetadata indexMappingMetadata = new MappingMetadata("_doc", indexMappings);
Map<String, MappingMetadata> mappings = Map.of("index", indexMappingMetadata);
GetMappingsResponse getMappingsResponse = new GetMappingsResponse(mappings);
MappingMetadata mergedMappings = MappingsMerger.mergeMappings(
newSourceWithExcludes("field_1", "runtime_field_2"),
getMappingsResponse
);
Map<String, Object> mappingsAsMap = mergedMappings.getSourceAsMap();
@SuppressWarnings("unchecked")
Map<String, Object> propertyMappings = (Map<String, Object>) mappingsAsMap.get("properties");
assertThat(propertyMappings.keySet(), containsInAnyOrder("field_2"));
@SuppressWarnings("unchecked")
Map<String, Object> runtimeMappings = (Map<String, Object>) mappingsAsMap.get("runtime");
assertThat(runtimeMappings.keySet(), containsInAnyOrder("runtime_field_1"));
}
private static DataFrameAnalyticsSource newSource() {
return new DataFrameAnalyticsSource(new String[] { "index" }, null, null, null);
}
private static DataFrameAnalyticsSource newSourceWithExcludes(String... excludes) {
return new DataFrameAnalyticsSource(new String[] { "index" }, null, FetchSourceContext.of(true, null, excludes), null);
}
}
|
MappingsMergerTests
|
java
|
spring-cloud__spring-cloud-gateway
|
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/filter/factory/cache/postprocessor/SetCacheDirectivesByMaxAgeAfterCacheExchangeMutator.java
|
{
"start": 1024,
"end": 2708
}
|
class ____ implements AfterCacheExchangeMutator {
final Pattern MAX_AGE_PATTERN = Pattern.compile("(?:,|^)\\s*max-age=(\\d+)");
@Override
public void accept(ServerWebExchange exchange, CachedResponse cachedResponse) {
Optional<Integer> maxAge = Optional.ofNullable(exchange.getResponse().getHeaders().getCacheControl())
.map(MAX_AGE_PATTERN::matcher)
.filter(Matcher::find)
.map(matcher -> matcher.group(1))
.map(Integer::parseInt);
if (maxAge.isPresent()) {
if (maxAge.get() > 0) {
removeNoCacheHeaders(exchange);
}
else {
keepNoCacheHeaders(exchange);
}
}
}
private void keepNoCacheHeaders(ServerWebExchange exchange) {
// at least it contains 'max-age' so we can append items with commas safely
String cacheControl = exchange.getResponse().getHeaders().getCacheControl();
StringBuilder newCacheControl = new StringBuilder(cacheControl);
if (!cacheControl.contains("no-cache")) {
newCacheControl.append(",no-cache");
}
if (!cacheControl.contains("must-revalidate")) {
newCacheControl.append(",must-revalidate");
}
exchange.getResponse().getHeaders().setCacheControl(newCacheControl.toString());
}
private void removeNoCacheHeaders(ServerWebExchange exchange) {
String cacheControl = exchange.getResponse().getHeaders().getCacheControl();
List<String> cacheControlValues = Arrays.asList(cacheControl.split("\\s*,\\s*"));
String newCacheControl = cacheControlValues.stream()
.filter(s -> !s.matches("must-revalidate|no-cache|no-store"))
.collect(Collectors.joining(","));
exchange.getResponse().getHeaders().setCacheControl(newCacheControl);
}
}
|
SetCacheDirectivesByMaxAgeAfterCacheExchangeMutator
|
java
|
google__guice
|
core/test/com/googlecode/guice/JakartaTest.java
|
{
"start": 12013,
"end": 12292
}
|
class ____ {
final B b;
@Inject @Red C c;
D d;
E e;
@Inject
F(@Named("jodie") B b) {
this.b = b;
}
@Inject
void injectD(@Red D d, @Named("jesse") E e) {
this.d = d;
this.e = e;
}
}
@Qualifier
@Retention(RUNTIME)
@
|
F
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/action/datastreams/GetDataStreamSettingsAction.java
|
{
"start": 3264,
"end": 5149
}
|
class ____ extends ActionResponse implements ChunkedToXContentObject {
private final List<DataStreamSettingsResponse> dataStreamSettingsResponses;
public Response(List<DataStreamSettingsResponse> dataStreamSettingsResponses) {
this.dataStreamSettingsResponses = dataStreamSettingsResponses;
}
public List<DataStreamSettingsResponse> getDataStreamSettingsResponses() {
return dataStreamSettingsResponses;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
assert false : "This ought to never be called because this action only runs locally";
}
@Override
public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params params) {
return Iterators.concat(
Iterators.single((builder, params1) -> builder.startObject().startArray("data_streams")),
dataStreamSettingsResponses.stream().map(dataStreamSettingsResponse -> (ToXContent) dataStreamSettingsResponse).iterator(),
Iterators.single((builder, params1) -> builder.endArray().endObject())
);
}
}
public record DataStreamSettingsResponse(String dataStreamName, Settings settings, Settings effectiveSettings) implements ToXContent {
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("name", dataStreamName);
builder.startObject("settings");
settings.toXContent(builder, params);
builder.endObject();
builder.startObject("effective_settings");
effectiveSettings.toXContent(builder, params);
builder.endObject();
builder.endObject();
return builder;
}
}
}
|
Response
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jms/src/test/java/org/springframework/boot/jms/autoconfigure/AcknowledgeModeTests.java
|
{
"start": 1063,
"end": 1592
}
|
class ____ {
@ParameterizedTest
@EnumSource
void stringIsMappedToInt(Mapping mapping) {
assertThat(AcknowledgeMode.of(mapping.actual)).extracting(AcknowledgeMode::getMode).isEqualTo(mapping.expected);
}
@Test
void mapShouldThrowWhenMapIsCalledWithUnknownNonIntegerString() {
assertThatIllegalArgumentException().isThrownBy(() -> AcknowledgeMode.of("some-string"))
.withMessage(
"'some-string' is neither a known acknowledge mode (auto, client, or dups_ok) nor an integer value");
}
private
|
AcknowledgeModeTests
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/net/TestDFSNetworkTopology.java
|
{
"start": 1983,
"end": 28620
}
|
class ____ {
private static final Logger LOG =
LoggerFactory.getLogger(TestDFSNetworkTopology.class);
private final static DFSNetworkTopology CLUSTER =
DFSNetworkTopology.getInstance(new Configuration());
private DatanodeDescriptor[] dataNodes;
@BeforeEach
public void setupDatanodes() {
final String[] racks = {
"/l1/d1/r1", "/l1/d1/r1", "/l1/d1/r2", "/l1/d1/r2", "/l1/d1/r2",
"/l1/d2/r3", "/l1/d2/r3", "/l1/d2/r3", "/l1/d2/r3",
"/l2/d3/r1", "/l2/d3/r2", "/l2/d3/r3", "/l2/d3/r4", "/l2/d3/r5",
"/l2/d4/r1", "/l2/d4/r1", "/l2/d4/r1", "/l2/d4/r1", "/l2/d4/r1",
"/l2/d4/r1", "/l2/d4/r1", "/l2/d4/r2",
"/l3/d5/r1", "/l3/d5/r1", "/l3/d5/r2"};
final String[] hosts = {
"host1", "host2", "host3", "host4", "host5",
"host6", "host7", "host8", "host9",
"host10", "host11", "host12", "host13", "host14",
"host15", "host16", "host17", "host18", "host19", "host20",
"host21", "host22", "host23", "host24", "host25"};
final StorageType[] types = {
StorageType.ARCHIVE, StorageType.DISK, StorageType.ARCHIVE,
StorageType.DISK, StorageType.DISK,
StorageType.DISK, StorageType.RAM_DISK, StorageType.SSD,
StorageType.NVDIMM,
StorageType.DISK, StorageType.RAM_DISK, StorageType.DISK,
StorageType.ARCHIVE, StorageType.ARCHIVE,
StorageType.DISK, StorageType.DISK, StorageType.RAM_DISK,
StorageType.RAM_DISK, StorageType.ARCHIVE, StorageType.ARCHIVE,
StorageType.SSD, StorageType.NVDIMM,
StorageType.NVDIMM, StorageType.ARCHIVE, StorageType.DISK};
final DatanodeStorageInfo[] storages =
DFSTestUtil.createDatanodeStorageInfos(25, racks, hosts, types);
dataNodes = DFSTestUtil.toDatanodeDescriptor(storages);
for (int i = 0; i < dataNodes.length; i++) {
CLUSTER.add(dataNodes[i]);
}
dataNodes[10].setDecommissioned();
dataNodes[11].setDecommissioned();
}
/**
* Test getting the storage type info of subtree.
* @throws Exception
*/
@Test
public void testGetStorageTypeInfo() throws Exception {
// checking level = 2 nodes
DFSTopologyNodeImpl d1 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l1/d1");
HashMap<String, EnumMap<StorageType, Integer>> d1info =
d1.getChildrenStorageInfo();
assertEquals(2, d1info.keySet().size());
assertTrue(d1info.get("r1").size() == 2 && d1info.get("r2").size() == 2);
assertEquals(1, (int)d1info.get("r1").get(StorageType.DISK));
assertEquals(1, (int)d1info.get("r1").get(StorageType.ARCHIVE));
assertEquals(2, (int)d1info.get("r2").get(StorageType.DISK));
assertEquals(1, (int)d1info.get("r2").get(StorageType.ARCHIVE));
DFSTopologyNodeImpl d2 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l1/d2");
HashMap<String, EnumMap<StorageType, Integer>> d2info =
d2.getChildrenStorageInfo();
assertEquals(1, d2info.keySet().size());
assertEquals(4, d2info.get("r3").size());
assertEquals(1, (int)d2info.get("r3").get(StorageType.DISK));
assertEquals(1, (int)d2info.get("r3").get(StorageType.RAM_DISK));
assertEquals(1, (int)d2info.get("r3").get(StorageType.SSD));
assertEquals(1, (int)d2info.get("r3").get(StorageType.NVDIMM));
DFSTopologyNodeImpl d3 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l2/d3");
HashMap<String, EnumMap<StorageType, Integer>> d3info =
d3.getChildrenStorageInfo();
assertEquals(5, d3info.keySet().size());
assertEquals(1, (int)d3info.get("r1").get(StorageType.DISK));
assertEquals(1, (int)d3info.get("r2").get(StorageType.RAM_DISK));
assertEquals(1, (int)d3info.get("r3").get(StorageType.DISK));
assertEquals(1, (int)d3info.get("r4").get(StorageType.ARCHIVE));
assertEquals(1, (int)d3info.get("r5").get(StorageType.ARCHIVE));
DFSTopologyNodeImpl d4 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l2/d4");
HashMap<String, EnumMap<StorageType, Integer>> d4info =
d4.getChildrenStorageInfo();
assertEquals(2, d4info.keySet().size());
assertEquals(2, (int)d4info.get("r1").get(StorageType.DISK));
assertEquals(2, (int)d4info.get("r1").get(StorageType.RAM_DISK));
assertEquals(2, (int)d4info.get("r1").get(StorageType.ARCHIVE));
assertEquals(1, (int)d4info.get("r1").get(StorageType.SSD));
assertEquals(1, (int)d4info.get("r2").get(StorageType.NVDIMM));
DFSTopologyNodeImpl d5 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l3/d5");
System.out.println(d5);
HashMap<String, EnumMap<StorageType, Integer>> d5info =
d5.getChildrenStorageInfo();
assertEquals(2, d5info.keySet().size());
assertEquals(1, (int)d5info.get("r1").get(StorageType.ARCHIVE));
assertEquals(1, (int)d5info.get("r1").get(StorageType.NVDIMM));
assertEquals(1, (int)d5info.get("r2").get(StorageType.DISK));
DFSTopologyNodeImpl l1 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l1");
HashMap<String, EnumMap<StorageType, Integer>> l1info =
l1.getChildrenStorageInfo();
assertEquals(2, l1info.keySet().size());
assertTrue(l1info.get("d1").size() == 2
&& l1info.get("d2").size() == 4);
assertEquals(2, (int)l1info.get("d1").get(StorageType.ARCHIVE));
assertEquals(3, (int)l1info.get("d1").get(StorageType.DISK));
assertEquals(1, (int)l1info.get("d2").get(StorageType.DISK));
assertEquals(1, (int)l1info.get("d2").get(StorageType.RAM_DISK));
assertEquals(1, (int)l1info.get("d2").get(StorageType.SSD));
assertEquals(1, (int)l1info.get("d2").get(StorageType.NVDIMM));
// checking level = 1 nodes
DFSTopologyNodeImpl l2 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l2");
HashMap<String, EnumMap<StorageType, Integer>> l2info =
l2.getChildrenStorageInfo();
assertTrue(l2info.get("d3").size() == 3
&& l2info.get("d4").size() == 5);
assertEquals(2, l2info.keySet().size());
assertEquals(2, (int)l2info.get("d3").get(StorageType.DISK));
assertEquals(2, (int)l2info.get("d3").get(StorageType.ARCHIVE));
assertEquals(1, (int)l2info.get("d3").get(StorageType.RAM_DISK));
assertEquals(2, (int)l2info.get("d4").get(StorageType.DISK));
assertEquals(2, (int)l2info.get("d4").get(StorageType.ARCHIVE));
assertEquals(2, (int)l2info.get("d4").get(StorageType.RAM_DISK));
assertEquals(1, (int)l2info.get("d4").get(StorageType.SSD));
assertEquals(1, (int)l2info.get("d4").get(StorageType.NVDIMM));
DFSTopologyNodeImpl l3 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l3");
HashMap<String, EnumMap<StorageType, Integer>> l3info =
l3.getChildrenStorageInfo();
assertTrue(l3info.get("d5").size() == 3);
assertEquals(1, l3info.keySet().size());
assertEquals(1, (int)l3info.get("d5").get(StorageType.NVDIMM));
assertEquals(1, (int)l3info.get("d5").get(StorageType.ARCHIVE));
assertEquals(1, (int)l3info.get("d5").get(StorageType.DISK));
}
/**
* Test the correctness of storage type info when nodes are added and removed.
* @throws Exception
*/
@Test
public void testAddAndRemoveTopology() throws Exception {
String[] newRack = {"/l1/d1/r1", "/l1/d1/r3", "/l1/d3/r3", "/l1/d3/r3",
"/l1/d3/r4"};
String[] newHost = {"nhost1", "nhost2", "nhost3", "nhost4", "nhost5"};
String[] newips = {"30.30.30.30", "31.31.31.31", "32.32.32.32",
"33.33.33.33", "34.34.34.34"};
StorageType[] newTypes = {StorageType.DISK, StorageType.SSD,
StorageType.SSD, StorageType.SSD, StorageType.NVDIMM};
DatanodeDescriptor[] newDD = new DatanodeDescriptor[5];
for (int i = 0; i < 5; i++) {
DatanodeStorageInfo dsi = DFSTestUtil.createDatanodeStorageInfo(
"s" + newHost[i], newips[i], newRack[i], newHost[i],
newTypes[i], null);
newDD[i] = dsi.getDatanodeDescriptor();
CLUSTER.add(newDD[i]);
}
DFSTopologyNodeImpl d1 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l1/d1");
HashMap<String, EnumMap<StorageType, Integer>> d1info =
d1.getChildrenStorageInfo();
assertEquals(3, d1info.keySet().size());
assertTrue(d1info.get("r1").size() == 2 && d1info.get("r2").size() == 2
&& d1info.get("r3").size() == 1);
assertEquals(2, (int)d1info.get("r1").get(StorageType.DISK));
assertEquals(1, (int)d1info.get("r1").get(StorageType.ARCHIVE));
assertEquals(2, (int)d1info.get("r2").get(StorageType.DISK));
assertEquals(1, (int)d1info.get("r2").get(StorageType.ARCHIVE));
assertEquals(1, (int)d1info.get("r3").get(StorageType.SSD));
DFSTopologyNodeImpl d3 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l1/d3");
HashMap<String, EnumMap<StorageType, Integer>> d3info =
d3.getChildrenStorageInfo();
assertEquals(2, d3info.keySet().size());
assertTrue(d3info.get("r3").size() == 1 && d3info.get("r4").size() == 1);
assertEquals(2, (int)d3info.get("r3").get(StorageType.SSD));
assertEquals(1, (int)d3info.get("r4").get(StorageType.NVDIMM));
DFSTopologyNodeImpl l1 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l1");
HashMap<String, EnumMap<StorageType, Integer>> l1info =
l1.getChildrenStorageInfo();
assertEquals(3, l1info.keySet().size());
assertTrue(l1info.get("d1").size() == 3 &&
l1info.get("d2").size() == 4 && l1info.get("d3").size() == 2);
assertEquals(4, (int)l1info.get("d1").get(StorageType.DISK));
assertEquals(2, (int)l1info.get("d1").get(StorageType.ARCHIVE));
assertEquals(1, (int)l1info.get("d1").get(StorageType.SSD));
assertEquals(1, (int)l1info.get("d2").get(StorageType.SSD));
assertEquals(1, (int)l1info.get("d2").get(StorageType.RAM_DISK));
assertEquals(1, (int)l1info.get("d2").get(StorageType.DISK));
assertEquals(2, (int)l1info.get("d3").get(StorageType.SSD));
assertEquals(1, (int)l1info.get("d3").get(StorageType.NVDIMM));
for (int i = 0; i < 5; i++) {
CLUSTER.remove(newDD[i]);
}
// /d1/r3 should've been out, /d1/r1 should've been resumed
DFSTopologyNodeImpl nd1 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l1/d1");
HashMap<String, EnumMap<StorageType, Integer>> nd1info =
nd1.getChildrenStorageInfo();
assertEquals(2, nd1info.keySet().size());
assertTrue(nd1info.get("r1").size() == 2 && nd1info.get("r2").size() == 2);
assertEquals(1, (int)nd1info.get("r1").get(StorageType.DISK));
assertEquals(1, (int)nd1info.get("r1").get(StorageType.ARCHIVE));
assertEquals(2, (int)nd1info.get("r2").get(StorageType.DISK));
assertEquals(1, (int)nd1info.get("r2").get(StorageType.ARCHIVE));
// /l1/d3 should've been out, and /l1/d1 should've been resumed
DFSTopologyNodeImpl nl1 =
(DFSTopologyNodeImpl) CLUSTER.getNode("/l1");
HashMap<String, EnumMap<StorageType, Integer>> nl1info =
nl1.getChildrenStorageInfo();
assertEquals(2, nl1info.keySet().size());
assertTrue(l1info.get("d1").size() == 2
&& l1info.get("d2").size() == 4);
assertEquals(2, (int)nl1info.get("d1").get(StorageType.ARCHIVE));
assertEquals(3, (int)nl1info.get("d1").get(StorageType.DISK));
assertEquals(1, (int)l1info.get("d2").get(StorageType.DISK));
assertEquals(1, (int)l1info.get("d2").get(StorageType.RAM_DISK));
assertEquals(1, (int)l1info.get("d2").get(StorageType.SSD));
assertEquals(1, (int)l1info.get("d2").get(StorageType.NVDIMM));
assertNull(CLUSTER.getNode("/l1/d3"));
}
@Test
public void testChooseRandomWithStorageType() throws Exception {
Node n;
DatanodeDescriptor dd;
// test the choose random can return desired storage type nodes without
// exclude
Set<String> diskUnderL1 =
new HashSet<>(Arrays.asList("host2", "host4", "host5", "host6"));
Set<String> archiveUnderL1 = new HashSet<>(Arrays.asList("host1", "host3"));
Set<String> ramdiskUnderL1 = new HashSet<>(Arrays.asList("host7"));
Set<String> ssdUnderL1 = new HashSet<>(Arrays.asList("host8"));
Set<String> nvdimmUnderL1 = new HashSet<>(Arrays.asList("host9"));
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageType("/l1", null, null,
StorageType.DISK);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(diskUnderL1.contains(dd.getHostName()));
n = CLUSTER.chooseRandomWithStorageType("/l1", null, null,
StorageType.RAM_DISK);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(ramdiskUnderL1.contains(dd.getHostName()));
n = CLUSTER.chooseRandomWithStorageType("/l1", null, null,
StorageType.ARCHIVE);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(archiveUnderL1.contains(dd.getHostName()));
n = CLUSTER.chooseRandomWithStorageType("/l1", null, null,
StorageType.SSD);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(ssdUnderL1.contains(dd.getHostName()));
}
}
@Test
public void testChooseRandomWithStorageTypeWithExcluded() throws Exception {
Node n;
DatanodeDescriptor dd;
// below test choose random with exclude, for /l2/d3, every rack has exactly
// one host
// /l2/d3 has five racks r[1~5] but only r4 and r5 have ARCHIVE
// host12 is the one under "/l2/d3/r4", host13 is the one under "/l2/d3/r5"
n = CLUSTER.chooseRandomWithStorageType("/l2/d3/r4", null, null,
StorageType.ARCHIVE);
HashSet<Node> excluded = new HashSet<>();
// exclude the host on r4 (since there is only one host, no randomness here)
excluded.add(n);
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageType("/l2/d3", null, null,
StorageType.ARCHIVE);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(dd.getHostName().equals("host13") ||
dd.getHostName().equals("host14"));
}
// test exclude nodes
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageType("/l2/d3", null, excluded,
StorageType.ARCHIVE);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(dd.getHostName().equals("host14"));
}
// test exclude scope
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageType("/l2/d3", "/l2/d3/r4", null,
StorageType.ARCHIVE);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(dd.getHostName().equals("host14"));
}
// test exclude scope + excluded node with expected null return node
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageType("/l2/d3", "/l2/d3/r5", excluded,
StorageType.ARCHIVE);
assertNull(n);
}
// test exclude scope + excluded node with expected non-null return node
n = CLUSTER.chooseRandomWithStorageType("/l1/d2", null, null,
StorageType.DISK);
dd = (DatanodeDescriptor)n;
assertEquals("host6", dd.getHostName());
// exclude the host on r4 (since there is only one host, no randomness here)
excluded.add(n);
Set<String> expectedSet = new HashSet<>(Arrays.asList("host4", "host5"));
for (int i = 0; i < 10; i++) {
// under l1, there are four hosts with DISK:
// /l1/d1/r1/host2, /l1/d1/r2/host4, /l1/d1/r2/host5 and /l1/d2/r3/host6
// host6 is excludedNode, host2 is under excluded range scope /l1/d1/r1
// so should always return r4 or r5
n = CLUSTER.chooseRandomWithStorageType(
"/l1", "/l1/d1/r1", excluded, StorageType.DISK);
dd = (DatanodeDescriptor) n;
assertTrue(expectedSet.contains(dd.getHostName()));
}
}
@Test
public void testChooseRandomWithStorageTypeWithExcludedforNullCheck()
throws Exception {
HashSet<Node> excluded = new HashSet<>();
excluded.add(new DatanodeInfoBuilder()
.setNodeID(DatanodeID.EMPTY_DATANODE_ID).build());
Node node = CLUSTER.chooseRandomWithStorageType("/", "/l1/d1/r1", excluded,
StorageType.ARCHIVE);
assertNotNull(node);
}
/**
* This test tests the wrapper method. The wrapper method only takes one scope
* where if it starts with a ~, it is an excluded scope, and searching always
* from root. Otherwise it is a scope.
* @throws Exception throws exception.
*/
@Test
public void testChooseRandomWithStorageTypeWrapper() throws Exception {
Node n;
DatanodeDescriptor dd;
n = CLUSTER.chooseRandomWithStorageType("/l2/d3/r4", null, null,
StorageType.ARCHIVE);
HashSet<Node> excluded = new HashSet<>();
// exclude the host on r4 (since there is only one host, no randomness here)
excluded.add(n);
// search with given scope being desired scope
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageType(
"/l2/d3", null, StorageType.ARCHIVE);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(dd.getHostName().equals("host13") ||
dd.getHostName().equals("host14"));
}
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageType(
"/l2/d3", excluded, StorageType.ARCHIVE);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(dd.getHostName().equals("host14"));
}
// search with given scope being exclude scope
// a total of 4 ramdisk nodes:
// /l1/d2/r3/host7, /l2/d3/r2/host10, /l2/d4/r1/host7 and /l2/d4/r1/host10
// so if we exclude /l2/d4/r1, if should be always either host7 or host10
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageType(
"~/l2/d4", null, StorageType.RAM_DISK);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(dd.getHostName().equals("host7") ||
dd.getHostName().equals("host11"));
}
// similar to above, except that we also exclude host10 here. so it should
// always be host7
n = CLUSTER.chooseRandomWithStorageType("/l2/d3/r2", null, null,
StorageType.RAM_DISK);
// add host10 to exclude
excluded.add(n);
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageType(
"~/l2/d4", excluded, StorageType.RAM_DISK);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(dd.getHostName().equals("host7"));
}
}
@Test
public void testNonExistingNode() throws Exception {
Node n;
n = CLUSTER.chooseRandomWithStorageType(
"/l100", null, null, StorageType.DISK);
assertNull(n);
n = CLUSTER.chooseRandomWithStorageType(
"/l100/d100", null, null, StorageType.DISK);
assertNull(n);
n = CLUSTER.chooseRandomWithStorageType(
"/l100/d100/r100", null, null, StorageType.DISK);
assertNull(n);
}
/**
* Tests getting subtree storage counts, and see whether it is correct when
* we update subtree.
* @throws Exception
*/
@Test
public void testGetSubtreeStorageCount() throws Exception {
// add and remove a node to rack /l2/d3/r1. So all the inner nodes /l2,
// /l2/d3 and /l2/d3/r1 should be affected. /l2/d3/r3 should still be the
// same, only checked as a reference
Node l2 = CLUSTER.getNode("/l2");
Node l2d3 = CLUSTER.getNode("/l2/d3");
Node l2d3r1 = CLUSTER.getNode("/l2/d3/r1");
Node l2d3r3 = CLUSTER.getNode("/l2/d3/r3");
assertTrue(l2 instanceof DFSTopologyNodeImpl);
assertTrue(l2d3 instanceof DFSTopologyNodeImpl);
assertTrue(l2d3r1 instanceof DFSTopologyNodeImpl);
assertTrue(l2d3r3 instanceof DFSTopologyNodeImpl);
DFSTopologyNodeImpl innerl2 = (DFSTopologyNodeImpl)l2;
DFSTopologyNodeImpl innerl2d3 = (DFSTopologyNodeImpl)l2d3;
DFSTopologyNodeImpl innerl2d3r1 = (DFSTopologyNodeImpl)l2d3r1;
DFSTopologyNodeImpl innerl2d3r3 = (DFSTopologyNodeImpl)l2d3r3;
assertEquals(4,
innerl2.getSubtreeStorageCount(StorageType.DISK));
assertEquals(2,
innerl2d3.getSubtreeStorageCount(StorageType.DISK));
assertEquals(1,
innerl2d3r1.getSubtreeStorageCount(StorageType.DISK));
assertEquals(1,
innerl2d3r3.getSubtreeStorageCount(StorageType.DISK));
DatanodeStorageInfo storageInfo =
DFSTestUtil.createDatanodeStorageInfo("StorageID",
"1.2.3.4", "/l2/d3/r1", "newhost");
DatanodeDescriptor newNode = storageInfo.getDatanodeDescriptor();
CLUSTER.add(newNode);
// after adding a storage to /l2/d3/r1, ancestor inner node should have
// DISK count incremented by 1.
assertEquals(5,
innerl2.getSubtreeStorageCount(StorageType.DISK));
assertEquals(3,
innerl2d3.getSubtreeStorageCount(StorageType.DISK));
assertEquals(2,
innerl2d3r1.getSubtreeStorageCount(StorageType.DISK));
assertEquals(1,
innerl2d3r3.getSubtreeStorageCount(StorageType.DISK));
CLUSTER.remove(newNode);
assertEquals(4,
innerl2.getSubtreeStorageCount(StorageType.DISK));
assertEquals(2,
innerl2d3.getSubtreeStorageCount(StorageType.DISK));
assertEquals(1,
innerl2d3r1.getSubtreeStorageCount(StorageType.DISK));
assertEquals(1,
innerl2d3r3.getSubtreeStorageCount(StorageType.DISK));
}
@Test
public void testChooseRandomWithStorageTypeTwoTrial() throws Exception {
Node n;
DatanodeDescriptor dd;
n = CLUSTER.chooseRandomWithStorageType("/l2/d3/r4", null, null,
StorageType.ARCHIVE);
HashSet<Node> excluded = new HashSet<>();
// exclude the host on r4 (since there is only one host, no randomness here)
excluded.add(n);
// search with given scope being desired scope
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageTypeTwoTrial(
"/l2/d3", null, StorageType.ARCHIVE);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(dd.getHostName().equals("host13") ||
dd.getHostName().equals("host14"));
}
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageTypeTwoTrial(
"/l2/d3", excluded, StorageType.ARCHIVE);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(dd.getHostName().equals("host14"));
}
// search with given scope being exclude scope
// a total of 4 ramdisk nodes:
// /l1/d2/r3/host7, /l2/d3/r2/host10, /l2/d4/r1/host7 and /l2/d4/r1/host10
// so if we exclude /l2/d4/r1, if should be always either host7 or host10
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageTypeTwoTrial(
"~/l2/d4", null, StorageType.RAM_DISK);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(dd.getHostName().equals("host7") ||
dd.getHostName().equals("host11"));
}
// similar to above, except that we also exclude host10 here. so it should
// always be host7
n = CLUSTER.chooseRandomWithStorageType("/l2/d3/r2", null, null,
StorageType.RAM_DISK);
// add host10 to exclude
excluded.add(n);
for (int i = 0; i < 10; i++) {
n = CLUSTER.chooseRandomWithStorageTypeTwoTrial(
"~/l2/d4", excluded, StorageType.RAM_DISK);
assertTrue(n instanceof DatanodeDescriptor);
dd = (DatanodeDescriptor) n;
assertTrue(dd.getHostName().equals("host7"));
}
}
@Test
public void testChooseRandomWithStorageTypeNoAvlblNode() {
DFSNetworkTopology dfsCluster =
DFSNetworkTopology.getInstance(new Configuration());
final String[] racks = {"/default/rack1", "/default/rack10"};
final String[] hosts = {"host1", "host2"};
final StorageType[] types = {StorageType.DISK, StorageType.DISK};
final DatanodeStorageInfo[] storages =
DFSTestUtil.createDatanodeStorageInfos(2, racks, hosts, types);
DatanodeDescriptor[] dns = DFSTestUtil.toDatanodeDescriptor(storages);
dfsCluster.add(dns[0]);
dfsCluster.add(dns[1]);
HashSet<Node> excluded = new HashSet<>();
excluded.add(dns[1]);
Node n = dfsCluster.chooseRandomWithStorageType("/default",
"/default/rack1", excluded, StorageType.DISK);
assertNull(n, "No node should have been selected.");
}
/**
* Tests it should getting no node, if a node from scope is DatanodeDescriptor
* and excludedNodes contain it in
* DFSNetworkTopology#chooseRandomWithStorageType().
*/
@Test
public void testChooseRandomWithStorageTypeScopeEqualsExcludedNodes() {
DFSNetworkTopology dfsCluster =
DFSNetworkTopology.getInstance(new Configuration());
final String[] racks = {"/default/rack1", "/default/rack2"};
final String[] hosts = {"host1", "host2"};
final StorageType[] types = {StorageType.DISK, StorageType.DISK};
DatanodeStorageInfo[] storages = new DatanodeStorageInfo[2];
for (int i = 0; i < 2; i++) {
final String storageID = "s" + i;
final String ip = i + "." + i + "." + i + "." + i;
storages[i] = DFSTestUtil.createDatanodeStorageInfo(storageID, ip,
racks[i], hosts[i], types[i], null);
}
DatanodeDescriptor[] dns = DFSTestUtil.toDatanodeDescriptor(storages);
dfsCluster.add(dns[0]);
dfsCluster.add(dns[1]);
HashSet<Node> excluded = new HashSet<>();
excluded.add(dns[0]);
Node n = dfsCluster.chooseRandomWithStorageType(
"/default/rack1/0.0.0.0:" + DFSConfigKeys.DFS_DATANODE_DEFAULT_PORT,
null, excluded, StorageType.DISK);
assertNull(n, "No node should have been selected.");
}
@Test
public void testChooseRandomWithStorageTypeWithExcludeNodes() {
DFSNetworkTopology dfsCluster =
DFSNetworkTopology.getInstance(new Configuration());
final String[] racks = {"/default/rack1", "/default/rack2"};
final String[] hosts = {"host1", "host2"};
final StorageType[] types = {StorageType.DISK, StorageType.DISK};
final DatanodeStorageInfo[] storages =
DFSTestUtil.createDatanodeStorageInfos(2, racks, hosts, types);
DatanodeDescriptor[] dns = DFSTestUtil.toDatanodeDescriptor(storages);
dfsCluster.add(dns[0]);
dfsCluster.add(dns[1]);
HashSet<Node> excluded = new HashSet<>();
excluded.add(dns[1]);
Node n = dfsCluster.chooseRandomWithStorageType("/default/rack1",
null, excluded, StorageType.DISK);
assertNotNull(n, "/default/rack1/host1 should be selected.");
}
}
|
TestDFSNetworkTopology
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/sql/results/jdbc/internal/AbstractResultSetAccess.java
|
{
"start": 939,
"end": 5516
}
|
class ____ implements ResultSetAccess {
private final SharedSessionContractImplementor persistenceContext;
private ResultSetMetaData resultSetMetaData;
public AbstractResultSetAccess(SharedSessionContractImplementor persistenceContext) {
this.persistenceContext = persistenceContext;
}
protected abstract SessionFactoryImplementor getFactory();
protected SharedSessionContractImplementor getPersistenceContext() {
return persistenceContext;
}
private SqlExceptionHelper getSqlExceptionHelper() {
return getFactory().getJdbcServices().getSqlExceptionHelper();
}
private Dialect getDialect() {
return getFactory().getJdbcServices().getDialect();
}
private ResultSetMetaData getResultSetMetaData() {
if ( resultSetMetaData == null ) {
try {
resultSetMetaData = getResultSet().getMetaData();
}
catch (SQLException e) {
throw getSqlExceptionHelper()
.convert( e, "Unable to access ResultSetMetaData" );
}
}
return resultSetMetaData;
}
@Override
public int getColumnCount() {
try {
return getResultSetMetaData().getColumnCount();
}
catch (SQLException e) {
throw getSqlExceptionHelper()
.convert( e, "Unable to access ResultSet column count" );
}
}
@Override
public int resolveColumnPosition(String columnName) {
try {
return getResultSet().findColumn( normalizeColumnName( columnName ) );
}
catch (SQLException e) {
throw getSqlExceptionHelper()
.convert( e, "Unable to find column position by name: " + columnName );
}
}
private String normalizeColumnName(String columnName) {
return getFactory().getJdbcServices().getJdbcEnvironment().getIdentifierHelper()
.toMetaDataObjectName( Identifier.toIdentifier( columnName ) );
}
@Override
public String resolveColumnName(int position) {
try {
return getDialect().getColumnAliasExtractor()
.extractColumnAlias( getResultSetMetaData(), position );
}
catch (SQLException e) {
throw getSqlExceptionHelper()
.convert( e, "Unable to find column name by position" );
}
}
@Override
public int getResultCountEstimate() {
return -1;
}
@Override
public <J> BasicType<J> resolveType(int position, JavaType<J> explicitJavaType, TypeConfiguration typeConfiguration) {
try {
final ResultSetMetaData metaData = getResultSetMetaData();
final JdbcTypeRegistry registry = typeConfiguration.getJdbcTypeRegistry();
final String columnTypeName = metaData.getColumnTypeName( position );
final int columnType = metaData.getColumnType( position );
final int scale = metaData.getScale( position );
final int precision = metaData.getPrecision( position );
final int displaySize = metaData.getColumnDisplaySize( position );
final Dialect dialect = getDialect();
final int length = dialect.resolveSqlTypeLength( columnTypeName, columnType, precision, scale, displaySize );
final JdbcType resolvedJdbcType =
dialect.resolveSqlTypeDescriptor( columnTypeName, columnType, length, scale, registry );
final JdbcType jdbcType =
explicitJavaType == null
? resolvedJdbcType
: jdbcType( explicitJavaType, resolvedJdbcType, length, precision, scale, typeConfiguration );
// If there is an explicit JavaType, then prefer its recommended JDBC type
final JavaType<J> javaType =
explicitJavaType == null
? jdbcType.getJdbcRecommendedJavaTypeMapping( length, scale, typeConfiguration )
: explicitJavaType;
return typeConfiguration.getBasicTypeRegistry().resolve( javaType, jdbcType );
}
catch (SQLException e) {
throw getSqlExceptionHelper()
.convert( e, "Unable to determine JDBC type code for ResultSet position " + position );
}
}
private <J> JdbcType jdbcType(
JavaType<J> javaType,
JdbcType resolvedJdbcType,
int length, int precision, int scale,
TypeConfiguration typeConfiguration) {
return javaType.getRecommendedJdbcType(
new JdbcTypeIndicators() {
@Override
public TypeConfiguration getTypeConfiguration() {
return typeConfiguration;
}
@Override
public long getColumnLength() {
return length;
}
@Override
public int getColumnPrecision() {
return precision;
}
@Override
public int getColumnScale() {
return scale;
}
@Override
public EnumType getEnumeratedType() {
return resolvedJdbcType.isNumber() ? EnumType.ORDINAL : EnumType.STRING;
}
@Override
public Dialect getDialect() {
return AbstractResultSetAccess.this.getDialect();
}
}
);
}
}
|
AbstractResultSetAccess
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/collect/ForwardingSortedSetMultimapTest.java
|
{
"start": 980,
"end": 2114
}
|
class ____ extends TestCase {
@SuppressWarnings("rawtypes")
public void testForwarding() {
new ForwardingWrapperTester()
.testForwarding(
SortedSetMultimap.class,
new Function<SortedSetMultimap, SortedSetMultimap<?, ?>>() {
@Override
public SortedSetMultimap<?, ?> apply(SortedSetMultimap delegate) {
return wrap((SortedSetMultimap<?, ?>) delegate);
}
});
}
public void testEquals() {
SortedSetMultimap<Integer, String> map1 = TreeMultimap.create(ImmutableMultimap.of(1, "one"));
SortedSetMultimap<Integer, String> map2 = TreeMultimap.create(ImmutableMultimap.of(2, "two"));
new EqualsTester()
.addEqualityGroup(map1, wrap(map1), wrap(map1))
.addEqualityGroup(map2, wrap(map2))
.testEquals();
}
private static <K, V> SortedSetMultimap<K, V> wrap(SortedSetMultimap<K, V> delegate) {
return new ForwardingSortedSetMultimap<K, V>() {
@Override
protected SortedSetMultimap<K, V> delegate() {
return delegate;
}
};
}
}
|
ForwardingSortedSetMultimapTest
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jooq/src/test/java/org/springframework/boot/jooq/autoconfigure/JooqAutoConfigurationTests.java
|
{
"start": 11699,
"end": 12152
}
|
class ____ implements TransactionalRunnable {
private final DSLContext dsl;
private final String sql;
private final String expected;
AssertFetch(DSLContext dsl, String sql, String expected) {
this.dsl = dsl;
this.sql = sql;
this.expected = expected;
}
@Override
public void run(org.jooq.Configuration configuration) {
assertThat(this.dsl.fetch(this.sql).getValue(0, 0)).hasToString(this.expected);
}
}
static
|
AssertFetch
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/type/AbstractAnnotationMetadataTests.java
|
{
"start": 16217,
"end": 16308
}
|
interface ____ {
}
@DirectAnnotation1
@DirectAnnotation2
public static
|
MetaAnnotation2
|
java
|
apache__maven
|
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4625SettingsXmlInterpolationWithXmlMarkupTest.java
|
{
"start": 1167,
"end": 2674
}
|
class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify that interpolation of the settings.xml doesn't fail if an expression's value contains
* XML special characters.
*
* @throws Exception in case of failure
*/
@Test
public void testit() throws Exception {
File testDir = extractResources("/mng-4625");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
// http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6468220
// A lot of bugs related to Windows arguments and quoting
// Directly called from commandline succeeds, indirect often fails
if (Os.isFamily(Os.FAMILY_WINDOWS) && !System.getProperties().contains("CLASSWORLDS_LAUNCHER")) {
verifier.addCliArgument("-Dtest.prop=\"&x=y<>\"");
verifier.setForkJvm(true); // force forked JVM, since the workaround expects forked run
} else {
verifier.addCliArgument("-Dtest.prop=&x=y<>");
}
verifier.addCliArgument("--settings");
verifier.addCliArgument("settings.xml");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
Properties props = verifier.loadProperties("target/pom.properties");
assertEquals("&x=y<>", props.getProperty("project.properties.jdbcUrl"));
}
}
|
MavenITmng4625SettingsXmlInterpolationWithXmlMarkupTest
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/atomic/longarray/AtomicLongArrayAssert_usingComparator_Test.java
|
{
"start": 1077,
"end": 1787
}
|
class ____ extends AtomicLongArrayAssertBaseTest {
private Comparator<AtomicLongArray> comparator = alwaysEqual();
private LongArrays arraysBefore;
@BeforeEach
void before() {
arraysBefore = getArrays(assertions);
}
@Override
protected AtomicLongArrayAssert invoke_api_method() {
// in that test, the comparator type is not important, we only check that we correctly switch of comparator
return assertions.usingComparator(comparator);
}
@Override
protected void verify_internal_effects() {
assertThat(getObjects(assertions).getComparator()).isSameAs(comparator);
assertThat(getArrays(assertions)).isSameAs(arraysBefore);
}
}
|
AtomicLongArrayAssert_usingComparator_Test
|
java
|
quarkusio__quarkus
|
extensions/redis-client/deployment/src/test/java/io/quarkus/redis/deployment/client/patterns/BinaryTest.java
|
{
"start": 748,
"end": 1755
}
|
class ____ {
@RegisterExtension
static final QuarkusUnitTest unitTest = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class).addClass(MyBinaryRepository.class))
.overrideConfigKey("quarkus.redis.hosts", "${quarkus.redis.tr}");
@Inject
MyBinaryRepository repo;
@Test
void binary() {
Random random = new Random();
byte[] pic1 = new byte[1024];
byte[] pic2 = new byte[1024];
random.nextBytes(pic1);
random.nextBytes(pic2);
Assertions.assertThrows(NoSuchElementException.class, () -> repo.get("binary-foo"));
repo.add("binary-foo", pic1);
repo.addIfAbsent("binary-bar", pic2);
repo.addIfAbsent("binary-bar", pic1);
byte[] p1 = repo.get("binary-foo");
byte[] p2 = repo.get("binary-bar");
Assertions.assertArrayEquals(p1, pic1);
Assertions.assertArrayEquals(p2, pic2);
}
@ApplicationScoped
public static
|
BinaryTest
|
java
|
apache__rocketmq
|
tools/src/test/java/org/apache/rocketmq/tools/monitor/DefaultMonitorListenerTest.java
|
{
"start": 1164,
"end": 3181
}
|
class ____ {
private DefaultMonitorListener defaultMonitorListener;
@Before
public void init() {
defaultMonitorListener = mock(DefaultMonitorListener.class);
}
@Test
public void testBeginRound() {
defaultMonitorListener.beginRound();
}
@Test
public void testReportUndoneMsgs() {
UndoneMsgs undoneMsgs = new UndoneMsgs();
undoneMsgs.setConsumerGroup("default-group");
undoneMsgs.setTopic("unit-test");
undoneMsgs.setUndoneMsgsDelayTimeMills(30000);
undoneMsgs.setUndoneMsgsSingleMQ(1);
undoneMsgs.setUndoneMsgsTotal(100);
defaultMonitorListener.reportUndoneMsgs(undoneMsgs);
}
@Test
public void testReportFailedMsgs() {
FailedMsgs failedMsgs = new FailedMsgs();
failedMsgs.setTopic("unit-test");
failedMsgs.setConsumerGroup("default-consumer");
failedMsgs.setFailedMsgsTotalRecently(2);
defaultMonitorListener.reportFailedMsgs(failedMsgs);
}
@Test
public void testReportDeleteMsgsEvent() {
DeleteMsgsEvent deleteMsgsEvent = new DeleteMsgsEvent();
deleteMsgsEvent.setEventTimestamp(System.currentTimeMillis());
deleteMsgsEvent.setOffsetMovedEvent(new OffsetMovedEvent());
defaultMonitorListener.reportDeleteMsgsEvent(deleteMsgsEvent);
}
@Test
public void testReportConsumerRunningInfo() {
TreeMap<String, ConsumerRunningInfo> criTable = new TreeMap<>();
ConsumerRunningInfo consumerRunningInfo = new ConsumerRunningInfo();
consumerRunningInfo.setSubscriptionSet(new TreeSet<>());
consumerRunningInfo.setStatusTable(new TreeMap<>());
consumerRunningInfo.setSubscriptionSet(new TreeSet<>());
consumerRunningInfo.setMqTable(new TreeMap<>());
consumerRunningInfo.setProperties(new Properties());
criTable.put("test", consumerRunningInfo);
defaultMonitorListener.reportConsumerRunningInfo(criTable);
}
}
|
DefaultMonitorListenerTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/transform/src/internalClusterTest/java/org/elasticsearch/xpack/transform/checkpoint/TransformCCSCanMatchIT.java
|
{
"start": 20997,
"end": 21461
}
|
class ____ extends Plugin implements EnginePlugin {
@Override
public Optional<EngineFactory> getEngineFactory(IndexSettings indexSettings) {
if (IndexMetadata.INDEX_BLOCKS_WRITE_SETTING.get(indexSettings.getSettings())) {
return Optional.of(EngineWithExposingTimestamp::new);
} else {
return Optional.of(new InternalEngineFactory());
}
}
}
}
|
ExposingTimestampEnginePlugin
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/contract/AbstractContractGetFileStatusTest.java
|
{
"start": 24949,
"end": 25216
}
|
class ____ implements PathFilter {
@Override
public boolean accept(Path path) {
return false;
}
}
/**
* Path filter which only expects paths whose final name element
* equals the {@code match} field.
*/
private static final
|
NoPathsFilter
|
java
|
netty__netty
|
handler/src/main/java/io/netty/handler/ipfilter/AbstractRemoteAddressFilter.java
|
{
"start": 937,
"end": 1087
}
|
class ____ the functionality to either accept or reject new {@link Channel}s
* based on their IP address.
* <p>
* You should inherit from this
|
provides
|
java
|
apache__kafka
|
storage/src/test/java/org/apache/kafka/storage/internals/log/LogConcurrencyTest.java
|
{
"start": 4352,
"end": 8720
}
|
class ____ basic leader/follower behavior.
*/
private Runnable logAppendTask(UnifiedLog log, int lastOffset) {
return () -> assertDoesNotThrow(() -> {
int leaderEpoch = 1;
boolean isLeader = true;
while (log.highWatermark() < lastOffset) {
switch (TestUtils.RANDOM.nextInt(2)) {
case 0 -> {
final LogOffsetMetadata logEndOffsetMetadata = log.logEndOffsetMetadata();
final long logEndOffset = logEndOffsetMetadata.messageOffset;
final int batchSize = TestUtils.RANDOM.nextInt(9) + 1;
final SimpleRecord[] records = IntStream.rangeClosed(0, batchSize)
.mapToObj(i -> new SimpleRecord(String.valueOf(i).getBytes()))
.toArray(SimpleRecord[]::new);
if (isLeader) {
log.appendAsLeader(MemoryRecords.withRecords(Compression.NONE, records), leaderEpoch);
log.maybeIncrementHighWatermark(logEndOffsetMetadata);
} else {
log.appendAsFollower(
MemoryRecords.withRecords(
logEndOffset,
Compression.NONE,
leaderEpoch,
records
),
Integer.MAX_VALUE
);
log.updateHighWatermark(logEndOffset);
}
}
case 1 -> {
isLeader = !isLeader;
leaderEpoch += 1;
if (!isLeader) {
log.truncateTo(log.highWatermark());
}
}
}
}
});
}
private UnifiedLog createLog() throws IOException {
return createLog(new LogConfig(Map.of()));
}
private UnifiedLog createLog(LogConfig config) throws IOException {
log = UnifiedLog.create(
logDir,
config,
0L,
0L,
scheduler,
brokerTopicStats,
Time.SYSTEM,
5 * 60 * 1000,
new ProducerStateManagerConfig(TransactionLogConfig.PRODUCER_ID_EXPIRATION_MS_DEFAULT, false),
TransactionLogConfig.PRODUCER_ID_EXPIRATION_CHECK_INTERVAL_MS_DEFAULT,
new LogDirFailureChannel(10),
true,
Optional.empty()
);
return log;
}
private void validateConsumedData(UnifiedLog log, Map<Long, Integer> consumedBatches) {
Iterator<Map.Entry<Long, Integer>> iter = consumedBatches.entrySet().iterator();
log.logSegments().forEach(segment ->
segment.log().batches().forEach(batch -> {
if (iter.hasNext()) {
final Map.Entry<Long, Integer> consumedBatch = iter.next();
final long consumedBatchBaseOffset = consumedBatch.getKey();
final int consumedBatchEpoch = consumedBatch.getValue();
final long logBatchBaseOffset = batch.baseOffset();
final int logBatchEpoch = batch.partitionLeaderEpoch();
assertEquals(logBatchBaseOffset,
consumedBatchBaseOffset,
"Consumed batch (offset=" + consumedBatchBaseOffset + ", epoch=" + consumedBatchEpoch + ") " +
"does not match next expected batch in log (offset=" + logBatchBaseOffset + ", epoch=" + logBatchEpoch + ")"
);
assertEquals(logBatchEpoch,
consumedBatchEpoch,
"Consumed batch (offset=" + consumedBatchBaseOffset + ", epoch=" + consumedBatchEpoch + ") " +
"does not match next expected batch in log (offset=" + logBatchBaseOffset + ", epoch=" + logBatchEpoch + ")"
);
}
})
);
}
}
|
simulates
|
java
|
apache__camel
|
components/camel-barcode/src/test/java/org/apache/camel/dataformat/barcode/BarcodeDataFormatTest.java
|
{
"start": 1310,
"end": 1397
}
|
class ____ all Camel independent test cases for {@link BarcodeDataFormat}.
*/
public
|
tests
|
java
|
hibernate__hibernate-orm
|
hibernate-testing/src/main/java/org/hibernate/testing/logger/TriggerOnPrefixLogListener.java
|
{
"start": 308,
"end": 1519
}
|
class ____ implements LogListener, Triggerable {
private Set<String> expectedPrefixes = new HashSet<>();
private final List<String> triggerMessages = new CopyOnWriteArrayList<>();
public TriggerOnPrefixLogListener(String expectedPrefix) {
expectedPrefixes.add( expectedPrefix );
}
public TriggerOnPrefixLogListener(Set<String> expectedPrefixes) {
this.expectedPrefixes = expectedPrefixes;
}
@Override
public String toString() {
return getClass().getSimpleName() + "{expectedPrefixes=" + expectedPrefixes + "}";
}
@Override
public void loggedEvent(Level level, String renderedMessage, Throwable thrown) {
if ( renderedMessage != null ) {
for ( String expectedPrefix : expectedPrefixes ) {
if ( renderedMessage.startsWith( expectedPrefix ) ) {
triggerMessages.add( renderedMessage );
}
}
}
}
@Override
public String triggerMessage() {
return !triggerMessages.isEmpty() ? triggerMessages.get(0) : null;
}
@Override
public List<String> triggerMessages() {
return triggerMessages;
}
@Override
public boolean wasTriggered() {
return !triggerMessages.isEmpty();
}
@Override
public void reset() {
triggerMessages.clear();
}
}
|
TriggerOnPrefixLogListener
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/action/LookupFromIndexIT.java
|
{
"start": 4843,
"end": 7776
}
|
class ____ extends AbstractEsqlIntegTestCase {
public void testKeywordKey() throws IOException {
runLookup(List.of(DataType.KEYWORD), new UsingSingleLookupTable(new Object[][] { new String[] { "aa", "bb", "cc", "dd" } }), null);
}
public void testJoinOnTwoKeys() throws IOException {
runLookup(
List.of(DataType.KEYWORD, DataType.LONG),
new UsingSingleLookupTable(new Object[][] { new String[] { "aa", "bb", "cc", "dd" }, new Long[] { 12L, 33L, 1L, 42L } }),
null
);
}
public void testJoinOnThreeKeys() throws IOException {
runLookup(
List.of(DataType.KEYWORD, DataType.LONG, DataType.KEYWORD),
new UsingSingleLookupTable(
new Object[][] {
new String[] { "aa", "bb", "cc", "dd" },
new Long[] { 12L, 33L, 1L, 42L },
new String[] { "one", "two", "three", "four" }, }
),
null
);
}
public void testJoinOnFourKeys() throws IOException {
runLookup(
List.of(DataType.KEYWORD, DataType.LONG, DataType.KEYWORD, DataType.INTEGER),
new UsingSingleLookupTable(
new Object[][] {
new String[] { "aa", "bb", "cc", "dd" },
new Long[] { 12L, 33L, 1L, 42L },
new String[] { "one", "two", "three", "four" },
new Integer[] { 1, 2, 3, 4 }, }
),
buildGreaterThanFilter(1L)
);
}
public void testLongKey() throws IOException {
runLookup(
List.of(DataType.LONG),
new UsingSingleLookupTable(new Object[][] { new Long[] { 12L, 33L, 1L } }),
buildGreaterThanFilter(0L)
);
}
/**
* LOOKUP multiple results match.
*/
public void testLookupIndexMultiResults() throws IOException {
runLookup(
List.of(DataType.KEYWORD),
new UsingSingleLookupTable(new Object[][] { new String[] { "aa", "bb", "bb", "dd" } }),
buildGreaterThanFilter(-1L)
);
}
public void testJoinOnTwoKeysMultiResults() throws IOException {
runLookup(
List.of(DataType.KEYWORD, DataType.LONG),
new UsingSingleLookupTable(new Object[][] { new String[] { "aa", "bb", "bb", "dd" }, new Long[] { 12L, 1L, 1L, 42L } }),
null
);
}
public void testJoinOnThreeKeysMultiResults() throws IOException {
runLookup(
List.of(DataType.KEYWORD, DataType.LONG, DataType.KEYWORD),
new UsingSingleLookupTable(
new Object[][] {
new String[] { "aa", "bb", "bb", "dd" },
new Long[] { 12L, 1L, 1L, 42L },
new String[] { "one", "two", "two", "four" } }
),
null
);
}
|
LookupFromIndexIT
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/CombineFileRecordReader.java
|
{
"start": 1291,
"end": 1481
}
|
class ____ using different RecordReaders for processing
* these data chunks from different files.
* @see CombineFileSplit
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public
|
allows
|
java
|
elastic__elasticsearch
|
plugins/examples/custom-significance-heuristic/src/test/java/org/elasticsearch/example/customsigheuristic/SimpleHeuristicWireTests.java
|
{
"start": 840,
"end": 2018
}
|
class ____ extends AbstractXContentSerializingTestCase<SimpleHeuristic> {
@Override
protected SimpleHeuristic doParseInstance(XContentParser parser) throws IOException {
/* Because Heuristics are XContent "fragments" we need to throw away
* the "extra" stuff before calling the parser. */
parser.nextToken();
assertThat(parser.currentToken(), equalTo(Token.START_OBJECT));
parser.nextToken();
assertThat(parser.currentToken(), equalTo(Token.FIELD_NAME));
assertThat(parser.currentName(), equalTo("simple"));
parser.nextToken();
SimpleHeuristic h = SimpleHeuristic.PARSER.apply(parser, null);
assertThat(parser.currentToken(), equalTo(Token.END_OBJECT));
parser.nextToken();
return h;
}
@Override
protected Reader<SimpleHeuristic> instanceReader() {
return SimpleHeuristic::new;
}
@Override
protected SimpleHeuristic createTestInstance() {
return new SimpleHeuristic();
}
@Override
protected SimpleHeuristic mutateInstance(SimpleHeuristic instance) throws IOException {
return null;
}
}
|
SimpleHeuristicWireTests
|
java
|
apache__camel
|
core/camel-util/src/test/java/org/apache/camel/util/StringQuoteHelperTest.java
|
{
"start": 2068,
"end": 2261
}
|
class ____ ", ',', false, true);
Assertions.assertEquals(2, arr.length);
Assertions.assertEquals(" String.class ${body} ", arr[0]);
Assertions.assertEquals(" String.
|
Mars
|
java
|
bumptech__glide
|
library/src/main/java/com/bumptech/glide/load/engine/bitmap_recycle/SizeConfigStrategy.java
|
{
"start": 1143,
"end": 6223
}
|
class ____ implements LruPoolStrategy {
private static final int MAX_SIZE_MULTIPLE = 8;
private static final Bitmap.Config[] ARGB_8888_IN_CONFIGS;
static {
Bitmap.Config[] result =
new Bitmap.Config[] {
Bitmap.Config.ARGB_8888,
// The value returned by Bitmaps with the hidden Bitmap config.
null,
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
result = Arrays.copyOf(result, result.length + 1);
result[result.length - 1] = Config.RGBA_F16;
}
ARGB_8888_IN_CONFIGS = result;
}
private static final Bitmap.Config[] RGBA_F16_IN_CONFIGS = ARGB_8888_IN_CONFIGS;
// We probably could allow ARGB_4444 and RGB_565 to decode into each other, but ARGB_4444 is
// deprecated and we'd rather be safe.
private static final Bitmap.Config[] RGB_565_IN_CONFIGS =
new Bitmap.Config[] {Bitmap.Config.RGB_565};
private static final Bitmap.Config[] ARGB_4444_IN_CONFIGS =
new Bitmap.Config[] {Bitmap.Config.ARGB_4444};
private static final Bitmap.Config[] ALPHA_8_IN_CONFIGS =
new Bitmap.Config[] {Bitmap.Config.ALPHA_8};
private final KeyPool keyPool = new KeyPool();
private final GroupedLinkedMap<Key, Bitmap> groupedMap = new GroupedLinkedMap<>();
private final Map<Bitmap.Config, NavigableMap<Integer, Integer>> sortedSizes = new HashMap<>();
@Override
public void put(Bitmap bitmap) {
int size = Util.getBitmapByteSize(bitmap);
Key key = keyPool.get(size, bitmap.getConfig());
groupedMap.put(key, bitmap);
NavigableMap<Integer, Integer> sizes = getSizesForConfig(bitmap.getConfig());
Integer current = sizes.get(key.size);
sizes.put(key.size, current == null ? 1 : current + 1);
}
@Override
@Nullable
public Bitmap get(int width, int height, Bitmap.Config config) {
int size = Util.getBitmapByteSize(width, height, config);
Key bestKey = findBestKey(size, config);
Bitmap result = groupedMap.get(bestKey);
if (result != null) {
// Decrement must be called before reconfigure.
decrementBitmapOfSize(bestKey.size, result);
result.reconfigure(width, height, config);
}
return result;
}
private Key findBestKey(int size, Bitmap.Config config) {
Key result = keyPool.get(size, config);
for (Bitmap.Config possibleConfig : getInConfigs(config)) {
NavigableMap<Integer, Integer> sizesForPossibleConfig = getSizesForConfig(possibleConfig);
Integer possibleSize = sizesForPossibleConfig.ceilingKey(size);
if (possibleSize != null && possibleSize <= size * MAX_SIZE_MULTIPLE) {
if (possibleSize != size
|| (possibleConfig == null ? config != null : !possibleConfig.equals(config))) {
keyPool.offer(result);
result = keyPool.get(possibleSize, possibleConfig);
}
break;
}
}
return result;
}
@Override
@Nullable
public Bitmap removeLast() {
Bitmap removed = groupedMap.removeLast();
if (removed != null) {
int removedSize = Util.getBitmapByteSize(removed);
decrementBitmapOfSize(removedSize, removed);
}
return removed;
}
private void decrementBitmapOfSize(Integer size, Bitmap removed) {
Bitmap.Config config = removed.getConfig();
NavigableMap<Integer, Integer> sizes = getSizesForConfig(config);
Integer current = sizes.get(size);
if (current == null) {
throw new NullPointerException(
"Tried to decrement empty size"
+ ", size: "
+ size
+ ", removed: "
+ logBitmap(removed)
+ ", this: "
+ this);
}
if (current == 1) {
sizes.remove(size);
} else {
sizes.put(size, current - 1);
}
}
private NavigableMap<Integer, Integer> getSizesForConfig(Bitmap.Config config) {
NavigableMap<Integer, Integer> sizes = sortedSizes.get(config);
if (sizes == null) {
sizes = new TreeMap<>();
sortedSizes.put(config, sizes);
}
return sizes;
}
@Override
public String logBitmap(Bitmap bitmap) {
int size = Util.getBitmapByteSize(bitmap);
return getBitmapString(size, bitmap.getConfig());
}
@Override
public String logBitmap(int width, int height, Bitmap.Config config) {
int size = Util.getBitmapByteSize(width, height, config);
return getBitmapString(size, config);
}
@Override
public int getSize(Bitmap bitmap) {
return Util.getBitmapByteSize(bitmap);
}
@Override
public String toString() {
StringBuilder sb =
new StringBuilder()
.append("SizeConfigStrategy{groupedMap=")
.append(groupedMap)
.append(", sortedSizes=(");
for (Map.Entry<Bitmap.Config, NavigableMap<Integer, Integer>> entry : sortedSizes.entrySet()) {
sb.append(entry.getKey()).append('[').append(entry.getValue()).append("], ");
}
if (!sortedSizes.isEmpty()) {
sb.replace(sb.length() - 2, sb.length(), "");
}
return sb.append(")}").toString();
}
@VisibleForTesting
static
|
SizeConfigStrategy
|
java
|
apache__maven
|
api/maven-api-di/src/main/java/org/apache/maven/di/tool/DiIndexProcessor.java
|
{
"start": 2166,
"end": 3468
}
|
class ____ that have been processed and contain the {@link Named} annotation.
*/
private final Set<String> processedClasses = new HashSet<>();
/**
* Processes classes with the {@link Named} annotation and generates an index file.
*
* @param annotations the annotation types requested to be processed
* @param roundEnv environment for information about the current and prior round
* @return whether or not the set of annotations are claimed by this processor
*/
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
logMessage(
Diagnostic.Kind.NOTE, "Processing " + roundEnv.getRootElements().size() + " classes");
for (Element element : roundEnv.getElementsAnnotatedWith(Named.class)) {
if (element instanceof TypeElement typeElement) {
String className = getFullClassName(typeElement);
processedClasses.add(className);
}
}
if (roundEnv.processingOver()) {
try {
updateFileIfChanged();
} catch (Exception e) {
logError("Error updating file", e);
}
}
return true;
}
/**
* Gets the fully qualified
|
names
|
java
|
spring-projects__spring-security
|
web/src/test/java/org/springframework/security/web/server/header/XContentTypeOptionsServerHttpHeadersWriterTests.java
|
{
"start": 1140,
"end": 2628
}
|
class ____ {
XContentTypeOptionsServerHttpHeadersWriter writer = new XContentTypeOptionsServerHttpHeadersWriter();
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
HttpHeaders headers = this.exchange.getResponse().getHeaders();
@Test
public void writeHeadersWhenNoHeadersThenWriteHeadersForXContentTypeOptionsServerHttpHeadersWriter() {
this.writer.writeHttpHeaders(this.exchange);
assertThat(this.headers.headerNames()).hasSize(1);
assertThat(this.headers.get(XContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS))
.containsOnly(XContentTypeOptionsServerHttpHeadersWriter.NOSNIFF);
}
@Test
public void writeHeadersWhenHeaderWrittenThenDoesNotOverrideForXContentTypeOptionsServerHttpHeadersWriter() {
String headerValue = "value";
this.headers.set(XContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue);
this.writer.writeHttpHeaders(this.exchange);
assertThat(this.headers.headerNames()).hasSize(1);
assertThat(this.headers.get(XContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS))
.containsOnly(headerValue);
}
@Test
public void constantsMatchExpectedHeaderAndValueForXContentTypeOptionsServerHttpHeadersWriter() {
assertThat(XContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS).isEqualTo("X-Content-Type-Options");
assertThat(XContentTypeOptionsServerHttpHeadersWriter.NOSNIFF).isEqualTo("nosniff");
}
}
|
XContentTypeOptionsServerHttpHeadersWriterTests
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/search/aggregations/InternalAggregationsTests.java
|
{
"start": 5258,
"end": 14765
}
|
class ____ extends InternalFilters {
InternalFiltersForF1(
String name,
List<InternalBucket> buckets,
boolean keyed,
boolean keyedBucket,
Map<String, Object> metadata
) {
super(name, buckets, keyed, keyedBucket, metadata);
}
@Override
protected AggregatorReducer getLeaderReducer(AggregationReduceContext reduceContext, int size) {
assertThat(reduceContext.builder().getName(), equalTo("f1"));
assertThat(reduceContext.builder(), instanceOf(FiltersAggregationBuilder.class));
f1Reduced.incrementAndGet();
return super.getLeaderReducer(reduceContext, size);
}
}
return InternalAggregations.from(
List.of(
new InternalFiltersForF1(
"f1",
List.of(
new InternalFilters.InternalBucket(
"f1k1",
k1,
InternalAggregations.from(
List.of(
new InternalFiltersForF2(
"f2",
List.of(
new InternalFilters.InternalBucket("f2k1", k1k1, InternalAggregations.EMPTY),
new InternalFilters.InternalBucket("f2k2", k1k2, InternalAggregations.EMPTY)
),
true,
true,
null
)
)
)
),
new InternalFilters.InternalBucket(
"f1k2",
k2,
InternalAggregations.from(
List.of(
new InternalFiltersForF2(
"f2",
List.of(
new InternalFilters.InternalBucket("f2k1", k2k1, InternalAggregations.EMPTY),
new InternalFilters.InternalBucket("f2k2", k2k2, InternalAggregations.EMPTY)
),
true,
true,
null
)
)
)
)
),
true,
true,
null
)
)
);
}
InternalAggregations reduced(int k1, int k2, int k1k1, int k1k2, int k2k1, int k2k2) {
return InternalAggregations.from(
List.of(
new InternalFilters(
"f1",
List.of(
new InternalFilters.InternalBucket(
"f1k1",
k1,
InternalAggregations.from(
List.of(
new InternalFilters(
"f2",
List.of(
new InternalFilters.InternalBucket("f2k1", k1k1, InternalAggregations.EMPTY),
new InternalFilters.InternalBucket("f2k2", k1k2, InternalAggregations.EMPTY)
),
true,
true,
null
)
)
)
),
new InternalFilters.InternalBucket(
"f1k2",
k2,
InternalAggregations.from(
List.of(
new InternalFilters(
"f2",
List.of(
new InternalFilters.InternalBucket("f2k1", k2k1, InternalAggregations.EMPTY),
new InternalFilters.InternalBucket("f2k2", k2k2, InternalAggregations.EMPTY)
),
true,
true,
null
)
)
)
)
),
true,
true,
null
)
)
);
}
public void testNonFinalReduceTopLevelPipelineAggs() {
InternalAggregation terms = new StringTerms(
"name",
BucketOrder.key(true),
BucketOrder.key(true),
10,
1,
Collections.emptyMap(),
DocValueFormat.RAW,
25,
false,
10,
Collections.emptyList(),
0L
);
List<InternalAggregations> aggs = singletonList(InternalAggregations.from(Collections.singletonList(terms)));
InternalAggregations reducedAggs = InternalAggregations.topLevelReduce(aggs, maxBucketReduceContext().forPartialReduction());
assertEquals(1, reducedAggs.asList().size());
}
public void testFinalReduceTopLevelPipelineAggs() {
InternalAggregation terms = new StringTerms(
"name",
BucketOrder.key(true),
BucketOrder.key(true),
10,
1,
Collections.emptyMap(),
DocValueFormat.RAW,
25,
false,
10,
Collections.emptyList(),
0L
);
InternalAggregations aggs = InternalAggregations.from(Collections.singletonList(terms));
InternalAggregations reducedAggs = InternalAggregations.topLevelReduce(List.of(aggs), maxBucketReduceContext().forFinalReduction());
assertEquals(2, reducedAggs.asList().size());
}
private AggregationReduceContext.Builder maxBucketReduceContext() {
AggregationBuilder aggBuilder = new TermsAggregationBuilder("name");
PipelineAggregationBuilder pipelineBuilder = new MaxBucketPipelineAggregationBuilder("test", "name");
return InternalAggregationTestCase.emptyReduceContextBuilder(
AggregatorFactories.builder().addAggregator(aggBuilder).addPipelineAggregator(pipelineBuilder)
);
}
public static InternalAggregations createTestInstance() throws Exception {
List<InternalAggregation> aggsList = new ArrayList<>();
if (randomBoolean()) {
StringTermsTests stringTermsTests = new StringTermsTests();
stringTermsTests.init();
stringTermsTests.setUp();
aggsList.add(stringTermsTests.createTestInstance());
}
if (randomBoolean()) {
InternalDateHistogramTests dateHistogramTests = new InternalDateHistogramTests();
dateHistogramTests.setUp();
aggsList.add(dateHistogramTests.createTestInstance());
}
if (randomBoolean()) {
InternalSimpleValueTests simpleValueTests = new InternalSimpleValueTests();
aggsList.add(simpleValueTests.createTestInstance());
}
return InternalAggregations.from(aggsList);
}
public void testSerialization() throws Exception {
InternalAggregations aggregations = createTestInstance();
writeToAndReadFrom(aggregations, TransportVersion.current(), 0);
}
public void testSerializedSize() throws Exception {
InternalAggregations aggregations = createTestInstance();
assertThat(
DelayableWriteable.getSerializedSize(aggregations),
equalTo((long) serialize(aggregations, TransportVersion.current()).length)
);
}
private void writeToAndReadFrom(InternalAggregations aggregations, TransportVersion version, int iteration) throws IOException {
BytesRef serializedAggs = serialize(aggregations, version);
try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(serializedAggs.bytes), registry)) {
in.setTransportVersion(version);
InternalAggregations deserialized = InternalAggregations.readFrom(in);
assertEquals(aggregations.asList(), deserialized.asList());
if (iteration < 2) {
writeToAndReadFrom(deserialized, version, iteration + 1);
}
}
}
private BytesRef serialize(InternalAggregations aggs, TransportVersion version) throws IOException {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.setTransportVersion(version);
aggs.writeTo(out);
return out.bytes().toBytesRef();
}
}
}
|
InternalFiltersForF1
|
java
|
google__guice
|
core/test/com/google/inject/MethodInterceptionTest.java
|
{
"start": 14815,
"end": 15675
}
|
class ____ extends Superclass<RetType> implements Interface {}
@Test
public void testInterceptionOrder() {
final List<String> callList = Lists.newArrayList();
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(
Matchers.any(),
Matchers.any(),
new NamedInterceptor("a", callList),
new NamedInterceptor("b", callList),
new NamedInterceptor("c", callList));
}
});
Interceptable interceptable = injector.getInstance(Interceptable.class);
assertEquals(0, callList.size());
interceptable.foo();
assertEquals(Arrays.asList("a", "b", "c"), callList);
}
private static final
|
Impl
|
java
|
micronaut-projects__micronaut-core
|
http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/filter/RequestFilterCompletionStageFutureProceedTest.java
|
{
"start": 1430,
"end": 2508
}
|
class ____ {
public static final String SPEC_NAME = "RequestFilterCompletionStageFutureProceedTest";
@Test
public void requestFilterProceedWithCompletableFuture() throws IOException {
TestScenario.builder()
.specName(SPEC_NAME)
.request(HttpRequest.GET("/foobar").header("X-FOOBAR", "123"))
.assertion((server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.ACCEPTED)
.build()))
.run();
TestScenario.builder()
.specName(SPEC_NAME)
.request(HttpRequest.GET("/foobar"))
.assertion((server, request) -> AssertionUtils.assertThrows(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.UNAUTHORIZED)
.build()))
.run();
}
/*
//tag::clazz[]
@ServerFilter(ServerFilter.MATCH_ALL_PATTERN)
|
RequestFilterCompletionStageFutureProceedTest
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/SpringAiEmbeddingsComponentBuilderFactory.java
|
{
"start": 1373,
"end": 1897
}
|
interface ____ {
/**
* Spring AI Embeddings (camel-spring-ai-embeddings)
* Spring AI Embeddings
*
* Category: ai
* Since: 4.17
* Maven coordinates: org.apache.camel:camel-spring-ai-embeddings
*
* @return the dsl builder
*/
static SpringAiEmbeddingsComponentBuilder springAiEmbeddings() {
return new SpringAiEmbeddingsComponentBuilderImpl();
}
/**
* Builder for the Spring AI Embeddings component.
*/
|
SpringAiEmbeddingsComponentBuilderFactory
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/TimeZoneMappingTests.java
|
{
"start": 3002,
"end": 3332
}
|
class ____ {
@Id
private Integer id;
//tag::basic-timeZone-example[]
// mapped as VARCHAR
private TimeZone timeZone;
//end::basic-timeZone-example[]
public EntityWithTimeZone() {
}
public EntityWithTimeZone(Integer id, TimeZone timeZone) {
this.id = id;
this.timeZone = timeZone;
}
}
}
|
EntityWithTimeZone
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/Aws2TranscribeComponentBuilderFactory.java
|
{
"start": 1407,
"end": 1951
}
|
interface ____ {
/**
* AWS Transcribe (camel-aws2-transcribe)
* Automatically convert speech to text using AWS Transcribe service
*
* Category: cloud,messaging
* Since: 4.15
* Maven coordinates: org.apache.camel:camel-aws2-transcribe
*
* @return the dsl builder
*/
static Aws2TranscribeComponentBuilder aws2Transcribe() {
return new Aws2TranscribeComponentBuilderImpl();
}
/**
* Builder for the AWS Transcribe component.
*/
|
Aws2TranscribeComponentBuilderFactory
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/api/queue/event/EnabledOperationEventListener.java
|
{
"start": 766,
"end": 882
}
|
interface ____ triggered when queue operation switched to enabled state.
*
* @author Nikita Koksharov
*
*/
public
|
is
|
java
|
apache__camel
|
components/camel-telemetry/src/main/java/org/apache/camel/telemetry/decorators/ActiveMQSpanDecorator.java
|
{
"start": 858,
"end": 1136
}
|
class ____ extends JmsSpanDecorator {
@Override
public String getComponent() {
return "activemq";
}
@Override
public String getComponentClassName() {
return "org.apache.camel.component.activemq.ActiveMQComponent";
}
}
|
ActiveMQSpanDecorator
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/TryWithResourcesVariableTest.java
|
{
"start": 1922,
"end": 2350
}
|
class ____ {
void f(AutoCloseable a1, AutoCloseable a2) {
try (AutoCloseable b1 = a1;
AutoCloseable b2 = a2) {
System.err.println(b1);
System.err.println(b2);
} catch (Exception e) {
}
}
}
""")
.addOutputLines(
"Test.java",
"""
|
Test
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/resolver/order/AvailableSpaceResolver.java
|
{
"start": 5420,
"end": 5483
}
|
class ____ stores cluster available space info.
*/
static
|
that
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/Langchain4jEmbeddingstoreComponentBuilderFactory.java
|
{
"start": 1420,
"end": 2040
}
|
interface ____ {
/**
* LangChain4j Embedding Store (camel-langchain4j-embeddingstore)
* Perform operations on the Langchain4jEmbeddingStores.
*
* Category: database,ai
* Since: 4.14
* Maven coordinates: org.apache.camel:camel-langchain4j-embeddingstore
*
* @return the dsl builder
*/
static Langchain4jEmbeddingstoreComponentBuilder langchain4jEmbeddingstore() {
return new Langchain4jEmbeddingstoreComponentBuilderImpl();
}
/**
* Builder for the LangChain4j Embedding Store component.
*/
|
Langchain4jEmbeddingstoreComponentBuilderFactory
|
java
|
jhy__jsoup
|
src/main/java/org/jsoup/helper/CookieUtil.java
|
{
"start": 681,
"end": 5302
}
|
class ____ {
// cookie manager get() wants request headers but doesn't use them, so we just pass a dummy object here
private static final Map<String, List<String>> EmptyRequestHeaders = Collections.unmodifiableMap(new HashMap<>());
private static final String Sep = "; ";
private static final String CookieName = "Cookie";
private static final String Cookie2Name = "Cookie2";
/**
Pre-request, get any applicable headers out of the Request cookies and the Cookie Store, and add them to the request
headers. If the Cookie Store duplicates any Request cookies (same name and value), they will be discarded.
*/
static void applyCookiesToRequest(HttpConnection.Request req, BiConsumer<String, String> setter) throws IOException {
// Request key/val cookies. LinkedHashSet used to preserve order, as cookie store will return most specific path first
Set<String> cookieSet = requestCookieSet(req);
Set<String> cookies2 = null;
// stored:
Map<String, List<String>> storedCookies = req.cookieManager().get(asUri(req.url), EmptyRequestHeaders);
for (Map.Entry<String, List<String>> entry : storedCookies.entrySet()) {
// might be Cookie: name=value; name=value\nCookie2: name=value; name=value
List<String> cookies = entry.getValue(); // these will be name=val
if (cookies == null || cookies.size() == 0) // the cookie store often returns just an empty "Cookie" key, no val
continue;
String key = entry.getKey(); // Cookie or Cookie2
Set<String> set;
if (CookieName.equals(key))
set = cookieSet;
else if (Cookie2Name.equals(key)) {
set = new HashSet<>();
cookies2 = set;
} else {
continue; // unexpected header key
}
set.addAll(cookies);
}
if (cookieSet.size() > 0)
setter.accept(CookieName, StringUtil.join(cookieSet, Sep));
if (cookies2 != null && cookies2.size() > 0)
setter.accept(Cookie2Name, StringUtil.join(cookies2, Sep));
}
private static LinkedHashSet<String> requestCookieSet(Connection.Request req) {
LinkedHashSet<String> set = new LinkedHashSet<>();
// req cookies are the wildcard key/val cookies (no domain, path, etc)
for (Map.Entry<String, String> cookie : req.cookies().entrySet()) {
set.add(cookie.getKey() + "=" + cookie.getValue());
}
return set;
}
static URI asUri(URL url) throws IOException {
try {
return url.toURI();
} catch (URISyntaxException e) { // this would be a WTF because we construct the URL
MalformedURLException ue = new MalformedURLException(e.getMessage());
ue.initCause(e);
throw ue;
}
}
/** Store the Result cookies into the cookie manager, and place relevant cookies into the Response object. */
static void storeCookies(HttpConnection.Request req, HttpConnection.Response res, URL url, Map<String, List<String>> resHeaders) throws IOException {
CookieManager manager = req.cookieManager();
URI uri = CookieUtil.asUri(url);
manager.put(uri, resHeaders); // stores cookies for session
// set up the simple cookies() map
// the response may include cookies that are not relevant to this request, but users may require them if they are not using the cookie manager (setting request cookies only from the simple cookies() response):
for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) {
String name = entry.getKey();
List<String> values = entry.getValue();
if (name.equalsIgnoreCase("Set-Cookie")) {
for (String value : values) {
parseCookie(value, res);
}
}
}
}
static void parseCookie(@Nullable String value, HttpConnection.Response res) {
if (value == null) return;
CharacterReader reader = new CharacterReader(value);
String cookieName = reader.consumeTo('=').trim();
reader.advance();
String cookieVal = reader.consumeTo(';').trim();
// ignores path, date, domain, validateTLSCertificates et al. full details will be available in cookiestore if required
// name not blank, value not null
if (!cookieName.isEmpty())
res.cookie(cookieName, cookieVal); // if duplicate names, last set will win
reader.close();
}
}
|
CookieUtil
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/event/spi/PersistEvent.java
|
{
"start": 267,
"end": 974
}
|
class ____ extends AbstractSessionEvent {
private Object object;
private String entityName;
public PersistEvent(String entityName, Object original, EventSource source) {
this(original, source);
this.entityName = entityName;
}
public PersistEvent(Object object, EventSource source) {
super(source);
if ( object == null ) {
throw new IllegalArgumentException( "Entity may not be null" );
}
this.object = object;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
}
|
PersistEvent
|
java
|
apache__camel
|
core/camel-core-xml/src/main/java/org/apache/camel/core/xml/util/jsse/AbstractSSLContextClientParametersFactoryBean.java
|
{
"start": 1182,
"end": 2057
}
|
class ____
extends AbstractBaseSSLContextParametersFactoryBean<SSLContextClientParameters> {
@XmlElement(name = "sniHostNames")
private SNIHostNamesDefinition sniHostNamesDefinition;
@Override
protected SSLContextClientParameters createInstance() {
SSLContextClientParameters newInstance = new SSLContextClientParameters();
newInstance.setCamelContext(getCamelContext());
if (sniHostNamesDefinition != null) {
newInstance.addAllSniHostNames(sniHostNamesDefinition.getSniHostName());
}
return newInstance;
}
@Override
public Class<SSLContextClientParameters> getObjectType() {
return SSLContextClientParameters.class;
}
public SNIHostNamesDefinition getSniHostNamesDefinition() {
return sniHostNamesDefinition;
}
}
|
AbstractSSLContextClientParametersFactoryBean
|
java
|
apache__kafka
|
coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorTimer.java
|
{
"start": 1006,
"end": 1530
}
|
interface ____<T, U> {
/**
* Generates the records needed to implement this timeout write operation. In general,
* this operation should not modify the hard state of the coordinator. That modifications
* will happen later on, when the records generated by this function are applied to the
* coordinator.
*
* A typical example of timeout operation is the session timeout used by the consumer
* group rebalance protocol.
*
* @param <T> The record type.
*/
|
CoordinatorTimer
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/intercepted/InterceptedRestClientTest.java
|
{
"start": 1088,
"end": 1775
}
|
class ____ {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(TestEndpoint.class, Client.class, MyAnnotation.class, MyInterceptorBinding.class,
MyInterceptor.class)
.addAsResource(new StringAsset(setUrlForClass(Client.class)), "application.properties"));
@Inject
@RestClient
Client client;
@Test
public void testFallbackWasUsed() {
assertEquals("skipped", client.hello("test"));
assertEquals("pong", client.ping("test"));
}
@Path("/test")
public static
|
InterceptedRestClientTest
|
java
|
apache__rocketmq
|
remoting/src/test/java/org/apache/rocketmq/remoting/protocol/statictopic/TopicQueueMappingUtilsTest.java
|
{
"start": 1168,
"end": 15953
}
|
class ____ {
private Set<String> buildTargetBrokers(int num) {
return buildTargetBrokers(num, "");
}
private Set<String> buildTargetBrokers(int num, String suffix) {
Set<String> brokers = new HashSet<>();
for (int i = 0; i < num; i++) {
brokers.add("broker" + suffix + i);
}
return brokers;
}
private Map<String, Integer> buildBrokerNumMap(int num) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < num; i++) {
map.put("broker" + i, 0);
}
return map;
}
private Map<String, Integer> buildBrokerNumMap(int num, int queues) {
Map<String, Integer> map = new HashMap<>();
int random = new Random().nextInt(num);
for (int i = 0; i < num; i++) {
map.put("broker" + i, queues);
if (i == random) {
map.put("broker" + i, queues + 1);
}
}
return map;
}
private void testIdToBroker(Map<Integer, String> idToBroker, Map<String, Integer> brokerNumMap) {
Map<String, Integer> brokerNumOther = new HashMap<>();
for (int i = 0; i < idToBroker.size(); i++) {
Assert.assertTrue(idToBroker.containsKey(i));
String broker = idToBroker.get(i);
if (brokerNumOther.containsKey(broker)) {
brokerNumOther.put(broker, brokerNumOther.get(broker) + 1);
} else {
brokerNumOther.put(broker, 1);
}
}
Assert.assertEquals(brokerNumMap.size(), brokerNumOther.size());
for (Map.Entry<String, Integer> entry: brokerNumOther.entrySet()) {
Assert.assertEquals(entry.getValue(), brokerNumMap.get(entry.getKey()));
}
}
@Test
public void testAllocator() {
//stability
for (int i = 0; i < 10; i++) {
int num = 3;
Map<String, Integer> brokerNumMap = buildBrokerNumMap(num);
TopicQueueMappingUtils.MappingAllocator allocator = TopicQueueMappingUtils.buildMappingAllocator(new HashMap<>(), brokerNumMap, null);
allocator.upToNum(num * 2);
for (Map.Entry<String, Integer> entry: allocator.getBrokerNumMap().entrySet()) {
Assert.assertEquals(2L, entry.getValue().longValue());
}
Assert.assertEquals(num * 2, allocator.getIdToBroker().size());
testIdToBroker(allocator.idToBroker, allocator.getBrokerNumMap());
allocator.upToNum(num * 3 - 1);
for (Map.Entry<String, Integer> entry: allocator.getBrokerNumMap().entrySet()) {
Assert.assertTrue(entry.getValue() >= 2);
Assert.assertTrue(entry.getValue() <= 3);
}
Assert.assertEquals(num * 3 - 1, allocator.getIdToBroker().size());
testIdToBroker(allocator.idToBroker, allocator.getBrokerNumMap());
}
}
@Test
public void testRemappingAllocator() {
for (int i = 0; i < 10; i++) {
int num = (i + 2) * 2;
Map<String, Integer> brokerNumMap = buildBrokerNumMap(num);
Map<String, Integer> brokerNumMapBeforeRemapping = buildBrokerNumMap(num, num);
TopicQueueMappingUtils.MappingAllocator allocator = TopicQueueMappingUtils.buildMappingAllocator(new HashMap<>(), brokerNumMap, brokerNumMapBeforeRemapping);
allocator.upToNum(num * num + 1);
Assert.assertEquals(brokerNumMapBeforeRemapping, allocator.getBrokerNumMap());
}
}
@Test(expected = RuntimeException.class)
public void testTargetBrokersComplete() {
String topic = "static";
String broker1 = "broker1";
String broker2 = "broker2";
Set<String> targetBrokers = new HashSet<>();
targetBrokers.add(broker1);
Map<String, TopicConfigAndQueueMapping> brokerConfigMap = new HashMap<>();
TopicQueueMappingDetail mappingDetail = new TopicQueueMappingDetail(topic, 0, broker2, 0);
mappingDetail.getHostedQueues().put(1, new ArrayList<>());
brokerConfigMap.put(broker2, new TopicConfigAndQueueMapping(new TopicConfig(topic, 0, 0), mappingDetail));
TopicQueueMappingUtils.checkTargetBrokersComplete(targetBrokers, brokerConfigMap);
}
@Test
public void testCreateStaticTopic() {
String topic = "static";
int queueNum;
Map<String, TopicConfigAndQueueMapping> brokerConfigMap = new HashMap<>();
for (int i = 1; i < 10; i++) {
Set<String> targetBrokers = buildTargetBrokers(2 * i);
Set<String> nonTargetBrokers = buildTargetBrokers(2 * i, "test");
queueNum = 10 * i;
TopicRemappingDetailWrapper wrapper = TopicQueueMappingUtils.createTopicConfigMapping(topic, queueNum, targetBrokers, brokerConfigMap);
Assert.assertEquals(wrapper.getBrokerConfigMap(), brokerConfigMap);
Assert.assertEquals(2 * i, brokerConfigMap.size());
//do the check manually
Map.Entry<Long, Integer> maxEpochAndNum = TopicQueueMappingUtils.checkNameEpochNumConsistence(topic, brokerConfigMap);
Assert.assertEquals(queueNum, maxEpochAndNum.getValue().longValue());
Map<Integer, TopicQueueMappingOne> globalIdMap = TopicQueueMappingUtils.checkAndBuildMappingItems(new ArrayList<>(TopicQueueMappingUtils.getMappingDetailFromConfig(brokerConfigMap.values())), false, true);
TopicQueueMappingUtils.checkIfReusePhysicalQueue(globalIdMap.values());
TopicQueueMappingUtils.checkPhysicalQueueConsistence(brokerConfigMap);
for (Map.Entry<String, TopicConfigAndQueueMapping> entry : brokerConfigMap.entrySet()) {
TopicConfigAndQueueMapping configMapping = entry.getValue();
if (nonTargetBrokers.contains(configMapping.getMappingDetail().bname)) {
Assert.assertEquals(0, configMapping.getReadQueueNums());
Assert.assertEquals(0, configMapping.getWriteQueueNums());
Assert.assertEquals(0, configMapping.getMappingDetail().getHostedQueues().size());
} else {
Assert.assertEquals(5, configMapping.getReadQueueNums());
Assert.assertEquals(5, configMapping.getWriteQueueNums());
Assert.assertTrue(configMapping.getMappingDetail().epoch > System.currentTimeMillis());
for (List<LogicQueueMappingItem> items: configMapping.getMappingDetail().getHostedQueues().values()) {
for (LogicQueueMappingItem item: items) {
Assert.assertEquals(0, item.getStartOffset());
Assert.assertEquals(0, item.getLogicOffset());
TopicConfig topicConfig = brokerConfigMap.get(item.getBname());
Assert.assertTrue(item.getQueueId() < topicConfig.getWriteQueueNums());
}
}
}
}
}
}
@Test
public void testRemappingStaticTopic() {
String topic = "static";
int queueNum = 7;
Map<String, TopicConfigAndQueueMapping> brokerConfigMap = new HashMap<>();
Set<String> originalBrokers = buildTargetBrokers(2);
TopicRemappingDetailWrapper wrapper = TopicQueueMappingUtils.createTopicConfigMapping(topic, queueNum, originalBrokers, brokerConfigMap);
Assert.assertEquals(wrapper.getBrokerConfigMap(), brokerConfigMap);
Assert.assertEquals(2, brokerConfigMap.size());
{
//do the check manually
TopicQueueMappingUtils.checkNameEpochNumConsistence(topic, brokerConfigMap);
TopicQueueMappingUtils.checkPhysicalQueueConsistence(brokerConfigMap);
Map<Integer, TopicQueueMappingOne> globalIdMap = TopicQueueMappingUtils.checkAndBuildMappingItems(new ArrayList<>(TopicQueueMappingUtils.getMappingDetailFromConfig(brokerConfigMap.values())), false, true);
TopicQueueMappingUtils.checkIfReusePhysicalQueue(globalIdMap.values());
}
for (int i = 0; i < 10; i++) {
Set<String> targetBrokers = buildTargetBrokers(2, "test" + i);
TopicQueueMappingUtils.remappingStaticTopic(topic, brokerConfigMap, targetBrokers);
//do the check manually
TopicQueueMappingUtils.checkNameEpochNumConsistence(topic, brokerConfigMap);
TopicQueueMappingUtils.checkPhysicalQueueConsistence(brokerConfigMap);
Map<Integer, TopicQueueMappingOne> globalIdMap = TopicQueueMappingUtils.checkAndBuildMappingItems(new ArrayList<>(TopicQueueMappingUtils.getMappingDetailFromConfig(brokerConfigMap.values())), false, true);
TopicQueueMappingUtils.checkIfReusePhysicalQueue(globalIdMap.values());
TopicQueueMappingUtils.checkLeaderInTargetBrokers(globalIdMap.values(), targetBrokers);
Assert.assertEquals((i + 2) * 2, brokerConfigMap.size());
//check and complete the logicOffset
for (Map.Entry<String, TopicConfigAndQueueMapping> entry : brokerConfigMap.entrySet()) {
TopicConfigAndQueueMapping configMapping = entry.getValue();
if (!targetBrokers.contains(configMapping.getMappingDetail().bname)) {
continue;
}
for (List<LogicQueueMappingItem> items: configMapping.getMappingDetail().getHostedQueues().values()) {
Assert.assertEquals(i + 2, items.size());
items.get(items.size() - 1).setLogicOffset(i + 1);
}
}
}
}
@Test
public void testRemappingStaticTopicStability() {
String topic = "static";
int queueNum = 7;
Map<String, TopicConfigAndQueueMapping> brokerConfigMap = new HashMap<>();
Set<String> originalBrokers = buildTargetBrokers(2);
{
TopicRemappingDetailWrapper wrapper = TopicQueueMappingUtils.createTopicConfigMapping(topic, queueNum, originalBrokers, brokerConfigMap);
Assert.assertEquals(wrapper.getBrokerConfigMap(), brokerConfigMap);
Assert.assertEquals(2, brokerConfigMap.size());
}
for (int i = 0; i < 10; i++) {
TopicRemappingDetailWrapper wrapper = TopicQueueMappingUtils.remappingStaticTopic(topic, brokerConfigMap, originalBrokers);
Assert.assertEquals(wrapper.getBrokerConfigMap(), brokerConfigMap);
Assert.assertEquals(2, brokerConfigMap.size());
Assert.assertTrue(wrapper.getBrokerToMapIn().isEmpty());
Assert.assertTrue(wrapper.getBrokerToMapOut().isEmpty());
}
}
@Test
public void testUtilsCheck() {
String topic = "static";
int queueNum = 10;
Map<String, TopicConfigAndQueueMapping> brokerConfigMap = new HashMap<>();
Set<String> targetBrokers = buildTargetBrokers(2);
TopicRemappingDetailWrapper wrapper = TopicQueueMappingUtils.createTopicConfigMapping(topic, queueNum, targetBrokers, brokerConfigMap);
Assert.assertEquals(wrapper.getBrokerConfigMap(), brokerConfigMap);
Assert.assertEquals(2, brokerConfigMap.size());
TopicConfigAndQueueMapping configMapping = brokerConfigMap.values().iterator().next();
List<LogicQueueMappingItem> items = configMapping.getMappingDetail().getHostedQueues().values().iterator().next();
Map.Entry<Long, Integer> maxEpochNum = TopicQueueMappingUtils.checkNameEpochNumConsistence(topic, brokerConfigMap);
int exceptionNum = 0;
try {
configMapping.getMappingDetail().setTopic("xxxx");
TopicQueueMappingUtils.checkNameEpochNumConsistence(topic, brokerConfigMap);
} catch (RuntimeException ignore) {
exceptionNum++;
configMapping.getMappingDetail().setTopic(topic);
TopicQueueMappingUtils.checkNameEpochNumConsistence(topic, brokerConfigMap);
}
try {
configMapping.getMappingDetail().setTotalQueues(1);
TopicQueueMappingUtils.checkNameEpochNumConsistence(topic, brokerConfigMap);
} catch (RuntimeException ignore) {
exceptionNum++;
configMapping.getMappingDetail().setTotalQueues(10);
TopicQueueMappingUtils.checkNameEpochNumConsistence(topic, brokerConfigMap);
}
try {
configMapping.getMappingDetail().setEpoch(0);
TopicQueueMappingUtils.checkNameEpochNumConsistence(topic, brokerConfigMap);
} catch (RuntimeException ignore) {
exceptionNum++;
configMapping.getMappingDetail().setEpoch(maxEpochNum.getKey());
TopicQueueMappingUtils.checkNameEpochNumConsistence(topic, brokerConfigMap);
}
try {
configMapping.getMappingDetail().getHostedQueues().put(10000, new ArrayList<>(Collections.singletonList(new LogicQueueMappingItem(1, 1, targetBrokers.iterator().next(), 0, 0, -1, -1, -1))));
TopicQueueMappingUtils.checkAndBuildMappingItems(TopicQueueMappingUtils.getMappingDetailFromConfig(brokerConfigMap.values()), false, true);
} catch (RuntimeException ignore) {
exceptionNum++;
configMapping.getMappingDetail().getHostedQueues().remove(10000);
TopicQueueMappingUtils.checkAndBuildMappingItems(TopicQueueMappingUtils.getMappingDetailFromConfig(brokerConfigMap.values()), false, true);
}
try {
configMapping.setWriteQueueNums(1);
TopicQueueMappingUtils.checkPhysicalQueueConsistence(brokerConfigMap);
} catch (RuntimeException ignore) {
exceptionNum++;
configMapping.setWriteQueueNums(5);
TopicQueueMappingUtils.checkPhysicalQueueConsistence(brokerConfigMap);
}
try {
items.add(new LogicQueueMappingItem(1, 1, targetBrokers.iterator().next(), 0, 0, -1, -1, -1));
Map<Integer, TopicQueueMappingOne> map = TopicQueueMappingUtils.checkAndBuildMappingItems(TopicQueueMappingUtils.getMappingDetailFromConfig(brokerConfigMap.values()), false, true);
TopicQueueMappingUtils.checkIfReusePhysicalQueue(map.values());
} catch (RuntimeException ignore) {
exceptionNum++;
items.remove(items.size() - 1);
Map<Integer, TopicQueueMappingOne> map = TopicQueueMappingUtils.checkAndBuildMappingItems(TopicQueueMappingUtils.getMappingDetailFromConfig(brokerConfigMap.values()), false, true);
TopicQueueMappingUtils.checkIfReusePhysicalQueue(map.values());
}
Assert.assertEquals(6, exceptionNum);
}
}
|
TopicQueueMappingUtilsTest
|
java
|
alibaba__nacos
|
plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/Mapper.java
|
{
"start": 769,
"end": 2480
}
|
interface ____ {
/**
* The select method contains columns and where params.
* @param columns The columns
* @param where The where params
* @return The sql of select
*/
String select(List<String> columns, List<String> where);
/**
* The insert method contains columns.
* @param columns The columns
* @return The sql of insert
*/
String insert(List<String> columns);
/**
* The update method contains columns and where params.
* @param columns The columns
* @param where The where params
* @return The sql of update
*/
String update(List<String> columns, List<String> where);
/**
* The delete method contains.
* @param params The params
* @return The sql of delete
*/
String delete(List<String> params);
/**
* The count method contains where params.
*
* @param where The where params
* @return The sql of count
*/
String count(List<String> where);
/**
* Get the name of table.
* @return The name of table.
*/
String getTableName();
/**
* Get the datasource name.
* @return The name of datasource.
*/
String getDataSource();
/**
* Get config_info table primary keys name.
* The old default value: Statement.RETURN_GENERATED_KEYS
* The new default value: new String[]{"id"}
* @return an array of column names indicating the columns
*/
String[] getPrimaryKeyGeneratedKeys();
/**
* Get function by functionName.
*
* @param functionName functionName
* @return function
*/
String getFunction(String functionName);
}
|
Mapper
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/transaction/managed/ManagedTransactionFactoryUnitTest.java
|
{
"start": 1578,
"end": 3527
}
|
class ____ extends TransactionFactoryBase {
@Mock
private Properties properties;
@Mock
private Connection connection;
@Mock
private DataSource dataSource;
private TransactionFactory transactionFactory;
@BeforeEach
void setup() {
this.transactionFactory = new ManagedTransactionFactory();
}
@Test
@Override
public void shouldSetProperties() throws Exception {
when(properties.getProperty("closeConnection")).thenReturn("false");
transactionFactory.setProperties(properties);
assertFalse(
(Boolean) getValue(transactionFactory.getClass().getDeclaredField("closeConnection"), transactionFactory));
}
@Test
@Override
public void shouldNewTransactionWithConnection() throws SQLException {
Transaction result = transactionFactory.newTransaction(connection);
assertNotNull(result);
assertInstanceOf(ManagedTransaction.class, result);
assertEquals(connection, result.getConnection());
}
@Test
@Override
public void shouldNewTransactionWithDataSource() throws Exception {
when(dataSource.getConnection()).thenReturn(connection);
when(properties.getProperty("closeConnection")).thenReturn("false");
transactionFactory.setProperties(properties);
Transaction result = transactionFactory.newTransaction(dataSource, TransactionIsolationLevel.READ_COMMITTED, true);
assertNotNull(result);
assertInstanceOf(ManagedTransaction.class, result);
assertEquals(connection, result.getConnection());
verify(connection).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
assertEquals(dataSource, getValue(result.getClass().getDeclaredField("dataSource"), result));
assertEquals(TransactionIsolationLevel.READ_COMMITTED,
getValue(result.getClass().getDeclaredField("level"), result));
assertEquals(false, getValue(result.getClass().getDeclaredField("closeConnection"), result));
}
}
|
ManagedTransactionFactoryUnitTest
|
java
|
apache__camel
|
components/camel-debezium/camel-debezium-common/camel-debezium-common-component/src/main/java/org/apache/camel/component/debezium/configuration/EmbeddedDebeziumConfiguration.java
|
{
"start": 3794,
"end": 5278
}
|
class ____ implement the interface "
+ "'OffsetCommitPolicy'. The default is a periodic commit policy based upon "
+ "time intervals.")
private String offsetCommitPolicy = OffsetCommitPolicy.PeriodicCommitOffsetPolicy.class.getName();
// offset.flush.interval.ms
@UriParam(label = LABEL_NAME, defaultValue = "60000", description = "Interval at which to try committing "
+ "offsets. The default is 1 minute.",
javaType = "java.time.Duration")
private long offsetFlushIntervalMs = 60000;
// offset.commit.timeout.ms
@UriParam(label = LABEL_NAME, defaultValue = "5000", description = "Maximum number of milliseconds "
+ "to wait for records to flush and partition offset data to be committed to offset storage "
+ "before cancelling the process and restoring the offset data to be committed in a future "
+ "attempt. The default is 5 seconds.",
javaType = "java.time.Duration")
private long offsetCommitTimeoutMs = 5000;
// internal.key.converter
@UriParam(label = LABEL_NAME, defaultValue = "org.apache.kafka.connect.json.JsonConverter",
description = "The Converter
|
must
|
java
|
spring-projects__spring-security
|
access/src/main/java/org/springframework/security/acls/afterinvocation/AbstractAclProvider.java
|
{
"start": 2065,
"end": 5123
}
|
class ____ implements AfterInvocationProvider {
protected final AclService aclService;
protected String processConfigAttribute;
protected Class<?> processDomainObjectClass = Object.class;
protected ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl();
protected SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl();
protected final List<Permission> requirePermission;
public AbstractAclProvider(AclService aclService, String processConfigAttribute,
List<Permission> requirePermission) {
Assert.hasText(processConfigAttribute, "A processConfigAttribute is mandatory");
Assert.notNull(aclService, "An AclService is mandatory");
Assert.isTrue(!ObjectUtils.isEmpty(requirePermission), "One or more requirePermission entries is mandatory");
this.aclService = aclService;
this.processConfigAttribute = processConfigAttribute;
this.requirePermission = requirePermission;
}
protected Class<?> getProcessDomainObjectClass() {
return this.processDomainObjectClass;
}
protected boolean hasPermission(Authentication authentication, Object domainObject) {
// Obtain the OID applicable to the domain object
ObjectIdentity objectIdentity = this.objectIdentityRetrievalStrategy.getObjectIdentity(domainObject);
// Obtain the SIDs applicable to the principal
List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication);
try {
// Lookup only ACLs for SIDs we're interested in
Acl acl = this.aclService.readAclById(objectIdentity, sids);
return acl.isGranted(this.requirePermission, sids, false);
}
catch (NotFoundException ex) {
return false;
}
}
public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) {
Assert.notNull(objectIdentityRetrievalStrategy, "ObjectIdentityRetrievalStrategy required");
this.objectIdentityRetrievalStrategy = objectIdentityRetrievalStrategy;
}
protected void setProcessConfigAttribute(String processConfigAttribute) {
Assert.hasText(processConfigAttribute, "A processConfigAttribute is mandatory");
this.processConfigAttribute = processConfigAttribute;
}
public void setProcessDomainObjectClass(Class<?> processDomainObjectClass) {
Assert.notNull(processDomainObjectClass, "processDomainObjectClass cannot be set to null");
this.processDomainObjectClass = processDomainObjectClass;
}
public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) {
Assert.notNull(sidRetrievalStrategy, "SidRetrievalStrategy required");
this.sidRetrievalStrategy = sidRetrievalStrategy;
}
@Override
public boolean supports(ConfigAttribute attribute) {
return this.processConfigAttribute.equals(attribute.getAttribute());
}
/**
* This implementation supports any type of class, because it does not query the
* presented secure object.
* @param clazz the secure object
* @return always <code>true</code>
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
}
}
|
AbstractAclProvider
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java
|
{
"start": 4972,
"end": 5034
}
|
interface ____ {
void execute();
}
abstract static
|
Executor
|
java
|
spring-projects__spring-boot
|
module/spring-boot-micrometer-metrics/src/main/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/elastic/ElasticMetricsExportAutoConfiguration.java
|
{
"start": 2474,
"end": 3623
}
|
class ____ {
private final ElasticProperties properties;
ElasticMetricsExportAutoConfiguration(ElasticProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean
ElasticConfig elasticConfig() {
MutuallyExclusiveConfigurationPropertiesException.throwIfMultipleNonNullValuesIn((entries) -> {
entries.put("api-key-credentials", this.properties.getApiKeyCredentials());
entries.put("user-name", this.properties.getUserName());
});
MutuallyExclusiveConfigurationPropertiesException.throwIfMultipleNonNullValuesIn((entries) -> {
entries.put("api-key-credentials", this.properties.getApiKeyCredentials());
entries.put("password", this.properties.getPassword());
});
return new ElasticPropertiesConfigAdapter(this.properties);
}
@Bean
@ConditionalOnMissingBean
ElasticMeterRegistry elasticMeterRegistry(ElasticConfig elasticConfig, Clock clock) {
return ElasticMeterRegistry.builder(elasticConfig)
.clock(clock)
.httpClient(
new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout()))
.build();
}
}
|
ElasticMetricsExportAutoConfiguration
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/internal/util/MutableObject.java
|
{
"start": 400,
"end": 1739
}
|
class ____<T> {
private T reference;
public T get() {
return reference;
}
public boolean isSet() {
return reference != null;
}
public boolean isNotSet() {
return reference == null;
}
public void set(T reference) {
this.reference = reference;
}
public void set(T reference, Consumer<T> existingConsumer) {
if ( this.reference != null ) {
existingConsumer.accept( this.reference );
}
this.reference = reference;
}
public void set(T reference, BiConsumer<T,T> existingConsumer) {
if ( this.reference != null ) {
existingConsumer.accept( reference, this.reference );
}
this.reference = reference;
}
public void setIfNot(T reference) {
if ( this.reference == null ) {
this.reference = reference;
}
}
public void setIfNot(T reference, Supplier<RuntimeException> overwriteHandler) {
if ( this.reference == null ) {
this.reference = reference;
}
else {
throw overwriteHandler.get();
}
}
public void setIfNot(Supplier<T> referenceSupplier) {
if ( this.reference == null ) {
this.reference = referenceSupplier.get();
}
}
public void setIfNot(Supplier<T> referenceSupplier, Supplier<RuntimeException> overwriteHandler) {
if ( this.reference == null ) {
this.reference = referenceSupplier.get();
}
else {
throw overwriteHandler.get();
}
}
}
|
MutableObject
|
java
|
apache__flink
|
flink-end-to-end-tests/flink-rocksdb-state-memory-control-test/src/main/java/org/apache/flink/streaming/tests/RocksDBStateMemoryControlTestProgram.java
|
{
"start": 6182,
"end": 7238
}
|
class ____ extends RichMapFunction<Event, Event> {
private static final long serialVersionUID = 1L;
private transient ListState<String> listState;
private final boolean useListState;
ListStateMapper(boolean useListState) {
this.useListState = useListState;
}
@Override
public void open(OpenContext openContext) {
int index = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask();
if (useListState) {
listState =
getRuntimeContext()
.getListState(
new ListStateDescriptor<>(
"listState-" + index, StringSerializer.INSTANCE));
}
}
@Override
public Event map(Event event) throws Exception {
if (useListState) {
listState.add(event.getPayload());
}
return event;
}
}
private static
|
ListStateMapper
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/naming/EmbeddedColumnNamingTests.java
|
{
"start": 6811,
"end": 6957
}
|
class ____ {
private String code;
private String plus4;
}
@Entity(name="BaselinePerson")
@Table(name="baseline_person")
public static
|
ZipPlus
|
java
|
grpc__grpc-java
|
android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/TestServiceGrpc.java
|
{
"start": 23633,
"end": 23875
}
|
class ____ the server implementation of the service TestService.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static abstract
|
for
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToIntegerSerializationTests.java
|
{
"start": 540,
"end": 766
}
|
class ____ extends AbstractUnaryScalarSerializationTests<ToInteger> {
@Override
protected ToInteger create(Source source, Expression child) {
return new ToInteger(source, child);
}
}
|
ToIntegerSerializationTests
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/validators/SourceAnnotationCheck.java
|
{
"start": 1536,
"end": 18544
}
|
class ____ {
@Test
public void checkCompletable() throws Exception {
processFile(Completable.class);
}
@Test
public void checkSingle() throws Exception {
processFile(Single.class);
}
@Test
public void checkMaybe() throws Exception {
processFile(Maybe.class);
}
@Test
public void checkObservable() throws Exception {
processFile(Observable.class);
}
@Test
public void checkFlowable() throws Exception {
processFile(Flowable.class);
}
@Test
public void checkParallelFlowable() throws Exception {
processFile(ParallelFlowable.class);
}
@Test
public void checkConnectableObservable() throws Exception {
processFile(ConnectableObservable.class);
}
@Test
public void checkConnectableFlowable() throws Exception {
processFile(ConnectableFlowable.class);
}
@Test
public void checkSubject() throws Exception {
processFile(Subject.class);
}
@Test
public void checkFlowableProcessor() throws Exception {
processFile(FlowableProcessor.class);
}
@Test
public void checkDisposable() throws Exception {
processFile(Disposable.class);
}
@Test
public void checkScheduler() throws Exception {
processFile(Scheduler.class);
}
@Test
public void checkSchedulers() throws Exception {
processFile(Schedulers.class);
}
@Test
public void checkAsyncSubject() throws Exception {
processFile(AsyncSubject.class);
}
@Test
public void checkBehaviorSubject() throws Exception {
processFile(BehaviorSubject.class);
}
@Test
public void checkPublishSubject() throws Exception {
processFile(PublishSubject.class);
}
@Test
public void checkReplaySubject() throws Exception {
processFile(ReplaySubject.class);
}
@Test
public void checkUnicastSubject() throws Exception {
processFile(UnicastSubject.class);
}
@Test
public void checkSingleSubject() throws Exception {
processFile(SingleSubject.class);
}
@Test
public void checkMaybeSubject() throws Exception {
processFile(MaybeSubject.class);
}
@Test
public void checkCompletableSubject() throws Exception {
processFile(CompletableSubject.class);
}
@Test
public void checkAsyncProcessor() throws Exception {
processFile(AsyncProcessor.class);
}
@Test
public void checkBehaviorProcessor() throws Exception {
processFile(BehaviorProcessor.class);
}
@Test
public void checkPublishProcessor() throws Exception {
processFile(PublishProcessor.class);
}
@Test
public void checkReplayProcessor() throws Exception {
processFile(ReplayProcessor.class);
}
@Test
public void checkUnicastProcessor() throws Exception {
processFile(UnicastProcessor.class);
}
@Test
public void checkMulticastProcessor() throws Exception {
processFile(MulticastProcessor.class);
}
@Test
public void checkRxJavaPlugins() throws Exception {
processFile(RxJavaPlugins.class);
}
static void processFile(Class<?> clazz) throws Exception {
String baseClassName = clazz.getSimpleName();
File f = TestHelper.findSource(baseClassName, clazz.getPackage().getName());
if (f == null) {
return;
}
String fullClassName = clazz.getName();
int errorCount = 0;
StringBuilder errors = new StringBuilder();
List<String> lines = Files.readAllLines(f.toPath());
for (int j = 0; j < lines.size(); j++) {
String line = lines.get(j).trim();
if (line.contains("class")) {
continue;
}
if (line.startsWith("public static")
|| line.startsWith("public final")
|| line.startsWith("protected final")
|| line.startsWith("protected abstract")
|| line.startsWith("public abstract")) {
int methodArgStart = line.indexOf("(");
int isBoolean = line.indexOf(" boolean ");
int isInt = line.indexOf(" int ");
int isLong = line.indexOf(" long ");
int isVoid = line.indexOf(" void ");
int isElementType = line.indexOf(" R ");
boolean hasSafeVarargsAnnotation = false;
if (!((isBoolean > 0 && isBoolean < methodArgStart)
|| (isInt > 0 && isInt < methodArgStart)
|| (isLong > 0 && isLong < methodArgStart)
|| (isVoid > 0 && isVoid < methodArgStart)
|| (isElementType > 0 && isElementType < methodArgStart)
)) {
boolean annotationFound = false;
for (int k = j - 1; k >= 0; k--) {
String prevLine = lines.get(k).trim();
if (prevLine.startsWith("}") || prevLine.startsWith("*/")) {
break;
}
if (prevLine.startsWith("@NonNull") || prevLine.startsWith("@Nullable")) {
annotationFound = true;
}
if (prevLine.startsWith("@SafeVarargs")) {
hasSafeVarargsAnnotation = true;
}
}
if (!annotationFound) {
errorCount++;
errors.append("L")
.append(j)
.append(" : Missing return type nullability annotation | ")
.append(line)
.append("\r\n")
.append(" at ")
.append(fullClassName)
.append(".method(")
.append(f.getName())
.append(":")
.append(j + 1)
.append(")\r\n")
;
}
}
// Extract arguments
StringBuilder arguments = new StringBuilder();
int methodArgEnd = line.indexOf(")", methodArgStart);
if (methodArgEnd > 0) {
arguments.append(line.substring(methodArgStart + 1, methodArgEnd));
} else {
arguments.append(line.substring(methodArgStart + 1));
for (int k = j + 1; k < lines.size(); k++) {
String ln = lines.get(k).trim();
int idx = ln.indexOf(")");
if (idx > 0) {
arguments.append(ln.substring(0, idx));
break;
}
arguments.append(ln).append(" ");
}
}
// Strip generics arguments
StringBuilder strippedArguments = new StringBuilder();
int skippingDepth = 0;
for (int k = 0; k < arguments.length(); k++) {
char c = arguments.charAt(k);
if (c == '<') {
skippingDepth++;
}
else if (c == '>') {
skippingDepth--;
}
else if (skippingDepth == 0) {
strippedArguments.append(c);
}
}
String strippedArgumentsStr = strippedArguments.toString();
String[] args = strippedArgumentsStr.split("\\s*,\\s*");
for (int k = 0; k < args.length; k++) {
String typeDef = args[k];
for (String typeName : CLASS_NAMES) {
String typeNameSpaced = typeName + " ";
if (typeDef.contains(typeNameSpaced)
&& !typeDef.contains("@NonNull")
&& !typeDef.contains("@Nullable")) {
if (!line.contains("@Nullable " + typeName)
&& !line.contains("@NonNull " + typeName)) {
errorCount++;
errors.append("L")
.append(j)
.append(" - argument ").append(k + 1)
.append(" : Missing argument type nullability annotation\r\n ")
.append(typeDef).append("\r\n ")
.append(strippedArgumentsStr)
.append("\r\n")
.append(" at ")
.append(fullClassName)
.append(".method(")
.append(f.getName())
.append(":")
.append(j + 1)
.append(")\r\n")
;
}
}
}
if (typeDef.contains("final ")) {
errorCount++;
errors.append("L")
.append(j)
.append(" - argument ").append(k + 1)
.append(" : unnecessary final on argument\r\n ")
.append(typeDef).append("\r\n ")
.append(strippedArgumentsStr)
.append("\r\n")
.append(" at ")
.append(fullClassName)
.append(".method(")
.append(f.getName())
.append(":")
.append(j + 1)
.append(")\r\n")
;
}
if (typeDef.contains("@NonNull int")
|| typeDef.contains("@NonNull long")
|| typeDef.contains("@Nullable int")
|| typeDef.contains("@Nullable long")
) {
errorCount++;
errors.append("L")
.append(j)
.append(" - argument ").append(k + 1)
.append(" : unnecessary nullability annotation\r\n ")
.append(typeDef).append("\r\n ")
.append(strippedArgumentsStr)
.append("\r\n")
.append(" at ")
.append(fullClassName)
.append(".method(")
.append(f.getName())
.append(":")
.append(j + 1)
.append(")\r\n")
;
}
}
if (strippedArgumentsStr.contains("...") && !hasSafeVarargsAnnotation) {
errorCount++;
errors.append("L")
.append(j)
.append(" : Missing @SafeVarargs annotation\r\n ")
.append(strippedArgumentsStr)
.append("\r\n")
.append(" at ")
.append(fullClassName)
.append(".method(")
.append(f.getName())
.append(":")
.append(j + 1)
.append(")\r\n")
;
}
}
for (String typeName : TYPES_REQUIRING_NONNULL_TYPEARG) {
String pattern = typeName + "<?";
String patternRegex = ".*" + typeName + "\\<\\? (extends|super) " + COMMON_TYPE_ARG_NAMES + "\\>.*";
if (line.contains(pattern) && !line.matches(patternRegex)) {
errorCount++;
errors.append("L")
.append(j)
.append(" : Missing @NonNull type argument annotation on ")
.append(typeName)
.append("\r\n")
.append(" at ")
.append(fullClassName)
.append(".method(")
.append(f.getName())
.append(":")
.append(j + 1)
.append(")\r\n")
;
}
}
for (String typeName : TYPES_FORBIDDEN_NONNULL_TYPEARG) {
String patternRegex = ".*" + typeName + "\\<@NonNull (\\? (extends|super) )?" + COMMON_TYPE_ARG_NAMES + "\\>.*";
if (line.matches(patternRegex)) {
errorCount++;
errors.append("L")
.append(j)
.append(" : @NonNull type argument should be on the arg declaration ")
.append(typeName)
.append("\r\n")
.append(" at ")
.append(fullClassName)
.append(".method(")
.append(f.getName())
.append(":")
.append(j + 1)
.append(")\r\n")
;
}
}
for (String typeName : TYPES_REQUIRING_NONNULL_TYPEARG_ON_FUNC) {
if (line.matches(".*Function[\\d]?\\<.*, (\\? (extends|super) )?" + typeName + ".*")) {
errorCount++;
errors.append("L")
.append(j)
.append(" : Missing @NonNull type argument annotation on Function argument ")
.append(typeName)
.append("\r\n")
.append(" at ")
.append(fullClassName)
.append(".method(")
.append(f.getName())
.append(":")
.append(j + 1)
.append(")\r\n")
;
}
}
}
if (errorCount != 0) {
errors.insert(0, errorCount + " problems\r\n");
errors.setLength(errors.length() - 2);
throw new AssertionError(errors.toString());
}
}
static final List<String> CLASS_NAMES = Arrays.asList(
"TimeUnit", "Scheduler", "Emitter",
"Completable", "CompletableSource", "CompletableObserver", "CompletableOnSubscribe",
"CompletableTransformer", "CompletableOperator", "CompletableEmitter", "CompletableConverter",
"Single", "SingleSource", "SingleObserver", "SingleOnSubscribe",
"SingleTransformer", "SingleOperator", "SingleEmitter", "SingleConverter",
"Maybe", "MaybeSource", "MaybeObserver", "MaybeOnSubscribe",
"MaybeTransformer", "MaybeOperator", "MaybeEmitter", "MaybeConverter",
"Observable", "ObservableSource", "Observer", "ObservableOnSubscribe",
"ObservableTransformer", "ObservableOperator", "ObservableEmitter", "ObservableConverter",
"Flowable", "Publisher", "Subscriber", "FlowableSubscriber", "FlowableOnSubscribe",
"FlowableTransformer", "FlowableOperator", "FlowableEmitter", "FlowableConverter",
"Function", "BiFunction", "Function3", "Function4", "Function5", "Function6",
"Function7", "Function8", "Function9",
"Action", "Runnable", "Consumer", "BiConsumer", "Supplier", "Callable", "Void",
"Throwable", "Optional", "CompletionStage", "BooleanSupplier", "LongConsumer",
"Predicate", "BiPredicate", "Object",
"Iterable", "Stream", "Iterator",
"BackpressureOverflowStrategy", "BackpressureStrategy",
"Subject", "Processor", "FlowableProcessor",
"T", "R", "U", "V"
);
static final List<String> TYPES_REQUIRING_NONNULL_TYPEARG = Arrays.asList(
"Iterable", "Stream", "Publisher", "Processor", "Subscriber", "Optional"
);
static final List<String> TYPES_FORBIDDEN_NONNULL_TYPEARG = Arrays.asList(
"Iterable", "Stream", "Publisher", "Processor", "Subscriber", "Optional"
);
static final List<String> TYPES_REQUIRING_NONNULL_TYPEARG_ON_FUNC = Arrays.asList(
"Iterable", "Stream", "Publisher", "Processor", "Subscriber", "Optional",
"Observer", "SingleObserver", "MaybeObserver", "CompletableObserver"
);
static final String COMMON_TYPE_ARG_NAMES = "([A-Z][0-9]?|TOpening|TClosing|TLeft|TLeftEnd|TRight|TRightEnd)";
}
|
SourceAnnotationCheck
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/webmonitor/retriever/GatewayRetriever.java
|
{
"start": 1064,
"end": 1157
}
|
interface ____ {@link RpcGateway}.
*
* @param <T> type of the object to retrieve
*/
public
|
for
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plan/logical/promql/operator/set/VectorBinarySet.java
|
{
"start": 736,
"end": 1608
}
|
enum ____ implements BinaryOp {
INTERSECT,
SUBTRACT,
UNION;
@Override
public ScalarFunctionFactory asFunction() {
throw new UnsupportedOperationException("not yet implemented");
}
}
private final SetOp op;
public VectorBinarySet(Source source, LogicalPlan left, LogicalPlan right, VectorMatch match, SetOp op) {
super(source, left, right, match, true, op);
this.op = op;
}
public SetOp op() {
return op;
}
@Override
public VectorBinarySet replaceChildren(LogicalPlan newLeft, LogicalPlan newRight) {
return new VectorBinarySet(source(), newLeft, newRight, match(), op());
}
@Override
protected NodeInfo<VectorBinarySet> info() {
return NodeInfo.create(this, VectorBinarySet::new, left(), right(), match(), op());
}
}
|
SetOp
|
java
|
spring-projects__spring-framework
|
spring-beans/src/main/java/org/springframework/beans/factory/support/BeanRegistryAdapter.java
|
{
"start": 7398,
"end": 8252
}
|
class ____ extends RootBeanDefinition {
public BeanRegistrarBeanDefinition(Class<?> beanClass, Class<? extends BeanRegistrar> beanRegistrarClass) {
super(beanClass);
this.setSource(beanRegistrarClass);
this.setAttribute("aotProcessingIgnoreRegistration", true);
}
public BeanRegistrarBeanDefinition(BeanRegistrarBeanDefinition original) {
super(original);
}
@Override
public Constructor<?> @Nullable [] getPreferredConstructors() {
if (this.getInstanceSupplier() != null) {
return null;
}
try {
return new Constructor<?>[] { BeanUtils.getResolvableConstructor(getBeanClass()) };
}
catch (IllegalStateException ex) {
return null;
}
}
@Override
public RootBeanDefinition cloneBeanDefinition() {
return new BeanRegistrarBeanDefinition(this);
}
}
private static
|
BeanRegistrarBeanDefinition
|
java
|
google__auto
|
value/src/test/java/com/google/auto/value/extension/memoized/MemoizedTest.java
|
{
"start": 16935,
"end": 16993
}
|
interface ____<InputT, ResultT> {}
abstract static
|
TypePath
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/state/KeyGroupPartitioner.java
|
{
"start": 13222,
"end": 13370
}
|
interface ____ consume elements from a key group.
*
* @param <T> type of the consumed elements.
*/
@FunctionalInterface
public
|
to
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest155.java
|
{
"start": 209,
"end": 942
}
|
class ____
extends MysqlTest {
public void test_0() throws Exception {
String sql = "create table pk(id int primary key , name varchar)";
SQLCreateTableStatement stmt = (SQLCreateTableStatement) SQLUtils.parseSingleMysqlStatement(sql);
assertTrue(stmt.isPrimaryColumn("id"));
assertTrue(stmt.isPrimaryColumn("`id`"));
}
public void test_1() throws Exception {
String sql = "create table pk(id int, name varchar, primary key(id, name))";
SQLCreateTableStatement stmt = (SQLCreateTableStatement) SQLUtils.parseSingleMysqlStatement(sql);
assertTrue(stmt.isPrimaryColumn("id"));
assertTrue(stmt.isPrimaryColumn("`id`"));
}
}
|
MySqlCreateTableTest155
|
java
|
bumptech__glide
|
annotation/compiler/src/main/java/com/bumptech/glide/annotation/compiler/RequestOptionsGenerator.java
|
{
"start": 2604,
"end": 19319
}
|
class ____ {
private static final String GENERATED_REQUEST_OPTIONS_SIMPLE_NAME = "GlideOptions";
static final String REQUEST_OPTIONS_PACKAGE_NAME = "com.bumptech.glide.request";
private static final String REQUEST_OPTIONS_SIMPLE_NAME = "RequestOptions";
static final String REQUEST_OPTIONS_QUALIFIED_NAME =
REQUEST_OPTIONS_PACKAGE_NAME + "." + REQUEST_OPTIONS_SIMPLE_NAME;
static final String BASE_REQUEST_OPTIONS_SIMPLE_NAME = "BaseRequestOptions";
static final String BASE_REQUEST_OPTIONS_QUALIFIED_NAME =
REQUEST_OPTIONS_PACKAGE_NAME + "." + BASE_REQUEST_OPTIONS_SIMPLE_NAME;
private int nextFieldId;
private final ClassName requestOptionsName;
private final TypeElement requestOptionsType;
private final ProcessorUtil processorUtil;
private final RequestOptionsOverrideGenerator requestOptionsOverrideGenerator;
private ClassName glideOptionsName;
RequestOptionsGenerator(
ProcessingEnvironment processingEnvironment, ProcessorUtil processorUtil) {
this.processorUtil = processorUtil;
requestOptionsName = ClassName.get(REQUEST_OPTIONS_PACKAGE_NAME, REQUEST_OPTIONS_SIMPLE_NAME);
requestOptionsType =
processingEnvironment.getElementUtils().getTypeElement(REQUEST_OPTIONS_QUALIFIED_NAME);
requestOptionsOverrideGenerator =
new RequestOptionsOverrideGenerator(processingEnvironment, processorUtil);
}
TypeSpec generate(String generatedCodePackageName, Set<String> glideExtensionClassNames) {
glideOptionsName =
ClassName.get(generatedCodePackageName, GENERATED_REQUEST_OPTIONS_SIMPLE_NAME);
RequestOptionsExtensionGenerator requestOptionsExtensionGenerator =
new RequestOptionsExtensionGenerator(glideOptionsName, processorUtil);
List<MethodAndStaticVar> instanceMethodsForExtensions =
FluentIterable.from(
requestOptionsExtensionGenerator.generateInstanceMethodsForExtensions(
glideExtensionClassNames))
.transform(
new Function<MethodSpec, MethodAndStaticVar>() {
@Override
public MethodAndStaticVar apply(MethodSpec input) {
return new MethodAndStaticVar(input);
}
})
.toList();
List<MethodAndStaticVar> staticMethodsForExtensions =
FluentIterable.from(
requestOptionsExtensionGenerator.getRequestOptionExtensionMethods(
glideExtensionClassNames))
.filter(
new Predicate<ExecutableElement>() {
@Override
public boolean apply(ExecutableElement input) {
return !skipStaticMethod(input);
}
})
.transform(
new Function<ExecutableElement, MethodAndStaticVar>() {
@Override
public MethodAndStaticVar apply(ExecutableElement input) {
return generateStaticMethodEquivalentForExtensionMethod(input);
}
})
.toList();
List<MethodAndStaticVar> methodsForExtensions = new ArrayList<>();
methodsForExtensions.addAll(instanceMethodsForExtensions);
methodsForExtensions.addAll(staticMethodsForExtensions);
Set<MethodSignature> extensionMethodSignatures =
ImmutableSet.copyOf(
Iterables.transform(
methodsForExtensions,
new Function<MethodAndStaticVar, MethodSignature>() {
@Override
public MethodSignature apply(MethodAndStaticVar f) {
return new MethodSignature(f.method);
}
}));
List<MethodAndStaticVar> staticOverrides = generateStaticMethodOverridesForRequestOptions();
List<MethodSpec> instanceOverrides =
requestOptionsOverrideGenerator.generateInstanceMethodOverridesForRequestOptions(
glideOptionsName);
List<MethodAndStaticVar> allMethodsAndStaticVars = new ArrayList<>();
for (MethodAndStaticVar item : staticOverrides) {
if (extensionMethodSignatures.contains(new MethodSignature(item.method))) {
continue;
}
allMethodsAndStaticVars.add(item);
}
for (MethodSpec methodSpec : instanceOverrides) {
if (extensionMethodSignatures.contains(new MethodSignature(methodSpec))) {
continue;
}
allMethodsAndStaticVars.add(new MethodAndStaticVar(methodSpec));
}
allMethodsAndStaticVars.addAll(methodsForExtensions);
TypeSpec.Builder classBuilder =
TypeSpec.classBuilder(GENERATED_REQUEST_OPTIONS_SIMPLE_NAME)
.addAnnotation(
AnnotationSpec.builder(SuppressWarnings.class)
.addMember("value", "$S", "deprecation")
.build())
.addJavadoc(generateClassJavadoc(glideExtensionClassNames))
.addModifiers(Modifier.FINAL)
.addModifiers(Modifier.PUBLIC)
.addSuperinterface(Cloneable.class)
.superclass(requestOptionsName);
for (MethodAndStaticVar methodAndStaticVar : allMethodsAndStaticVars) {
if (methodAndStaticVar.method != null) {
classBuilder.addMethod(methodAndStaticVar.method);
}
if (methodAndStaticVar.staticField != null) {
classBuilder.addField(methodAndStaticVar.staticField);
}
}
return classBuilder.build();
}
private CodeBlock generateClassJavadoc(Set<String> glideExtensionClassNames) {
Builder builder =
CodeBlock.builder()
.add(
"Automatically generated from {@link $T} annotated classes.\n",
GlideExtension.class)
.add("\n")
.add("@see $T\n", requestOptionsName);
for (String glideExtensionClass : glideExtensionClassNames) {
builder.add("@see $T\n", ClassName.bestGuess(glideExtensionClass));
}
return builder.build();
}
private List<MethodAndStaticVar> generateStaticMethodOverridesForRequestOptions() {
List<ExecutableElement> staticMethodsThatReturnRequestOptions =
processorUtil.findStaticMethodsReturning(requestOptionsType, requestOptionsType);
List<MethodAndStaticVar> staticMethods = new ArrayList<>();
for (ExecutableElement element : staticMethodsThatReturnRequestOptions) {
if (element.getAnnotation(Deprecated.class) != null) {
continue;
}
staticMethods.add(generateStaticMethodEquivalentForRequestOptionsStaticMethod(element));
}
return staticMethods;
}
/**
* This method is a bit of a hack, but it lets us tie the static version of a method with the
* instance version. In turn that lets us call the instance versions on the generated subclass,
* instead of just delegating to the RequestOptions static methods. Using the instance methods on
* the generated subclass allows our static methods to properly call code that overrides an
* existing method in RequestOptions.
*
* <p>The string names here just map between the static methods in {@code
* com.bumptech.glide.request.RequestOptions} and the instance methods they call.
*/
private static String getInstanceMethodNameFromStaticMethodName(String staticMethodName) {
String equivalentInstanceMethodName;
if ("bitmapTransform".equals(staticMethodName)) {
equivalentInstanceMethodName = "transform";
} else if ("decodeTypeOf".equals(staticMethodName)) {
equivalentInstanceMethodName = "decode";
} else if (staticMethodName.endsWith("Transform")) {
equivalentInstanceMethodName = staticMethodName.substring(0, staticMethodName.length() - 9);
} else if (staticMethodName.endsWith("Of")) {
equivalentInstanceMethodName = staticMethodName.substring(0, staticMethodName.length() - 2);
} else if ("noTransformation".equals(staticMethodName)) {
equivalentInstanceMethodName = "dontTransform";
} else if ("noAnimation".equals(staticMethodName)) {
equivalentInstanceMethodName = "dontAnimate";
} else if (staticMethodName.equals("option")) {
equivalentInstanceMethodName = "set";
} else {
throw new IllegalArgumentException("Unrecognized static method name: " + staticMethodName);
}
return equivalentInstanceMethodName;
}
private MethodAndStaticVar generateStaticMethodEquivalentForRequestOptionsStaticMethod(
ExecutableElement staticMethod) {
boolean memoize = memoizeStaticMethodFromArguments(staticMethod);
String staticMethodName = staticMethod.getSimpleName().toString();
String equivalentInstanceMethodName =
getInstanceMethodNameFromStaticMethodName(staticMethodName);
MethodSpec.Builder methodSpecBuilder =
MethodSpec.methodBuilder(staticMethodName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addJavadoc(processorUtil.generateSeeMethodJavadoc(staticMethod))
.returns(glideOptionsName);
StringBuilder createNewOptionAndCall =
createNewOptionAndCall(
memoize, methodSpecBuilder, "new $T().$N(", processorUtil.getParameters(staticMethod));
FieldSpec requiredStaticField = null;
if (memoize) {
// Generates code that looks like:
// if (GlideOptions.<methodName> == null) {
// GlideOptions.<methodName> = new GlideOptions().<methodName>().autoClone()
// }
// Mix in an incrementing unique id to handle method overloading.
String staticVariableName = staticMethodName + nextFieldId++;
requiredStaticField =
FieldSpec.builder(glideOptionsName, staticVariableName)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC)
.build();
methodSpecBuilder
.beginControlFlow("if ($T.$N == null)", glideOptionsName, staticVariableName)
.addStatement(
"$T.$N =\n" + createNewOptionAndCall + ".$N",
glideOptionsName,
staticVariableName,
glideOptionsName,
equivalentInstanceMethodName,
"autoClone()")
.endControlFlow()
.addStatement("return $T.$N", glideOptionsName, staticVariableName);
} else {
// Generates code that looks like:
// return new GlideOptions().<methodName>()
methodSpecBuilder.addStatement(
"return " + createNewOptionAndCall, glideOptionsName, equivalentInstanceMethodName);
}
List<? extends TypeParameterElement> typeParameters = staticMethod.getTypeParameters();
for (TypeParameterElement typeParameterElement : typeParameters) {
methodSpecBuilder.addTypeVariable(
TypeVariableName.get(typeParameterElement.getSimpleName().toString()));
}
methodSpecBuilder
.addAnnotation(processorUtil.checkResult())
.addAnnotation(processorUtil.nonNull());
return new MethodAndStaticVar(methodSpecBuilder.build(), requiredStaticField);
}
@SuppressWarnings("checkstyle:UnnecessaryParentheses") // Readability
private static boolean memoizeStaticMethodFromArguments(ExecutableElement staticMethod) {
return staticMethod.getParameters().isEmpty()
|| (staticMethod.getParameters().size() == 1
&& staticMethod
.getParameters()
.get(0)
.getSimpleName()
.toString()
.equals("android.content.Context"));
}
private StringBuilder createNewOptionAndCall(
boolean memoize,
MethodSpec.Builder methodSpecBuilder,
String start,
List<ParameterSpec> specs) {
StringBuilder createNewOptionAndCall = new StringBuilder(start);
if (!specs.isEmpty()) {
methodSpecBuilder.addParameters(specs);
for (ParameterSpec parameter : specs) {
createNewOptionAndCall.append(parameter.name);
// use the Application Context to avoid memory leaks.
if (memoize && isAndroidContext(parameter)) {
createNewOptionAndCall.append(".getApplicationContext()");
}
createNewOptionAndCall.append(", ");
}
createNewOptionAndCall =
new StringBuilder(
createNewOptionAndCall.substring(0, createNewOptionAndCall.length() - 2));
}
createNewOptionAndCall.append(")");
return createNewOptionAndCall;
}
private boolean isAndroidContext(ParameterSpec parameter) {
return parameter.type.toString().equals("android.content.Context");
}
private MethodAndStaticVar generateStaticMethodEquivalentForExtensionMethod(
ExecutableElement instanceMethod) {
String staticMethodName = getStaticMethodName(instanceMethod);
String instanceMethodName = instanceMethod.getSimpleName().toString();
if (Strings.isNullOrEmpty(staticMethodName)) {
if (instanceMethodName.startsWith("dont")) {
staticMethodName = "no" + instanceMethodName.replace("dont", "");
} else {
staticMethodName = instanceMethodName + "Of";
}
}
boolean memoize = memoizeStaticMethodFromAnnotation(instanceMethod);
//noinspection ResultOfMethodCallIgnored
Preconditions.checkNotNull(staticMethodName);
MethodSpec.Builder methodSpecBuilder =
MethodSpec.methodBuilder(staticMethodName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addJavadoc(processorUtil.generateSeeMethodJavadoc(instanceMethod))
.varargs(instanceMethod.isVarArgs())
.returns(glideOptionsName);
List<? extends VariableElement> parameters = instanceMethod.getParameters();
// Always remove the first parameter because it's always RequestOptions in extensions. The
// actual method we want to generate will pass the RequestOptions in to the extension method,
// but should not itself require a RequestOptions object to be passed in.
if (parameters.isEmpty()) {
throw new IllegalArgumentException("Expected non-empty parameters for: " + instanceMethod);
}
// Remove is not supported.
parameters = parameters.subList(1, parameters.size());
StringBuilder createNewOptionAndCall =
createNewOptionAndCall(
memoize, methodSpecBuilder, "new $T().$L(", processorUtil.getParameters(parameters));
FieldSpec requiredStaticField = null;
if (memoize) {
// Generates code that looks like:
// if (GlideOptions.<methodName> == null) {
// GlideOptions.<methodName> = new GlideOptions().<methodName>().autoClone()
// }
// Mix in an incrementing unique id to handle method overloading.
String staticVariableName = staticMethodName + nextFieldId++;
requiredStaticField =
FieldSpec.builder(glideOptionsName, staticVariableName)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC)
.build();
methodSpecBuilder
.beginControlFlow("if ($T.$N == null)", glideOptionsName, staticVariableName)
.addStatement(
"$T.$N =\n" + createNewOptionAndCall + ".$N",
glideOptionsName,
staticVariableName,
glideOptionsName,
instanceMethodName,
"autoClone()")
.endControlFlow()
.addStatement("return $T.$N", glideOptionsName, staticVariableName);
} else {
// Generates code that looks like:
// return new GlideOptions().<methodName>()
methodSpecBuilder.addStatement(
"return " + createNewOptionAndCall, glideOptionsName, instanceMethodName);
}
List<? extends TypeParameterElement> typeParameters = instanceMethod.getTypeParameters();
for (TypeParameterElement typeParameterElement : typeParameters) {
methodSpecBuilder.addTypeVariable(
TypeVariableName.get(typeParameterElement.getSimpleName().toString()));
}
methodSpecBuilder.addAnnotation(processorUtil.checkResult());
return new MethodAndStaticVar(methodSpecBuilder.build(), requiredStaticField);
}
@Nullable
private static String getStaticMethodName(ExecutableElement element) {
GlideOption glideOption = element.getAnnotation(GlideOption.class);
String result = glideOption != null ? glideOption.staticMethodName() : null;
return Strings.emptyToNull(result);
}
private static boolean memoizeStaticMethodFromAnnotation(ExecutableElement element) {
GlideOption glideOption = element.getAnnotation(GlideOption.class);
return glideOption != null && glideOption.memoizeStaticMethod();
}
private static boolean skipStaticMethod(ExecutableElement element) {
GlideOption glideOption = element.getAnnotation(GlideOption.class);
return glideOption != null && glideOption.skipStaticMethod();
}
private static final
|
RequestOptionsGenerator
|
java
|
quarkusio__quarkus
|
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/PersistenceUnitExtension.java
|
{
"start": 1066,
"end": 1495
}
|
class ____
extends AnnotationLiteral<PersistenceUnitExtension>
implements PersistenceUnitExtension {
private final String name;
public Literal(String name) {
this.name = name;
}
@Override
public String value() {
return name;
}
}
@Target({ TYPE, FIELD, METHOD, PARAMETER })
@Retention(RUNTIME)
@Documented
@
|
Literal
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/files/Files_assertDoesNotExist_Test.java
|
{
"start": 1284,
"end": 2014
}
|
class ____ extends FilesBaseTest {
@Test
void should_fail_if_actual_is_null() {
// GIVEN
File actual = null;
// WHEN
var error = expectAssertionError(() -> underTest.assertDoesNotExist(INFO, actual));
// THEN
then(error).hasMessage(actualIsNull());
}
@Test
void should_fail_if_actual_exists() {
// GIVEN
File actual = resourceFile("actual_file.txt");
// WHEN
expectAssertionError(() -> underTest.assertDoesNotExist(INFO, actual));
// THEN
verify(failures).failure(INFO, shouldNotExist(actual));
}
@Test
void should_pass_if_actual_does_not_exist() {
File actual = new File("xyz");
underTest.assertDoesNotExist(INFO, actual);
}
}
|
Files_assertDoesNotExist_Test
|
java
|
apache__logging-log4j2
|
log4j-core-test/src/main/java/org/apache/logging/log4j/core/test/net/mock/MockSyslogServerFactory.java
|
{
"start": 1038,
"end": 2086
}
|
class ____ {
public static MockSyslogServer createUDPSyslogServer(final int numberOfMessagesToReceive, final int port)
throws SocketException {
return new MockUdpSyslogServer(numberOfMessagesToReceive, port);
}
public static MockSyslogServer createUDPSyslogServer() throws SocketException {
return new MockUdpSyslogServer();
}
public static MockSyslogServer createTCPSyslogServer(final int numberOfMessagesToReceive, final int port)
throws IOException {
return new MockTcpSyslogServer(numberOfMessagesToReceive, port);
}
public static MockSyslogServer createTCPSyslogServer() throws IOException {
return new MockTcpSyslogServer();
}
public static MockSyslogServer createTLSSyslogServer(
final int numberOfMessagesToReceive,
final TlsSyslogMessageFormat format,
final SSLServerSocket serverSocket) {
return new MockTlsSyslogServer(numberOfMessagesToReceive, format, serverSocket);
}
}
|
MockSyslogServerFactory
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/tool/schema/spi/DelayedDropRegistryNotAvailableImpl.java
|
{
"start": 293,
"end": 729
}
|
class ____ implements DelayedDropRegistry {
/**
* Singleton access
*/
public static final DelayedDropRegistryNotAvailableImpl INSTANCE = new DelayedDropRegistryNotAvailableImpl();
@Override
public void registerOnCloseAction(DelayedDropAction action) {
throw new SchemaManagementException(
"DelayedDropRegistry is not available in this context. 'create-drop' action is not valid"
);
}
}
|
DelayedDropRegistryNotAvailableImpl
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/api/common/externalresource/ExternalResourceDriverFactory.java
|
{
"start": 1401,
"end": 1455
}
|
class ____ of the factory.
*/
@PublicEvolving
public
|
name
|
java
|
spring-projects__spring-framework
|
spring-jms/src/main/java/org/springframework/jms/connection/CachingConnectionFactory.java
|
{
"start": 18347,
"end": 19981
}
|
class ____ implements Comparable<DestinationCacheKey> {
private final Destination destination;
private @Nullable String destinationString;
public DestinationCacheKey(Destination destination) {
Assert.notNull(destination, "Destination must not be null");
this.destination = destination;
}
private String getDestinationString() {
if (this.destinationString == null) {
this.destinationString = this.destination.toString();
}
return this.destinationString;
}
protected boolean destinationEquals(DestinationCacheKey otherKey) {
return (this.destination.getClass() == otherKey.destination.getClass() &&
(this.destination.equals(otherKey.destination) ||
getDestinationString().equals(otherKey.getDestinationString())));
}
@Override
public boolean equals(@Nullable Object other) {
// Effectively checking object equality as well as toString equality.
// On WebSphere MQ, Destination objects do not implement equals...
return (this == other || (other instanceof DestinationCacheKey that && destinationEquals(that)));
}
@Override
public int hashCode() {
// Can't use a more specific hashCode since we can't rely on
// this.destination.hashCode() actually being the same value
// for equivalent destinations... Thanks a lot, WebSphere MQ!
return this.destination.getClass().hashCode();
}
@Override
public String toString() {
return getDestinationString();
}
@Override
public int compareTo(DestinationCacheKey other) {
return getDestinationString().compareTo(other.getDestinationString());
}
}
/**
* Simple wrapper
|
DestinationCacheKey
|
java
|
elastic__elasticsearch
|
modules/parent-join/src/main/java/org/elasticsearch/join/mapper/ParentJoinFieldMapper.java
|
{
"start": 6523,
"end": 14494
}
|
class ____ extends StringFieldType {
private final Joiner joiner;
private JoinFieldType(String name, Joiner joiner, Map<String, String> meta) {
super(name, IndexType.terms(true, true), false, TextSearchInfo.SIMPLE_MATCH_ONLY, meta);
this.joiner = joiner;
}
Joiner getJoiner() {
return joiner;
}
@Override
public String typeName() {
return CONTENT_TYPE;
}
@Override
public IndexFieldData.Builder fielddataBuilder(FieldDataContext fieldDataContext) {
return new SortedSetOrdinalsIndexFieldData.Builder(
name(),
CoreValuesSourceType.KEYWORD,
(dv, n) -> new DelegateDocValuesField(
new ScriptDocValues.Strings(new ScriptDocValues.StringsSupplier(FieldData.toString(dv))),
n
)
);
}
@Override
public ValueFetcher valueFetcher(SearchExecutionContext context, String format) {
if (format != null) {
throw new IllegalArgumentException("Field [" + name() + "] of type [" + typeName() + "] doesn't support formats.");
}
return SourceValueFetcher.identity(name(), context, format);
}
@Override
public Object valueForDisplay(Object value) {
if (value == null) {
return null;
}
BytesRef binaryValue = (BytesRef) value;
return binaryValue.utf8ToString();
}
}
private static boolean checkRelationsConflicts(List<Relations> previous, List<Relations> current, Conflicts conflicts) {
Joiner pj = new Joiner("f", previous);
Joiner cj = new Joiner("f", current);
return pj.canMerge(cj, s -> conflicts.addConflict("relations", s));
}
private final Map<String, ParentIdFieldMapper> parentIdFields;
private final boolean eagerGlobalOrdinals;
private final List<Relations> relations;
protected ParentJoinFieldMapper(
String simpleName,
MappedFieldType mappedFieldType,
Map<String, ParentIdFieldMapper> parentIdFields,
boolean eagerGlobalOrdinals,
List<Relations> relations
) {
super(simpleName, mappedFieldType, BuilderParams.empty());
this.parentIdFields = parentIdFields;
this.eagerGlobalOrdinals = eagerGlobalOrdinals;
this.relations = relations;
}
@Override
public Map<String, NamedAnalyzer> indexAnalyzers() {
return Map.of(mappedFieldType.name(), Lucene.KEYWORD_ANALYZER);
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
public JoinFieldType fieldType() {
return (JoinFieldType) super.fieldType();
}
@Override
public Iterator<Mapper> iterator() {
List<Mapper> mappers = new ArrayList<>(parentIdFields.values());
return mappers.iterator();
}
@Override
protected void parseCreateField(DocumentParserContext context) {
throw new UnsupportedOperationException("parsing is implemented in parse(), this method should NEVER be called");
}
@Override
protected boolean supportsParsingObject() {
return true;
}
@Override
public void parse(DocumentParserContext context) throws IOException {
context.path().add(leafName());
XContentParser.Token token = context.parser().currentToken();
String name = null;
String parent = null;
if (token == XContentParser.Token.START_OBJECT) {
String currentFieldName = null;
while ((token = context.parser().nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = context.parser().currentName();
} else if (token == XContentParser.Token.VALUE_STRING) {
if ("name".equals(currentFieldName)) {
name = context.parser().text();
} else if ("parent".equals(currentFieldName)) {
parent = context.parser().text();
} else {
throw new IllegalArgumentException(
"unknown field name [" + currentFieldName + "] in join field [" + fullPath() + "]"
);
}
} else if (token == XContentParser.Token.VALUE_NUMBER) {
if ("parent".equals(currentFieldName)) {
parent = context.parser().numberValue().toString();
} else {
throw new IllegalArgumentException(
"unknown field name [" + currentFieldName + "] in join field [" + fullPath() + "]"
);
}
}
}
} else if (token == XContentParser.Token.VALUE_STRING) {
name = context.parser().text();
parent = null;
} else {
throw new IllegalStateException("[" + fullPath() + "] expected START_OBJECT or VALUE_STRING but was: " + token);
}
if (name == null) {
throw new IllegalArgumentException("null join name in field [" + fullPath() + "]");
}
if (fieldType().joiner.knownRelation(name) == false) {
throw new IllegalArgumentException("unknown join name [" + name + "] for field [" + fullPath() + "]");
}
if (fieldType().joiner.childTypeExists(name)) {
// Index the document as a child
if (parent == null) {
throw new IllegalArgumentException("[parent] is missing for join field [" + fullPath() + "]");
}
if (context.routing() == null) {
throw new IllegalArgumentException("[routing] is missing for join field [" + fullPath() + "]");
}
String fieldName = fieldType().joiner.parentJoinField(name);
parentIdFields.get(fieldName).indexValue(context, parent);
}
if (fieldType().joiner.parentTypeExists(name)) {
// Index the document as a parent
String fieldName = fieldType().joiner.childJoinField(name);
parentIdFields.get(fieldName).indexValue(context, context.id());
}
BytesRef binaryValue = new BytesRef(name);
Field field = new StringField(fieldType().name(), binaryValue, Field.Store.NO);
context.doc().add(field);
context.doc().add(new SortedDocValuesField(fieldType().name(), binaryValue));
context.path().remove();
}
@Override
protected void doXContentBody(XContentBuilder builder, Params params) throws IOException {
builder.field("type", contentType());
builder.field("eager_global_ordinals", eagerGlobalOrdinals);
builder.startObject("relations");
for (Relations relation : relations) {
if (relation.children().size() == 1) {
builder.field(relation.parent(), relation.children().iterator().next());
} else {
builder.field(relation.parent(), relation.children());
}
}
builder.endObject();
}
@Override
public FieldMapper.Builder getMergeBuilder() {
return new Builder(leafName()).init(this);
}
@Override
protected void doValidate(MappingLookup mappingLookup) {
List<String> joinFields = mappingLookup.getMatchingFieldNames("*")
.stream()
.map(mappingLookup::getFieldType)
.filter(ft -> ft instanceof JoinFieldType)
.map(MappedFieldType::name)
.toList();
if (joinFields.size() > 1) {
throw new IllegalArgumentException("Only one [parent-join] field can be defined per index, got " + joinFields);
}
}
}
|
JoinFieldType
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/DeserializationContext.java
|
{
"start": 1566,
"end": 32714
}
|
class ____
extends DatabindContext
implements ObjectReadContext // 3.0
{
/*
/**********************************************************************
/* Per-mapper configuration (immutable via ObjectReader)
/**********************************************************************
*/
/**
* Low-level {@link TokenStreamFactory} that may be used for constructing
* embedded parsers.
*/
final protected TokenStreamFactory _streamFactory;
/**
* Read-only factory instance; exposed to let
* owners (<code>ObjectMapper</code>, <code>ObjectReader</code>)
* access it.
*/
final protected DeserializerFactory _factory;
/**
* Object that handle details of {@link ValueDeserializer} caching.
*/
final protected DeserializerCache _cache;
/*
/**********************************************************************
/* Configuration that may vary by ObjectReader
/**********************************************************************
*/
/**
* Generic deserialization processing configuration
*/
final protected DeserializationConfig _config;
/**
* Bitmap of {@link DeserializationFeature}s that are enabled
*/
final protected int _featureFlags;
/**
* Currently active view, if any.
*/
final protected Class<?> _activeView;
/**
* Schema for underlying parser to use, if any.
*/
final protected FormatSchema _schema;
/**
* Object used for resolving references to injectable
* values.
*/
final protected InjectableValues _injectableValues;
/*
/**********************************************************************
/* Other State
/**********************************************************************
*/
/**
* Currently active parser used for deserialization.
* May be different from the outermost parser
* when content is buffered.
*/
protected transient JsonParser _parser;
/**
* Capabilities of the input format.
*/
protected transient JacksonFeatureSet<StreamReadCapability> _readCapabilities;
/*
/**********************************************************************
/* Per-operation reusable helper objects (not for blueprints)
/**********************************************************************
*/
protected transient ArrayBuilders _arrayBuilders;
protected transient ObjectBuffer _objectBuffer;
protected transient DateFormat _dateFormat;
/**
* Lazily-constructed holder for per-call attributes.
*/
protected transient ContextAttributes _attributes;
/**
* Type of {@link ValueDeserializer} on which {@link ValueDeserializer#createContextual}
* is being called currently.
*/
protected LinkedNode<JavaType> _currentType;
/**
* Lazily constructed {@link ClassIntrospector} instance: created from "blueprint"
*/
protected transient ClassIntrospector _classIntrospector;
/*
/**********************************************************************
/* Life-cycle
/**********************************************************************
*/
protected DeserializationContext(TokenStreamFactory streamFactory,
DeserializerFactory df, DeserializerCache cache,
DeserializationConfig config, FormatSchema schema,
InjectableValues injectableValues)
{
_streamFactory = streamFactory;
_factory = Objects.requireNonNull(df, "Cannot pass null DeserializerFactory");
_cache = cache;
_config = config;
_featureFlags = config.getDeserializationFeatures();
_activeView = config.getActiveView();
_schema = schema;
_injectableValues = injectableValues;
_attributes = config.getAttributes();
}
/*
/**********************************************************************
/* DatabindContext implementation
/**********************************************************************
*/
@Override
public DeserializationConfig getConfig() { return _config; }
@Override
public final Class<?> getActiveView() { return _activeView; }
@Override
public final boolean canOverrideAccessModifiers() {
return _config.canOverrideAccessModifiers();
}
@Override
public final boolean isEnabled(MapperFeature feature) {
return _config.isEnabled(feature);
}
@Override
public final boolean isEnabled(DatatypeFeature feature) {
return _config.isEnabled(feature);
}
@Override
public final DatatypeFeatures getDatatypeFeatures() {
return _config.getDatatypeFeatures();
}
@Override
public final JsonFormat.Value getDefaultPropertyFormat(Class<?> baseType) {
return _config.getDefaultPropertyFormat(baseType);
}
@Override
public final AnnotationIntrospector getAnnotationIntrospector() {
return _config.getAnnotationIntrospector();
}
@Override
public final TypeFactory getTypeFactory() {
return _config.getTypeFactory();
}
@Override // since 2.11
public JavaType constructSpecializedType(JavaType baseType, Class<?> subclass)
throws IllegalArgumentException
{
if (baseType.hasRawClass(subclass)) {
return baseType;
}
// On deserialization side, still uses "strict" type-compatibility checking;
// see [databind#2632] about serialization side
return getConfig().getTypeFactory().constructSpecializedType(baseType, subclass, false);
}
/**
* Method for accessing default Locale to use: convenience method for
*<pre>
* getConfig().getLocale();
*</pre>
*/
@Override
public Locale getLocale() {
return _config.getLocale();
}
/**
* Method for accessing default TimeZone to use: convenience method for
*<pre>
* getConfig().getTimeZone();
*</pre>
*/
@Override
public TimeZone getTimeZone() {
return _config.getTimeZone();
}
/*
/**********************************************************************
/* Access to per-call state, like generic attributes
/**********************************************************************
*/
@Override
public Object getAttribute(Object key) {
return _attributes.getAttribute(key);
}
@Override
public DeserializationContext setAttribute(Object key, Object value)
{
_attributes = _attributes.withPerCallAttribute(key, value);
return this;
}
/**
* Accessor to {@link JavaType} of currently contextualized
* {@link ValueDeserializer}, if any.
* This is sometimes useful for generic {@link ValueDeserializer}s that
* do not get passed (or do not retain) type information when being
* constructed: happens for example for deserializers constructed
* from annotations.
*
* @return Type of {@link ValueDeserializer} being contextualized,
* if process is on-going; null if not.
*/
public JavaType getContextualType() {
return (_currentType == null) ? null : _currentType.value();
}
/*
/**********************************************************************
/* ObjectReadContext impl, config access
/**********************************************************************
*/
@Override
public TokenStreamFactory tokenStreamFactory() {
return _streamFactory;
}
@Override
public FormatSchema getSchema() {
return _schema;
}
@Override
public StreamReadConstraints streamReadConstraints() {
return _streamFactory.streamReadConstraints();
}
@Override
public int getStreamReadFeatures(int defaults) {
return _config.getStreamReadFeatures();
}
@Override
public int getFormatReadFeatures(int defaults) {
return _config.getFormatReadFeatures();
}
/*
/**********************************************************************
/* ObjectReadContext impl, Tree creation
/**********************************************************************
*/
@Override
public ArrayTreeNode createArrayNode() {
return getNodeFactory().arrayNode();
}
@Override
public ObjectTreeNode createObjectNode() {
return getNodeFactory().objectNode();
}
/*
/**********************************************************************
/* ObjectReadContext impl, databind
/**********************************************************************
*/
@SuppressWarnings("unchecked")
@Override
public JsonNode readTree(JsonParser p) throws JacksonException
{
// NOTE: inlined version of `_bindAsTree()` from `ObjectReader`
JsonToken t = p.currentToken();
if (t == null) {
t = p.nextToken();
if (t == null) { // [databind#1406]: expose end-of-input as `null`
return null;
}
}
if (t == JsonToken.VALUE_NULL) {
return getNodeFactory().nullNode();
}
ValueDeserializer<Object> deser = findRootValueDeserializer(ObjectReader.JSON_NODE_TYPE);
return (JsonNode) deser.deserialize(p, this);
}
/**
* Convenience method that may be used by composite or container deserializers,
* for reading one-off values contained (for sequences, it is more efficient
* to actually fetch deserializer once for the whole collection).
*<p>
* NOTE: when deserializing values of properties contained in composite types,
* rather use {@link #readPropertyValue(JsonParser, BeanProperty, Class)};
* this method does not allow use of contextual annotations.
*/
@Override
public <T> T readValue(JsonParser p, Class<T> type) throws JacksonException {
return readValue(p, getTypeFactory().constructType(type));
}
@Override
public <T> T readValue(JsonParser p, TypeReference<T> refType) throws JacksonException {
return readValue(p, getTypeFactory().constructType(refType));
}
@Override
public <T> T readValue(JsonParser p, ResolvedType type) throws JacksonException {
if (type instanceof JavaType jt) {
return readValue(p, jt);
}
throw new UnsupportedOperationException(
"Only support `JavaType` implementation of `ResolvedType`, not: "+type.getClass().getName());
}
@SuppressWarnings("unchecked")
public <T> T readValue(JsonParser p, JavaType type) throws JacksonException {
ValueDeserializer<Object> deser = findRootValueDeserializer(type);
if (deser == null) {
reportBadDefinition(type,
"Could not find `ValueDeserializer` for type "+ClassUtil.getTypeDescription(type));
}
return (T) _readValue(p, deser);
}
/**
* Helper method that should handle special cases for deserialization; most
* notably handling {@code null} (and possibly absent values).
*/
private Object _readValue(JsonParser p, ValueDeserializer<Object> deser) throws JacksonException
{
// 12-Oct-2025, tatu: As per [databind#5344], need to ensure parser points to token
if (!p.hasCurrentToken()) {
p.nextToken();
}
if (p.hasToken(JsonToken.VALUE_NULL)) {
return deser.getNullValue(this);
}
return deser.deserialize(p, this);
}
/*
/**********************************************************************
/* Public API, config feature accessors
/**********************************************************************
*/
/**
* Convenience method for checking whether specified on/off
* feature is enabled
*/
public final boolean isEnabled(DeserializationFeature feat) {
// 03-Dec-2010, tatu: minor shortcut; since this is called quite often,
// let's use a local copy of feature settings:
return (_featureFlags & feat.getMask()) != 0;
}
/**
* Bulk access method for getting the bit mask of all {@link DeserializationFeature}s
* that are enabled.
*/
public final int getDeserializationFeatures() {
return _featureFlags;
}
/**
* Bulk access method for checking that all features specified by
* mask are enabled.
*/
public final boolean hasDeserializationFeatures(int featureMask) {
return (_featureFlags & featureMask) == featureMask;
}
/**
* Bulk access method for checking that at least one of features specified by
* mask is enabled.
*/
public final boolean hasSomeOfFeatures(int featureMask) {
return (_featureFlags & featureMask) != 0;
}
/**
* Accessor for checking whether input format has specified capability
* or not.
*
* @return True if input format has specified capability; false if not
*/
public final boolean isEnabled(StreamReadCapability cap) {
return _readCapabilities.isEnabled(cap);
}
/*
/**********************************************************************
/* Public API, accessor for helper objects
/**********************************************************************
*/
/**
* Method for accessing the currently active parser.
* May be different from the outermost parser
* when content is buffered.
*<p>
* Use of this method is discouraged: if code has direct access
* to the active parser, that should be used instead.
*/
public final JsonParser getParser() { return _parser; }
public final Object findInjectableValue(Object valueId,
BeanProperty forProperty, Object beanInstance, Boolean optional, Boolean useInput)
{
InjectableValues injectables = _injectableValues;
if (injectables == null) {
injectables = InjectableValues.empty();
}
return injectables.findInjectableValue(this, valueId, forProperty, beanInstance,
optional, useInput);
}
/**
* Convenience method for accessing the default Base64 encoding
* used for decoding base64 encoded binary content.
* Same as calling:
*<pre>
* getConfig().getBase64Variant();
*</pre>
*/
public final Base64Variant getBase64Variant() {
return _config.getBase64Variant();
}
/**
* Convenience method, functionally equivalent to:
*<pre>
* getConfig().getNodeFactory();
* </pre>
*/
public final JsonNodeFactory getNodeFactory() {
return _config.getNodeFactory();
}
/*
/**********************************************************************
/* Annotation, BeanDescription introspection
/**********************************************************************
*/
@Override
protected ClassIntrospector classIntrospector() {
if (_classIntrospector == null) {
_classIntrospector = _config.classIntrospectorInstance();
}
return _classIntrospector;
}
@Override
public BeanDescription introspectBeanDescription(JavaType type, AnnotatedClass ac) {
return classIntrospector().introspectForDeserialization(type, ac);
}
public BeanDescription introspectBeanDescriptionForCreation(JavaType type) {
return introspectBeanDescriptionForCreation(type,
classIntrospector().introspectClassAnnotations(type));
}
public BeanDescription introspectBeanDescriptionForCreation(JavaType type, AnnotatedClass ac) {
return classIntrospector().introspectForCreation(type, ac);
}
public BeanDescription.Supplier lazyIntrospectBeanDescriptionForCreation(JavaType type) {
return new BeanDescription.LazySupplier(getConfig(), type) {
@Override
protected BeanDescription _construct(JavaType forType, AnnotatedClass ac) {
return introspectBeanDescriptionForCreation(forType, ac);
}
@Override
protected AnnotatedClass _introspect(JavaType forType) {
return introspectClassAnnotations(forType);
}
};
}
public BeanDescription introspectBeanDescriptionForBuilder(JavaType builderType,
BeanDescription valueTypeDesc) {
return classIntrospector().introspectForDeserializationWithBuilder(builderType,
valueTypeDesc);
}
public BeanDescription.Supplier lazyIntrospectBeanDescriptionForBuilder(final JavaType builderType,
final BeanDescription valueTypeDesc) {
return new BeanDescription.LazySupplier(getConfig(), builderType) {
@Override
protected BeanDescription _construct(JavaType forType, AnnotatedClass ac) {
return introspectBeanDescriptionForBuilder(forType, valueTypeDesc);
}
@Override
protected AnnotatedClass _introspect(JavaType forType) {
return introspectClassAnnotations(forType);
}
};
}
/*
/**********************************************************************
/* Misc config access
/**********************************************************************
*/
@Override
public PropertyName findRootName(JavaType rootType) {
return _config.findRootName(this, rootType);
}
@Override
public PropertyName findRootName(Class<?> rawRootType) {
return _config.findRootName(this, rawRootType);
}
/**
* Method that can be used to see whether there is an explicitly registered deserializer
* for given type: this is true for supported JDK types, as well as third-party types
* for which {@code Module} provides support but is NOT true (that is, returns {@code false})
* for POJO types for which {@code BeanDeserializer} is generated based on discovered
* properties.
*<p>
* Note that it is up to {@code Module}s to implement support for this method: some
* do (like basic {@code SimpleModule}).
*
* @param valueType Type-erased type to check
*
* @return True if this factory has explicit (non-POJO) deserializer for specified type,
* or has a provider (of type {@link Deserializers}) that has.
*/
public boolean hasExplicitDeserializerFor(Class<?> valueType) {
return _factory.hasExplicitDeserializerFor(this, valueType);
}
/*
/**********************************************************************
/* Public API, CoercionConfig access
/**********************************************************************
*/
/**
* General-purpose accessor for finding what to do when specified coercion
* from shape that is now always allowed to be coerced from is requested.
*
* @param targetType Logical target type of coercion
* @param targetClass Physical target type of coercion
* @param inputShape Input shape to coerce from
*
* @return CoercionAction configured for specific coercion
*/
public CoercionAction findCoercionAction(LogicalType targetType,
Class<?> targetClass, CoercionInputShape inputShape)
{
return _config.findCoercionAction(targetType, targetClass, inputShape);
}
/**
* More specialized accessor called in case of input being a blank
* String (one consisting of only white space characters with length of at least one).
* Will basically first determine if "blank as empty" is allowed: if not,
* returns {@code actionIfBlankNotAllowed}, otherwise returns action for
* {@link CoercionInputShape#EmptyString}.
*
* @param targetType Logical target type of coercion
* @param targetClass Physical target type of coercion
* @param actionIfBlankNotAllowed Return value to use in case "blanks as empty"
* is not allowed
*
* @return CoercionAction configured for specified coercion from blank string
*/
public CoercionAction findCoercionFromBlankString(LogicalType targetType,
Class<?> targetClass,
CoercionAction actionIfBlankNotAllowed)
{
return _config.findCoercionFromBlankString(targetType, targetClass, actionIfBlankNotAllowed);
}
/*
/**********************************************************************
/* Factory methods for getting appropriate TokenBuffer instances
/* (possibly overridden by backends for alternate data formats)
/**********************************************************************
*/
/**
* Factory method used for creating {@link TokenBuffer} to temporarily
* contain copy of content read from specified parser; usually for purpose
* of reading contents later on (possibly augmeneted with injected additional
* content)
*/
public TokenBuffer bufferForInputBuffering(JsonParser p) {
return TokenBuffer.forBuffering(p, this);
}
/**
* Convenience method that is equivalent to:
*<pre>
* ctxt.bufferForInputBuffering(ctxt.getParser());
*</pre>
*/
public final TokenBuffer bufferForInputBuffering() {
return bufferForInputBuffering(getParser());
}
/**
* Convenience method, equivalent to:
*<pre>
* TokenBuffer buffer = ctxt.bufferForInputBuffering(parser);
* buffer.copyCurrentStructure(parser);
* return buffer;
*</pre>
*<p>
* NOTE: the whole "current value" that parser points to is read and
* buffered, including Object and Array values (if parser pointing to
* start marker).
*/
public TokenBuffer bufferAsCopyOfValue(JsonParser p) throws JacksonException
{
TokenBuffer buf = bufferForInputBuffering(p);
buf.copyCurrentStructure(p);
return buf;
}
/*
/**********************************************************************
/* Public API, value deserializer access
/**********************************************************************
*/
/**
* Method for finding a value deserializer, and creating a contextual
* version if necessary, for value reached via specified property.
*/
@SuppressWarnings("unchecked")
public final ValueDeserializer<Object> findContextualValueDeserializer(JavaType type,
BeanProperty prop)
{
ValueDeserializer<Object> deser = _cache.findValueDeserializer(this, _factory, type);
if (deser != null) {
deser = (ValueDeserializer<Object>) handleSecondaryContextualization(deser, prop, type);
}
return deser;
}
/**
* Variant that will try to locate deserializer for current type, but without
* performing any contextualization (unlike {@link #findContextualValueDeserializer})
* or checking for need to create a {@link TypeDeserializer} (unlike
* {@link #findRootValueDeserializer(JavaType)}.
* This method is usually called from within {@link ValueDeserializer#resolve},
* and expectation is that caller then calls either
* {@link #handlePrimaryContextualization(ValueDeserializer, BeanProperty, JavaType)} or
* {@link #handleSecondaryContextualization(ValueDeserializer, BeanProperty, JavaType)} at a
* later point, as necessary.
*/
public final ValueDeserializer<Object> findNonContextualValueDeserializer(JavaType type)
{
return _cache.findValueDeserializer(this, _factory, type);
}
/**
* Method for finding a deserializer for root-level value.
*/
@SuppressWarnings("unchecked")
public final ValueDeserializer<Object> findRootValueDeserializer(JavaType type)
{
ValueDeserializer<Object> deser = _cache.findValueDeserializer(this,
_factory, type);
if (deser == null) { // can this occur?
return null;
}
deser = (ValueDeserializer<Object>) handleSecondaryContextualization(deser, null, type);
TypeDeserializer typeDeser = findTypeDeserializer(type);
if (typeDeser != null) {
// important: contextualize to indicate this is for root value
typeDeser = typeDeser.forProperty(null);
return new TypeWrappedDeserializer(typeDeser, deser);
}
return deser;
}
/*
/**********************************************************************
/* Public API, (value) type deserializer access
/**********************************************************************
*/
/**
* Method called to find and create a type information deserializer for given base type,
* if one is needed. If not needed (no polymorphic handling configured for type),
* should return null.
*<p>
* Note that this method is usually only directly called for values of container (Collection,
* array, Map) types and root values, but not for bean property values.
*
* @param baseType Declared base type of the value to deserializer (actual
* deserializer type will be this type or its subtype)
*
* @return Type deserializer to use for given base type, if one is needed; null if not.
*/
public TypeDeserializer findTypeDeserializer(JavaType baseType)
{
return findTypeDeserializer(baseType, introspectClassAnnotations(baseType));
}
public TypeDeserializer findTypeDeserializer(JavaType baseType,
AnnotatedClass classAnnotations)
{
try {
return _config.getTypeResolverProvider().findTypeDeserializer(this,
baseType, classAnnotations);
} catch (IllegalArgumentException | IllegalStateException e) {
throw InvalidDefinitionException.from(getParser(),
ClassUtil.exceptionMessage(e), baseType)
.withCause(e);
}
}
/**
* Method called to create a type information deserializer for values of
* given non-container property, if one is needed.
* If not needed (no polymorphic handling configured for property), should return null.
*<p>
* Note that this method is only called for non-container bean properties,
* and not for values in container types or root values (or container properties)
*
* @param baseType Declared base type of the value to deserializer (actual
* deserializer type will be this type or its subtype)
*
* @return Type deserializer to use for given base type, if one is needed; null if not.
*
* @since 3.0
*/
public TypeDeserializer findPropertyTypeDeserializer(JavaType baseType,
AnnotatedMember accessor)
{
try {
return _config.getTypeResolverProvider().findPropertyTypeDeserializer(this,
accessor, baseType);
} catch (IllegalArgumentException | IllegalStateException e) {
throw InvalidDefinitionException.from(getParser(),
ClassUtil.exceptionMessage(e), baseType)
.withCause(e);
}
}
/**
* Method called to find and create a type information deserializer for values of
* given container (list, array, map) property, if one is needed.
* If not needed (no polymorphic handling configured for property), should return null.
*<p>
* Note that this method is only called for container bean properties,
* and not for values in container types or root values (or non-container properties)
*
* @param containerType Type of property; must be a container type
* @param accessor Field or method that contains container property
*
* @since 3.0
*/
public TypeDeserializer findPropertyContentTypeDeserializer(JavaType containerType,
AnnotatedMember accessor)
{
try {
return _config.getTypeResolverProvider().findPropertyContentTypeDeserializer(this,
accessor, containerType);
} catch (IllegalArgumentException | IllegalStateException e) {
throw InvalidDefinitionException.from(getParser(),
ClassUtil.exceptionMessage(e), containerType)
.withCause(e);
}
}
/*
/**********************************************************************
/* Public API, key deserializer access
/**********************************************************************
*/
public final KeyDeserializer findKeyDeserializer(JavaType keyType,
BeanProperty prop)
{
KeyDeserializer kd;
// 15-Jun-2021, tatu: Needed wrt [databind#3143]
try {
kd = _cache.findKeyDeserializer(this, _factory, keyType);
} catch (IllegalArgumentException iae) {
// We better only expose checked exceptions, since those
// are what caller is expected to handle
reportBadDefinition(keyType, ClassUtil.exceptionMessage(iae));
kd = null;
}
// Second: contextualize?
if (kd instanceof ContextualKeyDeserializer ckd) {
kd = ckd.createContextual(this, prop);
}
return kd;
}
/**
* Method that will drop all dynamically constructed deserializers (ones that
* are counted as result value for {@link DeserializerCache#cachedDeserializersCount}).
* This can be used to remove memory usage (in case some deserializers are
* only used once or so), or to force re-construction of deserializers after
* configuration changes for mapper than owns the provider.
* @since 2.19
*/
public void flushCachedDeserializers() {
_cache.flushCachedDeserializers();
}
/*
/**********************************************************************
/* Public API, ObjectId handling
/**********************************************************************
*/
/**
* Method called to find and return entry corresponding to given
* Object Id: will add an entry if necessary, and never returns null
*/
public abstract ReadableObjectId findObjectId(Object id, ObjectIdGenerator<?> generator, ObjectIdResolver resolver);
/**
* Method called to ensure that every object id encounter during processing
* are resolved.
*
* @throws UnresolvedForwardReference
*/
public abstract void checkUnresolvedObjectId()
throws UnresolvedForwardReference;
/*
/**********************************************************************
/* Public API, type handling
/**********************************************************************
*/
/**
* Convenience method, functionally equivalent to:
*<pre>
* getConfig().constructType(cls);
* </pre>
*/
public final JavaType constructType(Class<?> cls) {
return (cls == null) ? null : _config.constructType(cls);
}
/**
* Helper method that is to be used when resolving basic
|
DeserializationContext
|
java
|
quarkusio__quarkus
|
integration-tests/main/src/test/java/io/quarkus/it/main/ParameterResolverTest.java
|
{
"start": 5297,
"end": 5456
}
|
class ____ {
private final String value;
public NonSerializable(String value) {
this.value = value;
}
}
}
|
NonSerializable
|
java
|
mybatis__mybatis-3
|
src/main/java/org/apache/ibatis/type/LocalDateTimeTypeHandler.java
|
{
"start": 903,
"end": 1680
}
|
class ____ extends BaseTypeHandler<LocalDateTime> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType)
throws SQLException {
ps.setObject(i, parameter);
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
return rs.getObject(columnName, LocalDateTime.class);
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getObject(columnIndex, LocalDateTime.class);
}
@Override
public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getObject(columnIndex, LocalDateTime.class);
}
}
|
LocalDateTimeTypeHandler
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/test/java/org/springframework/boot/ssl/pem/PemSslStoreBundleTests.java
|
{
"start": 1376,
"end": 12676
}
|
class ____ {
private static final String CERTIFICATE = """
-----BEGIN CERTIFICATE-----
MIIDqzCCApOgAwIBAgIIFMqbpqvipw0wDQYJKoZIhvcNAQELBQAwbDELMAkGA1UE
BhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExEjAQBgNVBAcTCVBhbG8gQWx0bzEP
MA0GA1UEChMGVk13YXJlMQ8wDQYDVQQLEwZTcHJpbmcxEjAQBgNVBAMTCWxvY2Fs
aG9zdDAgFw0yMzA1MDUxMTI2NThaGA8yMTIzMDQxMTExMjY1OFowbDELMAkGA1UE
BhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExEjAQBgNVBAcTCVBhbG8gQWx0bzEP
MA0GA1UEChMGVk13YXJlMQ8wDQYDVQQLEwZTcHJpbmcxEjAQBgNVBAMTCWxvY2Fs
aG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAPwHWxoE3xjRmNdD
+m+e/aFlr5wEGQUdWSDD613OB1w7kqO/audEp3c6HxDB3GPcEL0amJwXgY6CQMYu
sythuZX/EZSc2HdilTBu/5T+mbdWe5JkKThpiA0RYeucQfKuB7zv4ypioa4wiR4D
nPsZXjg95OF8pCzYEssv8wT49v+M3ohWUgfF0FPlMFCSo0YVTuzB1mhDlWKq/jhQ
11WpTmk/dQX+l6ts6bYIcJt4uItG+a68a4FutuSjZdTAE0f5SOYRBpGH96mjLwEP
fW8ZjzvKb9g4R2kiuoPxvCDs1Y/8V2yvKqLyn5Tx9x/DjFmOi0DRK/TgELvNceCb
UDJmhXMCAwEAAaNPME0wHQYDVR0OBBYEFMBIGU1nwix5RS3O5hGLLoMdR1+NMCwG
A1UdEQQlMCOCCWxvY2FsaG9zdIcQAAAAAAAAAAAAAAAAAAAAAYcEfwAAATANBgkq
hkiG9w0BAQsFAAOCAQEAhepfJgTFvqSccsT97XdAZfvB0noQx5NSynRV8NWmeOld
hHP6Fzj6xCxHSYvlUfmX8fVP9EOAuChgcbbuTIVJBu60rnDT21oOOnp8FvNonCV6
gJ89sCL7wZ77dw2RKIeUFjXXEV3QJhx2wCOVmLxnJspDoKFIEVjfLyiPXKxqe/6b
dG8zzWDZ6z+M2JNCtVoOGpljpHqMPCmbDktncv6H3dDTZ83bmLj1nbpOU587gAJ8
fl1PiUDyPRIl2cnOJd+wCHKsyym/FL7yzk0OSEZ81I92LpGd/0b2Ld3m/bpe+C4Z
ILzLXTnC6AhrLcDc9QN/EO+BiCL52n7EplNLtSn1LQ==
-----END CERTIFICATE-----
""".strip();
private static final String PRIVATE_KEY = """
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQD8B1saBN8Y0ZjX
Q/pvnv2hZa+cBBkFHVkgw+tdzgdcO5Kjv2rnRKd3Oh8Qwdxj3BC9GpicF4GOgkDG
LrMrYbmV/xGUnNh3YpUwbv+U/pm3VnuSZCk4aYgNEWHrnEHyrge87+MqYqGuMIke
A5z7GV44PeThfKQs2BLLL/ME+Pb/jN6IVlIHxdBT5TBQkqNGFU7swdZoQ5Viqv44
UNdVqU5pP3UF/perbOm2CHCbeLiLRvmuvGuBbrbko2XUwBNH+UjmEQaRh/epoy8B
D31vGY87ym/YOEdpIrqD8bwg7NWP/Fdsryqi8p+U8fcfw4xZjotA0Sv04BC7zXHg
m1AyZoVzAgMBAAECggEAfEqiZqANaF+BqXQIb4Dw42ZTJzWsIyYYnPySOGZRoe5t
QJ03uwtULYv34xtANe1DQgd6SMyc46ugBzzjtprQ3ET5Jhn99U6kdcjf+dpf85dO
hOEppP0CkDNI39nleinSfh6uIOqYgt/D143/nqQhn8oCdSOzkbwT9KnWh1bC9T7I
vFjGfElvt1/xl88qYgrWgYLgXaencNGgiv/4/M0FNhiHEGsVC7SCu6kapC/WIQpE
5IdV+HR+tiLoGZhXlhqorY7QC4xKC4wwafVSiFxqDOQAuK+SMD4TCEv0Aop+c+SE
YBigVTmgVeJkjK7IkTEhKkAEFmRF5/5w+bZD9FhTNQKBgQD+4fNG1ChSU8RdizZT
5dPlDyAxpETSCEXFFVGtPPh2j93HDWn7XugNyjn5FylTH507QlabC+5wZqltdIjK
GRB5MIinQ9/nR2fuwGc9s+0BiSEwNOUB1MWm7wWL/JUIiKq6sTi6sJIfsYg79zco
qxl5WE94aoINx9Utq1cdWhwJTQKBgQD9IjPksd4Jprz8zMrGLzR8k1gqHyhv24qY
EJ7jiHKKAP6xllTUYwh1IBSL6w2j5lfZPpIkb4Jlk2KUoX6fN81pWkBC/fTBUSIB
EHM9bL51+yKEYUbGIy/gANuRbHXsWg3sjUsFTNPN4hGTFk3w2xChCyl/f5us8Lo8
Z633SNdpvwKBgQCGyDU9XzNzVZihXtx7wS0sE7OSjKtX5cf/UCbA1V0OVUWR3SYO
J0HPCQFfF0BjFHSwwYPKuaR9C8zMdLNhK5/qdh/NU7czNi9fsZ7moh7SkRFbzJzN
OxbKD9t/CzJEMQEXeF/nWTfsSpUgILqqZtAxuuFLbAcaAnJYlCKdAumQgQKBgQCK
mqjJh68pn7gJwGUjoYNe1xtGbSsqHI9F9ovZ0MPO1v6e5M7sQJHH+Fnnxzv/y8e8
d6tz8e73iX1IHymDKv35uuZHCGF1XOR+qrA/KQUc+vcKf21OXsP/JtkTRs1HLoRD
S5aRf2DWcfvniyYARSNU2xTM8GWgi2ueWbMDHUp+ZwKBgA/swC+K+Jg5DEWm6Sau
e6y+eC6S+SoXEKkI3wf7m9aKoZo0y+jh8Gas6gratlc181pSM8O3vZG0n19b493I
apCFomMLE56zEzvyzfpsNhFhk5MBMCn0LPyzX6MiynRlGyWIj0c99fbHI3pOMufP
WgmVLTZ8uDcSW1MbdUCwFSk5
-----END PRIVATE KEY-----
""".strip();
private static final char[] EMPTY_KEY_PASSWORD = new char[] {};
@Test
void createWithDetailsWhenNullStores() {
PemSslStoreDetails keyStoreDetails = null;
PemSslStoreDetails trustStoreDetails = null;
PemSslStoreBundle bundle = new PemSslStoreBundle(keyStoreDetails, trustStoreDetails);
assertThat(bundle.getKeyStore()).isNull();
assertThat(bundle.getKeyStorePassword()).isNull();
assertThat(bundle.getTrustStore()).isNull();
}
@Test
void createWithDetailsWhenStoresHaveNoValues() {
PemSslStoreDetails keyStoreDetails = PemSslStoreDetails.forCertificate(null);
PemSslStoreDetails trustStoreDetails = PemSslStoreDetails.forCertificate(null);
PemSslStoreBundle bundle = new PemSslStoreBundle(keyStoreDetails, trustStoreDetails);
assertThat(bundle.getKeyStore()).isNull();
assertThat(bundle.getKeyStorePassword()).isNull();
assertThat(bundle.getTrustStore()).isNull();
}
@Test
@WithPackageResources({ "test-cert.pem", "test-key.pem" })
void createWithDetailsWhenHasKeyStoreDetailsCertAndKey() {
PemSslStoreDetails keyStoreDetails = PemSslStoreDetails.forCertificate("classpath:test-cert.pem")
.withPrivateKey("classpath:test-key.pem");
PemSslStoreDetails trustStoreDetails = null;
PemSslStoreBundle bundle = new PemSslStoreBundle(keyStoreDetails, trustStoreDetails);
assertThat(bundle.getKeyStore()).satisfies(storeContainingCertAndKey("ssl"));
assertThat(bundle.getTrustStore()).isNull();
}
@Test
@WithPackageResources({ "test-cert.pem", "pkcs8/key-rsa-encrypted.pem" })
void createWithDetailsWhenHasKeyStoreDetailsCertAndEncryptedKey() {
PemSslStoreDetails keyStoreDetails = PemSslStoreDetails.forCertificate("classpath:test-cert.pem")
.withPrivateKey("classpath:pkcs8/key-rsa-encrypted.pem")
.withPrivateKeyPassword("test");
PemSslStoreDetails trustStoreDetails = null;
PemSslStoreBundle bundle = new PemSslStoreBundle(keyStoreDetails, trustStoreDetails);
assertThat(bundle.getKeyStore()).satisfies(storeContainingCertAndKey("ssl"));
assertThat(bundle.getTrustStore()).isNull();
}
@Test
@WithPackageResources({ "test-cert.pem", "test-key.pem" })
void createWithDetailsWhenHasKeyStoreDetailsAndTrustStoreDetailsWithoutKey() {
PemSslStoreDetails keyStoreDetails = PemSslStoreDetails.forCertificate("classpath:test-cert.pem")
.withPrivateKey("classpath:test-key.pem");
PemSslStoreDetails trustStoreDetails = PemSslStoreDetails.forCertificate("classpath:test-cert.pem");
PemSslStoreBundle bundle = new PemSslStoreBundle(keyStoreDetails, trustStoreDetails);
assertThat(bundle.getKeyStore()).satisfies(storeContainingCertAndKey("ssl"));
assertThat(bundle.getTrustStore()).satisfies(storeContainingCert("ssl"));
}
@Test
@WithPackageResources({ "test-cert.pem", "test-key.pem" })
void createWithDetailsWhenHasKeyStoreDetailsAndTrustStoreDetails() {
PemSslStoreDetails keyStoreDetails = PemSslStoreDetails.forCertificate("classpath:test-cert.pem")
.withPrivateKey("classpath:test-key.pem");
PemSslStoreDetails trustStoreDetails = PemSslStoreDetails.forCertificate("classpath:test-cert.pem")
.withPrivateKey("classpath:test-key.pem");
PemSslStoreBundle bundle = new PemSslStoreBundle(keyStoreDetails, trustStoreDetails);
assertThat(bundle.getKeyStore()).satisfies(storeContainingCertAndKey("ssl"));
assertThat(bundle.getTrustStore()).satisfies(storeContainingCertAndKey("ssl"));
}
@Test
void createWithDetailsWhenHasEmbeddedKeyStoreDetailsAndTrustStoreDetails() {
PemSslStoreDetails keyStoreDetails = PemSslStoreDetails.forCertificate(CERTIFICATE).withPrivateKey(PRIVATE_KEY);
PemSslStoreDetails trustStoreDetails = PemSslStoreDetails.forCertificate(CERTIFICATE)
.withPrivateKey(PRIVATE_KEY);
PemSslStoreBundle bundle = new PemSslStoreBundle(keyStoreDetails, trustStoreDetails);
assertThat(bundle.getKeyStore()).satisfies(storeContainingCertAndKey("ssl"));
assertThat(bundle.getTrustStore()).satisfies(storeContainingCertAndKey("ssl"));
}
@Test
@WithPackageResources({ "test-cert.pem", "test-key.pem" })
void createWithDetailsWhenHasStoreType() {
PemSslStoreDetails keyStoreDetails = new PemSslStoreDetails("PKCS12", "classpath:test-cert.pem",
"classpath:test-key.pem");
PemSslStoreDetails trustStoreDetails = new PemSslStoreDetails("PKCS12", "classpath:test-cert.pem",
"classpath:test-key.pem");
PemSslStoreBundle bundle = new PemSslStoreBundle(keyStoreDetails, trustStoreDetails);
assertThat(bundle.getKeyStore()).satisfies(storeContainingCertAndKey("PKCS12", "ssl"));
assertThat(bundle.getTrustStore()).satisfies(storeContainingCertAndKey("PKCS12", "ssl"));
}
@Test
@WithPackageResources({ "test-cert.pem", "test-key.pem" })
void createWithDetailsWhenHasKeyStoreDetailsAndTrustStoreDetailsAndKeyPassword() {
PemSslStoreDetails keyStoreDetails = PemSslStoreDetails.forCertificate("classpath:test-cert.pem")
.withPrivateKey("classpath:test-key.pem")
.withAlias("ksa")
.withPassword("kss");
PemSslStoreDetails trustStoreDetails = PemSslStoreDetails.forCertificate("classpath:test-cert.pem")
.withPrivateKey("classpath:test-key.pem")
.withAlias("tsa")
.withPassword("tss");
PemSslStoreBundle bundle = new PemSslStoreBundle(keyStoreDetails, trustStoreDetails);
assertThat(bundle.getKeyStore()).satisfies(storeContainingCertAndKey("ksa", "kss".toCharArray()));
assertThat(bundle.getTrustStore()).satisfies(storeContainingCertAndKey("tsa", "tss".toCharArray()));
}
@Test
void createWithPemSslStoreCreatesInstance() {
List<X509Certificate> certificates = PemContent.of(CERTIFICATE).getCertificates();
PrivateKey privateKey = PemContent.of(PRIVATE_KEY).getPrivateKey();
PemSslStore pemSslStore = PemSslStore.of(certificates, privateKey);
PemSslStoreBundle bundle = new PemSslStoreBundle(pemSslStore, pemSslStore);
assertThat(bundle.getKeyStore()).satisfies(storeContainingCertAndKey("ssl"));
assertThat(bundle.getTrustStore()).satisfies(storeContainingCertAndKey("ssl"));
}
@Test
void storeCreationIsLazy() {
PemSslStore pemSslStore = mock(PemSslStore.class);
PemSslStoreBundle bundle = new PemSslStoreBundle(pemSslStore, pemSslStore);
given(pemSslStore.certificates()).willReturn(PemContent.of(CERTIFICATE).getCertificates());
then(pemSslStore).shouldHaveNoInteractions();
bundle.getKeyStore();
then(pemSslStore).should().certificates();
bundle.getTrustStore();
then(pemSslStore).should(times(2)).certificates();
}
private Consumer<KeyStore> storeContainingCert(String keyAlias) {
return storeContainingCert(KeyStore.getDefaultType(), keyAlias);
}
private Consumer<KeyStore> storeContainingCert(String keyStoreType, String keyAlias) {
return ThrowingConsumer.of((keyStore) -> {
assertThat(keyStore).isNotNull();
assertThat(keyStore.getType()).isEqualTo(keyStoreType);
assertThat(keyStore.containsAlias(keyAlias)).isTrue();
assertThat(keyStore.getCertificate(keyAlias)).isNotNull();
assertThat(keyStore.getKey(keyAlias, EMPTY_KEY_PASSWORD)).isNull();
});
}
private Consumer<KeyStore> storeContainingCertAndKey(String keyAlias) {
return storeContainingCertAndKey(KeyStore.getDefaultType(), keyAlias);
}
private Consumer<KeyStore> storeContainingCertAndKey(String keyStoreType, String keyAlias) {
return storeContainingCertAndKey(keyStoreType, keyAlias, EMPTY_KEY_PASSWORD);
}
private Consumer<KeyStore> storeContainingCertAndKey(String keyAlias, char[] keyPassword) {
return storeContainingCertAndKey(KeyStore.getDefaultType(), keyAlias, keyPassword);
}
private Consumer<KeyStore> storeContainingCertAndKey(String keyStoreType, String keyAlias, char[] keyPassword) {
return ThrowingConsumer.of((keyStore) -> {
assertThat(keyStore).isNotNull();
assertThat(keyStore.getType()).isEqualTo(keyStoreType);
assertThat(keyStore.containsAlias(keyAlias)).isTrue();
assertThat(keyStore.getCertificate(keyAlias)).isNotNull();
assertThat(keyStore.getKey(keyAlias, keyPassword)).isNotNull();
});
}
}
|
PemSslStoreBundleTests
|
java
|
apache__camel
|
components/camel-clickup/src/main/java/org/apache/camel/component/clickup/model/Webhook.java
|
{
"start": 1162,
"end": 4739
}
|
class ____ implements Serializable {
@Serial
private static final long serialVersionUID = 0L;
@JsonProperty("id")
private String id = null;
@JsonProperty("userid")
private Integer userid = null;
@JsonProperty("team_id")
private Integer teamId = null;
@JsonProperty("endpoint")
private String endpoint = null;
@JsonProperty("client_id")
private String clientId = null;
@JsonProperty("events")
private Set<String> events = new HashSet<>();
@JsonProperty("task_id")
private String taskId = null;
@JsonProperty("list_id")
private String listId = null;
@JsonProperty("folder_id")
private String folderId = null;
@JsonProperty("space_id")
private String spaceId = null;
@JsonProperty("health")
private WebhookHealth health = null;
@JsonProperty("secret")
private String secret = null;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public Integer getTeamId() {
return teamId;
}
public void setTeamId(Integer teamId) {
this.teamId = teamId;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public Set<String> getEvents() {
return events;
}
public void setEvents(Set<String> events) {
this.events = events;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getListId() {
return listId;
}
public void setListId(String listId) {
this.listId = listId;
}
public String getFolderId() {
return folderId;
}
public void setFolderId(String folderId) {
this.folderId = folderId;
}
public String getSpaceId() {
return spaceId;
}
public void setSpaceId(String spaceId) {
this.spaceId = spaceId;
}
public WebhookHealth getHealth() {
return health;
}
public void setHealth(WebhookHealth health) {
this.health = health;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean matchesConfiguration(String endpointUrl, Set<String> events) {
boolean sameEndpointUrl = this.getEndpoint().equals(endpointUrl);
boolean sameEvents = Sets.symmetricDifference(this.getEvents(), events).isEmpty();
return sameEndpointUrl && sameEvents;
}
@Override
public String toString() {
return "Webhook{" +
"id='" + id + '\'' +
", userid=" + userid +
", teamId=" + teamId +
", endpoint='" + endpoint + '\'' +
", clientId='" + clientId + '\'' +
", events=" + events +
", taskId='" + taskId + '\'' +
", listId='" + listId + '\'' +
", folderId='" + folderId + '\'' +
", spaceId='" + spaceId + '\'' +
", health=" + health +
", secret='" + secret + '\'' +
'}';
}
}
|
Webhook
|
java
|
apache__camel
|
test-infra/camel-test-infra-fhir/src/test/java/org/apache/camel/test/infra/fhir/services/FhirServiceFactory.java
|
{
"start": 1003,
"end": 1802
}
|
class ____ {
private static final Logger LOG = LoggerFactory.getLogger(FhirServiceFactory.class);
private FhirServiceFactory() {
}
public static SimpleTestServiceBuilder<FhirService> builder() {
return new SimpleTestServiceBuilder<>("fhir");
}
public static FhirService createService() {
return builder()
.addLocalMapping(FhirLocalContainerService::new)
.addRemoteMapping(FhirRemoteTestService::new)
.build();
}
public static FhirService createSingletonService() {
return builder()
.addLocalMapping(() -> new FhirLocalSingletonContainerService())
.addRemoteMapping(FhirRemoteTestService::new)
.build();
}
public static
|
FhirServiceFactory
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest.java
|
{
"start": 2042,
"end": 2353
}
|
class ____ {
public String ope;
public String use;
public String log;
public String rea;
public String gro;
public String gen;
public String hea;
public String nic;
}
@JSONType(parseFeatures = Feature.SupportArrayToBean)
public static
|
MO
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeConverters.java
|
{
"start": 5201,
"end": 5414
}
|
class ____ implements Converter<OffsetDateTime, LocalTime> {
@Override
public LocalTime convert(OffsetDateTime source) {
return source.toLocalTime();
}
}
private static
|
OffsetDateTimeToLocalTimeConverter
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/RPC.java
|
{
"start": 36914,
"end": 37502
}
|
class ____.
*
*
*/
static String serverNameFromClass(Class<?> clazz) {
String name = clazz.getName();
String[] names = clazz.getName().split("\\.", -1);
if (names != null && names.length > 0) {
name = names[names.length - 1];
}
Matcher matcher = COMPLEX_SERVER_NAME_PATTERN.matcher(name);
if (matcher.find()) {
return matcher.group(1);
} else {
return name;
}
}
/**
* Store a map of protocol and version to its implementation
*/
/**
* The key in Map
*/
static
|
TestRPC
|
java
|
elastic__elasticsearch
|
test/framework/src/main/java/org/elasticsearch/datageneration/matchers/source/SourceTransforms.java
|
{
"start": 763,
"end": 3892
}
|
class ____ {
/**
* This preprocessing step makes it easier to match the document using a unified structure.
* It performs following modifications:
* <ul>
* <li> Flattens all nested maps into top level map with full field path as key (e.g. "a.b.c.d") </li>
* <li> Transforms all field values to arrays of length >= 1 </li>
* </ul>
* <p>
* It also makes it possible to work with subobjects: false/auto settings.
*
* @return flattened map
*/
public static Map<String, List<Object>> normalize(Map<String, Object> documentMap, Map<String, Map<String, Object>> mappingLookup) {
var flattened = new TreeMap<String, List<Object>>();
descend(null, documentMap, flattened, mappingLookup);
return flattened;
}
public static <T> List<T> normalizeValues(List<T> values) {
if (values == null) {
return Collections.emptyList();
}
return normalizeValues(values, Function.identity());
}
public static <T, U> List<U> normalizeValues(List<T> values, Function<T, U> transform) {
if (values == null) {
return Collections.emptyList();
}
// Synthetic source modifications:
// * null values are not present
// * duplicates are removed
return values.stream()
.filter(v -> v != null && Objects.equals(v, "null") == false)
.map(transform)
.distinct()
.collect(Collectors.toList());
}
private static void descend(
String pathFromRoot,
Map<String, Object> currentLevel,
Map<String, List<Object>> flattened,
Map<String, Map<String, Object>> mappingLookup
) {
for (var entry : currentLevel.entrySet()) {
var pathToCurrentField = pathFromRoot == null ? entry.getKey() : pathFromRoot + "." + entry.getKey();
if (entry.getValue() instanceof List<?> list) {
for (var fieldValue : list) {
handleField(pathToCurrentField, fieldValue, flattened, mappingLookup);
}
} else {
handleField(pathToCurrentField, entry.getValue(), flattened, mappingLookup);
}
}
}
@SuppressWarnings("unchecked")
private static void handleField(
String pathToCurrentField,
Object currentField,
Map<String, List<Object>> flattened,
Map<String, Map<String, Object>> mappingLookup
) {
var mapping = mappingLookup.get(pathToCurrentField);
// Values of some fields are complex objects so we need to double-check that this is actually and object or a nested field
// we can descend into.
if (currentField instanceof Map<?, ?> map
&& (mapping == null || mapping.get("type").equals("object") || mapping.get("type").equals("nested"))) {
descend(pathToCurrentField, (Map<String, Object>) map, flattened, mappingLookup);
} else {
flattened.computeIfAbsent(pathToCurrentField, k -> new ArrayList<>()).add(currentField);
}
}
}
|
SourceTransforms
|
java
|
apache__camel
|
core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ManagedSupervisingRouteControllerMBean.java
|
{
"start": 1051,
"end": 4032
}
|
interface ____ extends ManagedRouteControllerMBean {
@ManagedAttribute(description = "Whether supervising is enabled")
boolean isEnabled();
@ManagedAttribute(description = "The number of threads used by the scheduled thread pool that are used for restarting routes")
int getThreadPoolSize();
@ManagedAttribute(description = "Initial delay in milli seconds before the route controller starts")
long getInitialDelay();
@ManagedAttribute(description = "Backoff delay in millis when restarting a route that failed to startup")
long getBackOffDelay();
@ManagedAttribute(description = "Backoff maximum delay in millis when restarting a route that failed to startup")
long getBackOffMaxDelay();
@ManagedAttribute(description = "Backoff maximum elapsed time in millis, after which the backoff should be considered exhausted and no more attempts should be made")
long getBackOffMaxElapsedTime();
@ManagedAttribute(description = "Backoff maximum number of attempts to restart a route that failed to startup")
long getBackOffMaxAttempts();
@ManagedAttribute(description = "Backoff multiplier to use for exponential backoff")
double getBackOffMultiplier();
@ManagedAttribute(description = "Pattern for filtering routes to be included as supervised")
String getIncludeRoutes();
@ManagedAttribute(description = "Pattern for filtering routes to be excluded as supervised")
String getExcludeRoutes();
@ManagedAttribute(description = "Whether to mark the route as unhealthy (down) when all restarting attempts (backoff) have failed and the route is not successfully started and the route manager is giving up.")
boolean isUnhealthyOnExhausted();
@ManagedAttribute(description = "Whether to mark the route as unhealthy (down) when the route failed to initially start, and is being controlled for restarting (backoff)")
boolean isUnhealthyOnRestarting();
@ManagedAttribute(description = "Number of routes controlled by the controller")
int getNumberOfControlledRoutes();
@ManagedAttribute(description = "Number of routes which have failed to startup and are currently managed to be restarted")
int getNumberOfRestartingRoutes();
@ManagedAttribute(description = "Number of routes which have failed all attempts to startup and are now exhausted")
int getNumberOfExhaustedRoutes();
@ManagedAttribute(description = "Exhausted routes")
Collection<String> getExhaustedRoutes();
@ManagedAttribute(description = "Routes that are restarting or scheduled to restart")
Collection<String> getRestartingRoutes();
@ManagedOperation(description = "Lists detailed status about all the routes (incl failure details for routes failed to start)")
TabularData routeStatus(boolean exhausted, boolean restarting, boolean includeStacktrace);
@ManagedOperation(description = "Starts all routes")
void startRoutes();
}
|
ManagedSupervisingRouteControllerMBean
|
java
|
apache__camel
|
components/camel-sql/src/test/java/org/apache/camel/processor/idempotent/jdbc/CustomizedJdbcMessageIdRepositoryTest.java
|
{
"start": 1431,
"end": 3521
}
|
class ____ extends CamelSpringTestSupport {
protected static final String SELECT_ALL_STRING
= "SELECT messageId FROM CUSTOMIZED_MESSAGE_REPOSITORY WHERE processorName = ?";
protected static final String PROCESSOR_NAME = "myProcessorName";
protected JdbcTemplate jdbcTemplate;
protected DataSource dataSource;
@EndpointInject("mock:result")
protected MockEndpoint resultEndpoint;
@EndpointInject("mock:error")
protected MockEndpoint errorEndpoint;
@Override
public void doPostSetup() {
dataSource = context.getRegistry().lookupByNameAndType("dataSource", DataSource.class);
jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.afterPropertiesSet();
}
@Test
public void testDuplicateMessagesAreFilteredOut() throws Exception {
resultEndpoint.expectedBodiesReceived("one", "two", "three");
errorEndpoint.expectedMessageCount(0);
template.sendBodyAndHeader("direct:start", "one", "messageId", "1");
template.sendBodyAndHeader("direct:start", "two", "messageId", "2");
template.sendBodyAndHeader("direct:start", "one", "messageId", "1");
template.sendBodyAndHeader("direct:start", "two", "messageId", "2");
template.sendBodyAndHeader("direct:start", "one", "messageId", "1");
template.sendBodyAndHeader("direct:start", "three", "messageId", "3");
MockEndpoint.assertIsSatisfied(context);
// all 3 messages should be in jdbc repo
List<String> receivedMessageIds = jdbcTemplate.queryForList(SELECT_ALL_STRING, String.class, PROCESSOR_NAME);
assertEquals(3, receivedMessageIds.size());
assertTrue(receivedMessageIds.contains("1"));
assertTrue(receivedMessageIds.contains("2"));
assertTrue(receivedMessageIds.contains("3"));
}
@Override
protected AbstractApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/processor/idempotent/jdbc/customized-spring.xml");
}
}
|
CustomizedJdbcMessageIdRepositoryTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/SelectClauseTests.java
|
{
"start": 2170,
"end": 13957
}
|
class ____ extends BaseSqmUnitTest {
@Test
public void testSimpleAliasSelection() {
SqmSelectStatement<?> statement = interpretSelect( "select p from Person p" );
assertEquals( 1, statement.getQuerySpec().getSelectClause().getSelections().size() );
SqmSelection<?> selection = statement.getQuerySpec().getSelectClause().getSelections().get( 0 );
assertThat( selection.getSelectableNode(), instanceOf( SqmRoot.class ) );
}
@Test
public void testSimpleAttributeSelection() {
SqmSelectStatement<?> statement = interpretSelect( "select p.nickName from Person p" );
assertEquals( 1, statement.getQuerySpec().getSelectClause().getSelections().size() );
SqmSelection<?> selection = statement.getQuerySpec().getSelectClause().getSelections().get( 0 );
assertThat( selection.getSelectableNode(), instanceOf( SqmSimplePath.class ) );
}
@Test
public void testCompoundAttributeSelection() {
SqmSelectStatement<?> statement = interpretSelect( "select p.nickName, p.name.firstName from Person p" );
assertEquals( 2, statement.getQuerySpec().getSelectClause().getSelections().size() );
assertThat(
statement.getQuerySpec().getSelectClause().getSelections().get( 0 ).getSelectableNode(),
instanceOf( SqmSimplePath.class )
);
assertThat(
statement.getQuerySpec().getSelectClause().getSelections().get( 1 ).getSelectableNode(),
instanceOf( SqmSimplePath.class )
);
}
@Test
public void testMixedAliasAndAttributeSelection() {
SqmSelectStatement<?> statement = interpretSelect( "select p, p.nickName from Person p" );
assertEquals( 2, statement.getQuerySpec().getSelectClause().getSelections().size() );
assertThat(
statement.getQuerySpec().getSelectClause().getSelections().get( 0 ).getSelectableNode(),
instanceOf( SqmRoot.class )
);
assertThat(
statement.getQuerySpec().getSelectClause().getSelections().get( 1 ).getSelectableNode(),
instanceOf( SqmSimplePath.class )
);
}
@Test
public void testBinaryArithmeticExpression() {
final String query = "select p.numberOfToes + p.numberOfToes as b from Person p";
final SqmSelectStatement<?> selectStatement = interpretSelect( query );
final SqmQuerySpec<?> querySpec = selectStatement.getQuerySpec();
final SqmSelection<?> selection = querySpec.getSelectClause().getSelections().get( 0 );
assertThat( querySpec.getFromClause().getRoots().size(), is(1) );
final SqmRoot<?> root = querySpec.getFromClause().getRoots().get( 0 );
assertThat( root.getEntityName(), endsWith( "Person" ) );
assertThat( root.getJoins().size(), is(0) );
SqmBinaryArithmetic expression = (SqmBinaryArithmetic) selection.getSelectableNode();
SqmPath<?> leftHandOperand = (SqmPath<?>) expression.getLeftHandOperand();
assertThat( leftHandOperand.getLhs(), sameInstance( root ) );
assertThat( leftHandOperand.getReferencedPathSource().getPathName(), is( "numberOfToes" ) );
// assertThat( leftHandOperand.getFromElement(), nullValue() );
SqmPath<?> rightHandOperand = (SqmPath<?>) expression.getRightHandOperand();
assertThat( rightHandOperand.getLhs(), sameInstance( root ) );
assertThat( rightHandOperand.getReferencedPathSource().getPathName(), is( "numberOfToes" ) );
// assertThat( leftHandOperand.getFromElement(), nullValue() );
}
@Test
public void testBinaryArithmeticExpressionWithMultipleFromSpaces() {
final String query = "select p.numberOfToes + p2.numberOfToes as b from Person p, Person p2";
final SqmSelectStatement<?> selectStatement = interpretSelect( query );
final SqmQuerySpec<?> querySpec = selectStatement.getQuerySpec();
final SqmSelection<?> selection = querySpec.getSelectClause().getSelections().get( 0 );
assertThat( querySpec.getFromClause().getRoots().size(), is(2) );
final SqmRoot<?> entityRoot = querySpec.getFromClause().getRoots().get( 0 );
assertThat( entityRoot.getEntityName(), endsWith( "Person" ) );
final SqmRoot<?> entity2Root = querySpec.getFromClause().getRoots().get( 1 );
assertThat( entity2Root.getEntityName(), endsWith( "Person" ) );
SqmBinaryArithmetic addExpression = (SqmBinaryArithmetic) selection.getSelectableNode();
SqmPath<?> leftHandOperand = (SqmPath<?>) addExpression.getLeftHandOperand();
assertThat( leftHandOperand.getLhs(), sameInstance( entityRoot ) );
assertThat( leftHandOperand.getReferencedPathSource().getPathName(), is( "numberOfToes" ) );
SqmPath<?> rightHandOperand = (SqmPath<?>) addExpression.getRightHandOperand();
assertThat( rightHandOperand.getLhs(), sameInstance( entity2Root ) );
assertThat( rightHandOperand.getReferencedPathSource().getPathName(), is( "numberOfToes" ) );
}
@Test
public void testMapKeyFunction() {
collectionIndexFunctionAssertions(
interpretSelect( "select key(m) from EntityOfMaps e join e.basicByBasic m" ),
CollectionClassification.MAP,
BasicDomainType.class,
"m"
);
collectionIndexFunctionAssertions(
interpretSelect( "select key(m) from EntityOfMaps e join e.basicByComponent m" ),
CollectionClassification.MAP,
EmbeddableDomainType.class,
"m"
);
}
private void collectionIndexFunctionAssertions(
SqmSelectStatement<?> statement,
CollectionClassification expectedCollectionClassification,
Class<? extends DomainType> expectedIndexDomainTypeType,
String expectedAlias) {
assertEquals( 1, statement.getQuerySpec().getSelectClause().getSelections().size() );
final SqmSelectableNode<?> selectedExpr = statement.getQuerySpec()
.getSelectClause()
.getSelections()
.get( 0 )
.getSelectableNode();
assertThat( selectedExpr, instanceOf( SqmSimplePath.class ) );
final SqmSimplePath<?> selectedPath = (SqmSimplePath<?>) selectedExpr;
assertThat( selectedPath.getLhs().getExplicitAlias(), is( expectedAlias ) );
final PluralPersistentAttribute attribute = (PluralPersistentAttribute) selectedPath.getLhs().getReferencedPathSource();
assertThat( attribute.getCollectionClassification(), is( expectedCollectionClassification ) );
final SimpleDomainType<?> indexDomainType = attribute.getKeyGraphType();
assertThat( indexDomainType, instanceOf( expectedIndexDomainTypeType ) );
assertThat( selectedPath.getReferencedPathSource(), sameInstance( attribute.getIndexPathSource() ) );
}
@Test
public void testMapValueFunction() {
collectionValueFunctionAssertions(
interpretSelect( "select value(m) from EntityOfMaps e join e.basicByBasic m" ),
EntityOfMaps.class.getName() + ".basicByBasic",
"m"
);
collectionValueFunctionAssertions(
interpretSelect( "select value(m) from EntityOfMaps e join e.componentByBasic m" ),
EntityOfMaps.class.getName() + ".componentByBasic",
"m"
);
collectionValueFunctionAssertions(
interpretSelect( "select value(m) from EntityOfMaps e join e.oneToManyByBasic m" ),
EntityOfMaps.class.getName() + ".oneToManyByBasic",
"m"
);
// todo : ManyToMany not properly handled atm
}
@Test
public void testPluralJoinSelection() {
collectionValueFunctionAssertions(
interpretSelect( "select l from EntityOfLists e join e.listOfBasics l" ),
EntityOfLists.class.getName() + ".listOfBasics",
"l"
);
collectionValueFunctionAssertions(
interpretSelect( "select l from EntityOfLists e join e.listOfComponents l" ),
EntityOfLists.class.getName() + ".listOfComponents",
"l"
);
collectionValueFunctionAssertions(
interpretSelect( "select l from EntityOfLists e join e.listOfOneToMany l" ),
EntityOfLists.class.getName() + ".listOfOneToMany",
"l"
);
}
@Test
public void testCollectionValueFunction() {
collectionValueFunctionAssertions(
interpretSelect( "select value(b) from EntityOfLists e join e.listOfBasics b" ),
EntityOfLists.class.getName() + ".listOfBasics",
"b"
);
collectionValueFunctionAssertions(
interpretSelect( "select value(b) from EntityOfLists e join e.listOfComponents b" ),
EntityOfLists.class.getName() + ".listOfComponents",
"b"
);
collectionValueFunctionAssertions(
interpretSelect( "select value(b) from EntityOfLists e join e.listOfOneToMany b" ),
EntityOfLists.class.getName() + ".listOfOneToMany",
"b"
);
collectionValueFunctionAssertions(
interpretSelect( "select value(b) from EntityOfSets e join e.setOfBasics b" ),
EntityOfSets.class.getName() + ".setOfBasics",
"b"
);
collectionValueFunctionAssertions(
interpretSelect( "select value(b) from EntityOfSets e join e.setOfComponents b" ),
EntityOfSets.class.getName() + ".setOfComponents",
"b"
);
collectionValueFunctionAssertions(
interpretSelect( "select value(b) from EntityOfSets e join e.setOfOneToMany b" ),
EntityOfSets.class.getName() + ".setOfOneToMany",
"b"
);
collectionValueFunctionAssertions(
interpretSelect( "select value(b) from EntityOfSets e join e.sortedSetOfBasics b" ),
EntityOfSets.class.getName() + ".sortedSetOfBasics",
"b"
);
// todo : ManyToMany not properly handled atm
}
private void collectionValueFunctionAssertions(
SqmSelectStatement<?> statement,
String collectionRole,
String collectionIdentificationVariable) {
assertEquals( 1, statement.getQuerySpec().getSelectClause().getSelections().size() );
final SqmSelectableNode<?> selectedExpression = statement.getQuerySpec()
.getSelectClause()
.getSelections()
.get( 0 )
.getSelectableNode();
assertThat( selectedExpression, instanceOf( SqmPath.class ) );
final SqmPath<?> selectedPath = (SqmPath<?>) selectedExpression;
final SqmPathSource<?> referencedPathSource = selectedPath.getReferencedPathSource();
final String ownerName = StringHelper.qualifier( collectionRole );
final String attributeName = StringHelper.unqualify( collectionRole );
final EntityDomainType<?> entity = sessionFactory().getJpaMetamodel().entity( ownerName );
final PluralPersistentAttribute<?,?,?> pluralAttribute = entity.findPluralAttribute( attributeName );
assertThat( referencedPathSource, sameInstance( pluralAttribute.getElementPathSource() ) );
assertThat( selectedPath.getLhs().getExplicitAlias(), is( collectionIdentificationVariable ) );
}
@Test
public void testMapEntryFunction() {
testMapEntryFunctionAssertions( interpretSelect( "select entry(m) from EntityOfMaps e join e.manyToManyByBasic m" ) );
testMapEntryFunctionAssertions( interpretSelect( "select entry(m) from EntityOfMaps e join e.sortedManyToManyByBasic m" ) );
}
private void testMapEntryFunctionAssertions(SqmSelectStatement<?> statement) {
assertEquals( 1, statement.getQuerySpec().getSelectClause().getSelections().size() );
final SqmMapEntryReference mapEntryPath = (SqmMapEntryReference) statement.getQuerySpec()
.getSelectClause()
.getSelections()
.get( 0 )
.getSelectableNode();
assertThat( mapEntryPath.getJavaTypeDescriptor().getJavaTypeClass(), is( equalTo( Map.Entry.class ) ) );
final SqmPath<?> selectedPathLhs = mapEntryPath.getMapPath();
assertThat( selectedPathLhs.getExplicitAlias(), is( "m" ) );
}
@Test
public void testSimpleRootEntitySelection() {
SqmSelectStatement<?> statement = interpretSelect( "select e from EntityOfBasics e" );
assertEquals( 1, statement.getQuerySpec().getSelectClause().getSelections().size() );
final SqmPath<?> sqmEntityReference = TestingUtil.cast(
statement.getQuerySpec().getSelectClause().getSelections().get( 0 ).getSelectableNode(),
SqmPath.class
);
assertThat( sqmEntityReference.getJavaTypeDescriptor().getJavaTypeClass(), equalTo( EntityOfBasics.class ));
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] {
Person.class,
EntityOfBasics.class,
EntityOfLists.class,
EntityOfMaps.class,
EntityOfSets.class,
SimpleEntity.class,
};
}
}
|
SelectClauseTests
|
java
|
junit-team__junit5
|
junit-jupiter-api/src/main/java/org/junit/jupiter/api/condition/DisabledIfEnvironmentVariable.java
|
{
"start": 828,
"end": 1041
}
|
class ____ test method is <em>disabled</em> if the value of the specified
* {@linkplain #named environment variable} matches the specified
* {@linkplain #matches regular expression}.
*
* <p>When declared at the
|
or
|
java
|
spring-projects__spring-boot
|
documentation/spring-boot-actuator-docs/src/test/java/org/springframework/boot/actuate/docs/liquibase/LiquibaseEndpointDocumentationTests.java
|
{
"start": 4132,
"end": 4279
}
|
class ____ {
@Bean
LiquibaseEndpoint endpoint(ApplicationContext context) {
return new LiquibaseEndpoint(context);
}
}
}
|
TestConfiguration
|
java
|
quarkusio__quarkus
|
extensions/vertx/deployment/src/main/java/io/quarkus/vertx/core/deployment/VertxOptionsConsumerBuildItem.java
|
{
"start": 478,
"end": 1099
}
|
class ____ extends MultiBuildItem implements Comparable<VertxOptionsConsumerBuildItem> {
private final Consumer<VertxOptions> optionsConsumer;
private final int priority;
public VertxOptionsConsumerBuildItem(Consumer<VertxOptions> optionsConsumer, int priority) {
this.optionsConsumer = optionsConsumer;
this.priority = priority;
}
public Consumer<VertxOptions> getConsumer() {
return optionsConsumer;
}
@Override
public int compareTo(VertxOptionsConsumerBuildItem o) {
return Integer.compare(this.priority, o.priority);
}
}
|
VertxOptionsConsumerBuildItem
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/error/ShouldNotBeInfinite_create_Test.java
|
{
"start": 1047,
"end": 1786
}
|
class ____ {
@Test
void should_create_error_message_with_double() {
// GIVEN
double actual = Double.POSITIVE_INFINITY;
// WHEN
String message = shouldNotBeInfinite(actual).create(new TestDescription("TEST"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo("[TEST] %nExpecting Infinity not to be infinite".formatted());
}
@Test
void should_create_error_message_with_float() {
// GIVEN
float actual = Float.POSITIVE_INFINITY;
// WHEN
String message = shouldNotBeInfinite(actual).create(new TestDescription("TEST"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo("[TEST] %nExpecting Infinityf not to be infinite".formatted());
}
}
|
ShouldNotBeInfinite_create_Test
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java
|
{
"start": 12322,
"end": 12464
}
|
interface ____ {
String value() default "";
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @
|
SimpleValueQualifier
|
java
|
google__auto
|
value/src/it/functional/src/test/java/com/google/auto/value/CompileWithEclipseTest.java
|
{
"start": 4001,
"end": 6174
}
|
class ____. Elsewhere it is unnecessary but harmless. Notably,
// on Java 9+ there is no rt.jar. There, fileManager.getLocation(PLATFORM_CLASS_PATH) returns
// null, because the relevant classes are in modules inside
// fileManager.getLocation(SYSTEM_MODULES).
File rtJar = new File(JAVA_HOME.value() + "/lib/rt.jar");
if (rtJar.exists()) {
List<File> bootClassPath =
ImmutableList.<File>builder()
.add(rtJar)
.addAll(fileManager.getLocation(StandardLocation.PLATFORM_CLASS_PATH))
.build();
fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, bootClassPath);
}
Iterable<? extends JavaFileObject> sourceFileObjects =
fileManager.getJavaFileObjectsFromFiles(sources);
String outputDir = tmp.getRoot().toString();
ImmutableList<String> options =
ImmutableList.of(
"-d",
outputDir,
"-s",
outputDir,
"-source",
version,
"-target",
version,
"-warn:-warningToken,-intfAnnotation");
JavaCompiler.CompilationTask task =
compiler.getTask(null, fileManager, null, options, null, sourceFileObjects);
// Explicitly supply an empty list of extensions for AutoValueProcessor, because otherwise this
// test will pick up a test one and get confused.
AutoValueProcessor autoValueProcessor = new AutoValueProcessor(ImmutableList.of());
ImmutableList<? extends Processor> processors =
ImmutableList.of(
autoValueProcessor,
new AutoOneOfProcessor(),
new AutoAnnotationProcessor(),
new AutoBuilderProcessor());
task.setProcessors(processors);
assertWithMessage("Compilation should succeed").that(task.call()).isTrue();
}
private static ImmutableSet<File> filesUnderDirectory(File dir, Predicate<File> predicate)
throws IOException {
assertWithMessage(dir.toString()).that(dir.isDirectory()).isTrue();
try (Stream<Path> paths = Files.walk(dir.toPath())) {
return paths.map(Path::toFile).filter(predicate).collect(toImmutableSet());
}
}
}
|
path
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/util/ReflectionUtils.java
|
{
"start": 30782,
"end": 31510
}
|
interface ____ {
/**
* Determine whether the given method matches.
* @param method the method to check
*/
boolean matches(Method method);
/**
* Create a composite filter based on this filter <em>and</em> the provided filter.
* <p>If this filter does not match, the next filter will not be applied.
* @param next the next {@code MethodFilter}
* @return a composite {@code MethodFilter}
* @throws IllegalArgumentException if the MethodFilter argument is {@code null}
* @since 5.3.2
*/
default MethodFilter and(MethodFilter next) {
Assert.notNull(next, "Next MethodFilter must not be null");
return method -> matches(method) && next.matches(method);
}
}
/**
* Callback
|
MethodFilter
|
java
|
quarkusio__quarkus
|
integration-tests/smallrye-config/src/test/java/io/quarkus/it/smallrye/config/ConfigLocationsTest.java
|
{
"start": 286,
"end": 1918
}
|
class ____ {
@Test
void locations() {
given()
.get("/config/{name}", "config.properties")
.then()
.statusCode(OK.getStatusCode())
.body("value", equalTo("1234"));
given()
.get("/config/{name}", "config.properties.common")
.then()
.statusCode(OK.getStatusCode())
.body("value", equalTo("1234"));
}
@Test
void fileSystemLocation() {
given()
.get("/config/{name}", "fs.key1")
.then()
.statusCode(OK.getStatusCode())
.body("value", equalTo("value1"));
}
@Test
void applicationPropertiesProfile() {
given()
.get("/config/{name}", "profile.main.properties")
.then()
.statusCode(OK.getStatusCode())
.body("value", equalTo("main"));
given()
.get("/config/{name}", "profile.common.properties")
.then()
.statusCode(OK.getStatusCode())
.body("value", equalTo("common"));
}
@Test
void applicationYamlProfile() {
given()
.get("/config/{name}", "profile.main.yaml")
.then()
.statusCode(OK.getStatusCode())
.body("value", equalTo("main"));
given()
.get("/config/{name}", "profile.common.yaml")
.then()
.statusCode(OK.getStatusCode())
.body("value", equalTo("common"));
}
}
|
ConfigLocationsTest
|
java
|
apache__camel
|
components/camel-splunk-hec/src/test/java/org/apache/camel/component/splunkhec/integration/SplunkHECITManualTest.java
|
{
"start": 1560,
"end": 3747
}
|
class ____ extends CamelTestSupport {
@Test
public void testSendHEC() throws Exception {
SplunkHECEndpoint endpoint = getMandatoryEndpoint(
"splunk-hec:localhost:8088?token=4b35e71f-6a0f-4bab-94ce-f591ff45eecd", SplunkHECEndpoint.class);
assertEquals("4b35e71f-6a0f-4bab-94ce-f591ff45eecd", endpoint.getConfiguration().getToken());
endpoint.getConfiguration().setSkipTlsVerify(true);
endpoint.getConfiguration().setIndex("camel");
endpoint.getConfiguration().setSource("camel");
endpoint.getConfiguration().setSourceType("camel");
SplunkHECProducer producer = new SplunkHECProducer(endpoint);
producer.start();
Exchange ex = new DefaultExchange(context());
DefaultMessage message = new DefaultMessage(ex);
message.setBody("TEST sending to Splunk");
message.setHeader("foo", "bar");
ex.setIn(message);
producer.process(ex);
Exchange ex2 = new DefaultExchange(context());
DefaultMessage message2 = new DefaultMessage(ex2);
message2.setBody(Collections.singletonMap("key", "value"));
ex2.setIn(message2);
producer.process(ex2);
Exchange ex3 = new DefaultExchange(context());
DefaultMessage message3 = new DefaultMessage(ex3);
message3.setBody(null);
ex3.setIn(message3);
producer.process(ex3);
producer.stop();
}
@Test
public void testCamelRoute() throws InterruptedException {
MockEndpoint mock = getMockEndpoint("mock:hec-result");
mock.expectedMinimumMessageCount(1);
template.sendBodyAndHeader("direct:hec", "My splunk data", "header", "headerValue");
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:hec").to(
"splunk-hec:localhost:8088?token=4b35e71f-6a0f-4bab-94ce-f591ff45eecd&source=camelsource&skipTlsVerify=true")
.to("mock:hec-result");
}
};
}
}
|
SplunkHECITManualTest
|
java
|
apache__flink
|
flink-python/src/main/java/org/apache/flink/table/runtime/operators/python/aggregate/arrow/stream/StreamArrowPythonProcTimeBoundedRowsOperator.java
|
{
"start": 1468,
"end": 3644
}
|
class ____<K>
extends AbstractStreamArrowPythonBoundedRowsOperator<K> {
private static final long serialVersionUID = 1L;
private transient long currentTime;
private transient List<RowData> rowList;
public StreamArrowPythonProcTimeBoundedRowsOperator(
Configuration config,
long minRetentionTime,
long maxRetentionTime,
PythonFunctionInfo[] pandasAggFunctions,
RowType inputType,
RowType udfInputType,
RowType udfOutputType,
int inputTimeFieldIndex,
long lowerBoundary,
GeneratedProjection inputGeneratedProjection) {
super(
config,
minRetentionTime,
maxRetentionTime,
pandasAggFunctions,
inputType,
udfInputType,
udfOutputType,
inputTimeFieldIndex,
lowerBoundary,
inputGeneratedProjection);
}
@Override
public void bufferInput(RowData input) throws Exception {
currentTime = timerService.currentProcessingTime();
// register state-cleanup timer
registerProcessingCleanupTimer(currentTime);
// buffer the event incoming event
// add current element to the window list of elements with corresponding timestamp
rowList = inputState.get(currentTime);
// null value means that this is the first event received for this timestamp
if (rowList == null) {
rowList = new ArrayList<>();
}
rowList.add(input);
inputState.put(currentTime, rowList);
}
@Override
public void processElementInternal(RowData value) throws Exception {
forwardedInputQueue.add(value);
Iterable<Long> keyIter = inputState.keys();
for (Long dataTs : keyIter) {
insertToSortedList(dataTs);
}
int index = sortedTimestamps.indexOf(currentTime);
triggerWindowProcess(rowList, rowList.size() - 1, index);
sortedTimestamps.clear();
windowData.clear();
}
}
|
StreamArrowPythonProcTimeBoundedRowsOperator
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/catalog/SchemaResolver.java
|
{
"start": 1037,
"end": 1110
}
|
interface ____ {
ResolvedSchema resolve(Schema schema);
}
|
SchemaResolver
|
java
|
junit-team__junit5
|
junit-platform-launcher/src/main/java/org/junit/platform/launcher/core/CompositeEngineExecutionListener.java
|
{
"start": 925,
"end": 3669
}
|
class ____ implements EngineExecutionListener {
private static final Logger logger = LoggerFactory.getLogger(CompositeEngineExecutionListener.class);
private final List<EngineExecutionListener> engineExecutionListeners;
CompositeEngineExecutionListener(List<EngineExecutionListener> engineExecutionListeners) {
this.engineExecutionListeners = new ArrayList<>(engineExecutionListeners);
}
@Override
public void dynamicTestRegistered(TestDescriptor testDescriptor) {
notifyEach(engineExecutionListeners, IterationOrder.ORIGINAL,
listener -> listener.dynamicTestRegistered(testDescriptor),
() -> "dynamicTestRegistered(" + testDescriptor + ")");
}
@Override
public void executionSkipped(TestDescriptor testDescriptor, String reason) {
notifyEach(engineExecutionListeners, IterationOrder.ORIGINAL,
listener -> listener.executionSkipped(testDescriptor, reason),
() -> "executionSkipped(" + testDescriptor + ", " + reason + ")");
}
@Override
public void executionStarted(TestDescriptor testDescriptor) {
notifyEach(engineExecutionListeners, IterationOrder.ORIGINAL,
listener -> listener.executionStarted(testDescriptor), () -> "executionStarted(" + testDescriptor + ")");
}
@Override
public void executionFinished(TestDescriptor testDescriptor, TestExecutionResult testExecutionResult) {
notifyEach(engineExecutionListeners, IterationOrder.REVERSED,
listener -> listener.executionFinished(testDescriptor, testExecutionResult),
() -> "executionFinished(" + testDescriptor + ", " + testExecutionResult + ")");
}
@Override
public void reportingEntryPublished(TestDescriptor testDescriptor, ReportEntry entry) {
notifyEach(engineExecutionListeners, IterationOrder.ORIGINAL,
listener -> listener.reportingEntryPublished(testDescriptor, entry),
() -> "reportingEntryPublished(" + testDescriptor + ", " + entry + ")");
}
@Override
public void fileEntryPublished(TestDescriptor testDescriptor, FileEntry file) {
notifyEach(engineExecutionListeners, IterationOrder.ORIGINAL,
listener -> listener.fileEntryPublished(testDescriptor, file),
() -> "fileEntryPublished(" + testDescriptor + ", " + file + ")");
}
private static <T extends EngineExecutionListener> void notifyEach(List<T> listeners, IterationOrder iterationOrder,
Consumer<T> consumer, Supplier<String> description) {
iterationOrder.forEach(listeners, listener -> {
try {
consumer.accept(listener);
}
catch (Throwable throwable) {
UnrecoverableExceptions.rethrowIfUnrecoverable(throwable);
logger.warn(throwable, () -> "EngineExecutionListener [%s] threw exception for method: %s".formatted(
listener.getClass().getName(), description.get()));
}
});
}
}
|
CompositeEngineExecutionListener
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/custom/response/RerankResponseParserTests.java
|
{
"start": 1558,
"end": 16999
}
|
class ____ extends AbstractBWCWireSerializationTestCase<RerankResponseParser> {
public static RerankResponseParser createRandom() {
var indexPath = randomBoolean() ? "$." + randomAlphaOfLength(5) : null;
var documentTextPath = randomBoolean() ? "$." + randomAlphaOfLength(5) : null;
return new RerankResponseParser("$." + randomAlphaOfLength(5), indexPath, documentTextPath);
}
public void testFromMap() {
var validation = new ValidationException();
var parser = RerankResponseParser.fromMap(
new HashMap<>(
Map.of(
RERANK_PARSER_SCORE,
"$.result.scores[*].score",
RERANK_PARSER_INDEX,
"$.result.scores[*].index",
RERANK_PARSER_DOCUMENT_TEXT,
"$.result.scores[*].document_text"
)
),
"scope",
validation
);
assertThat(
parser,
is(new RerankResponseParser("$.result.scores[*].score", "$.result.scores[*].index", "$.result.scores[*].document_text"))
);
}
public void testFromMap_WithoutOptionalFields() {
var validation = new ValidationException();
var parser = RerankResponseParser.fromMap(
new HashMap<>(Map.of(RERANK_PARSER_SCORE, "$.result.scores[*].score")),
"scope",
validation
);
assertThat(parser, is(new RerankResponseParser("$.result.scores[*].score", null, null)));
}
public void testFromMap_ThrowsException_WhenRequiredFieldsAreNotPresent() {
var validation = new ValidationException();
var exception = expectThrows(
ValidationException.class,
() -> RerankResponseParser.fromMap(new HashMap<>(Map.of("not_path", "$.result[*].embeddings")), "scope", validation)
);
assertThat(
exception.getMessage(),
is("Validation Failed: 1: [scope.json_parser] does not contain the required setting [relevance_score];")
);
}
public void testToXContent() throws IOException {
var entity = new RerankResponseParser("$.result.scores[*].score", "$.result.scores[*].index", "$.result.scores[*].document_text");
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
{
builder.startObject();
entity.toXContent(builder, null);
builder.endObject();
}
String xContentResult = Strings.toString(builder);
var expected = XContentHelper.stripWhitespace("""
{
"json_parser": {
"relevance_score": "$.result.scores[*].score",
"reranked_index": "$.result.scores[*].index",
"document_text": "$.result.scores[*].document_text"
}
}
""");
assertThat(xContentResult, is(expected));
}
public void testToXContent_WithoutOptionalFields() throws IOException {
var entity = new RerankResponseParser("$.result.scores[*].score");
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
{
builder.startObject();
entity.toXContent(builder, null);
builder.endObject();
}
String xContentResult = Strings.toString(builder);
var expected = XContentHelper.stripWhitespace("""
{
"json_parser": {
"relevance_score": "$.result.scores[*].score"
}
}
""");
assertThat(xContentResult, is(expected));
}
public void testParse() throws IOException {
String responseJson = """
{
"request_id": "450fcb80-f796-46c1-8d69-e1e86d29aa9f",
"latency": 564.903929,
"usage": {
"doc_count": 2
},
"result": {
"scores":[
{
"index":1,
"score": 1.37
},
{
"index":0,
"score": -0.3
}
]
}
}
""";
var parser = new RerankResponseParser("$.result.scores[*].score", "$.result.scores[*].index", null);
RankedDocsResults parsedResults = (RankedDocsResults) parser.parse(
new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8))
);
assertThat(
parsedResults,
is(
new RankedDocsResults(
List.of(new RankedDocsResults.RankedDoc(1, 1.37f, null), new RankedDocsResults.RankedDoc(0, -0.3f, null))
)
)
);
}
public void testParse_ThrowsException_WhenIndex_IsInvalid() {
String responseJson = """
{
"request_id": "450fcb80-f796-46c1-8d69-e1e86d29aa9f",
"latency": 564.903929,
"usage": {
"doc_count": 2
},
"result": {
"scores":[
{
"index":"abc",
"score": 1.37
},
{
"index":0,
"score": -0.3
}
]
}
}
""";
var parser = new RerankResponseParser("$.result.scores[*].score", "$.result.scores[*].index", null);
var exception = expectThrows(
IllegalStateException.class,
() -> parser.parse(new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)))
);
assertThat(
exception.getMessage(),
is(
"Failed to parse rerank indices, error: Failed to parse list entry [0], "
+ "error: Unable to convert field [result.scores] of type [String] to Number"
)
);
}
public void testParse_ThrowsException_WhenScore_IsInvalid() {
String responseJson = """
{
"request_id": "450fcb80-f796-46c1-8d69-e1e86d29aa9f",
"latency": 564.903929,
"usage": {
"doc_count": 2
},
"result": {
"scores":[
{
"index":1,
"score": true
},
{
"index":0,
"score": -0.3
}
]
}
}
""";
var parser = new RerankResponseParser("$.result.scores[*].score", "$.result.scores[*].index", null);
var exception = expectThrows(
IllegalStateException.class,
() -> parser.parse(new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)))
);
assertThat(
exception.getMessage(),
is(
"Failed to parse rerank scores, error: Failed to parse list entry [0], "
+ "error: Unable to convert field [result.scores] of type [Boolean] to Number"
)
);
}
public void testParse_ThrowsException_WhenDocument_IsInvalid() {
String responseJson = """
{
"request_id": "450fcb80-f796-46c1-8d69-e1e86d29aa9f",
"latency": 564.903929,
"usage": {
"doc_count": 2
},
"result": {
"scores":[
{
"index":1,
"score": 0.2,
"document": 1
},
{
"index":0,
"score": -0.3,
"document": "a document"
}
]
}
}
""";
var parser = new RerankResponseParser("$.result.scores[*].score", "$.result.scores[*].index", "$.result.scores[*].document");
var exception = expectThrows(
IllegalStateException.class,
() -> parser.parse(new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)))
);
assertThat(
exception.getMessage(),
is(
"Failed to parse rerank documents, error: Failed to parse list entry [0], error: "
+ "Unable to convert field [result.scores] of type [Integer] to [String]"
)
);
}
public void testParse_ThrowsException_WhenIndices_ListSizeDoesNotMatchScores() {
String responseJson = """
{
"request_id": "450fcb80-f796-46c1-8d69-e1e86d29aa9f",
"latency": 564.903929,
"usage": {
"doc_count": 2
},
"result": {
"indices": [1],
"scores": [0.2, 0.3],
"documents": ["a", "b"]
}
}
""";
var parser = new RerankResponseParser("$.result.scores", "$.result.indices", "$.result.documents");
var exception = expectThrows(
IllegalStateException.class,
() -> parser.parse(new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)))
);
assertThat(exception.getMessage(), is("The number of index fields [1] was not the same as the number of scores [2]"));
}
public void testParse_ThrowsException_WhenDocuments_ListSizeDoesNotMatchScores() {
String responseJson = """
{
"request_id": "450fcb80-f796-46c1-8d69-e1e86d29aa9f",
"latency": 564.903929,
"usage": {
"doc_count": 2
},
"result": {
"indices": [1, 0],
"scores": [0.2, 0.3],
"documents": ["a"]
}
}
""";
var parser = new RerankResponseParser("$.result.scores", "$.result.indices", "$.result.documents");
var exception = expectThrows(
IllegalStateException.class,
() -> parser.parse(new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)))
);
assertThat(exception.getMessage(), is("The number of document fields [1] was not the same as the number of scores [2]"));
}
public void testParse_WithoutIndex() throws IOException {
String responseJson = """
{
"request_id": "450fcb80-f796-46c1-8d69-e1e86d29aa9f",
"latency": 564.903929,
"usage": {
"doc_count": 2
},
"result": {
"scores":[
{
"score": 1.37
},
{
"score": -0.3
}
]
}
}
""";
var parser = new RerankResponseParser("$.result.scores[*].score", null, null);
RankedDocsResults parsedResults = (RankedDocsResults) parser.parse(
new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8))
);
assertThat(
parsedResults,
is(
new RankedDocsResults(
List.of(new RankedDocsResults.RankedDoc(0, 1.37f, null), new RankedDocsResults.RankedDoc(1, -0.3f, null))
)
)
);
}
public void testParse_CohereResponseFormat() throws IOException {
String responseJson = """
{
"index": "44873262-1315-4c06-8433-fdc90c9790d0",
"results": [
{
"document": {
"text": "Washington, D.C.."
},
"index": 2,
"relevance_score": 0.98005307
},
{
"document": {
"text": "Capital punishment has existed in the United States since beforethe United States was a country. "
},
"index": 3,
"relevance_score": 0.27904198
},
{
"document": {
"text": "Carson City is the capital city of the American state of Nevada."
},
"index": 0,
"relevance_score": 0.10194652
}
],
"meta": {
"api_version": {
"version": "1"
},
"billed_units": {
"search_units": 1
}
}
}
""";
var parser = new RerankResponseParser("$.results[*].relevance_score", "$.results[*].index", "$.results[*].document.text");
RankedDocsResults parsedResults = (RankedDocsResults) parser.parse(
new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8))
);
assertThat(
parsedResults,
is(
new RankedDocsResults(
List.of(
new RankedDocsResults.RankedDoc(2, 0.98005307f, "Washington, D.C.."),
new RankedDocsResults.RankedDoc(
3,
0.27904198f,
"Capital punishment has existed in the United States since beforethe United States was a country. "
),
new RankedDocsResults.RankedDoc(0, 0.10194652f, "Carson City is the capital city of the American state of Nevada.")
)
)
)
);
}
@Override
protected RerankResponseParser mutateInstanceForVersion(RerankResponseParser instance, TransportVersion version) {
return instance;
}
@Override
protected Writeable.Reader<RerankResponseParser> instanceReader() {
return RerankResponseParser::new;
}
@Override
protected RerankResponseParser createTestInstance() {
return createRandom();
}
@Override
protected RerankResponseParser mutateInstance(RerankResponseParser instance) throws IOException {
var relevanceScorePath = instance.getRelevanceScorePath();
var indexPath = instance.getRerankIndexPath();
var documentTextPath = instance.getDocumentTextPath();
switch (randomInt(2)) {
case 0 -> relevanceScorePath = randomValueOtherThan(relevanceScorePath, () -> "$." + randomAlphaOfLength(5));
case 1 -> indexPath = randomValueOtherThan(indexPath, () -> randomFrom("$." + randomAlphaOfLength(5), null));
case 2 -> documentTextPath = randomValueOtherThan(documentTextPath, () -> randomFrom("$." + randomAlphaOfLength(5), null));
default -> throw new AssertionError("Illegal randomisation branch");
}
return new RerankResponseParser(relevanceScorePath, indexPath, documentTextPath);
}
}
|
RerankResponseParserTests
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.