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
|
google__guice
|
core/test/com/google/inject/errors/MissingImplementationErrorTest.java
|
{
"start": 2382,
"end": 2462
}
|
class ____ {
@Inject
RequestHandler(Dao dao) {}
}
static
|
RequestHandler
|
java
|
netty__netty
|
common/src/main/java/io/netty/util/internal/SWARUtil.java
|
{
"start": 680,
"end": 749
}
|
class ____ SWAR (SIMD within a register) operations.
*/
public final
|
for
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/results/SingleValueInferenceResults.java
|
{
"start": 523,
"end": 1144
}
|
class ____ implements InferenceResults {
public static final String FEATURE_IMPORTANCE = "feature_importance";
private final double value;
SingleValueInferenceResults(StreamInput in) throws IOException {
value = in.readDouble();
}
SingleValueInferenceResults(double value) {
this.value = value;
}
public Double value() {
return value;
}
public String valueAsString() {
return String.valueOf(value);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeDouble(value);
}
}
|
SingleValueInferenceResults
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/contextual/ContextualDeserializationTest.java
|
{
"start": 1336,
"end": 1459
}
|
class ____ {
protected String value;
public StringValue(String v) { value = v; }
}
static
|
StringValue
|
java
|
netty__netty
|
common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java
|
{
"start": 22938,
"end": 24038
}
|
class ____ implements Runnable {
final AtomicBoolean ran = new AtomicBoolean();
TestRunnable() {
}
@Override
public void run() {
ran.set(true);
}
}
@Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testExceptionIsPropagatedToTerminationFuture() throws Exception {
final IllegalStateException exception = new IllegalStateException();
final SingleThreadEventExecutor executor =
new SingleThreadEventExecutor(null, Executors.defaultThreadFactory(), true) {
@Override
protected void run() {
throw exception;
}
};
// Schedule something so we are sure the run() method will be called.
executor.execute(new Runnable() {
@Override
public void run() {
// Noop.
}
});
executor.terminationFuture().await();
assertSame(exception, executor.terminationFuture().cause());
}
}
|
TestRunnable
|
java
|
spring-projects__spring-data-jpa
|
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/procedures/MySqlStoredProcedureIntegrationTests.java
|
{
"start": 6475,
"end": 7345
}
|
class ____ extends TestcontainerConfigSupport {
public Config() {
super(MySQLDialect.class, new ClassPathResource("scripts/mysql-stored-procedures.sql"));
}
@Override
protected PersistenceManagedTypes getManagedTypes() {
return new PersistenceManagedTypes() {
@Override
public List<String> getManagedClassNames() {
return List.of(Employee.class.getName());
}
@Override
public List<String> getManagedPackages() {
return List.of();
}
@Override
public @Nullable URL getPersistenceUnitRootUrl() {
return null;
}
};
}
@SuppressWarnings("resource")
@Bean(initMethod = "start", destroyMethod = "stop")
public MySQLContainer container() {
return new MySQLContainer("mysql:8.0.24") //
.withUsername("test") //
.withPassword("test") //
.withConfigurationOverride("");
}
}
}
|
Config
|
java
|
playframework__playframework
|
documentation/manual/working/javaGuide/main/http/code/javaguide/http/JavaActionsComposition.java
|
{
"start": 2539,
"end": 2644
}
|
class ____ {
public static final TypedKey<User> USER = TypedKey.<User>create("user");
}
public
|
Attrs
|
java
|
apache__camel
|
components/camel-master/src/generated/java/org/apache/camel/component/master/MasterEndpointUriFactory.java
|
{
"start": 516,
"end": 2326
}
|
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = ":namespace:delegateUri";
private static final Set<String> PROPERTY_NAMES;
private static final Set<String> SECRET_PROPERTY_NAMES;
private static final Map<String, String> MULTI_VALUE_PREFIXES;
static {
Set<String> props = new HashSet<>(5);
props.add("bridgeErrorHandler");
props.add("delegateUri");
props.add("exceptionHandler");
props.add("exchangePattern");
props.add("namespace");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
SECRET_PROPERTY_NAMES = Collections.emptySet();
MULTI_VALUE_PREFIXES = Collections.emptyMap();
}
@Override
public boolean isEnabled(String scheme) {
return "master".equals(scheme);
}
@Override
public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException {
String syntax = scheme + BASE;
String uri = syntax;
Map<String, Object> copy = new HashMap<>(properties);
uri = buildPathParameter(syntax, uri, "namespace", null, true, copy);
uri = buildPathParameter(syntax, uri, "delegateUri", null, true, copy);
uri = buildQueryParameters(uri, copy, encode);
return uri;
}
@Override
public Set<String> propertyNames() {
return PROPERTY_NAMES;
}
@Override
public Set<String> secretPropertyNames() {
return SECRET_PROPERTY_NAMES;
}
@Override
public Map<String, String> multiValuePrefixes() {
return MULTI_VALUE_PREFIXES;
}
@Override
public boolean isLenientProperties() {
return true;
}
}
|
MasterEndpointUriFactory
|
java
|
apache__camel
|
components/camel-aws/camel-aws2-s3/src/test/java/org/apache/camel/component/aws2/s3/integration/S3ConsumerManualIT.java
|
{
"start": 2656,
"end": 9768
}
|
class ____ extends CamelTestSupport {
private static final String ACCESS_KEY = System.getProperty("aws.manual.access.key");
private static final String SECRET_KEY = System.getProperty("aws.manual.secret.key");
@BindToRegistry("amazonS3Client")
S3Client client
= S3Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(ACCESS_KEY, SECRET_KEY)))
.region(Region.EU_WEST_1).build();
@EndpointInject
private ProducerTemplate template;
@EndpointInject("mock:result")
private MockEndpoint result;
@Test
public void sendIn() throws Exception {
result.expectedMessageCount(3);
template.send("direct:putObject", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test.txt");
exchange.getIn().setBody("Test");
}
});
template.send("direct:putObject", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test1.txt");
exchange.getIn().setBody("Test1");
}
});
template.send("direct:putObject", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test2.txt");
exchange.getIn().setBody("Test2");
}
});
Thread.sleep(10000);
MockEndpoint.assertIsSatisfied(context);
}
@Test
@DisplayName("Should consume S3StreamObject when include body is true and should close the stream when autocloseBody is true")
public void shouldConsumeS3StreamObjectWhenIncludeBodyIsTrueAndNotCloseStreamWhenAutoCloseBodyIsTrue()
throws InterruptedException {
result.reset();
result.expectedMessageCount(2);
template.setDefaultEndpointUri("direct:includeBodyTrueAutoCloseTrue");
template.send("direct:putObject", exchange -> {
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test1.txt");
exchange.getIn().setBody("Test");
});
Map<String, Object> headers = new HashMap<>();
headers.put(AWS2S3Constants.KEY, "test1.txt");
headers.put(Exchange.FILE_NAME, "test1.txt");
template.sendBodyAndHeaders("direct:includeBodyTrueAutoCloseTrue", headers);
result.assertIsSatisfied();
final Exchange exchange = result.getExchanges().get(1);
assertThat(exchange.getIn().getBody().getClass(), is(equalTo(String.class)));
assertThat(exchange.getIn().getBody(String.class), is("Test"));
}
@Test
@DisplayName("Should not consume S3StreamObject when include body is false and should not close the stream when autocloseBody is false")
public void shouldNotConsumeS3StreamObjectWhenIncludeBodyIsFalseAndNotCloseStreamWhenAutoCloseBodyIsFalse()
throws InterruptedException {
result.reset();
result.expectedMessageCount(2);
template.setDefaultEndpointUri("direct:includeBodyFalseAutoCloseFalse");
template.send("direct:putObject", exchange -> {
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test1.txt");
exchange.getIn().setBody("Test");
});
Map<String, Object> headers = new HashMap<>();
headers.put(AWS2S3Constants.KEY, "test1.txt");
headers.put(Exchange.FILE_NAME, "test1.txt");
template.sendBodyAndHeaders("direct:includeBodyFalseAutoCloseFalse", headers);
result.assertIsSatisfied();
final Exchange exchange = result.getExchanges().get(1);
assertThat(exchange.getIn().getBody().getClass(), is(equalTo(ResponseInputStream.class)));
assertDoesNotThrow(() -> {
final ResponseInputStream<GetObjectResponse> inputStream = exchange.getIn().getBody(ResponseInputStream.class);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
final String text = reader.lines().collect(Collectors.joining());
assertThat(text, is("Test"));
}
});
}
@Test
@DisplayName("Should not consume S3StreamObject when include body is false and should close the stream when autocloseBody is true")
public void shouldNotConsumeS3StreamObjectWhenIncludeBodyIsFalseAndCloseStreamWhenAutoCloseBodyIsTrue()
throws InterruptedException {
result.reset();
result.expectedMessageCount(2);
template.setDefaultEndpointUri("direct:includeBodyFalseAutoCloseTrue");
template.send("direct:putObject", exchange -> {
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test1.txt");
exchange.getIn().setBody("Test");
});
Map<String, Object> headers = new HashMap<>();
headers.put(AWS2S3Constants.KEY, "test1.txt");
headers.put(Exchange.FILE_NAME, "test1.txt");
template.sendBodyAndHeaders("direct:includeBodyFalseAutoCloseTrue", headers);
result.assertIsSatisfied();
final Exchange exchange = result.getExchanges().get(1);
assertThat(exchange.getIn().getBody().getClass(), is(equalTo(ResponseInputStream.class)));
assertThrows(IOException.class, () -> {
final ResponseInputStream<GetObjectResponse> inputStream = exchange.getIn().getBody(ResponseInputStream.class);
inputStream.read();
});
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
String template = "aws2-s3://mycamel?autoCreateBucket=true&includeBody=%s&autocloseBody=%s";
String includeBodyTrueAutoCloseTrue = String.format(template, true, true);
String includeBodyFalseAutoCloseFalse = String.format(template, false, false);
String includeBodyFalseAutoCloseTrue = String.format(template, false, true);
from("direct:includeBodyTrueAutoCloseTrue").pollEnrich(includeBodyTrueAutoCloseTrue, 5000).to("mock:result");
from("direct:includeBodyFalseAutoCloseFalse").pollEnrich(includeBodyFalseAutoCloseFalse, 5000)
.to("mock:result");
from("direct:includeBodyFalseAutoCloseTrue").pollEnrich(includeBodyFalseAutoCloseTrue, 5000).to("mock:result");
String awsEndpoint = "aws2-s3://mycamel?autoCreateBucket=false";
from("direct:putObject").startupOrder(1).to(awsEndpoint).to("mock:result");
from("aws2-s3://mycamel?moveAfterRead=true&destinationBucket=camel-kafka-connector&autoCreateBucket=false&destinationBucketPrefix=RAW(movedPrefix)&destinationBucketSuffix=RAW(movedSuffix)")
.startupOrder(2).log("${body}");
}
};
}
}
|
S3ConsumerManualIT
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/CustomObjectMapperTest.java
|
{
"start": 4835,
"end": 5361
}
|
class ____ implements ContextResolver<ObjectMapper> {
static final AtomicLong COUNT = new AtomicLong();
@Override
public ObjectMapper getContext(final Class<?> type) {
COUNT.incrementAndGet();
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE)
.enable(SerializationFeature.WRITE_ENUMS_USING_INDEX);
return objectMapper;
}
}
}
|
CustomObjectMapperContextResolver
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/indices/SystemIndexMappingUpdateService.java
|
{
"start": 2569,
"end": 7041
}
|
class ____ implements ClusterStateListener {
private static final Logger logger = LogManager.getLogger(SystemIndexMappingUpdateService.class);
public static final Set<String> MANAGED_SYSTEM_INDEX_SETTING_UPDATE_ALLOWLIST;
static {
Set<String> allowlist = new HashSet<>();
// Add all the blocks, we need to be able to clear those
for (IndexMetadata.APIBlock blockType : IndexMetadata.APIBlock.values()) {
allowlist.add(blockType.settingName());
}
MANAGED_SYSTEM_INDEX_SETTING_UPDATE_ALLOWLIST = Collections.unmodifiableSet(allowlist);
}
private final SystemIndices systemIndices;
private final Client client;
private final ProjectResolver projectResolver;
private final AtomicBoolean isUpgradeInProgress;
/**
* Creates a new manager
* @param systemIndices the indices to manage
* @param client used to update the cluster
*/
public SystemIndexMappingUpdateService(SystemIndices systemIndices, Client client, ProjectResolver projectResolver) {
this.systemIndices = systemIndices;
this.client = client;
this.projectResolver = projectResolver;
this.isUpgradeInProgress = new AtomicBoolean(false);
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
final ClusterState state = event.state();
if (state.blocks().hasGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK)) {
// wait until the gateway has recovered from disk, otherwise we may think we don't have some
// indices but they may not have been restored from the cluster state on disk
logger.debug("Waiting until state has been recovered");
return;
}
// If this node is not a master node, exit.
if (state.nodes().isLocalNodeElectedMaster() == false) {
return;
}
// if we're in a mixed-version cluster, exit
if (state.nodes().isMixedVersionCluster()) {
logger.debug("Skipping system indices up-to-date check as cluster has mixed versions");
return;
}
if (isUpgradeInProgress.compareAndSet(false, true)) {
// Use a RefCountingRunnable so that we only release the lock once all upgrade attempts have succeeded or failed.
// The failures are logged in upgradeIndexMetadata(), so we don't actually care about them here.
try (var refs = new RefCountingRunnable(() -> isUpgradeInProgress.set(false))) {
state.forEachProject(project -> {
for (SystemIndexDescriptor systemIndexDescriptor : getEligibleDescriptors(project.metadata())) {
UpgradeStatus upgradeStatus;
try {
upgradeStatus = getUpgradeStatus(project, systemIndexDescriptor);
} catch (Exception e) {
logger.warn(
Strings.format(
"Failed to calculate upgrade status for project [%s]: %s",
project.projectId(),
e.getMessage()
),
e
);
continue;
}
if (upgradeStatus == UpgradeStatus.NEEDS_MAPPINGS_UPDATE) {
upgradeIndexMappings(project.projectId(), systemIndexDescriptor, ActionListener.releasing(refs.acquire()));
}
}
});
}
} else {
logger.trace("Update already in progress");
}
}
/**
* Checks all known system index descriptors, looking for those that correspond to
* indices that can be automatically managed and that have already been created.
* @param projectMetadata the project metadata to consult
* @return a list of descriptors that could potentially be updated
*/
List<SystemIndexDescriptor> getEligibleDescriptors(ProjectMetadata projectMetadata) {
return this.systemIndices.getSystemIndexDescriptors()
.stream()
.filter(SystemIndexDescriptor::isAutomaticallyManaged)
.filter(d -> projectMetadata.hasIndexAbstraction(d.getPrimaryIndex()))
.toList();
}
|
SystemIndexMappingUpdateService
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java
|
{
"start": 56612,
"end": 56675
}
|
class ____ {
}
@TransactionalComponent
static
|
NonAnnotatedClass
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TrafficController.java
|
{
"start": 19363,
"end": 19713
}
|
class ____ dev eth0 parent 42:99 classid 42:99 htb rate 50mbit
// ceil 700mbit"
return String.format(FORMAT_CLASS_ADD_TO_PARENT_WITH_RATES, device,
ROOT_QDISC_HANDLE, YARN_ROOT_CLASS_ID, ROOT_QDISC_HANDLE, classId,
rateMbitStr, ceilMbitStr);
}
private String getStringForDeleteContainerClass(int classId) {
//example "
|
add
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/TaskImpl.java
|
{
"start": 47846,
"end": 48883
}
|
class ____
implements SingleArcTransition<TaskImpl, TaskEvent> {
@Override
public void transition(TaskImpl task, TaskEvent event) {
if (task.historyTaskStartGenerated) {
TaskFailedEvent taskFailedEvent = createTaskFailedEvent(task, null,
TaskStateInternal.KILLED, null); // TODO Verify failedAttemptId is null
task.eventHandler.handle(new JobHistoryEvent(task.taskId.getJobId(),
taskFailedEvent));
}else {
LOG.debug("Not generating HistoryFinish event since start event not" +
" generated for task: " + task.getID());
}
task.eventHandler.handle(new JobTaskEvent(task.taskId,
getExternalState(TaskStateInternal.KILLED)));
task.metrics.endWaitingTask(task);
}
}
private void killUnfinishedAttempt(TaskAttempt attempt, String logMsg) {
if (attempt != null && !attempt.isFinished()) {
eventHandler.handle(
new TaskAttemptKillEvent(attempt.getID(), logMsg));
}
}
private static
|
KillNewTransition
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/ser/jdk/MapKeySerializationTest.java
|
{
"start": 3320,
"end": 10802
}
|
class ____ extends ValueSerializer<Object>
{
@Override
public void serialize(Object value, JsonGenerator g, SerializationContext provider) {
g.writeName("DEFAULT:"+value);
}
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
final private ObjectMapper MAPPER = newJsonMapper();
@Test
public void testNotKarl() throws Exception {
final String serialized = MAPPER.writeValueAsString(new NotKarlBean());
assertEquals("{\"map\":{\"Not Karl\":1}}", serialized);
}
@Test
public void testKarl() throws Exception {
final String serialized = MAPPER.writeValueAsString(new KarlBean());
assertEquals("{\"map\":{\"Karl\":1}}", serialized);
}
// [databind#75]: caching of KeySerializers
@Test
public void testBoth() throws Exception
{
// Let's NOT use shared one, to ensure caching starts from clean slate
final ObjectMapper mapper = newJsonMapper();
final String value1 = mapper.writeValueAsString(new NotKarlBean());
assertEquals("{\"map\":{\"Not Karl\":1}}", value1);
final String value2 = mapper.writeValueAsString(new KarlBean());
assertEquals("{\"map\":{\"Karl\":1}}", value2);
}
// Test custom key serializer for enum
@Test
public void testCustomForEnum() throws Exception
{
// cannot use shared mapper as we are registering a module
SimpleModule mod = new SimpleModule("test");
mod.addKeySerializer(ABC.class, new ABCKeySerializer());
final ObjectMapper mapper = jsonMapperBuilder()
.addModule(mod)
.build();
String json = mapper.writeValueAsString(new ABCMapWrapper());
assertEquals("{\"stuff\":{\"xxxB\":\"bar\"}}", json);
}
@Test
public void testCustomNullSerializers() throws Exception
{
final SimpleModule mod = new SimpleModule()
.setDefaultNullKeySerializer(new NullKeySerializer("NULL-KEY"))
.setDefaultNullValueSerializer(new NullValueSerializer("NULL"));
final ObjectMapper mapper = jsonMapperBuilder()
.addModule(mod)
.build();
Map<String,Integer> input = new HashMap<>();
input.put(null, 3);
String json = mapper.writeValueAsString(input);
assertEquals("{\"NULL-KEY\":3}", json);
json = mapper.writeValueAsString(new Object[] { 1, null, true });
assertEquals("[1,\"NULL\",true]", json);
}
@Test
public void testCustomEnumInnerMapKey() throws Exception {
Map<Outer, Object> outerMap = new HashMap<Outer, Object>();
Map<ABC, Map<String, String>> map = new EnumMap<ABC, Map<String, String>>(ABC.class);
Map<String, String> innerMap = new HashMap<String, String>();
innerMap.put("one", "1");
map.put(ABC.A, innerMap);
outerMap.put(Outer.inner, map);
SimpleModule mod = new SimpleModule("test")
.setMixInAnnotation(ABC.class, ABCMixin.class)
.addKeySerializer(ABC.class, new ABCKeySerializer())
;
final ObjectMapper mapper = jsonMapperBuilder()
.addModule(mod)
.build();
JsonNode tree = mapper.convertValue(outerMap, JsonNode.class);
JsonNode innerNode = tree.get("inner");
String key = innerNode.propertyNames().iterator().next();
assertEquals("xxxA", key);
}
// 02-Nov-2020, tatu: No more "default key serializer" in 3.0, hence no test
/*
@Test
public void testDefaultKeySerializer() throws Exception
{
final SimpleModule mod = new SimpleModule()
.setDefaultNullKeySerializer(new NullKeySerializer("NULL-KEY"))
// 10-Oct-2019, tatu: Does not exist in 3.0.0 any more./..
.setDefaultKeySerializer(new DefaultKeySerializer());
;
final ObjectMapper mapper = jsonMapperBuilder()
.addModule(mod)
.build();
Map<String,String> map = new HashMap<String,String>();
map.put("a", "b");
assertEquals("{\"DEFAULT:a\":\"b\"}", m.writeValueAsString(map));
}
*/
// [databind#682]
@Test
public void testClassKey() throws Exception
{
Map<Class<?>,Integer> map = new LinkedHashMap<Class<?>,Integer>();
map.put(String.class, 2);
String json = MAPPER.writeValueAsString(map);
assertEquals(a2q("{'java.lang.String':2}"), json);
}
// [databind#838]
@Test
public void testUnWrappedMapWithKeySerializer() throws Exception{
SimpleModule mod = new SimpleModule("test");
mod.addKeySerializer(ABC.class, new ABCKeySerializer());
final ObjectMapper mapper = jsonMapperBuilder()
.changeDefaultPropertyInclusion(incl -> incl.withValueInclusion(JsonInclude.Include.NON_EMPTY))
.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
.disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS)
.addModule(mod)
.build()
;
Map<ABC,BAR<?>> stuff = new HashMap<ABC,BAR<?>>();
stuff.put(ABC.B, new BAR<String>("bar"));
String json = mapper.writerFor(new TypeReference<Map<ABC,BAR<?>>>() {})
.writeValueAsString(stuff);
assertEquals("{\"xxxB\":\"bar\"}", json);
}
// [databind#838]
@Test
public void testUnWrappedMapWithDefaultType() throws Exception{
SimpleModule mod = new SimpleModule("test");
mod.addKeySerializer(ABC.class, new ABCKeySerializer());
TypeResolverBuilder<?> typer = new DefaultTypeResolverBuilder(
NoCheckSubTypeValidator.instance,
DefaultTyping.NON_FINAL,
JsonTypeInfo.As.PROPERTY, JsonTypeInfo.Id.NAME, null)
.typeIdVisibility(true);
ObjectMapper mapper = jsonMapperBuilder()
.addModule(mod)
.setDefaultTyping(typer)
.build();
Map<ABC,String> stuff = new HashMap<ABC,String>();
stuff.put(ABC.B, "bar");
String json = mapper.writerFor(new TypeReference<Map<ABC, String>>() {})
.writeValueAsString(stuff);
assertEquals("{\"@type\":\"HashMap\",\"xxxB\":\"bar\"}", json);
}
// [databind#1552]
@Test
public void testMapsWithBinaryKeys() throws Exception
{
byte[] binary = new byte[] { 1, 2, 3, 4, 5 };
// First, using wrapper
MapWrapper<byte[], String> input = new MapWrapper<>(binary, "stuff");
String expBase64 = Base64Variants.MIME.encode(binary);
assertEquals(a2q("{'map':{'"+expBase64+"':'stuff'}}"),
MAPPER.writeValueAsString(input));
// and then dynamically..
Map<byte[],String> map = new LinkedHashMap<>();
map.put(binary, "xyz");
assertEquals(a2q("{'"+expBase64+"':'xyz'}"),
MAPPER.writeValueAsString(map));
}
// [databind#1679]
@Test
public void testMapKeyRecursion1679() throws Exception
{
Map<Object, Object> objectMap = new HashMap<Object, Object>();
objectMap.put(new Object(), "foo");
String json = MAPPER.writeValueAsString(objectMap);
assertNotNull(json);
}
}
|
DefaultKeySerializer
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/throughput/ThroughputCalculator.java
|
{
"start": 1063,
"end": 3423
}
|
class ____ {
private static final long NOT_TRACKED = -1;
private final Clock clock;
private static final long MILLIS_IN_SECOND = 1000;
private long currentThroughput;
private long currentAccumulatedDataSize;
private long currentMeasurementTime;
private long measurementStartTime = NOT_TRACKED;
public ThroughputCalculator(Clock clock) {
this.clock = clock;
}
public void incomingDataSize(long receivedDataSize) {
// Force resuming measurement.
if (measurementStartTime == NOT_TRACKED) {
measurementStartTime = clock.absoluteTimeMillis();
}
currentAccumulatedDataSize += receivedDataSize;
}
/** Mark when the time should not be taken into account. */
public void pauseMeasurement() {
if (measurementStartTime != NOT_TRACKED) {
currentMeasurementTime += clock.absoluteTimeMillis() - measurementStartTime;
}
measurementStartTime = NOT_TRACKED;
}
/** Mark when the time should be included to the throughput calculation. */
public void resumeMeasurement() {
if (measurementStartTime == NOT_TRACKED) {
measurementStartTime = clock.absoluteTimeMillis();
}
}
/**
* @return Calculated throughput based on the collected data for the last period.
*/
public long calculateThroughput() {
if (measurementStartTime != NOT_TRACKED) {
long absoluteTimeMillis = clock.absoluteTimeMillis();
currentMeasurementTime += absoluteTimeMillis - measurementStartTime;
measurementStartTime = absoluteTimeMillis;
}
long throughput = calculateThroughput(currentAccumulatedDataSize, currentMeasurementTime);
currentAccumulatedDataSize = currentMeasurementTime = 0;
return throughput;
}
public long calculateThroughput(long dataSize, long time) {
checkArgument(dataSize >= 0, "Size of data should be non negative");
checkArgument(time >= 0, "Time should be non negative");
if (time == 0) {
return currentThroughput;
}
return currentThroughput = instantThroughput(dataSize, time);
}
static long instantThroughput(long dataSize, long time) {
return (long) ((double) dataSize / time * MILLIS_IN_SECOND);
}
}
|
ThroughputCalculator
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/generics/CatTests.java
|
{
"start": 856,
"end": 1088
}
|
class ____ integration tests that demonstrate support for
* Java generics in JUnit Jupiter test classes when used with the Spring TestContext
* Framework and the {@link SpringExtension}.
*
* @author Sam Brannen
* @since 5.0
*/
|
for
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/EmbeddableInitializer.java
|
{
"start": 655,
"end": 1688
}
|
interface ____<Data extends InitializerData> extends InitializerParent<Data> {
@Override
EmbeddableValuedModelPart getInitializedPart();
@Override
@Nullable InitializerParent<?> getParent();
@Override
default boolean isEmbeddableInitializer() {
return true;
}
@Override
default EmbeddableInitializer<?> asEmbeddableInitializer() {
return this;
}
/**
* Resets the resolved entity registrations by i.e. removing {@link org.hibernate.engine.spi.EntityHolder}.
*
* This is used after {@link org.hibernate.sql.results.graph.entity.EntityInitializer#resolveEntityKeyOnly(RowProcessingState)}
* to deregister registrations for entities that were only resolved, but not initialized.
* Failing to do this will lead to errors, because {@link org.hibernate.engine.spi.PersistenceContext#postLoad(JdbcValuesSourceProcessingState, Consumer)}
* is called, which expects all registrations to be fully initialized.
*/
void resetResolvedEntityRegistrations(RowProcessingState rowProcessingState);
}
|
EmbeddableInitializer
|
java
|
apache__flink
|
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/data/DataFormatConvertersTest.java
|
{
"start": 10301,
"end": 10852
}
|
class ____ {
public int f1 = 0;
public int f2 = 0;
public MyPojo() {}
public MyPojo(int f1, int f2) {
this.f1 = f1;
this.f2 = f2;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MyPojo myPojo = (MyPojo) o;
return f1 == myPojo.f1 && f2 == myPojo.f2;
}
}
}
|
MyPojo
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/context/aot/RuntimeHintsBeanFactoryInitializationAotProcessor.java
|
{
"start": 2051,
"end": 4089
}
|
class ____ implements BeanFactoryInitializationAotProcessor {
private static final Log logger = LogFactory.getLog(RuntimeHintsBeanFactoryInitializationAotProcessor.class);
@Override
public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
Map<Class<? extends RuntimeHintsRegistrar>, RuntimeHintsRegistrar> registrars = AotServices
.factories(beanFactory.getBeanClassLoader()).load(RuntimeHintsRegistrar.class).stream()
.collect(LinkedHashMap::new, (map, item) -> map.put(item.getClass(), item), Map::putAll);
extractFromBeanFactory(beanFactory).forEach(registrarClass ->
registrars.computeIfAbsent(registrarClass, BeanUtils::instantiateClass));
return new RuntimeHintsRegistrarContribution(registrars.values(), beanFactory.getBeanClassLoader());
}
private Set<Class<? extends RuntimeHintsRegistrar>> extractFromBeanFactory(ConfigurableListableBeanFactory beanFactory) {
Set<Class<? extends RuntimeHintsRegistrar>> registrarClasses = new LinkedHashSet<>();
for (String beanName : beanFactory.getBeanDefinitionNames()) {
beanFactory.findAllAnnotationsOnBean(beanName, ImportRuntimeHints.class, true)
.forEach(annotation -> registrarClasses.addAll(extractFromBeanDefinition(beanName, annotation)));
}
return registrarClasses;
}
private Set<Class<? extends RuntimeHintsRegistrar>> extractFromBeanDefinition(String beanName,
ImportRuntimeHints annotation) {
Class<? extends RuntimeHintsRegistrar>[] registrarClasses = annotation.value();
Set<Class<? extends RuntimeHintsRegistrar>> registrars = CollectionUtils.newLinkedHashSet(registrarClasses.length);
for (Class<? extends RuntimeHintsRegistrar> registrarClass : registrarClasses) {
if (logger.isTraceEnabled()) {
logger.trace(LogMessage.format("Loaded [%s] registrar from annotated bean [%s]",
registrarClass.getCanonicalName(), beanName));
}
registrars.add(registrarClass);
}
return registrars;
}
static
|
RuntimeHintsBeanFactoryInitializationAotProcessor
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-csi/src/main/java/org/apache/hadoop/yarn/csi/translator/ValidationVolumeCapabilitiesResponseProtoTranslator.java
|
{
"start": 1202,
"end": 1985
}
|
class ____<A, B>
implements ProtoTranslator<ValidateVolumeCapabilitiesResponse,
Csi.ValidateVolumeCapabilitiesResponse> {
@Override
public Csi.ValidateVolumeCapabilitiesResponse convertTo(
ValidateVolumeCapabilitiesResponse response) throws YarnException {
return Csi.ValidateVolumeCapabilitiesResponse.newBuilder()
.setSupported(response.isSupported())
.setMessage(response.getResponseMessage())
.build();
}
@Override
public ValidateVolumeCapabilitiesResponse convertFrom(
Csi.ValidateVolumeCapabilitiesResponse response) throws YarnException {
return ValidateVolumeCapabilitiesResponse.newInstance(
response.getSupported(), response.getMessage());
}
}
|
ValidationVolumeCapabilitiesResponseProtoTranslator
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/reactive/CommandReactiveService.java
|
{
"start": 1138,
"end": 3033
}
|
class ____ extends CommandAsyncService implements CommandReactiveExecutor {
CommandReactiveService(CommandAsyncExecutor executor, boolean trackChanges) {
super(executor, trackChanges);
}
CommandReactiveService(ConnectionManager connectionManager, RedissonObjectBuilder objectBuilder) {
super(connectionManager, objectBuilder, RedissonObjectBuilder.ReferenceType.REACTIVE);
}
CommandReactiveService(CommandAsyncExecutor executor, ObjectParams objectParams) {
super(executor, objectParams);
}
@Override
public CommandReactiveExecutor copy(boolean trackChanges) {
return new CommandReactiveService(this, trackChanges);
}
@Override
public CommandReactiveExecutor copy(ObjectParams objectParams) {
return new CommandReactiveService(this, objectParams);
}
@Override
public <R> Mono<R> reactive(Callable<RFuture<R>> supplier) {
return Flux.<R>create(emitter -> {
emitter.onRequest(n -> {
RFuture<R> future;
try {
future = supplier.call();
} catch (Exception e) {
emitter.error(e);
return;
}
emitter.onDispose(() -> {
future.cancel(true);
});
future.whenComplete((v, e) -> {
if (e != null) {
if (e instanceof CompletionException) {
e = e.getCause();
}
emitter.error(e);
return;
}
if (v != null) {
emitter.next(v);
}
emitter.complete();
});
});
}).next();
}
}
|
CommandReactiveService
|
java
|
quarkusio__quarkus
|
integration-tests/spring-web/src/main/java/io/quarkus/it/spring/web/Person.java
|
{
"start": 91,
"end": 278
}
|
class ____ {
@NotBlank
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
Person
|
java
|
spring-cloud__spring-cloud-gateway
|
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestHeaderSizeGatewayFilterFactory.java
|
{
"start": 1713,
"end": 4084
}
|
class ____
extends AbstractGatewayFilterFactory<RequestHeaderSizeGatewayFilterFactory.Config> {
private static String ERROR_PREFIX = "Request Header/s size is larger than permissible limit (%s).";
private static String ERROR = " Request Header/s size for '%s' is %s.";
public RequestHeaderSizeGatewayFilterFactory() {
super(RequestHeaderSizeGatewayFilterFactory.Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Collections.singletonList("maxSize");
}
@Override
public GatewayFilter apply(RequestHeaderSizeGatewayFilterFactory.Config config) {
String errorHeaderName = config.getErrorHeaderName() != null ? config.getErrorHeaderName() : "errorMessage";
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
HashMap<String, Long> longHeaders = new HashMap<>();
for (Map.Entry<String, List<String>> headerEntry : headers.headerSet()) {
long headerSizeInBytes = 0L;
headerSizeInBytes += headerEntry.getKey().getBytes().length;
List<String> values = headerEntry.getValue();
for (String value : values) {
headerSizeInBytes += value.getBytes().length;
}
if (headerSizeInBytes > config.getMaxSize().toBytes()) {
longHeaders.put(headerEntry.getKey(), headerSizeInBytes);
}
}
if (!longHeaders.isEmpty()) {
exchange.getResponse().setStatusCode(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE);
exchange.getResponse()
.getHeaders()
.add(errorHeaderName, getErrorMessage(longHeaders, config.getMaxSize()));
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public String toString() {
return filterToStringCreator(RequestHeaderSizeGatewayFilterFactory.this)
.append("maxSize", config.getMaxSize())
.toString();
}
};
}
private static String getErrorMessage(HashMap<String, Long> longHeaders, DataSize maxSize) {
StringBuilder msg = new StringBuilder(String.format(ERROR_PREFIX, maxSize));
longHeaders
.forEach((header, size) -> msg.append(String.format(ERROR, header, DataSize.of(size, DataUnit.BYTES))));
return msg.toString();
}
public static
|
RequestHeaderSizeGatewayFilterFactory
|
java
|
spring-projects__spring-boot
|
module/spring-boot-gson/src/main/java/org/springframework/boot/gson/autoconfigure/GsonAutoConfiguration.java
|
{
"start": 1675,
"end": 2211
}
|
class ____ {
@Bean
@ConditionalOnMissingBean
GsonBuilder gsonBuilder(List<GsonBuilderCustomizer> customizers) {
GsonBuilder builder = new GsonBuilder();
customizers.forEach((c) -> c.customize(builder));
return builder;
}
@Bean
@ConditionalOnMissingBean
Gson gson(GsonBuilder gsonBuilder) {
return gsonBuilder.create();
}
@Bean
StandardGsonBuilderCustomizer standardGsonBuilderCustomizer(GsonProperties gsonProperties) {
return new StandardGsonBuilderCustomizer(gsonProperties);
}
static final
|
GsonAutoConfiguration
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/FieldCanBeFinalTest.java
|
{
"start": 10752,
"end": 10954
}
|
interface ____ {}
""")
.addSourceLines(
"Test.java",
"""
import com.googlecode.objectify.v4.annotation.Entity;
@Entity
|
Entity
|
java
|
apache__camel
|
components/camel-openapi-java/src/test/java/org/apache/camel/openapi/model/OneOfFormWrapper.java
|
{
"start": 1073,
"end": 1810
}
|
class ____ {
@JsonProperty("formType")
String formType;
@JsonProperty("form")
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "code")
@JsonSubTypes({
@Type(value = XOfFormA.class, name = "Form A"),
@Type(value = XOfFormB.class, name = "Form B")
})
OneOfForm form;
public String getFormType() {
return this.formType;
}
public void setFormType(String formType) {
this.formType = formType;
}
public OneOfForm getForm() {
return this.form;
}
public void setForm(OneOfForm form) {
this.form = form;
}
}
|
OneOfFormWrapper
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/metrics/ReporterSetupBuilder.java
|
{
"start": 7602,
"end": 7858
}
|
interface ____ unify access to different reporter factories that don't have a proper
* superclass.
*
* @param <REPORTER_FACTORY> type of the reporter factory.
* @param <REPORTER> type of the reporter.
*/
@FunctionalInterface
|
to
|
java
|
apache__camel
|
components/camel-stax/src/test/java/org/apache/camel/language/xtokenizer/XMLTokenizeWrapLanguageGroupingTest.java
|
{
"start": 1137,
"end": 9190
}
|
class ____ extends CamelTestSupport {
@Test
public void testSendClosedTagMessageToTokenize() throws Exception {
String expected
= "<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child some_attr='a' anotherAttr='a'></c:child>"
+ "<c:child some_attr='b' anotherAttr='b'></c:child></c:parent>";
template
.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child some_attr='a' anotherAttr='a'></c:child><c:child some_attr='b' anotherAttr='b'></c:child></c:parent>");
verify(expected);
}
@Test
public void testSendClosedTagWithLineBreaksMessageToTokenize() throws Exception {
String expected
= "<?xml version='1.0' encoding='UTF-8'?>\n<c:parent xmlns:c='urn:c'>\n<c:child some_attr='a' anotherAttr='a'>\n</c:child>"
+ "<c:child some_attr='b' anotherAttr='b'>\n</c:child></c:parent>";
template.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?>\n" + "<c:parent xmlns:c='urn:c'>\n"
+ "<c:child some_attr='a' anotherAttr='a'>\n" + "</c:child>\n"
+ "<c:child some_attr='b' anotherAttr='b'>\n" + "</c:child>\n" + "</c:parent>");
verify(expected);
}
@Test
public void testSendSelfClosingTagMessageToTokenize() throws Exception {
String expected
= "<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child some_attr='a' anotherAttr='a' />"
+ "<c:child some_attr='b' anotherAttr='b' /></c:parent>";
template
.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child some_attr='a' anotherAttr='a' /><c:child some_attr='b' anotherAttr='b' /></c:parent>");
verify(expected);
}
@Test
public void testSendMixedClosingTagMessageToTokenize() throws Exception {
String[] expected = new String[] {
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child some_attr='a' anotherAttr='a'>ha</c:child>"
+ "<c:child some_attr='b' anotherAttr='b' /></c:parent>",
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child some_attr='c'></c:child></c:parent>" };
template.sendBody(
"direct:start",
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child some_attr='a' anotherAttr='a'>ha</c:child>"
+ "<c:child some_attr='b' anotherAttr='b' /><c:child some_attr='c'></c:child></c:parent>");
verify(expected);
}
@Test
public void testSendMixedClosingTagInsideMessageToTokenize() throws Exception {
String expected
= "<c:parent xmlns:c='urn:c'><c:child name='child1'><grandchild name='grandchild1'/> <grandchild name='grandchild2'/></c:child>"
+ "<c:child name='child2'><grandchild name='grandchild1'></grandchild><grandchild name='grandchild2'></grandchild></c:child></c:parent>";
template.sendBody(
"direct:start",
"<c:parent xmlns:c='urn:c'><c:child name='child1'><grandchild name='grandchild1'/> <grandchild name='grandchild2'/></c:child>"
+ "<c:child name='child2'><grandchild name='grandchild1'></grandchild><grandchild name='grandchild2'></grandchild></c:child></c:parent>");
verify(expected);
}
@Test
public void testSendNamespacedChildMessageToTokenize() throws Exception {
String expected
= "<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child xmlns:c='urn:c' some_attr='a' anotherAttr='a'></c:child>"
+ "<c:child xmlns:c='urn:c' some_attr='b' anotherAttr='b' /></c:parent>";
template.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child xmlns:c='urn:c' some_attr='a' anotherAttr='a'></c:child>"
+ "<c:child xmlns:c='urn:c' some_attr='b' anotherAttr='b' /></c:parent>");
verify(expected);
}
@Test
public void testSendNamespacedParentMessageToTokenize() throws Exception {
String expected
= "<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c' xmlns:d=\"urn:d\"><c:child some_attr='a' anotherAttr='a'></c:child>"
+ "<c:child some_attr='b' anotherAttr='b'/></c:parent>";
template
.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c' xmlns:d=\"urn:d\"><c:child some_attr='a' anotherAttr='a'></c:child><c:child some_attr='b' anotherAttr='b'/></c:parent>");
verify(expected);
}
@Test
public void testSendMoreParentsMessageToTokenize() throws Exception {
String expected
= "<?xml version='1.0' encoding='UTF-8'?><g:greatgrandparent xmlns:g='urn:g'><grandparent><uncle/><aunt>emma</aunt><c:parent xmlns:c='urn:c' xmlns:d=\"urn:d\">"
+ "<c:child some_attr='a' anotherAttr='a'></c:child>"
+ "<c:child some_attr='b' anotherAttr='b'/></c:parent></grandparent></g:greatgrandparent>";
template
.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?><g:greatgrandparent xmlns:g='urn:g'><grandparent><uncle/><aunt>emma</aunt><c:parent xmlns:c='urn:c' xmlns:d=\"urn:d\">"
+ "<c:child some_attr='a' anotherAttr='a'></c:child><c:child some_attr='b' anotherAttr='b'/></c:parent></grandparent></g:greatgrandparent>");
verify(expected);
}
@Test
public void testSendParentMessagesWithDifferentAttributesToTokenize() throws Exception {
String[] expected = new String[] {
"<?xml version='1.0' encoding='UTF-8'?><g:grandparent xmlns:g='urn:g'><c:parent name='e' xmlns:c='urn:c' xmlns:d=\"urn:d\">"
+ "<c:child some_attr='a' anotherAttr='a'></c:child></c:parent></g:grandparent>",
"<?xml version='1.0' encoding='UTF-8'?><g:grandparent xmlns:g='urn:g'><c:parent name='f' xmlns:c='urn:c' xmlns:d=\"urn:d\">"
+ "<c:child some_attr='b' anotherAttr='b'/></c:parent></g:grandparent>" };
template
.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?><g:grandparent xmlns:g='urn:g'><c:parent name='e' xmlns:c='urn:c' xmlns:d=\"urn:d\">"
+ "<c:child some_attr='a' anotherAttr='a'></c:child></c:parent><c:parent name='f' xmlns:c='urn:c' xmlns:d=\"urn:d\"><c:child some_attr='b' anotherAttr='b'/>"
+ "</c:parent></g:grandparent>");
verify(expected);
}
private void verify(String... expected) throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(expected.length);
MockEndpoint.assertIsSatisfied(context);
int i = 0;
for (String target : expected) {
String body = getMockEndpoint("mock:result").getReceivedExchanges().get(i).getMessage().getBody(String.class);
XmlAssert.assertThat(body).and(target).areIdentical();
i++;
}
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
Namespaces ns = new Namespaces("C", "urn:c");
public void configure() {
from("direct:start").split().xtokenize("//C:child", 'w', ns, 2).to("mock:result").end();
}
};
}
}
|
XMLTokenizeWrapLanguageGroupingTest
|
java
|
apache__dubbo
|
dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/TelnetUtilsTest.java
|
{
"start": 1062,
"end": 2496
}
|
class ____ {
/**
* abc - abc - abc
* 1 - 2 - 3
* x - y - z
*/
@Test
void testToList() {
List<List<String>> table = new LinkedList<>();
table.add(Arrays.asList("abc", "abc", "abc"));
table.add(Arrays.asList("1", "2", "3"));
table.add(Arrays.asList("x", "y", "z"));
String toList = TelnetUtils.toList(table);
Assertions.assertTrue(toList.contains("abc - abc - abc"));
Assertions.assertTrue(toList.contains("1 - 2 - 3"));
Assertions.assertTrue(toList.contains("x - y - z"));
}
/**
* +-----+-----+-----+
* | A | B | C |
* +-----+-----+-----+
* | abc | abc | abc |
* | 1 | 2 | 3 |
* | x | y | z |
* +-----+-----+-----+
*/
@Test
void testToTable() {
List<List<String>> table = new LinkedList<>();
table.add(Arrays.asList("abc", "abc", "abc"));
table.add(Arrays.asList("1", "2", "3"));
table.add(Arrays.asList("x", "y", "z"));
String toTable = TelnetUtils.toTable(new String[] {"A", "B", "C"}, table);
Assertions.assertTrue(toTable.contains("| A | B | C |"));
Assertions.assertTrue(toTable.contains("| abc | abc | abc |"));
Assertions.assertTrue(toTable.contains("| 1 | 2 | 3 |"));
Assertions.assertTrue(toTable.contains("| x | y | z |"));
}
}
|
TelnetUtilsTest
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jdbc/src/test/java/org/springframework/boot/jdbc/autoconfigure/health/DataSourceHealthContributorAutoConfigurationTests.java
|
{
"start": 14162,
"end": 14743
}
|
class ____ {
@Bean
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
DataSource dataSourcePrototype(String username, String password) {
return createHikariDataSource(username, password);
}
private HikariDataSource createHikariDataSource(String username, String password) {
String url = "jdbc:hsqldb:mem:test-" + UUID.randomUUID();
HikariDataSource hikariDataSource = DataSourceBuilder.create()
.url(url)
.type(HikariDataSource.class)
.username(username)
.password(password)
.build();
return hikariDataSource;
}
}
}
|
PrototypeDataSourceConfiguration
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/time/JodaPlusMinusLongTest.java
|
{
"start": 7516,
"end": 8546
}
|
class ____ {
private static final Duration D = Duration.ZERO;
// BUG: Diagnostic contains: DateMidnight.now().plus(Duration.millis(42L));
private static final DateMidnight PLUS = DateMidnight.now().plus(42L);
// BUG: Diagnostic contains: DateMidnight.now().plus(D);
private static final DateMidnight PLUS2 = DateMidnight.now().plus(D.getMillis());
// BUG: Diagnostic contains: DateMidnight.now().minus(Duration.millis(42L));
private static final DateMidnight MINUS = DateMidnight.now().minus(42L);
// BUG: Diagnostic contains: DateMidnight.now().minus(D);
private static final DateMidnight MINUS2 = DateMidnight.now().minus(D.getMillis());
}
""")
.doTest();
}
@Test
public void dateMidnightPlusMinusLong_insideJodaTime() {
helper
.addSourceLines(
"TestClass.java",
"""
package org.joda.time;
public
|
TestClass
|
java
|
FasterXML__jackson-core
|
src/test/java/tools/jackson/core/unittest/filter/ParserFilterEmpty1418Test.java
|
{
"start": 1214,
"end": 8898
}
|
class ____ extends TokenFilter {
@Override
public TokenFilter includeProperty(String name) {
if ("one".equals(name)) {
return this;
}
return null;
}
@Override
public boolean includeEmptyObject(boolean contentsFiltered) {
return true;
}
}
/*
/**********************************************************************
/* Test methods, original
/**********************************************************************
*/
private final JsonFactory JSON_F = newStreamFactory();
// [core#1418]: case #1
@Test
void filterArrayWithObjectsEndingWithFilteredProperty1() throws Exception
{
final String json = "[{\"one\":1},{\"two\":2}]";
JsonParser p0 = _createParser(JSON_F, json);
JsonParser p = new FilteringParserDelegate(p0,
new OnePropertyFilter1418Orig(),
Inclusion.INCLUDE_ALL_AND_PATH,
true // multipleMatches
);
// Expected output: [{"one":1}]
assertToken(JsonToken.START_ARRAY, p.nextToken());
_assertOneObject(p);
// Second object has no "one" property, should be filtered out
assertToken(JsonToken.END_ARRAY, p.nextToken());
assertNull(p.nextToken());
p.close();
}
// [core#1418]: case #2
@Test
void filterArrayWithObjectsEndingWithFilteredProperty2() throws Exception
{
final String json = "[{\"one\":1},{\"one\":1,\"two\":2}]";
JsonParser p0 = _createParser(JSON_F, json);
JsonParser p = new FilteringParserDelegate(p0,
new OnePropertyFilter1418Orig(),
Inclusion.INCLUDE_ALL_AND_PATH,
true // multipleMatches
);
// Expected output: [{"one":1},{"one":1}]
assertToken(JsonToken.START_ARRAY, p.nextToken());
_assertOneObject(p);
_assertOneObject(p);
assertToken(JsonToken.END_ARRAY, p.nextToken());
assertNull(p.nextToken());
p.close();
}
// [core#1418]: case #3
@Test
void filterArrayWithObjectsEndingWithFilteredProperty3() throws Exception
{
final String json = "[{\"one\":1},{\"one\":1,\"two\":2},{\"one\":1}]";
JsonParser p0 = _createParser(JSON_F, json);
JsonParser p = new FilteringParserDelegate(p0,
new OnePropertyFilter1418Orig(),
Inclusion.INCLUDE_ALL_AND_PATH,
true // multipleMatches
);
// Expected output: [{"one":1},{"one":1},{"one":1}]
assertToken(JsonToken.START_ARRAY, p.nextToken());
_assertOneObject(p);
_assertOneObject(p);
_assertOneObject(p);
assertToken(JsonToken.END_ARRAY, p.nextToken());
assertNull(p.nextToken());
p.close();
}
// One additional test, for excluding all properties
@Test
void filterWithEmptyArray() throws Exception
{
final String json = "[{\"two\":2},{\"three\":3}]";
JsonParser p0 = _createParser(JSON_F, json);
JsonParser p = new FilteringParserDelegate(p0,
new OnePropertyFilter1418Orig(),
Inclusion.INCLUDE_ALL_AND_PATH,
true // multipleMatches
);
// Expected output: []
assertToken(JsonToken.START_ARRAY, p.nextToken());
assertToken(JsonToken.END_ARRAY, p.nextToken());
assertNull(p.nextToken());
p.close();
}
/*
/**********************************************************************
/* Test methods, with corrected "empty Object" filtering
/**********************************************************************
*/
// [core#1418]: case #1 / corrected
@Test
void filterArray1Corrected() throws Exception
{
final String json = "[{\"one\":1},{\"two\":2}]";
JsonParser p0 = _createParser(JSON_F, json);
JsonParser p = new FilteringParserDelegate(p0,
new OnePropertyFilter1418Fixed(),
Inclusion.INCLUDE_ALL_AND_PATH,
true // multipleMatches
);
// Expected output: [{"one":1}]
assertToken(JsonToken.START_ARRAY, p.nextToken());
_assertOneObject(p);
// Second object has no "one" property, should be included as empty
_assertEmptyObject(p);
assertToken(JsonToken.END_ARRAY, p.nextToken());
assertNull(p.nextToken());
p.close();
}
// [core#1418]: case #2 / corrected
@Test
void filterArray2Corrected() throws Exception
{
final String json = "[{\"one\":1},{\"one\":1,\"two\":2}]";
JsonParser p0 = _createParser(JSON_F, json);
JsonParser p = new FilteringParserDelegate(p0,
new OnePropertyFilter1418Fixed(),
Inclusion.INCLUDE_ALL_AND_PATH,
true // multipleMatches
);
// Expected output: [{"one":1},{"one":1}]
assertToken(JsonToken.START_ARRAY, p.nextToken());
_assertOneObject(p);
_assertOneObject(p);
assertToken(JsonToken.END_ARRAY, p.nextToken());
assertNull(p.nextToken());
p.close();
}
// [core#1418]: case #3 / corrected
@Test
void filterArray3Corrected() throws Exception
{
final String json = "[{\"one\":1},{\"one\":1,\"two\":2},{\"one\":1}]";
JsonParser p0 = _createParser(JSON_F, json);
JsonParser p = new FilteringParserDelegate(p0,
new OnePropertyFilter1418Fixed(),
Inclusion.INCLUDE_ALL_AND_PATH,
true // multipleMatches
);
// Expected output: [{"one":1},{"one":1},{"one":1}]
assertToken(JsonToken.START_ARRAY, p.nextToken());
_assertOneObject(p);
_assertOneObject(p);
_assertOneObject(p);
assertToken(JsonToken.END_ARRAY, p.nextToken());
assertNull(p.nextToken());
p.close();
}
// Case #4, extra
@Test
void filterArray4Corrected() throws Exception
{
final String json = "[{\"two\":2},{\"three\":3}]";
JsonParser p0 = _createParser(JSON_F, json);
JsonParser p = new FilteringParserDelegate(p0,
new OnePropertyFilter1418Fixed(),
Inclusion.INCLUDE_ALL_AND_PATH,
true // multipleMatches
);
// Expected output: [{},{}]
assertToken(JsonToken.START_ARRAY, p.nextToken());
_assertEmptyObject(p);
_assertEmptyObject(p);
assertToken(JsonToken.END_ARRAY, p.nextToken());
assertNull(p.nextToken());
p.close();
}
/*
/**********************************************************************
/* Helper methods
/**********************************************************************
*/
private JsonParser _createParser(TokenStreamFactory f, String json) throws Exception {
return f.createParser(ObjectReadContext.empty(), json);
}
private void _assertOneObject(JsonParser p) throws Exception {
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
assertEquals("one", p.currentName());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertEquals(1, p.getIntValue());
assertToken(JsonToken.END_OBJECT, p.nextToken());
}
private void _assertEmptyObject(JsonParser p) throws Exception {
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.END_OBJECT, p.nextToken());
}
}
|
OnePropertyFilter1418Fixed
|
java
|
apache__spark
|
sql/core/src/test/java/test/org/apache/spark/sql/connector/JavaColumnarDataSourceV2.java
|
{
"start": 1566,
"end": 1636
}
|
class ____ implements TestingV2Source {
static
|
JavaColumnarDataSourceV2
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/operations/converters/table/AbstractCreateTableConverter.java
|
{
"start": 1874,
"end": 2077
}
|
class ____<T extends SqlCreateTable>
implements SqlNodeConverter<T> {
/** Context of create table converters while merging source and derived items. */
protected
|
AbstractCreateTableConverter
|
java
|
quarkusio__quarkus
|
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanInfo.java
|
{
"start": 22599,
"end": 23181
}
|
class ____ a JDK package
packageName = AbstractGenerator.DEFAULT_PACKAGE;
}
return packageName;
}
public String getClientProxyPackageName() {
if (isProducer()) {
AnnotationTarget target = getTarget().get();
DotName typeName = target.kind() == Kind.FIELD ? target.asField().type().name()
: target.asMethod().returnType().name();
String packageName = DotNames.packagePrefix(typeName);
if (packageName.startsWith("java.")) {
// It is not possible to place a
|
in
|
java
|
quarkusio__quarkus
|
integration-tests/cache/src/main/java/io/quarkus/it/cache/CaffeineResource.java
|
{
"start": 1914,
"end": 2265
}
|
class ____ implements CacheLoader<String, String> {
@Override
public String load(String unused) throws Exception {
return null;
}
@Override
public Map<String, String> loadAll(Set<? extends String> unused) throws Exception {
return Collections.emptyMap();
}
}
}
|
MyBulkCacheLoader
|
java
|
netty__netty
|
codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicheQuicConnection.java
|
{
"start": 1066,
"end": 7640
}
|
class ____ {
private static final int TOTAL_RECV_INFO_SIZE = Quiche.SIZEOF_QUICHE_RECV_INFO +
Quiche.SIZEOF_SOCKADDR_STORAGE + Quiche.SIZEOF_SOCKADDR_STORAGE;
private static final ResourceLeakDetector<QuicheQuicConnection> leakDetector =
ResourceLeakDetectorFactory.instance().newResourceLeakDetector(QuicheQuicConnection.class);
private final QuicheQuicSslEngine engine;
private final ResourceLeakTracker<QuicheQuicConnection> leakTracker;
final long ssl;
private ReferenceCounted refCnt;
// This block of memory is used to store the following structs (in this order):
// - quiche_recv_info
// - sockaddr_storage
// - quiche_recv_info
// - sockaddr_storage
// - quiche_send_info
// - quiche_send_info
//
// We need to have every stored 2 times as we need to check if the last sockaddr has changed between
// quiche_conn_recv and quiche_conn_send calls. If this happens we know a QUIC connection migration did happen.
private final ByteBuf recvInfoBuffer;
private final ByteBuf sendInfoBuffer;
private boolean sendInfoFirst = true;
private final ByteBuffer recvInfoBuffer1;
private final ByteBuffer sendInfoBuffer1;
private final ByteBuffer sendInfoBuffer2;
private long connection;
QuicheQuicConnection(long connection, long ssl, QuicheQuicSslEngine engine, ReferenceCounted refCnt) {
assert connection != -1;
this.connection = connection;
this.ssl = ssl;
this.engine = engine;
this.refCnt = refCnt;
// TODO: Maybe cache these per thread as we only use them temporary within a limited scope.
recvInfoBuffer = Quiche.allocateNativeOrder(TOTAL_RECV_INFO_SIZE);
sendInfoBuffer = Quiche.allocateNativeOrder(2 * Quiche.SIZEOF_QUICHE_SEND_INFO);
// Let's memset the memory.
recvInfoBuffer.setZero(0, recvInfoBuffer.capacity());
sendInfoBuffer.setZero(0, sendInfoBuffer.capacity());
recvInfoBuffer1 = recvInfoBuffer.nioBuffer(0, TOTAL_RECV_INFO_SIZE);
sendInfoBuffer1 = sendInfoBuffer.nioBuffer(0, Quiche.SIZEOF_QUICHE_SEND_INFO);
sendInfoBuffer2 = sendInfoBuffer.nioBuffer(Quiche.SIZEOF_QUICHE_SEND_INFO, Quiche.SIZEOF_QUICHE_SEND_INFO);
this.engine.connection = this;
leakTracker = leakDetector.track(this);
}
synchronized void reattach(ReferenceCounted refCnt) {
this.refCnt.release();
this.refCnt = refCnt;
}
void free() {
free(true);
}
boolean isFreed() {
return connection == -1;
}
private void free(boolean closeLeakTracker) {
boolean release = false;
synchronized (this) {
if (connection != -1) {
try {
BoringSSL.SSL_cleanup(ssl);
Quiche.quiche_conn_free(connection);
engine.ctx.remove(engine);
release = true;
refCnt.release();
} finally {
connection = -1;
}
}
}
if (release) {
recvInfoBuffer.release();
sendInfoBuffer.release();
if (closeLeakTracker && leakTracker != null) {
leakTracker.close(this);
}
}
}
@Nullable
Runnable sslTask() {
final Runnable task;
synchronized (this) {
if (connection != -1) {
task = BoringSSL.SSL_getTask(ssl);
} else {
task = null;
}
}
if (task == null) {
return null;
}
return () -> {
if (connection == -1) {
return;
}
task.run();
};
}
@Nullable
QuicConnectionAddress sourceId() {
return connectionId(() -> Quiche.quiche_conn_source_id(connection));
}
@Nullable
QuicConnectionAddress destinationId() {
return connectionId(() -> Quiche.quiche_conn_destination_id(connection));
}
@Nullable
QuicConnectionAddress connectionId(Supplier<byte[]> idSupplier) {
final byte[] id;
synchronized (this) {
if (connection == -1) {
return null;
}
id = idSupplier.get();
}
return id == null ? QuicConnectionAddress.NULL_LEN : new QuicConnectionAddress(id);
}
@Nullable
QuicheQuicTransportParameters peerParameters() {
final long[] ret;
synchronized (this) {
if (connection == -1) {
return null;
}
ret = Quiche.quiche_conn_peer_transport_params(connection);
}
if (ret == null) {
return null;
}
return new QuicheQuicTransportParameters(ret);
}
QuicheQuicSslEngine engine() {
return engine;
}
long address() {
assert connection != -1;
return connection;
}
void init(InetSocketAddress local, InetSocketAddress remote, Consumer<String> sniSelectedCallback) {
assert connection != -1;
assert recvInfoBuffer.refCnt() != 0;
assert sendInfoBuffer.refCnt() != 0;
// Fill quiche_recv_info struct with the addresses.
QuicheRecvInfo.setRecvInfo(recvInfoBuffer1, remote, local);
// Fill both quiche_send_info structs with the same addresses.
QuicheSendInfo.setSendInfo(sendInfoBuffer1, local, remote);
QuicheSendInfo.setSendInfo(sendInfoBuffer2, local, remote);
engine.sniSelectedCallback = sniSelectedCallback;
}
ByteBuffer nextRecvInfo() {
assert recvInfoBuffer.refCnt() != 0;
return recvInfoBuffer1;
}
ByteBuffer nextSendInfo() {
assert sendInfoBuffer.refCnt() != 0;
sendInfoFirst = !sendInfoFirst;
return sendInfoFirst ? sendInfoBuffer1 : sendInfoBuffer2;
}
boolean isSendInfoChanged() {
assert sendInfoBuffer.refCnt() != 0;
return !QuicheSendInfo.isSameAddress(sendInfoBuffer1, sendInfoBuffer2);
}
boolean isClosed() {
return isFreed() || Quiche.quiche_conn_is_closed(connection);
}
// Let's override finalize() as we want to ensure we never leak memory even if the user will miss to close
// Channel that uses this connection and just let it get GC'ed
@Override
protected void finalize() throws Throwable {
try {
free(false);
} finally {
super.finalize();
}
}
}
|
QuicheQuicConnection
|
java
|
apache__camel
|
test-infra/camel-test-infra-pulsar/src/test/java/org/apache/camel/test/infra/pulsar/services/PulsarServiceFactory.java
|
{
"start": 1109,
"end": 2203
}
|
class ____ extends SingletonService<PulsarService> implements PulsarService {
public SingletonPulsarService(PulsarService service, String name) {
super(service, name);
}
@Override
public String getPulsarAdminUrl() {
return getService().getPulsarAdminUrl();
}
@Override
public String getPulsarBrokerUrl() {
return getService().getPulsarBrokerUrl();
}
}
public static SimpleTestServiceBuilder<PulsarService> builder() {
return new SimpleTestServiceBuilder<>("pulsar");
}
public static PulsarService createService() {
return builder()
.addLocalMapping(PulsarLocalContainerService::new)
.addRemoteMapping(PulsarRemoteService::new)
.build();
}
public static PulsarService createSingletonService() {
return builder()
.addLocalMapping(() -> new SingletonPulsarService(new PulsarLocalContainerService(), "pulsar"))
.build();
}
public static
|
SingletonPulsarService
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/UnresolvedDataType.java
|
{
"start": 1523,
"end": 2671
}
|
class ____ implements AbstractDataType<UnresolvedDataType> {
private static final String FORMAT = "[%s]"; // indicates that this is an unresolved type
private final @Nullable Boolean isNullable;
private final @Nullable Class<?> conversionClass;
private final Supplier<String> description;
private final Function<DataTypeFactory, DataType> resolutionFactory;
private UnresolvedDataType(
@Nullable Boolean isNullable,
@Nullable Class<?> conversionClass,
Supplier<String> description,
Function<DataTypeFactory, DataType> resolutionFactory) {
this.isNullable = isNullable;
this.conversionClass = conversionClass;
this.description = description;
this.resolutionFactory = resolutionFactory;
}
public UnresolvedDataType(
Supplier<String> description, Function<DataTypeFactory, DataType> resolutionFactory) {
this(null, null, description, resolutionFactory);
}
/**
* Converts this instance to a resolved {@link DataType} possibly enriched with additional
* nullability and conversion
|
UnresolvedDataType
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/issue_2100/Issue2132.java
|
{
"start": 1566,
"end": 2325
}
|
class ____ {
private int width;
private int height;
private String name;
public Screen(int width, int height, String name) {
this.width = width;
this.height = height;
this.name = name;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static
|
Screen
|
java
|
apache__avro
|
lang/java/avro/src/test/java/org/apache/avro/reflect/TestReflectDatumReader.java
|
{
"start": 13563,
"end": 14253
}
|
class ____ {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PojoWithBasicTypeNullableAnnotationV1 other = (PojoWithBasicTypeNullableAnnotationV1) obj;
return id == other.id;
}
}
public static
|
PojoWithBasicTypeNullableAnnotationV1
|
java
|
google__guava
|
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Platform.java
|
{
"start": 1161,
"end": 3979
}
|
class ____ {
static <K extends @Nullable Object, V extends @Nullable Object>
Map<K, V> newHashMapWithExpectedSize(int expectedSize) {
return Maps.newHashMapWithExpectedSize(expectedSize);
}
static <K extends @Nullable Object, V extends @Nullable Object>
Map<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
return Maps.newLinkedHashMapWithExpectedSize(expectedSize);
}
static <E extends @Nullable Object> Set<E> newHashSetWithExpectedSize(int expectedSize) {
return Sets.newHashSetWithExpectedSize(expectedSize);
}
static <E extends @Nullable Object> Set<E> newConcurrentHashSet() {
// GWT's ConcurrentHashMap is a wrapper around HashMap, but it rejects null keys, which matches
// the behaviour of the non-GWT implementation of newConcurrentHashSet().
// On the other hand HashSet might be better for code size if apps aren't
// already using Collections.newSetFromMap and ConcurrentHashMap.
return Collections.newSetFromMap(new ConcurrentHashMap<E, Boolean>());
}
static <E extends @Nullable Object> Set<E> newLinkedHashSetWithExpectedSize(int expectedSize) {
return Sets.newLinkedHashSetWithExpectedSize(expectedSize);
}
/**
* Returns the platform preferred map implementation that preserves insertion order when used only
* for insertions.
*/
static <K extends @Nullable Object, V extends @Nullable Object>
Map<K, V> preservesInsertionOrderOnPutsMap() {
return new LinkedHashMap<>();
}
/**
* Returns the platform preferred map implementation that preserves insertion order when used only
* for insertions, with a hint for how many entries to expect.
*/
static <K extends @Nullable Object, V extends @Nullable Object>
Map<K, V> preservesInsertionOrderOnPutsMapWithExpectedSize(int expectedSize) {
return Maps.newLinkedHashMapWithExpectedSize(expectedSize);
}
/**
* Returns the platform preferred set implementation that preserves insertion order when used only
* for insertions.
*/
static <E extends @Nullable Object> Set<E> preservesInsertionOrderOnAddsSet() {
return new LinkedHashSet<>();
}
static <T extends @Nullable Object> T[] newArray(T[] reference, int length) {
T[] empty = reference.length == 0 ? reference : Arrays.copyOf(reference, 0);
return Arrays.copyOf(empty, length);
}
/** Equivalent to Arrays.copyOfRange(source, from, to, arrayOfType.getClass()). */
static <T extends @Nullable Object> T[] copy(Object[] source, int from, int to, T[] arrayOfType) {
T[] result = newArray(arrayOfType, to - from);
System.arraycopy(source, from, result, 0, to - from);
return result;
}
// TODO(user): Move this logic to a utility class.
@JsType(isNative = true, name = "Array", namespace = JsPackage.GLOBAL)
private
|
Platform
|
java
|
spring-projects__spring-framework
|
spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java
|
{
"start": 50025,
"end": 50528
}
|
class ____<T extends ServerResponse> implements RouterFunction<T> {
@Override
public String toString() {
ToStringVisitor visitor = new ToStringVisitor();
accept(visitor);
return visitor.toString();
}
}
/**
* A composed routing function that first invokes one function,
* and then invokes another function (of the same response type {@code T})
* if this route had {@linkplain Mono#empty() no result}.
* @param <T> the server response type
*/
static final
|
AbstractRouterFunction
|
java
|
quarkusio__quarkus
|
integration-tests/kafka-avro-apicurio2/src/test/java/io/quarkus/it/kafka/KafkaAvroTest.java
|
{
"start": 174,
"end": 345
}
|
class ____ extends KafkaAvroTestBase {
@Inject
AvroKafkaCreator creator;
@Override
AvroKafkaCreator creator() {
return creator;
}
}
|
KafkaAvroTest
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/dynamic/output/CommandOutputFactoryResolver.java
|
{
"start": 57,
"end": 544
}
|
interface ____ resolve a {@link CommandOutputFactory} based on a {@link OutputSelector}. Resolution of
* {@link CommandOutputFactory} is based on {@link io.lettuce.core.dynamic.CommandMethod} result types and can be influenced
* whether the result type is a key or value result type. Additional type variables (based on the used
* {@link io.lettuce.core.codec.RedisCodec} are hints to improve output resolution.
*
* @author Mark Paluch
* @since 5.0
* @see OutputSelector
*/
public
|
to
|
java
|
apache__camel
|
components/camel-wal/src/main/java/org/apache/camel/component/wal/exceptions/BufferOverflow.java
|
{
"start": 932,
"end": 1472
}
|
class ____ extends IOException {
private final int remaining;
private final int requested;
public BufferOverflow(int remaining, int requested) {
super(format("There is not enough space on the buffer for an offset entry: %d bytes remaining, %d bytes needed",
remaining, requested));
this.remaining = remaining;
this.requested = requested;
}
public int getRemaining() {
return remaining;
}
public int getRequested() {
return requested;
}
}
|
BufferOverflow
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java
|
{
"start": 28086,
"end": 28253
}
|
class ____ {
public final ITestBean tb;
public DependsOnITestBean(ITestBean tb) {
this.tb = tb;
}
}
/**
* Aspect interface
*/
public
|
DependsOnITestBean
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/RevisionConstraintQuery.java
|
{
"start": 961,
"end": 7326
}
|
class ____ {
private Integer id1;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) {
// Revision 1
scope.inEntityManager( em -> {
em.getTransaction().begin();
StrIntTestEntity site1 = new StrIntTestEntity( "a", 10 );
StrIntTestEntity site2 = new StrIntTestEntity( "b", 15 );
em.persist( site1 );
em.persist( site2 );
id1 = site1.getId();
Integer id2 = site2.getId();
em.getTransaction().commit();
// Revision 2
em.getTransaction().begin();
StrIntTestEntity site1_2 = em.find( StrIntTestEntity.class, id1 );
StrIntTestEntity site2_2 = em.find( StrIntTestEntity.class, id2 );
site1_2.setStr1( "d" );
site2_2.setNumber( 20 );
em.getTransaction().commit();
// Revision 3
em.getTransaction().begin();
StrIntTestEntity site1_3 = em.find( StrIntTestEntity.class, id1 );
StrIntTestEntity site2_3 = em.find( StrIntTestEntity.class, id2 );
site1_3.setNumber( 1 );
site2_3.setStr1( "z" );
em.getTransaction().commit();
// Revision 4
em.getTransaction().begin();
StrIntTestEntity site1_4 = em.find( StrIntTestEntity.class, id1 );
StrIntTestEntity site2_4 = em.find( StrIntTestEntity.class, id2 );
site1_4.setNumber( 5 );
site2_4.setStr1( "a" );
em.getTransaction().commit();
} );
}
@Test
public void testRevisionsLtQuery(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
List result = AuditReaderFactory.get( em ).createQuery()
.forRevisionsOfEntity( StrIntTestEntity.class, false, true )
.addProjection( AuditEntity.revisionNumber().distinct() )
.add( AuditEntity.revisionNumber().lt( 3 ) )
.addOrder( AuditEntity.revisionNumber().asc() )
.getResultList();
assertEquals( Arrays.asList( 1, 2 ), result );
} );
}
@Test
public void testRevisionsGeQuery(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
List result = AuditReaderFactory.get( em ).createQuery()
.forRevisionsOfEntity( StrIntTestEntity.class, false, true )
.addProjection( AuditEntity.revisionNumber().distinct() )
.add( AuditEntity.revisionNumber().ge( 2 ) )
.addOrder( AuditEntity.revisionNumber().asc() )
.getResultList();
assertEquals( TestTools.makeSet( 2, 3, 4 ), new HashSet( result ) );
} );
}
@Test
public void testRevisionsLeWithPropertyQuery(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
List result = AuditReaderFactory.get( em ).createQuery()
.forRevisionsOfEntity( StrIntTestEntity.class, false, true )
.addProjection( AuditEntity.revisionNumber() )
.add( AuditEntity.revisionNumber().le( 3 ) )
.add( AuditEntity.property( "str1" ).eq( "a" ) )
.getResultList();
assertEquals( Arrays.asList( 1 ), result );
} );
}
@Test
public void testRevisionsGtWithPropertyQuery(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
List result = AuditReaderFactory.get( em ).createQuery()
.forRevisionsOfEntity( StrIntTestEntity.class, false, true )
.addProjection( AuditEntity.revisionNumber() )
.add( AuditEntity.revisionNumber().gt( 1 ) )
.add( AuditEntity.property( "number" ).lt( 10 ) )
.getResultList();
assertEquals( TestTools.makeSet( 3, 4 ), new HashSet<>( result ) );
} );
}
@Test
public void testRevisionProjectionQuery(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
Object[] result = (Object[]) AuditReaderFactory.get( em ).createQuery()
.forRevisionsOfEntity( StrIntTestEntity.class, false, true )
.addProjection( AuditEntity.revisionNumber().max() )
.addProjection( AuditEntity.revisionNumber().count() )
.addProjection( AuditEntity.revisionNumber().countDistinct() )
.addProjection( AuditEntity.revisionNumber().min() )
.add( AuditEntity.id().eq( id1 ) )
.getSingleResult();
assertEquals( Integer.valueOf( 4 ), result[0] );
assertEquals( Long.valueOf( 4 ), result[1] );
assertEquals( Long.valueOf( 4 ), result[2] );
assertEquals( Integer.valueOf( 1 ), result[3] );
} );
}
@Test
public void testRevisionOrderQuery(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
List result = AuditReaderFactory.get( em ).createQuery()
.forRevisionsOfEntity( StrIntTestEntity.class, false, true )
.addProjection( AuditEntity.revisionNumber() )
.add( AuditEntity.id().eq( id1 ) )
.addOrder( AuditEntity.revisionNumber().desc() )
.getResultList();
assertEquals( Arrays.asList( 4, 3, 2, 1 ), result );
} );
}
@Test
public void testRevisionCountQuery(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
// The query shouldn't be ordered as always, otherwise - we get an exception.
Object result = AuditReaderFactory.get( em ).createQuery()
.forRevisionsOfEntity( StrIntTestEntity.class, false, true )
.addProjection( AuditEntity.revisionNumber().count() )
.add( AuditEntity.id().eq( id1 ) )
.getSingleResult();
assertEquals( Long.valueOf( 4 ), result );
} );
}
@Test
public void testRevisionTypeEqQuery(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
// The query shouldn't be ordered as always, otherwise - we get an exception.
List results = AuditReaderFactory.get( em ).createQuery()
.forRevisionsOfEntity( StrIntTestEntity.class, true, true )
.add( AuditEntity.id().eq( id1 ) )
.add( AuditEntity.revisionType().eq( RevisionType.MOD ) )
.getResultList();
assertEquals( 3, results.size() );
assertEquals( new StrIntTestEntity( "d", 10, id1 ), results.get( 0 ) );
assertEquals( new StrIntTestEntity( "d", 1, id1 ), results.get( 1 ) );
assertEquals( new StrIntTestEntity( "d", 5, id1 ), results.get( 2 ) );
} );
}
@Test
public void testRevisionTypeNeQuery(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
// The query shouldn't be ordered as always, otherwise - we get an exception.
List results = AuditReaderFactory.get( em ).createQuery()
.forRevisionsOfEntity( StrIntTestEntity.class, true, true )
.add( AuditEntity.id().eq( id1 ) )
.add( AuditEntity.revisionType().ne( RevisionType.MOD ) )
.getResultList();
assertEquals( 1, results.size() );
assertEquals( new StrIntTestEntity( "a", 10, id1 ), results.get( 0 ) );
} );
}
}
|
RevisionConstraintQuery
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/loader/Team.java
|
{
"start": 570,
"end": 1529
}
|
class ____ {
private Long id;
private String name;
private Set<Player> players = new HashSet<>();
public Team() {
}
public Team(Long id) {
this( id, "Team #" + id );
}
public Team(Long id, String name) {
this.id = id;
this.name = name;
}
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(targetEntity = Player.class, mappedBy = "team", fetch = FetchType.EAGER)
@Fetch(FetchMode.SELECT)
@SQLSelect(sql = "select * from Player where team_id = ?1",
resultSetMapping = @SqlResultSetMapping(name = "",
entities = @EntityResult(entityClass = Player.class)))
public Set<Player> getPlayers() {
return players;
}
public void setPlayers(Set<Player> players) {
this.players = players;
}
public void addPlayer(Player p) {
players.add( p );
p.setTeam( this );
}
}
|
Team
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/FunctionFunctionAuditExpression.java
|
{
"start": 703,
"end": 1550
}
|
class ____ implements AuditCriterion {
private AuditFunction leftFunction;
private AuditFunction rightFunction;
private String op;
public FunctionFunctionAuditExpression(
AuditFunction leftFunction,
AuditFunction rightFunction,
String op) {
this.leftFunction = leftFunction;
this.rightFunction = rightFunction;
this.op = op;
}
@Override
public void addToQuery(
EnversService enversService,
AuditReaderImplementor auditReader,
Map<String, String> aliasToEntityNameMap,
Map<String, String> aliasToComponentPropertyNameMap,
String baseAlias,
QueryBuilder queryBuilder,
Parameters parameters) {
parameters.addWhereWithFunction(
enversService.getConfig(),
aliasToEntityNameMap,
aliasToComponentPropertyNameMap,
leftFunction,
op,
rightFunction
);
}
}
|
FunctionFunctionAuditExpression
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/OptionalArgument.java
|
{
"start": 325,
"end": 524
}
|
interface ____ that a function accepts one optional argument (typically the last one).
* This is used by the {@link FunctionRegistry} to perform validation of function declaration.
*/
public
|
indicating
|
java
|
apache__dubbo
|
dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIExtension.java
|
{
"start": 1009,
"end": 1103
}
|
interface ____ {
default String[] getGroups() {
return null;
}
}
|
OpenAPIExtension
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/subclassmapping/abstractsuperclass/CustomSubclassMappingException.java
|
{
"start": 222,
"end": 380
}
|
class ____ extends RuntimeException {
public CustomSubclassMappingException(String message) {
super( message );
}
}
|
CustomSubclassMappingException
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/context/weaving/LoadTimeWeaverAware.java
|
{
"start": 1100,
"end": 2445
}
|
interface ____ extends Aware {
/**
* Set the {@link LoadTimeWeaver} of this object's containing
* {@link org.springframework.context.ApplicationContext ApplicationContext}.
* <p>Invoked after the population of normal bean properties but before an
* initialization callback like
* {@link org.springframework.beans.factory.InitializingBean InitializingBean's}
* {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet() afterPropertiesSet()}
* or a custom init-method. Invoked after
* {@link org.springframework.context.ApplicationContextAware ApplicationContextAware's}
* {@link org.springframework.context.ApplicationContextAware#setApplicationContext setApplicationContext(..)}.
* <p><b>NOTE:</b> This method will only be called if there actually is a
* {@code LoadTimeWeaver} available in the application context. If
* there is none, the method will simply not get invoked, assuming that the
* implementing object is able to activate its weaving dependency accordingly.
* @param loadTimeWeaver the {@code LoadTimeWeaver} instance (never {@code null})
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
* @see org.springframework.context.ApplicationContextAware#setApplicationContext
*/
void setLoadTimeWeaver(LoadTimeWeaver loadTimeWeaver);
}
|
LoadTimeWeaverAware
|
java
|
mapstruct__mapstruct
|
integrationtest/src/test/resources/java8Test/src/main/java/org/mapstruct/ap/test/bugs/_636/Target.java
|
{
"start": 197,
"end": 493
}
|
class ____ {
private Foo foo;
private Bar bar;
public Foo getFoo() {
return foo;
}
public void setFoo(Foo foo) {
this.foo = foo;
}
public Bar getBar() {
return bar;
}
public void setBar(Bar bar) {
this.bar = bar;
}
}
|
Target
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/main/java/io/vertx/core/http/impl/ServerCookie.java
|
{
"start": 560,
"end": 1238
}
|
interface ____ extends Cookie {
/**
* Has the cookie been changed? Changed cookie jar will be saved out in the response and sent to the browser.
*
* @return true if changed
*/
boolean isChanged();
/**
* Set the cookie as being changed. Changed will be true for a cookie just created, false by default if just
* read from the request
*
* @param changed true if changed
*/
void setChanged(boolean changed);
/**
* Has this Cookie been sent from the User Agent (the browser)? or was created during the executing on the request.
*
* @return true if the cookie comes from the User Agent.
*/
boolean isFromUserAgent();
}
|
ServerCookie
|
java
|
apache__flink
|
flink-table/flink-sql-parser/src/main/java/org/apache/flink/sql/parser/ddl/SqlCreateFunction.java
|
{
"start": 1468,
"end": 4940
}
|
class ____ extends SqlCreateObject {
private static final SqlSpecialOperator OPERATOR =
new SqlSpecialOperator("CREATE FUNCTION", SqlKind.CREATE_FUNCTION);
private final SqlCharStringLiteral functionClassName;
private final String functionLanguage;
private final boolean isSystemFunction;
private final SqlNodeList resourceInfos;
public SqlCreateFunction(
SqlParserPos pos,
SqlIdentifier functionIdentifier,
SqlCharStringLiteral functionClassName,
String functionLanguage,
boolean ifNotExists,
boolean isTemporary,
boolean isSystemFunction,
SqlNodeList resourceInfos,
SqlNodeList propertyList) {
super(
OPERATOR,
pos,
functionIdentifier,
isTemporary,
false,
ifNotExists,
propertyList,
null);
this.functionClassName = requireNonNull(functionClassName);
this.isSystemFunction = isSystemFunction;
this.functionLanguage = functionLanguage;
this.resourceInfos = resourceInfos;
requireNonNull(propertyList);
}
@Nonnull
@Override
public List<SqlNode> getOperandList() {
return ImmutableNullableList.of(name, functionClassName, resourceInfos);
}
public boolean isSystemFunction() {
return isSystemFunction;
}
public SqlCharStringLiteral getFunctionClassName() {
return this.functionClassName;
}
public String getFunctionLanguage() {
return this.functionLanguage;
}
public List<SqlNode> getResourceInfos() {
return resourceInfos.getList();
}
@Override
protected String getScope() {
return "FUNCTION";
}
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
unparseCreateIfNotExists(writer, leftPrec, rightPrec);
unparseFunctionLanguage(writer, leftPrec, rightPrec);
unparseResourceInfo(writer, leftPrec, rightPrec);
SqlUnparseUtils.unparseProperties(properties, writer, leftPrec, rightPrec);
}
@Override
protected void unparseCreateIfNotExists(SqlWriter writer, int leftPrec, int rightPrec) {
writer.keyword("CREATE");
if (isTemporary()) {
writer.keyword("TEMPORARY");
}
if (isSystemFunction) {
writer.keyword("SYSTEM");
}
writer.keyword(getScope());
if (ifNotExists) {
writer.keyword("IF NOT EXISTS");
}
name.unparse(writer, leftPrec, rightPrec);
writer.keyword("AS");
functionClassName.unparse(writer, leftPrec, rightPrec);
}
private void unparseFunctionLanguage(SqlWriter writer, int leftPrec, int rightPrec) {
if (functionLanguage != null) {
writer.keyword("LANGUAGE");
writer.keyword(functionLanguage);
}
}
private void unparseResourceInfo(SqlWriter writer, int leftPrec, int rightPrec) {
if (!resourceInfos.isEmpty()) {
writer.keyword("USING");
SqlWriter.Frame withFrame = writer.startList("", "");
for (SqlNode resourcePath : resourceInfos) {
writer.sep(",");
resourcePath.unparse(writer, leftPrec, rightPrec);
}
writer.endList(withFrame);
}
}
}
|
SqlCreateFunction
|
java
|
netty__netty
|
codec-classes-quic/src/main/java/io/netty/handler/codec/quic/BoringSSLSessionCallback.java
|
{
"start": 1045,
"end": 3497
}
|
class ____ {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(BoringSSLSessionCallback.class);
private final QuicClientSessionCache sessionCache;
private final QuicheQuicSslEngineMap engineMap;
BoringSSLSessionCallback(QuicheQuicSslEngineMap engineMap, @Nullable QuicClientSessionCache sessionCache) {
this.engineMap = engineMap;
this.sessionCache = sessionCache;
}
@SuppressWarnings("unused")
void newSession(long ssl, long creationTime, long timeout, byte[] session, boolean isSingleUse,
byte @Nullable [] peerParams) {
if (sessionCache == null) {
return;
}
QuicheQuicSslEngine engine = engineMap.get(ssl);
if (engine == null) {
logger.warn("engine is null ssl: {}", ssl);
return;
}
if (peerParams == null) {
peerParams = EmptyArrays.EMPTY_BYTES;
}
if (logger.isDebugEnabled()) {
logger.debug("ssl: {}, session: {}, peerParams: {}", ssl, Arrays.toString(session),
Arrays.toString(peerParams));
}
byte[] quicSession = toQuicheQuicSession(session, peerParams);
if (quicSession != null) {
logger.debug("save session host={}, port={}",
engine.getSession().getPeerHost(), engine.getSession().getPeerPort());
sessionCache.saveSession(engine.getSession().getPeerHost(), engine.getSession().getPeerPort(),
TimeUnit.SECONDS.toMillis(creationTime), TimeUnit.SECONDS.toMillis(timeout),
quicSession, isSingleUse);
}
}
// Mimic the encoding of quiche: https://github.com/cloudflare/quiche/blob/0.10.0/src/lib.rs#L1668
private static byte @Nullable [] toQuicheQuicSession(byte @Nullable [] sslSession, byte @Nullable [] peerParams) {
if (sslSession != null && peerParams != null) {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos)) {
dos.writeLong(sslSession.length);
dos.write(sslSession);
dos.writeLong(peerParams.length);
dos.write(peerParams);
return bos.toByteArray();
} catch (IOException e) {
return null;
}
}
return null;
}
}
|
BoringSSLSessionCallback
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/main/java/org/apache/hadoop/yarn/server/timelineservice/reader/filter/TimelineCompareFilter.java
|
{
"start": 1029,
"end": 1207
}
|
class ____ represents filter to be applied based on key-value pair
* and the relation between them represented by different relational operators.
*/
@Private
@Unstable
public
|
which
|
java
|
quarkusio__quarkus
|
integration-tests/main/src/main/java/io/quarkus/it/rest/ServiceWithConfig.java
|
{
"start": 172,
"end": 575
}
|
class ____ {
@ConfigProperty(name = "quarkus.http.host")
String quarkusHost;
@ConfigProperty(name = "web-message")
String message;
@ConfigProperty(name = "names")
String[] names;
public String host() {
return quarkusHost;
}
public String message() {
return message;
}
public String[] names() {
return names;
}
}
|
ServiceWithConfig
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/internal/schedulers/BooleanRunnableTest.java
|
{
"start": 1050,
"end": 1675
}
|
class ____ extends RxJavaTest {
@Test
public void runnableThrows() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
BooleanRunnable task = new BooleanRunnable(() -> {
throw new TestException();
});
try {
task.run();
fail("Should have thrown!");
} catch (TestException expected) {
// expected
}
TestHelper.assertUndeliverable(errors, 0, TestException.class);
} finally {
RxJavaPlugins.reset();
}
}
}
|
BooleanRunnableTest
|
java
|
apache__camel
|
core/camel-management/src/main/java/org/apache/camel/management/DefaultManagementObjectNameStrategy.java
|
{
"start": 16824,
"end": 24163
}
|
class ____ the mbean name (eg Tracer, BacklogTracer, BacklogDebugger)
String name = tracer.getClass().getSimpleName();
// backwards compatible names
if ("DefaultBacklogDebugger".equals(name)) {
name = "BacklogDebugger";
} else if ("DefaultBacklogTracer".equals(name)) {
name = "BacklogTracer";
}
StringBuilder buffer = new StringBuilder();
buffer.append(domainName).append(":");
buffer.append(KEY_CONTEXT).append("=").append(getContextId(context)).append(",");
buffer.append(KEY_TYPE).append("=").append(TYPE_TRACER).append(",");
buffer.append(KEY_NAME).append("=").append(name);
return createObjectName(buffer);
}
@Override
public ObjectName getObjectNameForEventNotifier(CamelContext context, EventNotifier eventNotifier)
throws MalformedObjectNameException {
StringBuilder buffer = new StringBuilder();
buffer.append(domainName).append(":");
buffer.append(KEY_CONTEXT).append("=").append(getContextId(context)).append(",");
buffer.append(KEY_TYPE).append("=").append(TYPE_EVENT_NOTIFIER).append(",");
if (eventNotifier instanceof JmxNotificationEventNotifier) {
// JMX notifier shall have an easy to use name
buffer.append(KEY_NAME).append("=").append("JmxEventNotifier");
} else {
// others can be per instance
buffer.append(KEY_NAME).append("=")
.append("EventNotifier")
.append("(").append(ObjectHelper.getIdentityHashCode(eventNotifier)).append(")");
}
return createObjectName(buffer);
}
@Override
public ObjectName getObjectNameForRoute(org.apache.camel.Route route) throws MalformedObjectNameException {
StringBuilder buffer = new StringBuilder();
buffer.append(domainName).append(":");
buffer.append(KEY_CONTEXT).append("=").append(getContextId(route.getCamelContext())).append(",");
buffer.append(KEY_TYPE).append("=").append(TYPE_ROUTE).append(",");
buffer.append(KEY_NAME).append("=").append(ObjectName.quote(route.getId()));
return createObjectName(buffer);
}
@Override
public ObjectName getObjectNameForRouteGroup(CamelContext camelContext, String group) throws MalformedObjectNameException {
StringBuilder buffer = new StringBuilder();
buffer.append(domainName).append(":");
buffer.append(KEY_CONTEXT).append("=").append(getContextId(camelContext)).append(",");
buffer.append(KEY_TYPE).append("=").append(TYPE_ROUTE_GROUP).append(",");
buffer.append(KEY_NAME).append("=").append(ObjectName.quote(group));
return createObjectName(buffer);
}
@Override
public ObjectName getObjectNameForService(CamelContext context, Service service) throws MalformedObjectNameException {
StringBuilder buffer = new StringBuilder();
buffer.append(domainName).append(":");
buffer.append(KEY_CONTEXT).append("=").append(getContextId(context)).append(",");
buffer.append(KEY_TYPE).append("=").append(TYPE_SERVICE).append(",");
buffer.append(KEY_NAME).append("=").append(service.getClass().getSimpleName());
if (!(service instanceof StaticService)) {
buffer.append("(").append(ObjectHelper.getIdentityHashCode(service)).append(")");
}
return createObjectName(buffer);
}
@Override
public ObjectName getObjectNameForClusterService(CamelContext context, CamelClusterService service)
throws MalformedObjectNameException {
StringBuilder buffer = new StringBuilder();
buffer.append(domainName).append(":");
buffer.append(KEY_CONTEXT).append("=").append(getContextId(context)).append(",");
buffer.append(KEY_TYPE).append("=").append(TYPE_HA).append(",");
buffer.append(KEY_NAME).append("=").append(service.getClass().getSimpleName());
if (!(service instanceof StaticService)) {
buffer.append("(").append(ObjectHelper.getIdentityHashCode(service)).append(")");
}
return createObjectName(buffer);
}
@Override
public ObjectName getObjectNameForThreadPool(
CamelContext context, ThreadPoolExecutor threadPool, String id, String sourceId)
throws MalformedObjectNameException {
StringBuilder buffer = new StringBuilder();
buffer.append(domainName).append(":");
buffer.append(KEY_CONTEXT).append("=").append(getContextId(context)).append(",");
buffer.append(KEY_TYPE).append("=").append(TYPE_THREAD_POOL).append(",");
String name = id;
if (sourceId != null) {
// provide source id if we know it, this helps end user to know where the pool is used
name = name + "(" + sourceId + ")";
}
buffer.append(KEY_NAME).append("=").append(ObjectName.quote(name));
return createObjectName(buffer);
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
protected String getContextId(CamelContext context) {
if (context == null) {
return getContextId(VALUE_UNKNOWN);
} else {
String name = context.getManagementName() != null ? context.getManagementName() : context.getName();
return getContextId(name);
}
}
protected String getContextId(String name) {
boolean includeHostName
= camelContext != null && camelContext.getManagementStrategy().getManagementAgent().getIncludeHostName();
if (includeHostName) {
return hostName + "/" + (name != null ? name : VALUE_UNKNOWN);
} else {
return name != null ? name : VALUE_UNKNOWN;
}
}
protected String getEndpointId(Endpoint ep) {
String answer = doGetEndpointId(ep);
boolean sanitize = camelContext != null && camelContext.getManagementStrategy().getManagementAgent().getMask();
if (sanitize) {
// use xxxxxx as replacements as * has to be quoted for MBean names
answer = URISupport.sanitizeUri(answer);
}
return answer;
}
private String doGetEndpointId(Endpoint ep) {
if (ep.isSingleton()) {
return ep.getEndpointKey();
} else {
// non singleton then add hashcoded id
String uri = ep.getEndpointKey();
String id = StringHelper.before(uri, "?", uri);
id += "?id=" + ObjectHelper.getIdentityHashCode(ep);
return id;
}
}
/**
* Factory method to create an ObjectName escaping any required characters
*/
protected ObjectName createObjectName(StringBuilder buffer) throws MalformedObjectNameException {
String text = buffer.toString();
try {
return new ObjectName(text);
} catch (MalformedObjectNameException e) {
throw new MalformedObjectNameException("Could not create ObjectName from: " + text + ". Reason: " + e);
}
}
}
|
as
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/catalog/CatalogStoreHolder.java
|
{
"start": 2040,
"end": 2798
}
|
class ____ implements AutoCloseable {
private CatalogStore catalogStore;
private @Nullable CatalogStoreFactory factory;
private ReadableConfig config;
private ClassLoader classLoader;
private CatalogStoreHolder(
CatalogStore catalogStore,
@Nullable CatalogStoreFactory factory,
ReadableConfig config,
ClassLoader classLoader) {
this.catalogStore = catalogStore;
this.factory = factory;
this.config = config;
this.classLoader = classLoader;
}
public static Builder newBuilder() {
return new Builder();
}
/** Builder for a fluent definition of a {@link CatalogStoreHolder}. */
@Internal
public static final
|
CatalogStoreHolder
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/AbstractMultivalueFunction.java
|
{
"start": 2583,
"end": 4604
}
|
class ____ extends AbstractNullableEvaluator {
protected AbstractEvaluator(DriverContext driverContext, EvalOperator.ExpressionEvaluator field) {
super(driverContext, field);
}
/**
* Called when evaluating a {@link Block} that does not contain null values.
* It’s useful to specialize this from {@link #evalNullable} because it knows
* that it’s producing an "array vector" because it only ever emits single
* valued fields and no null values. Building an array vector directly is
* generally faster than building it via a {@link Block.Builder}.
*
* @return the returned Block has its own reference and the caller is responsible for releasing it.
*/
protected abstract Block evalNotNullable(Block fieldVal);
/**
* Called to evaluate single valued fields when the target block does not have null values.
*
* @return the returned Block has its own reference and the caller is responsible for releasing it.
*/
protected Block evalSingleValuedNotNullable(Block fieldRef) {
fieldRef.incRef();
return fieldRef;
}
@Override
public final Block eval(Page page) {
try (Block block = field.eval(page)) {
if (block.mayHaveMultivaluedFields()) {
if (block.mayHaveNulls()) {
return evalNullable(block);
} else {
return evalNotNullable(block);
}
}
if (block.mayHaveNulls()) {
return evalSingleValuedNullable(block);
} else {
return evalSingleValuedNotNullable(block);
}
}
}
}
/**
* Base evaluator that can handle evaluator-checked exceptions; i.e. for expressions that can be evaluated to null.
*/
public abstract static
|
AbstractEvaluator
|
java
|
apache__kafka
|
streams/src/main/java/org/apache/kafka/streams/state/internals/TimeOrderedKeyValueBuffer.java
|
{
"start": 1464,
"end": 3275
}
|
class ____<K, T> {
private final K key;
private final T value;
private final ProcessorRecordContext recordContext;
Eviction(final K key, final T value, final ProcessorRecordContext recordContext) {
this.key = key;
this.value = value;
this.recordContext = recordContext;
}
public K key() {
return key;
}
public T value() {
return value;
}
public Record<K, T> record() {
return new Record<>(key, value, recordContext.timestamp());
}
public ProcessorRecordContext recordContext() {
return recordContext;
}
@Override
public String toString() {
return "Eviction{key=" + key + ", value=" + value + ", recordContext=" + recordContext + '}';
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Eviction<?, ?> eviction = (Eviction<?, ?>) o;
return Objects.equals(key, eviction.key) &&
Objects.equals(value, eviction.value) &&
Objects.equals(recordContext, eviction.recordContext);
}
@Override
public int hashCode() {
return Objects.hash(key, value, recordContext);
}
}
void setSerdesIfNull(final SerdeGetter getter);
void evictWhile(final Supplier<Boolean> predicate, final Consumer<Eviction<K, T>> callback);
Maybe<ValueAndTimestamp<V>> priorValueForBuffered(K key);
boolean put(long time, Record<K, T> record, ProcessorRecordContext recordContext);
int numRecords();
long bufferSize();
long minTimestamp();
}
|
Eviction
|
java
|
apache__camel
|
components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/approval/ApprovalRequest.java
|
{
"start": 1694,
"end": 1869
}
|
enum ____ {
Submit,
Approve,
Reject
}
/**
* Lazy holder of fields defined in {@link ApprovalRequest}.
*/
private static final
|
Action
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java
|
{
"start": 30627,
"end": 36920
}
|
enum ____ {
ONE,
TWO,
THREE,
FOUR,
FIVE;
}
public void testRandomAddsAndRemoves_duplicateElements() {
Random random = new Random(0);
Multiset<Element> elements = HashMultiset.create();
MinMaxPriorityQueue<Element> queue = MinMaxPriorityQueue.create();
int range = Element.values().length;
for (int iter = 0; iter < reduceIterationsIfGwt(1000); iter++) {
for (int i = 0; i < 100; i++) {
Element element = Element.values()[random.nextInt(range)];
elements.add(element);
queue.add(element);
}
Iterator<Element> queueIterator = queue.iterator();
int remaining = queue.size();
while (queueIterator.hasNext()) {
Element element = queueIterator.next();
remaining--;
assertThat(elements).contains(element);
if (random.nextBoolean()) {
elements.remove(element);
queueIterator.remove();
}
}
assertThat(remaining).isEqualTo(0);
assertIntact(queue);
assertThat(queue).containsExactlyElementsIn(elements);
}
}
/** Returns the seed used for the randomization. */
private long insertRandomly(ArrayList<Integer> elements, MinMaxPriorityQueue<Integer> q) {
long seed = new Random().nextLong();
Random random = new Random(seed);
insertRandomly(elements, q, random);
return seed;
}
private static void insertRandomly(
ArrayList<Integer> elements, MinMaxPriorityQueue<Integer> q, Random random) {
while (!elements.isEmpty()) {
int selectedIndex = random.nextInt(elements.size());
q.offer(elements.remove(selectedIndex));
}
}
private ArrayList<Integer> createOrderedList(int size) {
ArrayList<Integer> elements = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
elements.add(i);
}
return elements;
}
public void testIsEvenLevel() {
assertTrue(MinMaxPriorityQueue.isEvenLevel(0));
assertFalse(MinMaxPriorityQueue.isEvenLevel(1));
assertFalse(MinMaxPriorityQueue.isEvenLevel(2));
assertTrue(MinMaxPriorityQueue.isEvenLevel(3));
assertFalse(MinMaxPriorityQueue.isEvenLevel((1 << 10) - 2));
assertTrue(MinMaxPriorityQueue.isEvenLevel((1 << 10) - 1));
int i = 1 << 29;
assertTrue(MinMaxPriorityQueue.isEvenLevel(i - 2));
assertFalse(MinMaxPriorityQueue.isEvenLevel(i - 1));
assertFalse(MinMaxPriorityQueue.isEvenLevel(i));
i = 1 << 30;
assertFalse(MinMaxPriorityQueue.isEvenLevel(i - 2));
assertTrue(MinMaxPriorityQueue.isEvenLevel(i - 1));
assertTrue(MinMaxPriorityQueue.isEvenLevel(i));
// 1 << 31 is negative because of overflow, 1 << 31 - 1 is positive
// since isEvenLevel adds 1, we need to do - 2.
assertTrue(MinMaxPriorityQueue.isEvenLevel((1 << 31) - 2));
assertTrue(MinMaxPriorityQueue.isEvenLevel(Integer.MAX_VALUE - 1));
assertThrows(IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel((1 << 31) - 1));
assertThrows(
IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel(Integer.MAX_VALUE));
assertThrows(IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel(1 << 31));
assertThrows(
IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel(Integer.MIN_VALUE));
}
@J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicConstructors(MinMaxPriorityQueue.class);
tester.testAllPublicStaticMethods(MinMaxPriorityQueue.class);
tester.testAllPublicInstanceMethods(MinMaxPriorityQueue.<String>create());
}
private static void insertIntoReplica(Map<Integer, AtomicInteger> replica, int newValue) {
if (replica.containsKey(newValue)) {
replica.get(newValue).incrementAndGet();
} else {
replica.put(newValue, new AtomicInteger(1));
}
}
private static void removeMinFromReplica(
SortedMap<Integer, AtomicInteger> replica, int minValue) {
Integer replicatedMinValue = replica.firstKey();
assertEquals(replicatedMinValue, (Integer) minValue);
removeFromReplica(replica, replicatedMinValue);
}
private static void removeMaxFromReplica(
SortedMap<Integer, AtomicInteger> replica, int maxValue) {
Integer replicatedMaxValue = replica.lastKey();
assertTrue("maxValue is incorrect", replicatedMaxValue == maxValue);
removeFromReplica(replica, replicatedMaxValue);
}
private static void removeFromReplica(Map<Integer, AtomicInteger> replica, int value) {
AtomicInteger numOccur = replica.get(value);
if (numOccur.decrementAndGet() == 0) {
replica.remove(value);
}
}
private static void assertIntact(MinMaxPriorityQueue<?> q) {
if (!q.isIntact()) {
fail("State " + Arrays.toString(q.toArray()));
}
}
private static void assertIntactUsingSeed(long seed, MinMaxPriorityQueue<?> q) {
if (!q.isIntact()) {
fail("Using seed " + seed + ". State " + Arrays.toString(q.toArray()));
}
}
private static void assertIntactUsingStartedWith(
Collection<?> startedWith, MinMaxPriorityQueue<?> q) {
if (!q.isIntact()) {
fail("Started with " + startedWith + ". State " + Arrays.toString(q.toArray()));
}
}
private static void assertEqualsUsingSeed(
long seed, @Nullable Object expected, @Nullable Object actual) {
if (!Objects.equals(actual, expected)) {
// fail(), but with the JUnit-supplied message.
assertEquals("Using seed " + seed, expected, actual);
}
}
private static void assertEqualsUsingStartedWith(
Collection<?> startedWith, @Nullable Object expected, @Nullable Object actual) {
if (!Objects.equals(actual, expected)) {
// fail(), but with the JUnit-supplied message.
assertEquals("Started with " + startedWith, expected, actual);
}
}
// J2kt cannot translate the Comparable rawtype in a usable way (it becomes Comparable<Object>
// but types are typically only Comparable to themselves).
@SuppressWarnings({"rawtypes", "unchecked"})
private static MinMaxPriorityQueue.Builder<Comparable<?>> rawtypeToWildcard(
MinMaxPriorityQueue.Builder<Comparable> builder) {
return (MinMaxPriorityQueue.Builder) builder;
}
}
|
Element
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/component/bean/BeanExpressionConcurrentTest.java
|
{
"start": 1183,
"end": 2907
}
|
class ____ extends ContextTestSupport {
@Test
public void testBeanConcurrent() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1000);
mock.expectsNoDuplicates(body());
// start from 1000 to be 4 digit always (easier to string compare)
for (int i = 1000; i < 2000; i++) {
template.sendBody("seda:foo", Integer.toString(i));
}
context.getRouteController().startRoute("foo");
assertMockEndpointsSatisfied();
// should be 1000 messages
List<String> list = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
String body = mock.getReceivedExchanges().get(i).getIn().getBody(String.class);
list.add(body);
}
list.sort(null);
// and they should be unique and no lost messages
assertEquals(1000, list.size());
for (int i = 1; i < 1000; i++) {
int num = 1000 + i;
String s = num + " " + num;
assertEquals(s, list.get(i));
}
}
@Override
protected Registry createCamelRegistry() throws Exception {
Registry jndi = super.createCamelRegistry();
jndi.bind("myBean", new MyBean());
return jndi;
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("seda:foo?concurrentConsumers=10").routeId("foo").autoStartup(false).transform(method("myBean"))
.to("mock:result");
}
};
}
@SuppressWarnings("unused")
private static
|
BeanExpressionConcurrentTest
|
java
|
netty__netty
|
codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicSslSessionContext.java
|
{
"start": 844,
"end": 1456
}
|
interface ____ extends SSLSessionContext {
/**
* Sets the {@link SslSessionTicketKey}s that should be used. The first key of the array is used for encryption
* and decryption while the rest of the array is only used for decryption. This allows you to better handling
* rotating of the keys. The rotating is the responsibility of the user.
* If {@code null} is used for {@code keys} a key will automatically generated by the library and also rotated.
*
* @param keys the tickets to use.
*/
void setTicketKeys(SslSessionTicketKey @Nullable ... keys);
}
|
QuicSslSessionContext
|
java
|
reactor__reactor-core
|
reactor-core/src/test/java/reactor/core/scheduler/ExecutorSchedulerTest.java
|
{
"start": 1480,
"end": 7253
}
|
class ____ extends AbstractSchedulerTest {
@Override
protected boolean shouldCheckInit() {
return false;
}
@Override
protected boolean shouldCheckDisposeTask() {
return false;
}
@Override
protected boolean shouldCheckDirectTimeScheduling() {
return false;
}
@Override
protected boolean shouldCheckWorkerTimeScheduling() {
return false;
}
@Override
protected boolean shouldCheckSupportRestart() {
return false;
}
@Override
protected Scheduler scheduler() {
return Schedulers.fromExecutor(Runnable::run);
}
@Override
protected Scheduler freshScheduler() {
return new ExecutorScheduler(Runnable::run, false);
}
@Test
public void directAndWorkerTimeSchedulingRejected() {
Scheduler scheduler = scheduler();
Scheduler.Worker worker = scheduler.createWorker();
try {
assertThatExceptionOfType(RejectedExecutionException.class)
.isThrownBy(() -> scheduler.schedule(() -> { }, 100, TimeUnit.MILLISECONDS))
.isSameAs(Exceptions.failWithRejectedNotTimeCapable());
assertThatExceptionOfType(RejectedExecutionException.class)
.isThrownBy(() -> scheduler.schedulePeriodically(() -> { }, 100, 100, TimeUnit.MILLISECONDS))
.isSameAs(Exceptions.failWithRejectedNotTimeCapable());
assertThatExceptionOfType(RejectedExecutionException.class)
.isThrownBy(() -> worker.schedule(() -> { }, 100, TimeUnit.MILLISECONDS))
.isSameAs(Exceptions.failWithRejectedNotTimeCapable());
assertThatExceptionOfType(RejectedExecutionException.class)
.isThrownBy(() -> worker.schedulePeriodically(() -> { }, 100, 100, TimeUnit.MILLISECONDS))
.isSameAs(Exceptions.failWithRejectedNotTimeCapable());
}
finally {
worker.dispose();
}
}
@Test
public void failingExecutorRejects() {
final IllegalStateException boom = new IllegalStateException("boom");
ExecutorScheduler scheduler = new ExecutorScheduler(
task -> { throw boom;},
false
);
AtomicBoolean done = new AtomicBoolean();
assertThatExceptionOfType(RejectedExecutionException.class)
.isThrownBy(() -> scheduler.schedule(() -> done.set(true)))
.withCause(boom);
assertThat(done.get()).isFalse();
}
@Test
public void failingPlainExecutorIsNotTerminated() {
AtomicInteger count = new AtomicInteger();
final IllegalStateException boom = new IllegalStateException("boom");
ExecutorScheduler scheduler = new ExecutorScheduler(
task -> {
if (count.incrementAndGet() % 2 == 0)
throw boom;
},
false
);
assertThatCode(() -> scheduler.schedule(() -> {}))
.as("initial-no rejection")
.doesNotThrowAnyException();
assertThatExceptionOfType(RejectedExecutionException.class)
.as("second-transient rejection")
.isThrownBy(() -> scheduler.schedule(() -> {}))
.withCause(boom);
assertThatCode(() -> scheduler.schedule(() -> {}))
.as("third-no rejection")
.doesNotThrowAnyException();
assertThat(count).hasValue(3);
}
@Test
public void failingExecutorServiceIsNotTerminated() {
AtomicInteger count = new AtomicInteger();
final IllegalStateException boom = new IllegalStateException("boom");
ExecutorService service = new AbstractExecutorService() {
boolean shutdown;
@Override
public void shutdown() {
shutdown = true;
}
@NonNull
@Override
public List<Runnable> shutdownNow() {
return Collections.emptyList();
}
@Override
public boolean isShutdown() {
return shutdown;
}
@Override
public boolean isTerminated() {
return shutdown;
}
@Override
public boolean awaitTermination(long timeout, @NonNull TimeUnit unit)
throws InterruptedException {
return false;
}
@Override
public void execute(@NonNull Runnable command) {
if (count.incrementAndGet() % 2 == 0)
throw boom;
}
};
ExecutorScheduler scheduler = new ExecutorScheduler(service, false);
assertThatCode(() -> scheduler.schedule(() -> {}))
.as("initial-no rejection")
.doesNotThrowAnyException();
assertThatExceptionOfType(RejectedExecutionException.class)
.as("second-transient rejection")
.isThrownBy(() -> scheduler.schedule(() -> {}))
.withCause(boom);
assertThatCode(() -> scheduler.schedule(() -> {}))
.as("third-no rejection")
.doesNotThrowAnyException();
assertThat(count).hasValue(3);
}
@Test
public void failingAndShutDownExecutorServiceIsTerminated() {
final IllegalStateException boom = new IllegalStateException("boom");
ExecutorService service = new AbstractExecutorService() {
boolean shutdown;
@Override
public void shutdown() {
shutdown = true;
}
@NonNull
@Override
public List<Runnable> shutdownNow() {
return Collections.emptyList();
}
@Override
public boolean isShutdown() {
return shutdown;
}
@Override
public boolean isTerminated() {
return shutdown;
}
@Override
public boolean awaitTermination(long timeout, @NonNull TimeUnit unit)
throws InterruptedException {
return false;
}
@Override
public void execute(@NonNull Runnable command) {
if (shutdown) throw boom;
shutdown = true;
}
};
ExecutorScheduler scheduler = new ExecutorScheduler(service, false);
assertThatCode(() -> scheduler.schedule(() -> {}))
.as("initial-no rejection")
.doesNotThrowAnyException();
assertThatExceptionOfType(RejectedExecutionException.class)
.as("second-transient rejection")
.isThrownBy(() -> scheduler.schedule(() -> {}))
.withCause(boom);
assertThatExceptionOfType(RejectedExecutionException.class)
.as("third scheduler terminated rejection")
.isThrownBy(() -> scheduler.schedule(() -> {}))
.isSameAs(Exceptions.failWithRejected())
.withNoCause();
}
static final
|
ExecutorSchedulerTest
|
java
|
quarkusio__quarkus
|
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/valueextractor/NestedContainerTypeCustomValueExtractorTest.java
|
{
"start": 756,
"end": 1315
}
|
class ____ {
@Inject
ValidatorFactory validatorFactory;
@RegisterExtension
static final QuarkusUnitTest test = new QuarkusUnitTest().setArchiveProducer(() -> ShrinkWrap
.create(JavaArchive.class)
.addClasses(TestBean.class, NestedContainerType.class, NestedContainerClassValueExtractor.class));
@Test
public void testNestedContainerTypeValueExtractor() {
assertThat(validatorFactory.getValidator().validate(new TestBean())).hasSize(1);
}
public static
|
NestedContainerTypeCustomValueExtractorTest
|
java
|
quarkusio__quarkus
|
extensions/jackson/spi/src/main/java/io/quarkus/jackson/spi/JacksonModuleBuildItem.java
|
{
"start": 2675,
"end": 3612
}
|
class ____ {
private final String targetClassName;
private final String serializerClassName;
private final String deserializerClassName;
public Item(String targetClassName, String serializerClassName, String deserializerClassName) {
this.serializerClassName = serializerClassName;
this.deserializerClassName = deserializerClassName;
if (targetClassName == null || targetClassName.isEmpty()) {
throw new IllegalArgumentException("targetClassName cannot be null or empty");
}
this.targetClassName = targetClassName;
}
public String getSerializerClassName() {
return serializerClassName;
}
public String getDeserializerClassName() {
return deserializerClassName;
}
public String getTargetClassName() {
return targetClassName;
}
}
}
|
Item
|
java
|
assertj__assertj-core
|
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/presentation/StandardRepresentation_throwable_format_Test.java
|
{
"start": 1426,
"end": 4313
}
|
class ____ {
static void boom2() {
throw new RuntimeException();
}
}
static void boom() {
Test2.boom2();
}
}
@Test
void should_not_display_stacktrace_if_maxStackTraceElementsDisplayed_is_zero() {
// GIVEN
Configuration configuration = new Configuration();
configuration.setMaxStackTraceElementsDisplayed(0);
configuration.apply();
// WHEN
String toString = REPRESENTATION.toStringOf(catchThrowable(Test1::boom));
// THEN
then(toString).isEqualTo("java.lang.RuntimeException");
}
@Test
void should_display_the_configured_number_of_stacktrace_elements() {
// GIVEN
Configuration configuration = new Configuration();
// configuration.setMaxStackTraceElementsDisplayed(3);
configuration.apply();
// WHEN
String toString = REPRESENTATION.toStringOf(catchThrowable(Test1::boom));
// THEN
then(toString.split("\\R")).satisfiesExactly(s -> then(s).isEqualTo("java.lang.RuntimeException"),
s -> then(s).startsWith("\tat org.assertj.tests.core/org.assertj.tests.core.presentation.StandardRepresentation_throwable_format_Test$Test1$Test2.boom2(StandardRepresentation_throwable_format_Test.java:"),
s -> then(s).startsWith("\tat org.assertj.tests.core/org.assertj.tests.core.presentation.StandardRepresentation_throwable_format_Test$Test1.boom(StandardRepresentation_throwable_format_Test.java:"),
s -> then(s).contains("at",
"org.assertj.core.api.ThrowableAssert.catchThrowable(ThrowableAssert.java:"),
s -> then(s).endsWith("remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed)"));
}
@Test
void should_display_the_full_stacktrace() {
// GIVEN
Configuration configuration = new Configuration();
configuration.setMaxStackTraceElementsDisplayed(100);
configuration.apply();
// WHEN
String toString = REPRESENTATION.toStringOf(catchThrowable(Test1::boom));
// THEN
then(toString).startsWith(format("java.lang.RuntimeException%n"
+ "\tat org.assertj.tests.core/org.assertj.tests.core.presentation.StandardRepresentation_throwable_format_Test$Test1$Test2.boom2(StandardRepresentation_throwable_format_Test.java"))
.doesNotContain("remaining lines not displayed");
}
@Test
void should_display_toString_when_null_stack() {
// GIVEN
Throwable throwable = mock();
when(throwable.toString()).thenReturn("throwable string");
// WHEN
String actual = REPRESENTATION.toStringOf(throwable);
// THEN
then(actual).isEqualTo("throwable string");
}
}
|
Test2
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/docker/compose/OracleFreeJdbcDockerComposeConnectionDetailsFactory.java
|
{
"start": 1035,
"end": 1256
}
|
class ____ extends OracleJdbcDockerComposeConnectionDetailsFactory {
protected OracleFreeJdbcDockerComposeConnectionDetailsFactory() {
super(OracleContainer.FREE);
}
}
|
OracleFreeJdbcDockerComposeConnectionDetailsFactory
|
java
|
spring-projects__spring-boot
|
module/spring-boot-webmvc/src/main/java/org/springframework/boot/webmvc/autoconfigure/WebMvcAutoConfiguration.java
|
{
"start": 29030,
"end": 29154
}
|
interface ____ {
void customize(ResourceHandlerRegistration registration);
}
static
|
ResourceHandlerRegistrationCustomizer
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/JsonWithArrayEmbeddableTest.java
|
{
"start": 13315,
"end": 13931
}
|
class ____ {
@Id
private Long id;
@JdbcTypeCode(SqlTypes.JSON)
private EmbeddableWithArrayAggregate aggregate;
//Getters and setters are omitted for brevity
public JsonHolder() {
}
public JsonHolder(Long id, EmbeddableWithArrayAggregate aggregate) {
this.id = id;
this.aggregate = aggregate;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public EmbeddableWithArrayAggregate getAggregate() {
return aggregate;
}
public void setAggregate(EmbeddableWithArrayAggregate aggregate) {
this.aggregate = aggregate;
}
}
}
|
JsonHolder
|
java
|
apache__camel
|
components/camel-rest-openapi/src/main/java/org/apache/camel/component/rest/openapi/RestOpenApiProcessor.java
|
{
"start": 1687,
"end": 10826
}
|
class ____ extends DelegateAsyncProcessor implements CamelContextAware {
private static final Logger LOG = LoggerFactory.getLogger(RestOpenApiProcessor.class);
// just use the most common verbs
private static final List<String> METHODS = Arrays.asList("GET", "HEAD", "POST", "PUT", "DELETE", "PATCH");
private CamelContext camelContext;
private final RestOpenApiEndpoint endpoint;
private final OpenAPI openAPI;
private final String basePath;
private final String apiContextPath;
private final List<RestConsumerContextPathMatcher.ConsumerPath<Operation>> paths = new ArrayList<>();
private final RestOpenapiProcessorStrategy restOpenapiProcessorStrategy;
private PlatformHttpConsumerAware platformHttpConsumer;
private Consumer consumer;
private OpenApiUtils openApiUtils;
public RestOpenApiProcessor(RestOpenApiEndpoint endpoint, OpenAPI openAPI, String basePath, String apiContextPath,
Processor processor, RestOpenapiProcessorStrategy restOpenapiProcessorStrategy) {
super(processor);
this.endpoint = endpoint;
this.basePath = basePath;
// ensure starts with leading slash
this.apiContextPath = apiContextPath != null && !apiContextPath.startsWith("/") ? "/" + apiContextPath : apiContextPath;
this.openAPI = openAPI;
this.restOpenapiProcessorStrategy = restOpenapiProcessorStrategy;
}
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
public PlatformHttpConsumerAware getPlatformHttpConsumer() {
return platformHttpConsumer;
}
public void setPlatformHttpConsumer(PlatformHttpConsumerAware platformHttpConsumer) {
this.platformHttpConsumer = platformHttpConsumer;
}
public Consumer getConsumer() {
return consumer;
}
public void setConsumer(Consumer consumer) {
this.consumer = consumer;
}
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
// use HTTP_URI as this works for all runtimes
String path = exchange.getMessage().getHeader(Exchange.HTTP_PATH, String.class);
// if (path != null) {
// path = URISupport.stripQuery(path);
// }
if (path != null && path.startsWith(basePath)) {
path = path.substring(basePath.length());
}
String verb = exchange.getMessage().getHeader(Exchange.HTTP_METHOD, String.class);
RestConsumerContextPathMatcher.ConsumerPath<Operation> m
= RestConsumerContextPathMatcher.matchBestPath(verb, path, paths);
if (m instanceof RestOpenApiConsumerPath rcp) {
Operation o = rcp.getConsumer();
String consumerPath = rcp.getConsumerPath();
//if uri is not starting with slash then remove the slash in the consumerPath from the openApi spec
if (consumerPath.startsWith("/") && path != null && !path.startsWith("/")) {
consumerPath = consumerPath.substring(1);
}
// map path-parameters from operation to camel headers
HttpHelper.evalPlaceholders(exchange.getMessage().getHeaders(), path, consumerPath);
// process the incoming request
return restOpenapiProcessorStrategy.process(openAPI, o, verb, path, rcp.getBinding(), exchange, callback);
}
// is it the api-context path
if (path != null && path.equals(apiContextPath)) {
return restOpenapiProcessorStrategy.processApiSpecification(endpoint.getSpecificationUri(), exchange, callback);
}
// okay we cannot process this requires so return either 404 or 405.
// to know if its 405 then we need to check if any other HTTP method would have a consumer for the "same" request
final String contextPath = path;
List<String> allow = METHODS.stream()
.filter(v -> RestConsumerContextPathMatcher.matchBestPath(v, contextPath, paths) != null).toList();
if (allow.isEmpty()) {
exchange.getMessage().setHeader(Exchange.HTTP_RESPONSE_CODE, 404);
} else {
exchange.getMessage().setHeader(Exchange.HTTP_RESPONSE_CODE, 405);
// include list of allowed VERBs
exchange.getMessage().setHeader("Allow", String.join(", ", allow));
}
exchange.setRouteStop(true);
callback.done(true);
return true;
}
@Override
protected void doInit() throws Exception {
super.doInit();
this.openApiUtils = new OpenApiUtils(camelContext, endpoint.getBindingPackageScan(), openAPI.getComponents());
CamelContextAware.trySetCamelContext(restOpenapiProcessorStrategy, getCamelContext());
// register all openapi paths
for (var e : openAPI.getPaths().entrySet()) {
String path = e.getKey(); // path
for (var o : e.getValue().readOperationsMap().entrySet()) {
String v = o.getKey().name(); // verb
// create per operation binding
RestBindingConfiguration bc = createRestBindingConfiguration(o.getValue());
String url = basePath + path;
if (platformHttpConsumer != null) {
url = platformHttpConsumer.getPlatformHttpConsumer().getEndpoint().getServiceUrl() + url;
}
String desc = o.getValue().getSummary();
if (desc != null && desc.isBlank()) {
desc = null;
}
String routeId = null;
if (consumer instanceof RouteAware ra) {
routeId = ra.getRoute().getRouteId();
}
camelContext.getRestRegistry().addRestService(consumer, true, url, path, basePath, null, v, bc.getConsumes(),
bc.getProduces(), bc.getType(), bc.getOutType(), routeId, desc);
RestBindingAdvice binding = RestBindingAdviceFactory.build(camelContext, bc);
ServiceHelper.buildService(binding);
paths.add(new RestOpenApiConsumerPath(v, path, o.getValue(), binding));
}
}
openApiUtils.clear(); // no longer needed
restOpenapiProcessorStrategy.setMissingOperation(endpoint.getMissingOperation());
restOpenapiProcessorStrategy.setMockIncludePattern(endpoint.getMockIncludePattern());
ServiceHelper.initService(restOpenapiProcessorStrategy);
// validate openapi contract
restOpenapiProcessorStrategy.validateOpenApi(openAPI, basePath, platformHttpConsumer);
}
private RestBindingConfiguration createRestBindingConfiguration(Operation o) throws Exception {
RestConfiguration config = camelContext.getRestConfiguration();
RestConfiguration.RestBindingMode mode = config.getBindingMode();
RestBindingConfiguration bc = new RestBindingConfiguration();
bc.setBindingMode(mode.name());
bc.setEnableCORS(config.isEnableCORS());
bc.setCorsHeaders(config.getCorsHeaders());
bc.setClientRequestValidation(config.isClientRequestValidation() || endpoint.isClientRequestValidation());
bc.setClientResponseValidation(config.isClientResponseValidation() || endpoint.isClientResponseValidation());
bc.setEnableNoContentResponse(config.isEnableNoContentResponse());
bc.setSkipBindingOnErrorCode(config.isSkipBindingOnErrorCode());
String consumes = Optional.ofNullable(openApiUtils.getConsumes(o)).orElse(endpoint.getConsumes());
String produces = Optional.ofNullable(openApiUtils.getProduces(o)).orElse(endpoint.getProduces());
bc.setConsumes(consumes);
bc.setProduces(produces);
bc.setRequiredBody(openApiUtils.isRequiredBody(o));
bc.setRequiredQueryParameters(openApiUtils.getRequiredQueryParameters(o));
bc.setRequiredHeaders(openApiUtils.getRequiredHeaders(o));
bc.setQueryDefaultValues(openApiUtils.getQueryParametersDefaultValue(o));
// input and output types binding to java classes
bc.setType(openApiUtils.manageRequestBody(o));
bc.setOutType(openApiUtils.manageResponseBody(o));
return bc;
}
@Override
protected void doStart() throws Exception {
super.doStart();
ServiceHelper.startService(restOpenapiProcessorStrategy);
for (var p : paths) {
if (p instanceof RestOpenApiConsumerPath rcp) {
ServiceHelper.startService(rcp.getBinding());
}
}
}
@Override
protected void doStop() throws Exception {
super.doStop();
ServiceHelper.stopService(restOpenapiProcessorStrategy);
for (var p : paths) {
if (p instanceof RestOpenApiConsumerPath rcp) {
ServiceHelper.stopService(rcp.getBinding());
}
}
paths.clear();
}
}
|
RestOpenApiProcessor
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestLocalFileSystem.java
|
{
"start": 24906,
"end": 27680
}
|
class ____
extends FSDataOutputStreamBuilder<FSDataOutputStream,
BuilderWithSupportedKeys> {
private final Set<String> supportedKeys = new HashSet<>();
BuilderWithSupportedKeys(@Nonnull final Collection<String> supportedKeys,
@Nonnull FileSystem fileSystem, @Nonnull Path p) {
super(fileSystem, p);
this.supportedKeys.addAll(supportedKeys);
}
@Override
public BuilderWithSupportedKeys getThisBuilder() {
return this;
}
@Override
public FSDataOutputStream build()
throws IllegalArgumentException, IOException {
Set<String> unsupported = new HashSet<>(getMandatoryKeys());
unsupported.removeAll(supportedKeys);
Preconditions.checkArgument(unsupported.isEmpty(),
"unsupported key found: " + supportedKeys);
return getFS().create(
getPath(), getPermission(), getFlags(), getBufferSize(),
getReplication(), getBlockSize(), getProgress(), getChecksumOpt());
}
}
@Test
public void testFSOutputStreamBuilderOptions() throws Exception {
Path path = new Path(TEST_ROOT_DIR, "testBuilderOpt");
final List<String> supportedKeys = Arrays.asList("strM");
FSDataOutputStreamBuilder<?, ?> builder =
new BuilderWithSupportedKeys(supportedKeys, fileSys, path);
builder.opt("strKey", "value");
builder.opt("intKey", 123);
builder.opt("strM", "ignored");
// Over-write an optional value with a mandatory value.
builder.must("strM", "value");
builder.must("unsupported", 12.34);
assertEquals("value", builder.getOptions().get("strM"),
"Optional value should be overwrite by a mandatory value");
Set<String> mandatoryKeys = builder.getMandatoryKeys();
Set<String> expectedKeys = new HashSet<>();
expectedKeys.add("strM");
expectedKeys.add("unsupported");
assertEquals(expectedKeys, mandatoryKeys);
assertEquals(2, mandatoryKeys.size());
LambdaTestUtils.intercept(IllegalArgumentException.class,
"unsupported key found", builder::build
);
}
private static final int CRC_SIZE = 12;
private static final byte[] DATA = "1234567890".getBytes();
/**
* Get the statistics for the file schema. Contains assertions
* @return the statistics on all file:// IO.
*/
protected Statistics getFileStatistics() {
final List<Statistics> all = FileSystem.getAllStatistics();
final List<Statistics> fileStats = all
.stream()
.filter(s -> s.getScheme().equals("file"))
.collect(Collectors.toList());
assertEquals(1, fileStats.size(),
"Number of statistics counters for file://");
// this should be used for local and rawLocal, as they share the
// same schema (although their
|
BuilderWithSupportedKeys
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/customexceptions/GlobalThrowableExceptionMapperTest.java
|
{
"start": 786,
"end": 1397
}
|
class ____ {
@RegisterExtension
static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(Resource.class, ThrowableExceptionMapper.class);
}
});
@Test
public void test() {
RestAssured.get("/test/throwable")
.then().statusCode(415);
}
@Path("test")
public static
|
GlobalThrowableExceptionMapperTest
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java
|
{
"start": 29931,
"end": 30898
}
|
class ____ implements HandlerInterceptor, CorsConfigurationSource {
private final @Nullable CorsConfiguration config;
public CorsInterceptor(@Nullable CorsConfiguration config) {
this.config = config;
}
@Override
public @Nullable CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
return this.config;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// Consistent with CorsFilter, ignore ASYNC dispatches
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
if (asyncManager.hasConcurrentResult()) {
return true;
}
return invokeCorsProcessor(request, response);
}
protected boolean invokeCorsProcessor(
HttpServletRequest request, HttpServletResponse response) throws IOException {
return corsProcessor.processRequest(this.config, request, response);
}
}
private final
|
CorsInterceptor
|
java
|
alibaba__nacos
|
plugin/control/src/test/java/com/alibaba/nacos/plugin/control/ControlManagerBuilderTest.java
|
{
"start": 1563,
"end": 3580
}
|
class ____ implements ControlManagerBuilder {
@Override
public String getName() {
return "test";
}
@Override
public ConnectionControlManager buildConnectionControlManager() {
return new ConnectionControlManager() {
@Override
public String getName() {
return "testConnection";
}
@Override
public void applyConnectionLimitRule(ConnectionControlRule connectionControlRule) {
}
@Override
public ConnectionCheckResponse check(ConnectionCheckRequest connectionCheckRequest) {
ConnectionCheckResponse connectionCheckResponse = new ConnectionCheckResponse();
connectionCheckResponse.setSuccess(true);
connectionCheckResponse.setCode(ConnectionCheckCode.PASS_BY_TOTAL);
return connectionCheckResponse;
}
};
}
@Override
public TpsControlManager buildTpsControlManager() {
return new TpsControlManager() {
@Override
public void registerTpsPoint(String pointName) {
}
@Override
public Map<String, TpsBarrier> getPoints() {
return null;
}
@Override
public Map<String, TpsControlRule> getRules() {
return null;
}
@Override
public void applyTpsRule(String pointName, TpsControlRule rule) {
}
@Override
public TpsCheckResponse check(TpsCheckRequest tpsRequest) {
return new TpsCheckResponse(true, TpsResultCode.CHECK_SKIP, "skip");
}
@Override
public String getName() {
return "testTps";
}
};
}
}
|
ControlManagerBuilderTest
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/shell/TestPathExceptions.java
|
{
"start": 1163,
"end": 2844
}
|
class ____ {
protected String path = "some/file";
protected String error = "KABOOM";
@Test
public void testWithDefaultString() throws Exception {
PathIOException pe = new PathIOException(path);
assertEquals(new Path(path), pe.getPath());
assertEquals("`" + path + "': Input/output error", pe.getMessage());
}
@Test
public void testWithThrowable() throws Exception {
IOException ioe = new IOException("KABOOM");
PathIOException pe = new PathIOException(path, ioe);
assertEquals(new Path(path), pe.getPath());
assertEquals("`" + path + "': Input/output error: " + error, pe.getMessage());
}
@Test
public void testWithCustomString() throws Exception {
PathIOException pe = new PathIOException(path, error);
assertEquals(new Path(path), pe.getPath());
assertEquals("`" + path + "': " + error, pe.getMessage());
}
@Test
public void testRemoteExceptionUnwrap() throws Exception {
PathIOException pe;
RemoteException re;
IOException ie;
pe = new PathIOException(path);
re = new RemoteException(PathIOException.class.getName(), "test constructor1");
ie = re.unwrapRemoteException();
assertTrue(ie instanceof PathIOException);
ie = re.unwrapRemoteException(PathIOException.class);
assertTrue(ie instanceof PathIOException);
pe = new PathIOException(path, "constructor2");
re = new RemoteException(PathIOException.class.getName(), "test constructor2");
ie = re.unwrapRemoteException();
assertTrue(ie instanceof PathIOException);
ie = re.unwrapRemoteException(PathIOException.class);
assertTrue(ie instanceof PathIOException);
}
}
|
TestPathExceptions
|
java
|
apache__camel
|
components/camel-servicenow/camel-servicenow-component/src/test/java/org/apache/camel/component/servicenow/ServiceNowTableIT.java
|
{
"start": 1833,
"end": 14473
}
|
class ____ extends ServiceNowITSupport {
@Test
public void testRetrieveSome() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:servicenow");
mock.expectedMessageCount(1);
template().sendBodyAndHeaders(
"direct:servicenow",
null,
kvBuilder()
.put(ServiceNowConstants.RESOURCE, "table")
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_RETRIEVE)
.put(ServiceNowParams.SYSPARM_LIMIT, 10)
.put(ServiceNowParams.PARAM_TABLE_NAME, "incident")
.build());
mock.assertIsSatisfied();
Exchange exchange = mock.getExchanges().get(0);
List<Incident> items = exchange.getIn().getBody(List.class);
assertNotNull(items);
assertTrue(items.size() <= 10);
assertNotNull(exchange.getIn().getHeader(ServiceNowConstants.RESPONSE_TYPE));
assertNotNull(exchange.getIn().getHeader(ServiceNowConstants.OFFSET_FIRST));
assertNotNull(exchange.getIn().getHeader(ServiceNowConstants.OFFSET_NEXT));
assertNotNull(exchange.getIn().getHeader(ServiceNowConstants.OFFSET_LAST));
}
@Test
public void testRetrieveSomeWithParams() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:servicenow");
mock.expectedMessageCount(1);
template().sendBodyAndHeaders(
"direct:servicenow",
null,
kvBuilder()
.put(ServiceNowConstants.RESOURCE, "table")
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_RETRIEVE)
.put(ServiceNowParams.SYSPARM_LIMIT, 10)
.put(ServiceNowParams.SYSPARM_EXCLUDE_REFERENCE_LINK, false)
.put(ServiceNowParams.PARAM_TABLE_NAME, "incident")
.put(ServiceNowConstants.MODEL, IncidentWithParms.class)
.build());
mock.assertIsSatisfied();
Exchange exchange = mock.getExchanges().get(0);
List<Incident> items = exchange.getIn().getBody(List.class);
assertNotNull(items);
assertFalse(items.isEmpty());
assertTrue(items.size() <= 10);
assertNotNull(exchange.getIn().getHeader(ServiceNowConstants.RESPONSE_TYPE));
assertNotNull(exchange.getIn().getHeader(ServiceNowConstants.OFFSET_FIRST));
assertNotNull(exchange.getIn().getHeader(ServiceNowConstants.OFFSET_NEXT));
assertNotNull(exchange.getIn().getHeader(ServiceNowConstants.OFFSET_LAST));
}
@Test
public void testRetrieveSomeWithDefaults() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:servicenow-defaults");
mock.expectedMessageCount(1);
template().sendBodyAndHeaders(
"direct:servicenow-defaults",
null,
kvBuilder()
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_RETRIEVE)
.put(ServiceNowParams.SYSPARM_LIMIT, 10)
.build());
mock.assertIsSatisfied();
Exchange exchange = mock.getExchanges().get(0);
List<Incident> items = exchange.getIn().getBody(List.class);
assertNotNull(items);
assertTrue(items.size() <= 10);
}
@Test
public void testIncidentWorkflow() throws Exception {
Incident incident = null;
String sysId;
String number;
MockEndpoint mock = getMockEndpoint("mock:servicenow");
// ************************
// Create incident
// ************************
{
mock.reset();
mock.expectedMessageCount(1);
incident = new Incident();
incident.setDescription("my incident");
incident.setShortDescription("An incident");
incident.setSeverity(1);
incident.setImpact(1);
template().sendBodyAndHeaders(
"direct:servicenow",
incident,
kvBuilder()
.put(ServiceNowConstants.RESOURCE, "table")
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_CREATE)
.put(ServiceNowParams.PARAM_TABLE_NAME, "incident")
.build());
mock.assertIsSatisfied();
incident = mock.getExchanges().get(0).getIn().getBody(Incident.class);
sysId = incident.getId();
number = incident.getNumber();
LOGGER.info("****************************************************");
LOGGER.info(" Incident created");
LOGGER.info(" sysid = {}", sysId);
LOGGER.info(" number = {}", number);
LOGGER.info("****************************************************");
}
// ************************
// Search for the incident
// ************************
{
LOGGER.info("Search the record {}", sysId);
mock.reset();
mock.expectedMessageCount(1);
template().sendBodyAndHeaders(
"direct:servicenow",
null,
kvBuilder()
.put(ServiceNowConstants.RESOURCE, "table")
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_RETRIEVE)
.put(ServiceNowParams.PARAM_TABLE_NAME, "incident")
.put(ServiceNowParams.SYSPARM_QUERY, "number=" + number)
.build());
mock.assertIsSatisfied();
List<Incident> incidents = mock.getExchanges().get(0).getIn().getBody(List.class);
assertEquals(1, incidents.size());
assertEquals(number, incidents.get(0).getNumber());
assertEquals(sysId, incidents.get(0).getId());
}
// ************************
// Modify the incident
// ************************
{
LOGGER.info("Update the record {}", sysId);
mock.reset();
mock.expectedMessageCount(1);
incident = new Incident();
incident.setDescription("my incident");
incident.setShortDescription("The incident");
incident.setSeverity(2);
incident.setImpact(3);
template().sendBodyAndHeaders(
"direct:servicenow",
incident,
kvBuilder()
.put(ServiceNowConstants.RESOURCE, "table")
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_MODIFY)
.put(ServiceNowParams.PARAM_TABLE_NAME, "incident")
.put(ServiceNowParams.PARAM_SYS_ID, sysId)
.build());
mock.assertIsSatisfied();
incident = mock.getExchanges().get(0).getIn().getBody(Incident.class);
assertEquals(number, incident.getNumber());
assertEquals(2, incident.getSeverity());
assertEquals(3, incident.getImpact());
assertEquals("The incident", incident.getShortDescription());
}
// ************************
// Retrieve it via query
// ************************
{
LOGGER.info("Retrieve the record {}", sysId);
mock.reset();
mock.expectedMessageCount(1);
template().sendBodyAndHeaders(
"direct:servicenow",
null,
kvBuilder()
.put(ServiceNowConstants.RESOURCE, "table")
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_RETRIEVE)
.put(ServiceNowParams.PARAM_TABLE_NAME, "incident")
.put(ServiceNowParams.SYSPARM_QUERY, "number=" + number)
.build());
mock.assertIsSatisfied();
List<Incident> incidents = mock.getExchanges().get(0).getIn().getBody(List.class);
assertEquals(1, incidents.size());
assertEquals(number, incidents.get(0).getNumber());
assertEquals(sysId, incidents.get(0).getId());
assertEquals(2, incidents.get(0).getSeverity());
assertEquals(3, incidents.get(0).getImpact());
assertEquals("The incident", incidents.get(0).getShortDescription());
}
// ************************
// Retrieve by sys id
// ************************
{
LOGGER.info("Search the record {}", sysId);
mock.reset();
mock.expectedMessageCount(1);
template().sendBodyAndHeaders(
"direct:servicenow",
null,
kvBuilder()
.put(ServiceNowConstants.RESOURCE, "table")
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_RETRIEVE)
.put(ServiceNowParams.PARAM_TABLE_NAME, "incident")
.put(ServiceNowParams.PARAM_SYS_ID, sysId)
.build());
mock.assertIsSatisfied();
incident = mock.getExchanges().get(0).getIn().getBody(Incident.class);
assertEquals(2, incident.getSeverity());
assertEquals(3, incident.getImpact());
assertEquals("The incident", incident.getShortDescription());
assertEquals(number, incident.getNumber());
}
// ************************
// Delete it
// ************************
{
LOGGER.info("Delete the record {}", sysId);
mock.reset();
mock.expectedMessageCount(1);
template().sendBodyAndHeaders(
"direct:servicenow",
null,
kvBuilder()
.put(ServiceNowConstants.RESOURCE, "table")
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_DELETE)
.put(ServiceNowParams.PARAM_TABLE_NAME, "incident")
.put(ServiceNowParams.PARAM_SYS_ID, sysId)
.build());
mock.assertIsSatisfied();
}
// ************************
// Retrieve by id, should fail
// ************************
{
LOGGER.info("Find the record {}, should fail", sysId);
Map<String, Object> build = kvBuilder()
.put(ServiceNowConstants.RESOURCE, "table")
.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_RETRIEVE)
.put(ServiceNowParams.PARAM_SYS_ID, sysId)
.put(ServiceNowParams.PARAM_TABLE_NAME, "incident")
.build();
ProducerTemplate producerTemplate = template();
Exception ex = assertThrows(CamelExecutionException.class,
() -> producerTemplate.sendBodyAndHeaders("direct:servicenow", null, build));
assertTrue(ex.getCause() instanceof ServiceNowException);
}
}
// *************************************************************************
//
// *************************************************************************
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:servicenow")
.to("servicenow:{{env:SERVICENOW_INSTANCE}}"
+ "?model.incident=org.apache.camel.component.servicenow.model.Incident")
.to("log:org.apache.camel.component.servicenow?level=INFO&showAll=true")
.to("mock:servicenow");
from("direct:servicenow-defaults")
.to("servicenow:{{env:SERVICENOW_INSTANCE}}"
+ "?model.incident=org.apache.camel.component.servicenow.model.Incident"
+ "&resource=table"
+ "&table=incident")
.to("log:org.apache.camel.component.servicenow?level=INFO&showAll=true")
.to("mock:servicenow-defaults");
}
};
}
}
|
ServiceNowTableIT
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/ShortArrayAssertBaseTest.java
|
{
"start": 1012,
"end": 1511
}
|
class ____ extends BaseTestTemplate<ShortArrayAssert, short[]> {
protected ShortArrays arrays;
@Override
protected ShortArrayAssert create_assertions() {
return new ShortArrayAssert(emptyArray());
}
@Override
protected void inject_internal_objects() {
super.inject_internal_objects();
arrays = mock(ShortArrays.class);
writeField(assertions, "arrays", arrays);
}
@AfterEach
public void tearDown() {
arrays = ShortArrays.instance();
}
}
|
ShortArrayAssertBaseTest
|
java
|
apache__flink
|
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/TypeInferenceExtractorTest.java
|
{
"start": 127857,
"end": 128235
}
|
class ____
extends ProcessTableFunction<Integer> {
public void eval(
@ArgumentHint(
value = ArgumentTrait.ROW_SEMANTIC_TABLE,
type = @DataTypeHint(inputGroup = InputGroup.ANY))
Row r) {}
}
private static
|
InvalidInputGroupTableArgProcessTableFunction
|
java
|
apache__camel
|
test-infra/camel-test-infra-postgres/src/test/java/org/apache/camel/test/infra/postgres/services/PostgresServiceFactory.java
|
{
"start": 950,
"end": 1408
}
|
class ____ {
private PostgresServiceFactory() {
}
public static SimpleTestServiceBuilder<PostgresService> builder() {
return new SimpleTestServiceBuilder<>("postgres");
}
public static PostgresService createService() {
return builder().addLocalMapping(PostgresLocalContainerService::new)
.addRemoteMapping(PostgresRemoteService::new)
.build();
}
public static
|
PostgresServiceFactory
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/FairCallQueueMXBean.java
|
{
"start": 847,
"end": 1045
}
|
interface ____ {
// Get the size of each subqueue, the index corresponding to the priority
// level.
int[] getQueueSizes();
long[] getOverflowedCalls();
int getRevision();
}
|
FairCallQueueMXBean
|
java
|
spring-projects__spring-boot
|
buildSrc/src/test/java/org/springframework/boot/build/architecture/annotations/TestConditionalOnClass.java
|
{
"start": 1024,
"end": 1125
}
|
interface ____ {
Class<?>[] value() default {};
String[] name() default {};
}
|
TestConditionalOnClass
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/ITestAbfsMsiTokenProvider.java
|
{
"start": 2005,
"end": 3713
}
|
class ____
extends AbstractAbfsIntegrationTest {
public ITestAbfsMsiTokenProvider() throws Exception {
super();
}
@Test
public void test() throws IOException {
AbfsConfiguration conf = getConfiguration();
assumeThat(conf.get(FS_AZURE_ACCOUNT_OAUTH_MSI_ENDPOINT))
.isNotNull().isNotEmpty();
assumeThat(conf.get(FS_AZURE_ACCOUNT_OAUTH_MSI_TENANT))
.isNotNull().isNotEmpty();
assumeThat(conf.get(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ID))
.isNotNull().isNotEmpty();
assumeThat(conf.get(FS_AZURE_ACCOUNT_OAUTH_MSI_AUTHORITY))
.isNotNull().isNotEmpty();
String tenantGuid = conf
.getPasswordString(FS_AZURE_ACCOUNT_OAUTH_MSI_TENANT);
String clientId = conf.getPasswordString(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ID);
String authEndpoint = getTrimmedPasswordString(conf,
FS_AZURE_ACCOUNT_OAUTH_MSI_ENDPOINT,
DEFAULT_FS_AZURE_ACCOUNT_OAUTH_MSI_ENDPOINT);
String authority = getTrimmedPasswordString(conf,
FS_AZURE_ACCOUNT_OAUTH_MSI_AUTHORITY,
DEFAULT_FS_AZURE_ACCOUNT_OAUTH_MSI_AUTHORITY);
AccessTokenProvider tokenProvider = new MsiTokenProvider(authEndpoint,
tenantGuid, clientId, authority);
AzureADToken token = null;
token = tokenProvider.getToken();
assertThat(token.getAccessToken()).isNotEmpty();
assertThat(token.getExpiry().after(new Date())).isEqualTo(true);
}
private String getTrimmedPasswordString(AbfsConfiguration conf, String key,
String defaultValue) throws IOException {
String value = conf.getPasswordString(key);
if (StringUtils.isBlank(value)) {
value = defaultValue;
}
return value.trim();
}
}
|
ITestAbfsMsiTokenProvider
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/MockInputSplitProvider.java
|
{
"start": 1218,
"end": 1285
}
|
interface ____ serve input
* splits to the test jobs.
*
* <p>This
|
to
|
java
|
apache__kafka
|
storage/src/main/java/org/apache/kafka/storage/internals/log/VerificationStateEntry.java
|
{
"start": 860,
"end": 1659
}
|
class ____ the verification state of a specific producer id.
* It contains a VerificationGuard that is used to uniquely identify the transaction we want to verify.
* After verifying, we retain this object until we append to the log. This prevents any race conditions where the transaction
* may end via a control marker before we write to the log. This mechanism is used to prevent hanging transactions.
* We remove the VerificationGuard whenever we write data to the transaction or write an end marker for the transaction.
*
* We also store the lowest seen sequence to block a higher sequence from being written in the case of the lower sequence needing retries.
*
* Any lingering entries that are never verified are removed via the producer state entry cleanup mechanism.
*/
public
|
represents
|
java
|
spring-projects__spring-framework
|
spring-web/src/main/java/org/springframework/http/support/Netty4HeadersAdapter.java
|
{
"start": 5681,
"end": 6436
}
|
class ____ implements Iterator<String> {
private final Iterator<String> iterator;
private @Nullable String currentName;
private HeaderNamesIterator(Iterator<String> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return this.iterator.hasNext();
}
@Override
public String next() {
this.currentName = this.iterator.next();
return this.currentName;
}
@Override
public void remove() {
if (this.currentName == null) {
throw new IllegalStateException("No current Header in iterator");
}
if (!headers.contains(this.currentName)) {
throw new IllegalStateException("Header not present: " + this.currentName);
}
headers.remove(this.currentName);
}
}
}
|
HeaderNamesIterator
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/matchers/MethodReturnsNonNullStringTest.java
|
{
"start": 2394,
"end": 3315
}
|
class ____ {
public String getString() {
return "test string";
}
public void testMethodInvocation() {
getString();
}
}
""");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ false, Matchers.methodReturnsNonNull()));
}
private Scanner methodInvocationMatches(boolean shouldMatch, Matcher<ExpressionTree> toMatch) {
return new Scanner() {
@Override
public Void visitMethodInvocation(MethodInvocationTree node, VisitorState visitorState) {
ExpressionTree methodSelect = node.getMethodSelect();
if (!methodSelect.toString().equals("super")) {
assertWithMessage(methodSelect.toString())
.that(!shouldMatch ^ toMatch.matches(node, visitorState))
.isTrue();
}
return super.visitMethodInvocation(node, visitorState);
}
};
}
}
|
A
|
java
|
apache__camel
|
core/camel-cloud/src/test/java/org/apache/camel/impl/cloud/CombinedServiceDiscoveryTest.java
|
{
"start": 1333,
"end": 4953
}
|
class ____ extends ContextTestSupport {
@Test
public void testCombinedServiceDiscovery() {
StaticServiceDiscovery discovery1 = new StaticServiceDiscovery();
discovery1.addServer(new DefaultServiceDefinition("discovery1", "localhost", 1111));
discovery1.addServer(new DefaultServiceDefinition("discovery1", "localhost", 1112));
StaticServiceDiscovery discovery2 = new StaticServiceDiscovery();
discovery2.addServer(new DefaultServiceDefinition("discovery1", "localhost", 1113));
discovery2.addServer(new DefaultServiceDefinition("discovery2", "localhost", 1114));
CombinedServiceDiscovery discovery = CombinedServiceDiscovery.wrap(discovery1, discovery2);
assertEquals(3, discovery.getServices("discovery1").size());
assertEquals(1, discovery.getServices("discovery2").size());
}
@Test
public void testCombinedServiceDiscoveryConfiguration() throws Exception {
StaticServiceCallServiceDiscoveryConfiguration staticConf1 = new StaticServiceCallServiceDiscoveryConfiguration();
staticConf1.setServers(Arrays.asList("discovery1@localhost:1111", "discovery1@localhost:1112"));
StaticServiceCallServiceDiscoveryConfiguration staticConf2 = new StaticServiceCallServiceDiscoveryConfiguration();
staticConf2.setServers(Arrays.asList("discovery1@localhost:1113", "discovery2@localhost:1114"));
CombinedServiceCallServiceDiscoveryConfiguration multiConf = new CombinedServiceCallServiceDiscoveryConfiguration();
multiConf.setServiceDiscoveryConfigurations(Arrays.asList(staticConf1, staticConf2));
CombinedServiceDiscovery discovery = (CombinedServiceDiscovery) multiConf.newInstance(context);
assertEquals(2, discovery.getDelegates().size());
assertEquals(3, discovery.getServices("discovery1").size());
assertEquals(1, discovery.getServices("discovery2").size());
}
@Test
public void testCombinedServiceDiscoveryConfigurationDsl() throws Exception {
CombinedServiceCallServiceDiscoveryConfiguration multiConf = new CombinedServiceCallServiceDiscoveryConfiguration();
multiConf.staticServiceDiscovery().setServers(Arrays.asList("discovery1@localhost:1111", "discovery1@localhost:1112"));
multiConf.staticServiceDiscovery().setServers(Arrays.asList("discovery1@localhost:1113", "discovery2@localhost:1114"));
CombinedServiceDiscovery discovery = (CombinedServiceDiscovery) multiConf.newInstance(context);
assertEquals(2, discovery.getDelegates().size());
assertEquals(3, discovery.getServices("discovery1").size());
assertEquals(1, discovery.getServices("discovery2").size());
}
@Test
public void testCombinedServiceDiscoveryConfigurationWithPlaceholders() throws Exception {
System.setProperty("svc-list-1", "discovery1@localhost:1111,discovery1@localhost:1112");
System.setProperty("svc-list-2", "discovery1@localhost:1113,discovery2@localhost:1114");
CombinedServiceCallServiceDiscoveryConfiguration multiConf = new CombinedServiceCallServiceDiscoveryConfiguration();
multiConf.staticServiceDiscovery().servers("{{svc-list-1}}");
multiConf.staticServiceDiscovery().servers("{{svc-list-2}}");
CombinedServiceDiscovery discovery = (CombinedServiceDiscovery) multiConf.newInstance(context);
assertEquals(2, discovery.getDelegates().size());
assertEquals(3, discovery.getServices("discovery1").size());
assertEquals(1, discovery.getServices("discovery2").size());
}
}
|
CombinedServiceDiscoveryTest
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/routebuilder/SpringTemplatedRouteTest.java
|
{
"start": 1971,
"end": 2331
}
|
class ____ {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Handler
public String addName(String body) {
return String.format("%s %s!", body, name);
}
}
public static
|
MySpecialBean
|
java
|
elastic__elasticsearch
|
test/framework/src/main/java/org/elasticsearch/test/readiness/ReadinessClientProbe.java
|
{
"start": 1232,
"end": 3474
}
|
interface ____ {
Logger probeLogger = LogManager.getLogger(ReadinessClientProbe.class);
default void tcpReadinessProbeTrue(ReadinessService readinessService) throws Exception {
tcpReadinessProbeTrue(readinessService.boundAddress().publishAddress().getPort());
}
// extracted because suppress forbidden checks have issues with lambdas
@SuppressForbidden(reason = "Intentional socket open")
default boolean channelConnect(SocketChannel channel, InetSocketAddress socketAddress) throws IOException {
return channel.connect(socketAddress);
}
@SuppressForbidden(reason = "Intentional socket open")
default void tcpReadinessProbeTrue(Integer port) throws Exception {
InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
try (SocketChannel channel = SocketChannel.open(StandardProtocolFamily.INET)) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
try {
channelConnect(channel, socketAddress);
// if we succeeded to connect the server is ready
} catch (IOException e) {
fail("Shouldn't reach here");
}
return null;
});
}
}
default void tcpReadinessProbeFalse(ReadinessService readinessService) throws Exception {
tcpReadinessProbeFalse(readinessService.boundAddress().publishAddress().getPort());
}
@SuppressForbidden(reason = "Intentional socket open")
default void tcpReadinessProbeFalse(Integer port) throws Exception {
InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
try (SocketChannel channel = SocketChannel.open(StandardProtocolFamily.INET)) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
expectThrows(ConnectException.class, () -> {
var result = channelConnect(channel, socketAddress);
probeLogger.info("No exception on channel connect, connection success [{}]", result);
});
return null;
});
}
}
}
|
ReadinessClientProbe
|
java
|
apache__camel
|
components/camel-micrometer/src/main/java/org/apache/camel/component/micrometer/DistributionStatisticConfigFilter.java
|
{
"start": 1681,
"end": 7821
}
|
class ____ implements MeterFilter {
private Predicate<Meter.Id> appliesTo = ALWAYS;
private Long maximumExpectedValue;
private Long minimumExpectedValue;
private Boolean publishPercentileHistogram = true;
private Integer percentilePrecision;
private Integer bufferLength;
private Duration expiry;
private double[] percentiles;
private long[] slas;
@Override
public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) {
if (CAMEL_METERS.and(appliesTo).test(id)) {
return DistributionStatisticConfig.builder()
.percentilesHistogram(publishPercentileHistogram)
.percentiles(percentiles)
.percentilePrecision(percentilePrecision)
.maximumExpectedValue((double) maximumExpectedValue)
.minimumExpectedValue((double) minimumExpectedValue)
.serviceLevelObjectives(LongStream.of(slas).asDoubleStream().toArray())
.bufferLength(bufferLength)
.expiry(expiry)
.build()
.merge(config);
}
return config;
}
/**
* Restrict a condition under which this config applies to a Camel meter
*
* @param appliesTo predicate that must return true so that this config applies
*/
public DistributionStatisticConfigFilter andAppliesTo(Predicate<Meter.Id> appliesTo) {
this.appliesTo = this.appliesTo.and(appliesTo);
return this;
}
/**
* Add a condition under which this config applies to a Camel meter
*
* @param appliesTo predicate that must return true so that this config applies
*/
public DistributionStatisticConfigFilter orAppliesTo(Predicate<Meter.Id> appliesTo) {
this.appliesTo = this.appliesTo.or(appliesTo);
return this;
}
/**
* Sets the maximum expected value for a distribution summary value. Controls the number of buckets shipped by
* publishPercentileHistogram as well as controlling the accuracy and memory footprint of the underlying
* HdrHistogram structure.
*
* @param maximumExpectedValue the maximum expected value for a distribution summary value
*/
public DistributionStatisticConfigFilter setMaximumExpectedValue(Long maximumExpectedValue) {
this.maximumExpectedValue = maximumExpectedValue;
return this;
}
/**
* Sets the minimum expected value for a distribution summary value. Controls the number of buckets shipped by
* publishPercentileHistogram as well as controlling the accuracy and memory footprint of the underlying
* HdrHistogram structure.
*
* @param minimumExpectedValue the minimum expected value for a distribution summary value
*/
public DistributionStatisticConfigFilter setMinimumExpectedValue(Long minimumExpectedValue) {
this.minimumExpectedValue = minimumExpectedValue;
return this;
}
/**
* Sets the maximum expected duration for a timer value Controls the number of buckets shipped by
* publishPercentileHistogram as well as controlling the accuracy and memory footprint of the underlying
* HdrHistogram structure.
*
* @param maximumExpectedDuration the maximum expected duration for a timer value
*/
public DistributionStatisticConfigFilter setMaximumExpectedDuration(Duration maximumExpectedDuration) {
this.maximumExpectedValue = maximumExpectedDuration.toNanos();
return this;
}
/**
* Sets the minimum expected duration for a timer value Controls the number of buckets shipped by
* publishPercentileHistogram as well as controlling the accuracy and memory footprint of the underlying
* HdrHistogram structure.
*
* @param minimumExpectedDuration the minimum expected duration for a timer value
*/
public DistributionStatisticConfigFilter setMinimumExpectedDuration(Duration minimumExpectedDuration) {
this.minimumExpectedValue = minimumExpectedDuration.toNanos();
return this;
}
/**
* Whether to publish aggregatable percentile approximations for Prometheus or Atlas. Has no effect on systems that
* do not support aggregatable percentile approximations. This defaults to true.
*
* @param publishPercentileHistogram Whether to publish aggregatable percentile approximations.
*/
public DistributionStatisticConfigFilter setPublishPercentileHistogram(Boolean publishPercentileHistogram) {
this.publishPercentileHistogram = publishPercentileHistogram;
return this;
}
public DistributionStatisticConfigFilter setBufferLength(Integer bufferLength) {
this.bufferLength = bufferLength;
return this;
}
public DistributionStatisticConfigFilter setExpiry(Duration expiry) {
this.expiry = expiry;
return this;
}
/**
* Calculate and publish percentile values. These values are non-aggregatable across dimensions.
*
* @param percentiles array of percentiles to be published
*/
public DistributionStatisticConfigFilter setPercentiles(double[] percentiles) {
this.percentiles = percentiles;
return this;
}
public DistributionStatisticConfigFilter setPercentilePrecision(Integer percentilePrecision) {
this.percentilePrecision = percentilePrecision;
return this;
}
/**
* Publish a cumulative histogram with buckets defined by your SLAs. Used together with publishPercentileHistogram
* on a monitoring system that supports aggregatable percentiles, this setting adds additional buckets to the
* published histogram. Used on a system that does not support aggregatable percentiles, this setting causes a
* histogram to be published with only these buckets.
*
* @param slas array of percentiles to be published
*/
public DistributionStatisticConfigFilter setSlas(long[] slas) {
this.slas = slas;
return this;
}
}
|
DistributionStatisticConfigFilter
|
java
|
google__auto
|
common/src/test/java/com/google/auto/common/AnnotationMirrorsTest.java
|
{
"start": 8558,
"end": 8692
}
|
interface ____ {}
@AnnotatedAnnotation1
@NotAnnotatedAnnotation
@AnnotatedAnnotation2
private static final
|
NotAnnotatedAnnotation
|
java
|
quarkusio__quarkus
|
integration-tests/kafka-devservices/src/test/java/io/quarkus/it/kafka/continuoustesting/DevServicesContainerSharingTest.java
|
{
"start": 766,
"end": 1895
}
|
class ____ extends BaseDevServiceTest {
@RegisterExtension
public static QuarkusDevModeTest test = new QuarkusDevModeTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.deleteClass(KafkaEndpoint.class)
.addClass(BundledEndpoint.class)
.addClass(KafkaAdminManager.class))
.setTestArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class).addClass(KafkaAdminTest.class));
static StrimziKafkaContainer kafka;
@BeforeAll
static void beforeAll() {
kafka = new StrimziKafkaContainer().withLabel("quarkus-dev-service-kafka", "kafka");
kafka.start();
}
@AfterAll
static void afterAll() {
if (kafka != null) {
kafka.stop();
kafka = null;
}
}
@Test
void test() {
ping();
assertTrue(getKafkaContainers(LaunchMode.DEVELOPMENT).isEmpty());
}
void ping() {
when().get("/kafka/partitions/test").then()
.statusCode(200)
.body(is("2"));
}
}
|
DevServicesContainerSharingTest
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.