language
stringclasses 1
value | repo
stringclasses 60
values | path
stringlengths 22
294
| class_span
dict | source
stringlengths 13
1.16M
| target
stringlengths 1
113
|
|---|---|---|---|---|---|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/join/TestDatamerge.java
|
{
"start": 5495,
"end": 6253
}
|
class ____
extends SimpleCheckerBase<TupleWritable> {
public void map(IntWritable key, TupleWritable val,
OutputCollector<IntWritable, IntWritable> out, Reporter reporter)
throws IOException {
int k = key.get();
final String kvstr = "Unexpected tuple: " + stringify(key, val);
assertEquals(0, k % (srcs * srcs), kvstr);
for (int i = 0; i < val.size(); ++i) {
final int vali = ((IntWritable)val.get(i)).get();
assertEquals((vali - i) * srcs, 10 * k, kvstr);
}
out.collect(key, one);
}
public boolean verify(int key, int occ) {
return (key == 0 && occ == 2) ||
(key != 0 && (key % (srcs * srcs) == 0) && occ == 1);
}
}
private static
|
InnerJoinChecker
|
java
|
square__retrofit
|
retrofit/java-test/src/test/java/retrofit2/RetrofitTest.java
|
{
"start": 39990,
"end": 41172
}
|
class ____.lang.String.\n"
+ " Tried:\n"
+ " * retrofit2.BuiltInConverters\n"
+ " * retrofit2.helpers.NonMatchingConverterFactory\n"
+ " * retrofit2.OptionalConverterFactory");
}
assertThat(nonMatchingFactory.called).isTrue();
}
@Test
public void responseConverterFactorySkippedNoMatchThrows() {
Type type = String.class;
Annotation[] annotations = new Annotation[0];
NonMatchingConverterFactory nonMatchingFactory1 = new NonMatchingConverterFactory();
NonMatchingConverterFactory nonMatchingFactory2 = new NonMatchingConverterFactory();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addConverterFactory(nonMatchingFactory1)
.addConverterFactory(nonMatchingFactory2)
.build();
try {
retrofit.nextResponseBodyConverter(nonMatchingFactory1, type, annotations);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessageThat()
.isEqualTo(
""
+ "Could not locate ResponseBody converter for
|
java
|
java
|
apache__camel
|
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/JettyStreamCacheIssueTest.java
|
{
"start": 1104,
"end": 2644
}
|
class ____ extends BaseJettyTest {
private String input;
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
// ensure we overflow and spool to disk
context.getStreamCachingStrategy().setSpoolEnabled(true);
context.getStreamCachingStrategy().setSpoolThreshold(5000);
context.setStreamCaching(true);
return context;
}
@Test
public void testStreamCache() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
sb.append("0123456789");
}
input = sb.toString();
String out = template.requestBody("direct:input", input, String.class);
assertEquals(input, out);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:input").to("http://localhost:" + getPort() + "/input");
from("jetty:http://localhost:" + getPort() + "/input").process(new Processor() {
@Override
public void process(final Exchange exchange) {
// Get message returns the in message if an out one is not present, which is the expectation here
assertEquals(input, exchange.getMessage().getBody(String.class));
}
});
}
};
}
}
|
JettyStreamCacheIssueTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/emops/MergeMultipleEntityCopiesAllowedTest.java
|
{
"start": 1074,
"end": 4255
}
|
class ____ {
@AfterEach
void cleanup(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory().getSchemaManager().truncate();
}
@Test
public void testCascadeFromDetachedToNonDirtyRepresentations(EntityManagerFactoryScope scope) {
Item item1 = new Item();
item1.setName( "item1" );
Hoarder hoarder = new Hoarder();
hoarder.setName( "joe" );
scope.inTransaction(
entityManager -> {
entityManager.persist( item1 );
entityManager.persist( hoarder );
}
);
// Get another representation of the same Item from a different EntityManager.
Item item1_1 = scope.fromTransaction(
entityManager -> entityManager.find( Item.class, item1.getId() )
);
// item1_1 and item1_2 are unmodified representations of the same persistent entity.
assertFalse( item1 == item1_1 );
assertTrue( item1.equals( item1_1 ) );
// Update hoarder (detached) to reference both representations.
hoarder.getItems().add( item1 );
hoarder.setFavoriteItem( item1_1 );
Hoarder hoarder2 = scope.fromTransaction(
entityManager -> {
Hoarder _hoarder = entityManager.merge( hoarder );
assertEquals( 1, _hoarder.getItems().size() );
assertSame( _hoarder.getFavoriteItem(), _hoarder.getItems().iterator().next() );
assertEquals( item1.getId(), _hoarder.getFavoriteItem().getId() );
assertEquals( item1.getCategory(), _hoarder.getFavoriteItem().getCategory() );
return _hoarder;
}
);
scope.inTransaction(
entityManager -> {
Hoarder _hoarder = entityManager.merge( hoarder2 );
assertEquals( 1, _hoarder.getItems().size() );
assertSame( _hoarder.getFavoriteItem(), _hoarder.getItems().iterator().next() );
assertEquals( item1.getId(), _hoarder.getFavoriteItem().getId() );
assertEquals( item1.getCategory(), _hoarder.getFavoriteItem().getCategory() );
}
);
}
@Test
public void testTopLevelManyToOneManagedNestedIsDetached(EntityManagerFactoryScope scope) {
Item item1 = new Item();
item1.setName( "item1 name" );
Category category = new Category();
category.setName( "category" );
item1.setCategory( category );
category.setExampleItem( item1 );
scope.inTransaction(
entityManager -> {
entityManager.persist( item1 );
}
);
// get another representation of item1
Item item1_1 = scope.fromTransaction(
entityManager -> entityManager.find( Item.class, item1.getId() )
);
scope.inTransaction(
entityManager -> {
Item item1Merged = entityManager.merge( item1 );
item1Merged.setCategory( category );
category.setExampleItem( item1_1 );
// now item1Merged is managed and it has a nested detached item
entityManager.merge( item1Merged );
assertEquals( category.getName(), item1Merged.getCategory().getName() );
assertSame( item1Merged, item1Merged.getCategory().getExampleItem() );
}
);
scope.inTransaction(
entityManager -> {
Item _item1 = entityManager.find( Item.class, item1.getId() );
assertEquals( category.getName(), _item1.getCategory().getName() );
assertSame( _item1, _item1.getCategory().getExampleItem() );
}
);
}
}
|
MergeMultipleEntityCopiesAllowedTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/OpenIndexStep.java
|
{
"start": 770,
"end": 1919
}
|
class ____ extends AsyncActionStep {
static final String NAME = "open-index";
OpenIndexStep(StepKey key, StepKey nextStepKey, Client client) {
super(key, nextStepKey, client);
}
@Override
public void performAction(
IndexMetadata indexMetadata,
ProjectState currentState,
ClusterStateObserver observer,
ActionListener<Void> listener
) {
if (indexMetadata.getState() == IndexMetadata.State.CLOSE) {
OpenIndexRequest request = new OpenIndexRequest(indexMetadata.getIndex().getName()).masterNodeTimeout(TimeValue.MAX_VALUE);
getClient(currentState.projectId()).admin().indices().open(request, listener.delegateFailureAndWrap((l, openIndexResponse) -> {
if (openIndexResponse.isAcknowledged() == false) {
throw new ElasticsearchException("open index request failed to be acknowledged");
}
l.onResponse(null);
}));
} else {
listener.onResponse(null);
}
}
@Override
public boolean isRetryable() {
return true;
}
}
|
OpenIndexStep
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DebeziumMySqlEndpointBuilderFactory.java
|
{
"start": 121063,
"end": 124593
}
|
class ____ should be used to
* determine the topic name for data change, schema change, transaction,
* heartbeat event etc.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: io.debezium.schema.SchemaTopicNamingStrategy
* Group: mysql
*
* @param topicNamingStrategy the value to set
* @return the dsl builder
*/
default DebeziumMySqlEndpointBuilder topicNamingStrategy(String topicNamingStrategy) {
doSetProperty("topicNamingStrategy", topicNamingStrategy);
return this;
}
/**
* Topic prefix that identifies and provides a namespace for the
* particular database server/cluster is capturing changes. The topic
* prefix should be unique across all other connectors, since it is used
* as a prefix for all Kafka topic names that receive events emitted by
* this connector. Only alphanumeric characters, hyphens, dots and
* underscores must be accepted.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: mysql
*
* @param topicPrefix the value to set
* @return the dsl builder
*/
default DebeziumMySqlEndpointBuilder topicPrefix(String topicPrefix) {
doSetProperty("topicPrefix", topicPrefix);
return this;
}
/**
* Class to make transaction context & transaction struct/schemas.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default:
* io.debezium.pipeline.txmetadata.DefaultTransactionMetadataFactory
* Group: mysql
*
* @param transactionMetadataFactory the value to set
* @return the dsl builder
*/
default DebeziumMySqlEndpointBuilder transactionMetadataFactory(String transactionMetadataFactory) {
doSetProperty("transactionMetadataFactory", transactionMetadataFactory);
return this;
}
/**
* Whether to use socket.setSoLinger(true, 0) when BinaryLogClient
* keepalive thread triggers a disconnect for a stale connection.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: mysql
*
* @param useNongracefulDisconnect the value to set
* @return the dsl builder
*/
default DebeziumMySqlEndpointBuilder useNongracefulDisconnect(boolean useNongracefulDisconnect) {
doSetProperty("useNongracefulDisconnect", useNongracefulDisconnect);
return this;
}
/**
* Whether to use socket.setSoLinger(true, 0) when BinaryLogClient
* keepalive thread triggers a disconnect for a stale connection.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: mysql
*
* @param useNongracefulDisconnect the value to set
* @return the dsl builder
*/
default DebeziumMySqlEndpointBuilder useNongracefulDisconnect(String useNongracefulDisconnect) {
doSetProperty("useNongracefulDisconnect", useNongracefulDisconnect);
return this;
}
}
/**
* Advanced builder for endpoint for the Debezium MySQL Connector component.
*/
public
|
that
|
java
|
netty__netty
|
transport-classes-kqueue/src/main/java/io/netty/channel/kqueue/KQueueEventLoopGroup.java
|
{
"start": 1993,
"end": 9551
}
|
class ____ loaded by this time!
KQueue.ensureAvailability();
}
private static final InternalLogger LOGGER = InternalLoggerFactory.getInstance(KQueueEventLoopGroup.class);
/**
* Create a new instance using the default number of threads and the default {@link ThreadFactory}.
*/
public KQueueEventLoopGroup() {
this(0);
}
/**
* Create a new instance using the specified number of threads and the default {@link ThreadFactory}.
*/
public KQueueEventLoopGroup(int nThreads) {
this(nThreads, (ThreadFactory) null);
}
/**
* Create a new instance using the default number of threads and the given {@link ThreadFactory}.
*/
@SuppressWarnings("deprecation")
public KQueueEventLoopGroup(ThreadFactory threadFactory) {
this(0, threadFactory, 0);
}
/**
* Create a new instance using the specified number of threads and the default {@link ThreadFactory}.
*/
@SuppressWarnings("deprecation")
public KQueueEventLoopGroup(int nThreads, SelectStrategyFactory selectStrategyFactory) {
this(nThreads, (ThreadFactory) null, selectStrategyFactory);
}
/**
* Create a new instance using the specified number of threads and the given {@link ThreadFactory}.
*/
@SuppressWarnings("deprecation")
public KQueueEventLoopGroup(int nThreads, ThreadFactory threadFactory) {
this(nThreads, threadFactory, 0);
}
public KQueueEventLoopGroup(int nThreads, Executor executor) {
this(nThreads, executor, DefaultSelectStrategyFactory.INSTANCE);
}
/**
* Create a new instance using the specified number of threads and the given {@link ThreadFactory}.
*/
@SuppressWarnings("deprecation")
public KQueueEventLoopGroup(int nThreads, ThreadFactory threadFactory,
SelectStrategyFactory selectStrategyFactory) {
this(nThreads, threadFactory, 0, selectStrategyFactory);
}
/**
* Create a new instance using the specified number of threads, the given {@link ThreadFactory} and the given
* maximal amount of epoll events to handle per epollWait(...).
*
* @deprecated Use {@link #KQueueEventLoopGroup(int)} or {@link #KQueueEventLoopGroup(int, ThreadFactory)}
*/
@Deprecated
public KQueueEventLoopGroup(int nThreads, ThreadFactory threadFactory, int maxEventsAtOnce) {
this(nThreads, threadFactory, maxEventsAtOnce, DefaultSelectStrategyFactory.INSTANCE);
}
/**
* Create a new instance using the specified number of threads, the given {@link ThreadFactory} and the given
* maximal amount of epoll events to handle per epollWait(...).
*
* @deprecated Use {@link #KQueueEventLoopGroup(int)}, {@link #KQueueEventLoopGroup(int, ThreadFactory)}, or
* {@link #KQueueEventLoopGroup(int, SelectStrategyFactory)}
*/
@Deprecated
public KQueueEventLoopGroup(int nThreads, ThreadFactory threadFactory, int maxEventsAtOnce,
SelectStrategyFactory selectStrategyFactory) {
super(nThreads, threadFactory, KQueueIoHandler.newFactory(maxEventsAtOnce, selectStrategyFactory),
RejectedExecutionHandlers.reject());
}
public KQueueEventLoopGroup(int nThreads, Executor executor, SelectStrategyFactory selectStrategyFactory) {
super(nThreads, executor, KQueueIoHandler.newFactory(0, selectStrategyFactory),
RejectedExecutionHandlers.reject());
}
public KQueueEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
SelectStrategyFactory selectStrategyFactory) {
super(nThreads, executor, KQueueIoHandler.newFactory(0, selectStrategyFactory),
chooserFactory, RejectedExecutionHandlers.reject());
}
public KQueueEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
SelectStrategyFactory selectStrategyFactory,
RejectedExecutionHandler rejectedExecutionHandler) {
super(nThreads, executor, KQueueIoHandler.newFactory(0, selectStrategyFactory), chooserFactory,
rejectedExecutionHandler);
}
public KQueueEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
SelectStrategyFactory selectStrategyFactory,
RejectedExecutionHandler rejectedExecutionHandler,
EventLoopTaskQueueFactory queueFactory) {
super(nThreads, executor, KQueueIoHandler.newFactory(0, selectStrategyFactory), chooserFactory,
rejectedExecutionHandler, queueFactory);
}
/**
* @param nThreads the number of threads that will be used by this instance.
* @param executor the Executor to use, or {@code null} if default one should be used.
* @param chooserFactory the {@link EventExecutorChooserFactory} to use.
* @param selectStrategyFactory the {@link SelectStrategyFactory} to use.
* @param rejectedExecutionHandler the {@link RejectedExecutionHandler} to use.
* @param taskQueueFactory the {@link EventLoopTaskQueueFactory} to use for
* {@link SingleThreadEventLoop#execute(Runnable)},
* or {@code null} if default one should be used.
* @param tailTaskQueueFactory the {@link EventLoopTaskQueueFactory} to use for
* {@link SingleThreadEventLoop#executeAfterEventLoopIteration(Runnable)},
* or {@code null} if default one should be used.
*/
public KQueueEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
SelectStrategyFactory selectStrategyFactory,
RejectedExecutionHandler rejectedExecutionHandler,
EventLoopTaskQueueFactory taskQueueFactory,
EventLoopTaskQueueFactory tailTaskQueueFactory) {
super(nThreads, executor, KQueueIoHandler.newFactory(0, selectStrategyFactory), chooserFactory,
rejectedExecutionHandler, taskQueueFactory, tailTaskQueueFactory);
}
/**
* This method is a no-op.
*
* @deprecated
*/
@Deprecated
public void setIoRatio(int ioRatio) {
LOGGER.debug("EpollEventLoopGroup.setIoRatio(int) logic was removed, this is a no-op");
}
@Override
protected IoEventLoop newChild(Executor executor, IoHandlerFactory ioHandlerFactory, Object... args) {
RejectedExecutionHandler rejectedExecutionHandler = null;
EventLoopTaskQueueFactory taskQueueFactory = null;
EventLoopTaskQueueFactory tailTaskQueueFactory = null;
int argsLength = args.length;
if (argsLength > 0) {
rejectedExecutionHandler = (RejectedExecutionHandler) args[0];
}
if (argsLength > 1) {
taskQueueFactory = (EventLoopTaskQueueFactory) args[2];
}
if (argsLength > 2) {
tailTaskQueueFactory = (EventLoopTaskQueueFactory) args[1];
}
return new KQueueEventLoop(this, executor, ioHandlerFactory,
KQueueEventLoop.newTaskQueue(taskQueueFactory),
KQueueEventLoop.newTaskQueue(tailTaskQueueFactory),
rejectedExecutionHandler);
}
private static final
|
is
|
java
|
apache__camel
|
components/camel-opensearch/src/generated/java/org/apache/camel/component/opensearch/OpensearchComponentConfigurer.java
|
{
"start": 737,
"end": 5736
}
|
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
OpensearchComponent target = (OpensearchComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "client": target.setClient(property(camelContext, org.opensearch.client.RestClient.class, value)); return true;
case "connectiontimeout":
case "connectionTimeout": target.setConnectionTimeout(property(camelContext, int.class, value)); return true;
case "enablessl":
case "enableSSL": target.setEnableSSL(property(camelContext, boolean.class, value)); return true;
case "enablesniffer":
case "enableSniffer": target.setEnableSniffer(property(camelContext, boolean.class, value)); return true;
case "hostaddresses":
case "hostAddresses": target.setHostAddresses(property(camelContext, java.lang.String.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "maxretrytimeout":
case "maxRetryTimeout": target.setMaxRetryTimeout(property(camelContext, int.class, value)); return true;
case "password": target.setPassword(property(camelContext, java.lang.String.class, value)); return true;
case "sniffafterfailuredelay":
case "sniffAfterFailureDelay": target.setSniffAfterFailureDelay(property(camelContext, int.class, value)); return true;
case "snifferinterval":
case "snifferInterval": target.setSnifferInterval(property(camelContext, int.class, value)); return true;
case "sockettimeout":
case "socketTimeout": target.setSocketTimeout(property(camelContext, int.class, value)); return true;
case "user": target.setUser(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public String[] getAutowiredNames() {
return new String[]{"client"};
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "client": return org.opensearch.client.RestClient.class;
case "connectiontimeout":
case "connectionTimeout": return int.class;
case "enablessl":
case "enableSSL": return boolean.class;
case "enablesniffer":
case "enableSniffer": return boolean.class;
case "hostaddresses":
case "hostAddresses": return java.lang.String.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "maxretrytimeout":
case "maxRetryTimeout": return int.class;
case "password": return java.lang.String.class;
case "sniffafterfailuredelay":
case "sniffAfterFailureDelay": return int.class;
case "snifferinterval":
case "snifferInterval": return int.class;
case "sockettimeout":
case "socketTimeout": return int.class;
case "user": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
OpensearchComponent target = (OpensearchComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "client": return target.getClient();
case "connectiontimeout":
case "connectionTimeout": return target.getConnectionTimeout();
case "enablessl":
case "enableSSL": return target.isEnableSSL();
case "enablesniffer":
case "enableSniffer": return target.isEnableSniffer();
case "hostaddresses":
case "hostAddresses": return target.getHostAddresses();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "maxretrytimeout":
case "maxRetryTimeout": return target.getMaxRetryTimeout();
case "password": return target.getPassword();
case "sniffafterfailuredelay":
case "sniffAfterFailureDelay": return target.getSniffAfterFailureDelay();
case "snifferinterval":
case "snifferInterval": return target.getSnifferInterval();
case "sockettimeout":
case "socketTimeout": return target.getSocketTimeout();
case "user": return target.getUser();
default: return null;
}
}
}
|
OpensearchComponentConfigurer
|
java
|
apache__flink
|
flink-metrics/flink-metrics-otel/src/main/java/org/apache/flink/metrics/otel/OpenTelemetryReporterBase.java
|
{
"start": 1375,
"end": 3156
}
|
class ____ {
private static final Logger LOG = LoggerFactory.getLogger(OpenTelemetryReporterBase.class);
protected Resource resource;
protected MetricExporter exporter;
protected OpenTelemetryReporterBase() {
resource = Resource.getDefault();
}
protected void open(MetricConfig metricConfig) {
if (metricConfig.containsKey(OpenTelemetryReporterOptions.SERVICE_NAME.key())) {
resource =
resource.merge(
Resource.create(
Attributes.of(
ResourceAttributes.SERVICE_NAME,
metricConfig.getString(
OpenTelemetryReporterOptions.SERVICE_NAME.key(),
OpenTelemetryReporterOptions.SERVICE_NAME
.defaultValue()))));
}
if (metricConfig.containsKey(OpenTelemetryReporterOptions.SERVICE_VERSION.key())) {
resource =
resource.merge(
Resource.create(
Attributes.of(
ResourceAttributes.SERVICE_VERSION,
metricConfig.getString(
OpenTelemetryReporterOptions.SERVICE_VERSION
.key(),
OpenTelemetryReporterOptions.SERVICE_VERSION
.defaultValue()))));
}
}
}
|
OpenTelemetryReporterBase
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/clients/MockClient.java
|
{
"start": 24925,
"end": 25865
}
|
class ____ {
final MetadataResponse updateResponse;
final boolean expectMatchRefreshTopics;
MetadataUpdate(MetadataResponse updateResponse, boolean expectMatchRefreshTopics) {
this.updateResponse = updateResponse;
this.expectMatchRefreshTopics = expectMatchRefreshTopics;
}
private Set<String> topics() {
return updateResponse.topicMetadata().stream()
.map(MetadataResponse.TopicMetadata::topic)
.collect(Collectors.toSet());
}
}
/**
* This is a dumbed down version of {@link MetadataUpdater} which is used to facilitate
* metadata tracking primarily in order to serve {@link KafkaClient#leastLoadedNode(long)}
* and bookkeeping through {@link Metadata}. The extensibility allows AdminClient, which does
* not rely on {@link Metadata} to do its own thing.
*/
public
|
MetadataUpdate
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/bidirectional/BidirectionalOneToOneCascadeRemoveTest.java
|
{
"start": 1797,
"end": 2175
}
|
class ____ {
@Id
protected String id;
@Column( name = "name_col" )
protected String name;
@Column( name = "value_col" )
protected int value;
@OneToOne( mappedBy = "a1" )
protected B b1;
public A() {
}
public A(String id, String name, int value) {
this.id = id;
this.name = name;
this.value = value;
}
}
@Entity( name = "EntityB" )
static
|
A
|
java
|
dropwizard__dropwizard
|
dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/NonEmptyStringParamValueExtractor.java
|
{
"start": 677,
"end": 1210
}
|
class ____ implements ValueExtractor<@ExtractedValue(type = String.class) NonEmptyStringParam> {
static final ValueExtractorDescriptor DESCRIPTOR = new ValueExtractorDescriptor(new NonEmptyStringParamValueExtractor());
private NonEmptyStringParamValueExtractor() {
}
@Override
public void extractValues(NonEmptyStringParam originalValue, ValueExtractor.ValueReceiver receiver) {
receiver.value(null, originalValue == null ? null : originalValue.get().orElse(null));
}
}
|
NonEmptyStringParamValueExtractor
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/dialect/DB2iDialect.java
|
{
"start": 1697,
"end": 6825
}
|
class ____ extends DB2Dialect {
private final static DatabaseVersion MINIMUM_VERSION = DatabaseVersion.make( 7, 2 );
public final static DatabaseVersion DB2_LUW_VERSION = DB2Dialect.MINIMUM_VERSION;
private static final String FOR_UPDATE_SQL = " for update with rs";
private static final String FOR_UPDATE_SKIP_LOCKED_SQL = FOR_UPDATE_SQL + " skip locked data";
public DB2iDialect(DialectResolutionInfo info) {
this( info.makeCopyOrDefault( MINIMUM_VERSION ) );
registerKeywords( info );
}
public DB2iDialect() {
this( MINIMUM_VERSION );
}
public DB2iDialect(DatabaseVersion version) {
super(version);
}
@Override
protected LockingSupport buildLockingSupport() {
return DB2LockingSupport.forDB2i();
}
@Override
public void initializeFunctionRegistry(FunctionContributions functionContributions) {
super.initializeFunctionRegistry( functionContributions );
// DB2 for i doesn't allow code units: https://www.ibm.com/docs/en/i/7.1.0?topic=functions-substring
functionContributions.getFunctionRegistry().register(
"substring",
new DB2SubstringFunction( false, functionContributions.getTypeConfiguration() )
);
}
@Override
protected DatabaseVersion getMinimumSupportedVersion() {
return MINIMUM_VERSION;
}
@Override
public DatabaseVersion getDB2Version() {
return DB2_LUW_VERSION;
}
@Override
public String getCreateIndexString(boolean unique) {
// we only create unique indexes, as opposed to unique constraints,
// when the column is nullable, so safe to infer unique => nullable
return unique ? "create unique where not null index" : "create index";
}
@Override
public String getCreateIndexTail(boolean unique, List<Column> columns) {
return "";
}
@Override
public boolean supportsIfExistsBeforeTableName() {
return false;
}
@Override
public boolean supportsUpdateReturning() {
// Only supported as of version 7.6: https://www.ibm.com/docs/en/i/7.6.0?topic=clause-table-reference
return getVersion().isSameOrAfter( 7, 6 );
}
/**
* No support for sequences.
*/
@Override
public SequenceSupport getSequenceSupport() {
return getVersion().isSameOrAfter(7, 3)
? DB2iSequenceSupport.INSTANCE : NoSequenceSupport.INSTANCE;
}
@Override
public String getQuerySequencesString() {
if ( getVersion().isSameOrAfter(7,3) ) {
return "select distinct sequence_schema as seqschema, sequence_name as seqname, START, minimum_value as minvalue, maximum_value as maxvalue, increment from qsys2.syssequences " +
"where current_schema='*LIBL' and sequence_schema in (select schema_name from qsys2.library_list_info) " +
"or sequence_schema=current_schema";
}
else {
return null;
}
}
@Override
public LimitHandler getLimitHandler() {
return getVersion().isSameOrAfter(7, 3)
? FetchLimitHandler.INSTANCE : LegacyDB2LimitHandler.INSTANCE;
}
@Override
public IdentityColumnSupport getIdentityColumnSupport() {
return getVersion().isSameOrAfter(7, 3)
? DB2IdentityColumnSupport.INSTANCE
: DB2zIdentityColumnSupport.INSTANCE;
}
@Override
public SqlAstTranslatorFactory getSqlAstTranslatorFactory() {
return new StandardSqlAstTranslatorFactory() {
@Override
protected <T extends JdbcOperation> SqlAstTranslator<T> buildTranslator(
SessionFactoryImplementor sessionFactory, Statement statement) {
return new DB2iSqlAstTranslator<>( sessionFactory, statement, getVersion() );
}
};
}
// I speculate that this is a correct implementation of rowids for DB2 for i,
// just on the basis of the DB2 docs, but I currently have no way to test it
// Note that the implementation inherited from DB2Dialect for LUW will not work!
@Override
public String rowId(String rowId) {
return rowId == null || rowId.isEmpty() ? "rowid_" : rowId;
}
@Override
public int rowIdSqlType() {
return ROWID;
}
@Override
public String getRowIdColumnString(String rowId) {
return rowId( rowId ) + " rowid not null generated always";
}
@Override
public String getForUpdateString() {
return FOR_UPDATE_SQL;
}
@Override
public String getForUpdateSkipLockedString() {
return supportsSkipLocked()
? FOR_UPDATE_SKIP_LOCKED_SQL
: FOR_UPDATE_SQL;
}
@Override
public String getForUpdateSkipLockedString(String aliases) {
return getForUpdateSkipLockedString();
}
@Override
public String getWriteLockString(Timeout timeout) {
return timeout.milliseconds() == Timeouts.SKIP_LOCKED_MILLI && supportsSkipLocked()
? FOR_UPDATE_SKIP_LOCKED_SQL
: FOR_UPDATE_SQL;
}
@Override
public String getReadLockString(Timeout timeout) {
return timeout.milliseconds() == Timeouts.SKIP_LOCKED_MILLI && supportsSkipLocked()
? FOR_UPDATE_SKIP_LOCKED_SQL
: FOR_UPDATE_SQL;
}
@Override
public String getWriteLockString(int timeout) {
return timeout == Timeouts.SKIP_LOCKED_MILLI && supportsSkipLocked()
? FOR_UPDATE_SKIP_LOCKED_SQL
: FOR_UPDATE_SQL;
}
@Override
public String getReadLockString(int timeout) {
return timeout == Timeouts.SKIP_LOCKED_MILLI && supportsSkipLocked()
? FOR_UPDATE_SKIP_LOCKED_SQL
: FOR_UPDATE_SQL;
}
}
|
DB2iDialect
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/BasicTypeSerializerUpgradeTestSpecifications.java
|
{
"start": 25188,
"end": 25635
}
|
class ____
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<LongValue> {
@Override
public TypeSerializer<LongValue> createPriorSerializer() {
return LongValueSerializer.INSTANCE;
}
@Override
public LongValue createTestData() {
return new LongValue(1234567890);
}
}
/** LongValueSerializerVerifier. */
public static final
|
LongValueSerializerSetup
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/internal/Extends.java
|
{
"start": 489,
"end": 618
}
|
interface ____ {
/**
* The type extended. String because dynamic models have named "classes".
*/
String superType();
}
|
Extends
|
java
|
quarkusio__quarkus
|
extensions/spring-security/deployment/src/main/java/io/quarkus/spring/security/deployment/BeanMethodInvocationGenerator.java
|
{
"start": 1674,
"end": 2829
}
|
class ____ {
private static final String METHOD_PARAMETER_REGEX = "#(\\w+)";
private static final Pattern METHOD_PARAMETER_PATTERN = Pattern.compile(METHOD_PARAMETER_REGEX);
private final IndexView index;
private final Map<String, DotName> springBeansNameToDotName;
private final Map<String, ClassInfo> springBeansNameToClassInfo;
private final Set<String> beansReferencedInPreAuthorized;
private final ClassOutput classOutput;
private final Map<String, String> alreadyGeneratedClasses = new HashMap<>();
public BeanMethodInvocationGenerator(IndexView index, Map<String, DotName> springBeansNameToDotName,
Map<String, ClassInfo> springBeansNameToClassInfo, Set<String> beansReferencedInPreAuthorized,
ClassOutput classOutput) {
this.index = index;
this.springBeansNameToDotName = springBeansNameToDotName;
this.springBeansNameToClassInfo = springBeansNameToClassInfo;
this.beansReferencedInPreAuthorized = beansReferencedInPreAuthorized;
this.classOutput = classOutput;
}
/**
* Returns the name of the generated
|
BeanMethodInvocationGenerator
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/LogicalAssignmentTest.java
|
{
"start": 998,
"end": 1229
}
|
class ____ {
@Test
public void positive() {
BugCheckerRefactoringTestHelper.newInstance(LogicalAssignment.class, getClass())
.addInputLines(
"in/Test.java",
"""
|
LogicalAssignmentTest
|
java
|
elastic__elasticsearch
|
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/InternalYamlRestTestPlugin.java
|
{
"start": 1145,
"end": 3262
}
|
class ____ implements Plugin<Project> {
public static final String SOURCE_SET_NAME = "yamlRestTest";
@Override
public void apply(Project project) {
project.getPluginManager().apply(RestTestBasePlugin.class);
project.getPluginManager().apply(RestResourcesPlugin.class);
// create source set
SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class);
SourceSet yamlTestSourceSet = sourceSets.create(SOURCE_SET_NAME);
TaskProvider<RestIntegTestTask> testTask = registerTestTask(project, yamlTestSourceSet, SOURCE_SET_NAME, RestIntegTestTask.class);
project.getTasks().named(JavaBasePlugin.CHECK_TASK_NAME).configure(check -> check.dependsOn(testTask));
// setup the dependencies
setupYamlRestTestDependenciesDefaults(project, yamlTestSourceSet, true);
// setup the copy for the rest resources
project.getTasks().withType(CopyRestApiTask.class).configureEach(copyRestApiTask -> {
copyRestApiTask.setSourceResourceDir(
yamlTestSourceSet.getResources()
.getSrcDirs()
.stream()
.filter(f -> f.isDirectory() && f.getName().equals("resources"))
.findFirst()
.orElse(null)
);
});
// Register rest resources with source set
yamlTestSourceSet.getOutput()
.dir(
project.getTasks()
.withType(CopyRestApiTask.class)
.named(RestResourcesPlugin.COPY_REST_API_SPECS_TASK)
.flatMap(CopyRestApiTask::getOutputResourceDir)
);
yamlTestSourceSet.getOutput()
.dir(
project.getTasks()
.withType(CopyRestTestsTask.class)
.named(RestResourcesPlugin.COPY_YAML_TESTS_TASK)
.flatMap(CopyRestTestsTask::getOutputResourceDir)
);
GradleUtils.setupIdeForTestSourceSet(project, yamlTestSourceSet);
}
}
|
InternalYamlRestTestPlugin
|
java
|
google__dagger
|
hilt-compiler/main/java/dagger/hilt/processor/internal/Processors.java
|
{
"start": 11420,
"end": 12999
}
|
class ____. */
public static ClassName prepend(ClassName name, String prefix) {
return name.peerClass(prefix + name.simpleName());
}
/**
* Removes the string {@code suffix} from the simple name of {@code type} and returns it.
*
* @throws BadInputException if the simple name of {@code type} does not end with {@code suffix}
*/
public static ClassName removeNameSuffix(XTypeElement type, String suffix) {
ClassName originalName = type.getClassName();
String originalSimpleName = originalName.simpleName();
ProcessorErrors.checkState(
originalSimpleName.endsWith(suffix),
type,
"Name of type %s must end with '%s'",
originalName,
suffix);
String withoutSuffix =
originalSimpleName.substring(0, originalSimpleName.length() - suffix.length());
return originalName.peerClass(withoutSuffix);
}
/** Returns {@code true} if element inherits directly or indirectly from the className. */
public static boolean isAssignableFrom(XTypeElement element, ClassName className) {
return isAssignableFromAnyOf(element, ImmutableSet.of(className));
}
/** Returns {@code true} if element inherits directly or indirectly from any of the classNames. */
public static boolean isAssignableFromAnyOf(
XTypeElement element, ImmutableSet<ClassName> classNames) {
for (ClassName className : classNames) {
if (element.getClassName().equals(className)) {
return true;
}
}
XType superClass = element.getSuperClass();
// None type is returned if this is an
|
name
|
java
|
spring-projects__spring-security
|
access/src/test/java/org/springframework/security/messaging/access/intercept/ChannelSecurityInterceptorTests.java
|
{
"start": 2084,
"end": 6029
}
|
class ____ {
@Mock
Message<Object> message;
@Mock
MessageChannel channel;
@Mock
MessageSecurityMetadataSource source;
@Mock
AccessDecisionManager accessDecisionManager;
@Mock
RunAsManager runAsManager;
@Mock
Authentication runAs;
Authentication originalAuth;
List<ConfigAttribute> attrs;
ChannelSecurityInterceptor interceptor;
@BeforeEach
public void setup() {
this.attrs = Arrays.<ConfigAttribute>asList(new SecurityConfig("ROLE_USER"));
this.interceptor = new ChannelSecurityInterceptor(this.source);
this.interceptor.setAccessDecisionManager(this.accessDecisionManager);
this.interceptor.setRunAsManager(this.runAsManager);
this.originalAuth = new TestingAuthenticationToken("user", "pass", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(this.originalAuth);
}
@AfterEach
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void constructorMessageSecurityMetadataSourceNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new ChannelSecurityInterceptor(null));
}
@Test
public void getSecureObjectClass() {
assertThat(this.interceptor.getSecureObjectClass()).isEqualTo(Message.class);
}
@Test
public void obtainSecurityMetadataSource() {
assertThat(this.interceptor.obtainSecurityMetadataSource()).isEqualTo(this.source);
}
@Test
public void preSendNullAttributes() {
assertThat(this.interceptor.preSend(this.message, this.channel)).isSameAs(this.message);
}
@Test
public void preSendGrant() {
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
Message<?> result = this.interceptor.preSend(this.message, this.channel);
assertThat(result).isSameAs(this.message);
}
@Test
public void preSendDeny() {
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
willThrow(new AccessDeniedException("")).given(this.accessDecisionManager)
.decide(any(Authentication.class), eq(this.message), eq(this.attrs));
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.interceptor.preSend(this.message, this.channel));
}
@SuppressWarnings("unchecked")
@Test
public void preSendPostSendRunAs() {
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
given(this.runAsManager.buildRunAs(any(Authentication.class), any(), any(Collection.class)))
.willReturn(this.runAs);
Message<?> preSend = this.interceptor.preSend(this.message, this.channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.runAs);
this.interceptor.postSend(preSend, this.channel, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.originalAuth);
}
@Test
public void afterSendCompletionNotTokenMessageNoExceptionThrown() {
this.interceptor.afterSendCompletion(this.message, this.channel, true, null);
}
@SuppressWarnings("unchecked")
@Test
public void preSendFinallySendRunAs() {
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
given(this.runAsManager.buildRunAs(any(Authentication.class), any(), any(Collection.class)))
.willReturn(this.runAs);
Message<?> preSend = this.interceptor.preSend(this.message, this.channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.runAs);
this.interceptor.afterSendCompletion(preSend, this.channel, true, new RuntimeException());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.originalAuth);
}
@Test
public void preReceive() {
assertThat(this.interceptor.preReceive(this.channel)).isTrue();
}
@Test
public void postReceive() {
assertThat(this.interceptor.postReceive(this.message, this.channel)).isSameAs(this.message);
}
@Test
public void afterReceiveCompletionNullExceptionNoExceptionThrown() {
this.interceptor.afterReceiveCompletion(this.message, this.channel, null);
}
}
|
ChannelSecurityInterceptorTests
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/action/AbstractCrossClusterTestCase.java
|
{
"start": 3988,
"end": 4401
}
|
class ____ extends Plugin {
@Override
public List<Setting<?>> getSettings() {
return List.of(
Setting.timeSetting(
ExchangeService.INACTIVE_SINKS_INTERVAL_SETTING,
TimeValue.timeValueSeconds(30),
Setting.Property.NodeScope
)
);
}
}
public static
|
InternalExchangePlugin
|
java
|
apache__maven
|
impl/maven-core/src/main/java/org/apache/maven/plugin/LegacySupport.java
|
{
"start": 1283,
"end": 2158
}
|
interface ____ {
/**
* Sets the currently active session. Some legacy components are basically stateful and their API is missing
* parameters that would be required to delegate to a stateless component. Saving the session (in a thread-local
* variable) is our best effort to record any state that is required to enable proper delegation.
*
* @param session The currently active session, may be {@code null}.
*/
void setSession(MavenSession session);
/**
* Gets the currently active session.
*
* @return The currently active session or {@code null} if none.
*/
MavenSession getSession();
/**
* Gets the currently active repository session.
*
* @return The currently active repository session or {@code null} if none.
*/
RepositorySystemSession getRepositorySession();
}
|
LegacySupport
|
java
|
square__moshi
|
moshi/src/test/java/com/squareup/moshi/internal/ClassJsonAdapterTest.java
|
{
"start": 12342,
"end": 12810
}
|
class ____ {}
@Test
public void abstractClassNotSupported() throws Exception {
try {
ClassJsonAdapter.Factory.create(Abstract.class, NO_ANNOTATIONS, moshi);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected)
.hasMessageThat()
.isEqualTo(
"Cannot serialize abstract class "
+ "com.squareup.moshi.internal.ClassJsonAdapterTest$Abstract");
}
}
static
|
Abstract
|
java
|
grpc__grpc-java
|
core/src/main/java/io/grpc/internal/Framer.java
|
{
"start": 735,
"end": 1452
}
|
interface ____ {
/**
* Writes out a payload message.
*
* @param message contains the message to be written out. It will be completely consumed.
*/
void writePayload(InputStream message);
/** Flush the buffered payload. */
void flush();
/** Returns whether the framer is closed. */
boolean isClosed();
/** Closes, with flush. */
void close();
/** Closes, without flush. */
void dispose();
/** Enable or disable compression. */
Framer setMessageCompression(boolean enable);
/** Set the compressor used for compression. */
Framer setCompressor(Compressor compressor);
/** Set a size limit for each outbound message. */
void setMaxOutboundMessageSize(int maxSize);
}
|
Framer
|
java
|
elastic__elasticsearch
|
modules/lang-painless/src/main/java/org/elasticsearch/painless/ir/TypedInterfaceReferenceNode.java
|
{
"start": 616,
"end": 1152
}
|
class ____ extends ExpressionNode {
/* ---- begin visitor ---- */
@Override
public <Scope> void visit(IRTreeVisitor<Scope> irTreeVisitor, Scope scope) {
irTreeVisitor.visitTypedInterfaceReference(this, scope);
}
@Override
public <Scope> void visitChildren(IRTreeVisitor<Scope> irTreeVisitor, Scope scope) {
// do nothing; terminal node
}
/* ---- end visitor ---- */
public TypedInterfaceReferenceNode(Location location) {
super(location);
}
}
|
TypedInterfaceReferenceNode
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionHandleAndThrowNewExceptionTest.java
|
{
"start": 1259,
"end": 2607
}
|
class ____ extends ContextTestSupport {
@Test
public void testOnExceptionHandleAndThrowNewException() {
try {
template.sendBody("direct:start", "Hello World");
fail("Should have thrown exception");
} catch (CamelExecutionException e) {
IOException cause = assertIsInstanceOf(IOException.class, e.getCause());
assertNotNull(cause);
assertEquals("First failure message is: Damn", cause.getMessage());
}
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
onException(IllegalArgumentException.class).handled(true).to("log:onException").process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
assertNotNull(cause);
throw new IOException("First failure message is: " + cause.getMessage());
}
});
from("direct:start").throwException(new IllegalArgumentException("Damn"));
}
};
}
}
|
OnExceptionHandleAndThrowNewExceptionTest
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableWindowBoundary.java
|
{
"start": 7757,
"end": 8619
}
|
class ____<T, B> extends DisposableObserver<B> {
final WindowBoundaryMainObserver<T, B> parent;
boolean done;
WindowBoundaryInnerObserver(WindowBoundaryMainObserver<T, B> parent) {
this.parent = parent;
}
@Override
public void onNext(B t) {
if (done) {
return;
}
parent.innerNext();
}
@Override
public void onError(Throwable t) {
if (done) {
RxJavaPlugins.onError(t);
return;
}
done = true;
parent.innerError(t);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
parent.innerComplete();
}
}
}
|
WindowBoundaryInnerObserver
|
java
|
apache__dubbo
|
dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.java
|
{
"start": 1699,
"end": 3207
}
|
class ____ extends AbstractConditionMatcher {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ArgumentConditionMatcher.class);
private static final Pattern ARGUMENTS_PATTERN = Pattern.compile("arguments\\[([0-9]+)\\]");
public ArgumentConditionMatcher(String key, ModuleModel model) {
super(key, model);
}
@Override
public String getValue(Map<String, String> sample, URL url, Invocation invocation) {
try {
// split the rule
String[] expressArray = key.split("\\.");
String argumentExpress = expressArray[0];
final Matcher matcher = ARGUMENTS_PATTERN.matcher(argumentExpress);
if (!matcher.find()) {
return DOES_NOT_FOUND_VALUE;
}
// extract the argument index
int index = Integer.parseInt(matcher.group(1));
if (index < 0 || index > invocation.getArguments().length) {
return DOES_NOT_FOUND_VALUE;
}
// extract the argument value
return String.valueOf(invocation.getArguments()[index]);
} catch (Exception e) {
logger.warn(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"Parse argument match condition failed",
"",
"Invalid , will ignore., ",
e);
}
return DOES_NOT_FOUND_VALUE;
}
}
|
ArgumentConditionMatcher
|
java
|
apache__camel
|
components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/service/WordpressServicePostRevision.java
|
{
"start": 1025,
"end": 1292
}
|
interface ____ extends WordpressService {
void delete(Integer postId, Integer revisionId);
PostRevision retrieve(Integer postId, Integer revisionId, Context context);
List<PostRevision> list(Integer postId, Context context);
}
|
WordpressServicePostRevision
|
java
|
spring-projects__spring-boot
|
loader/spring-boot-loader/src/test/java/org/springframework/boot/loader/net/protocol/jar/JarUrlClassLoaderTests.java
|
{
"start": 3321,
"end": 4352
}
|
class ____.Application");
}
}
@Test
void loadClassFromNested() throws Exception {
File appJar = new File("src/test/resources/jars/app.jar");
File jarFile = new File(this.tempDir, "test.jar");
FileOutputStream fileOutputStream = new FileOutputStream(jarFile);
try (JarOutputStream jarOutputStream = new JarOutputStream(fileOutputStream)) {
JarEntry nestedEntry = new JarEntry("app.jar");
byte[] nestedJarData = Files.readAllBytes(appJar.toPath());
nestedEntry.setSize(nestedJarData.length);
nestedEntry.setCompressedSize(nestedJarData.length);
CRC32 crc32 = new CRC32();
crc32.update(nestedJarData);
nestedEntry.setCrc(crc32.getValue());
nestedEntry.setMethod(ZipEntry.STORED);
jarOutputStream.putNextEntry(nestedEntry);
jarOutputStream.write(nestedJarData);
jarOutputStream.closeEntry();
}
URL url = JarUrl.create(jarFile, "app.jar");
try (JarUrlClassLoader loader = new TestJarUrlClassLoader(url)) {
assertThat(loader.loadClass("demo.Application")).isNotNull().hasToString("
|
demo
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpCustomFilterTests.java
|
{
"start": 5193,
"end": 5651
}
|
class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
TestHttpSecurities.disableDefaults(http);
http
// this works so long as the CustomFilter extends one of the standard filters
// if not, use addFilterBefore or addFilterAfter
.addFilter(new CustomFilter());
return http.build();
// @formatter:on
}
}
@Configuration
@EnableWebSecurity
static
|
CustomFilterPositionConfig
|
java
|
redisson__redisson
|
redisson-hibernate/redisson-hibernate-5/src/main/java/org/redisson/hibernate/strategy/ReadWriteNaturalIdRegionAccessStrategy.java
|
{
"start": 1260,
"end": 2829
}
|
class ____ extends AbstractReadWriteAccessStrategy implements NaturalIdRegionAccessStrategy {
public ReadWriteNaturalIdRegionAccessStrategy(Settings settings, GeneralDataRegion region,
RMapCache<Object, Object> mapCache) {
super(settings, region, mapCache);
}
@Override
public NaturalIdRegion getRegion() {
return (NaturalIdRegion) region;
}
@Override
public boolean insert(SessionImplementor session, Object key, Object value) throws CacheException {
return false;
}
@Override
public boolean afterInsert(SessionImplementor session, Object key, Object value) throws CacheException {
region.put(session, key, value);
return true;
}
@Override
public boolean update(SessionImplementor session, Object key, Object value) throws CacheException {
return false;
}
@Override
public boolean afterUpdate(SessionImplementor session, Object key, Object value, SoftLock lock) throws CacheException {
region.put(session, key, value);
return true;
}
@Override
public Object generateCacheKey(Object[] naturalIdValues, EntityPersister persister, SessionImplementor session) {
return ((RedissonNaturalIdRegion)region).getCacheKeysFactory().createNaturalIdKey(naturalIdValues, persister, session);
}
@Override
public Object[] getNaturalIdValues(Object cacheKey) {
return ((RedissonNaturalIdRegion)region).getCacheKeysFactory().getNaturalIdValues(cacheKey);
}
}
|
ReadWriteNaturalIdRegionAccessStrategy
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/protocol/HasQueuedCommands.java
|
{
"start": 279,
"end": 365
}
|
interface ____ {
Collection<RedisCommand<?, ?, ?>> drainQueue();
}
|
HasQueuedCommands
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringRecipientListWithStringDelimitedPropertyTest.java
|
{
"start": 1065,
"end": 1411
}
|
class ____ extends RecipientListWithStringDelimitedPropertyTest {
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this,
"org/apache/camel/spring/processor/recipientListWithStringDelimitedProperty.xml");
}
}
|
SpringRecipientListWithStringDelimitedPropertyTest
|
java
|
apache__camel
|
components/camel-stream/src/main/java/org/apache/camel/component/stream/StreamProducer.java
|
{
"start": 1592,
"end": 8128
}
|
class ____ extends DefaultAsyncProducer {
private static final Logger LOG = LoggerFactory.getLogger(StreamProducer.class);
private static final String TYPES = "out,err,file,header";
private static final String INVALID_URI = "Invalid uri, valid form: 'stream:{" + TYPES + "}'";
private static final List<String> TYPES_LIST = Arrays.asList(TYPES.split(","));
private StreamEndpoint endpoint;
private String uri;
private OutputStream outputStream;
private final AtomicInteger count = new AtomicInteger();
public StreamProducer(StreamEndpoint endpoint, String uri) throws Exception {
super(endpoint);
this.endpoint = endpoint;
validateUri(uri);
}
@Override
protected void doStop() throws Exception {
super.doStop();
closeStream(null, true);
}
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
try {
delay(endpoint.getDelay());
lock.lock();
try {
try {
openStream(exchange);
writeToStream(outputStream, exchange);
} finally {
closeStream(exchange, false);
}
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
exchange.setException(e);
Thread.currentThread().interrupt();
} catch (Exception e) {
exchange.setException(e);
}
callback.done(true);
return true;
}
private OutputStream resolveStreamFromFile() throws IOException {
String fileName = endpoint.getFileName();
StringHelper.notEmpty(fileName, "fileName");
LOG.debug("About to write to file: {}", fileName);
File f = new File(fileName);
// will create a new file if missing or append to existing
f.getParentFile().mkdirs();
f.createNewFile();
return new FileOutputStream(f, true);
}
private OutputStream resolveStreamFromHeader(Object o, Exchange exchange) {
return exchange.getContext().getTypeConverter().convertTo(OutputStream.class, o);
}
private void delay(long ms) throws InterruptedException {
if (ms == 0) {
return;
}
LOG.trace("Delaying {} millis", ms);
Thread.sleep(ms);
}
private void writeToStream(OutputStream outputStream, Exchange exchange) throws IOException, CamelExchangeException {
Object body = exchange.getIn().getBody();
if (body == null) {
LOG.debug("Body is null, cannot write it to the stream.");
return;
}
// if not a string then try as byte array first
if (!(body instanceof String)) {
byte[] bytes = exchange.getIn().getBody(byte[].class);
if (bytes != null) {
LOG.debug("Writing as byte[]: {} to {}", bytes, outputStream);
outputStream.write(bytes);
if (endpoint.isAppendNewLine()) {
outputStream.write(System.lineSeparator().getBytes());
}
return;
}
}
// okay now fallback to mandatory converterable to string
String s = exchange.getIn().getMandatoryBody(String.class);
Charset charset = endpoint.getCharset();
Writer writer = charset != null ? new OutputStreamWriter(outputStream, charset) : new OutputStreamWriter(outputStream);
BufferedWriter bw = IOHelper.buffered(writer);
if (LOG.isDebugEnabled()) {
LOG.debug("Writing as text: {} to {} using encoding: {}", body, outputStream, charset);
}
bw.write(s);
if (endpoint.isAppendNewLine()) {
bw.write(System.lineSeparator());
}
bw.flush();
}
private void openStream() throws Exception {
if (outputStream != null) {
return;
}
if ("out".equals(uri)) {
outputStream = System.out;
} else if ("err".equals(uri)) {
outputStream = System.err;
} else if ("file".equals(uri)) {
outputStream = resolveStreamFromFile();
}
count.set(outputStream == null ? 0 : endpoint.getAutoCloseCount());
LOG.debug("Opened stream '{}'", endpoint.getEndpointKey());
}
private void openStream(final Exchange exchange) throws Exception {
if (outputStream != null) {
return;
}
if ("header".equals(uri)) {
outputStream = resolveStreamFromHeader(exchange.getIn().getHeader("stream"), exchange);
LOG.debug("Opened stream '{}'", endpoint.getEndpointKey());
} else {
openStream();
}
}
private Boolean isDone(Exchange exchange) {
return exchange != null && exchange.getProperty(ExchangePropertyKey.SPLIT_COMPLETE, Boolean.FALSE, Boolean.class);
}
private void closeStream(Exchange exchange, boolean force) throws Exception {
if (outputStream == null) {
return;
}
// never close a standard stream (system.out or system.err)
// always close a 'header' stream (unless it's a system stream)
boolean systemStream = outputStream == System.out || outputStream == System.err;
boolean headerStream = "header".equals(uri);
boolean reachedLimit = endpoint.getAutoCloseCount() > 0 && count.decrementAndGet() <= 0;
boolean isDone = endpoint.isCloseOnDone() && isDone(exchange);
boolean expiredStream = force || headerStream || isDone || reachedLimit; // evaluation order is important!
// never ever close a system stream
if (!systemStream && expiredStream) {
outputStream.close();
outputStream = null;
LOG.debug("Closed stream '{}'", endpoint.getEndpointKey());
}
}
private void validateUri(String uri) throws Exception {
String[] s = uri.split(":");
if (s.length < 2) {
throw new IllegalArgumentException(INVALID_URI);
}
String[] t = s[1].split("\\?");
if (t.length < 1) {
throw new IllegalArgumentException(INVALID_URI);
}
this.uri = t[0].trim();
if (this.uri.startsWith("//")) {
this.uri = this.uri.substring(2);
}
if (!TYPES_LIST.contains(this.uri)) {
throw new IllegalArgumentException(INVALID_URI);
}
}
}
|
StreamProducer
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/error/ShouldHaveSameClass_create_Test.java
|
{
"start": 1530,
"end": 1579
}
|
class ____: java.lang.String".formatted());
}
}
|
was
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authz/RoleDescriptorsIntersectionTests.java
|
{
"start": 1448,
"end": 4911
}
|
class ____ extends ESTestCase {
public void testSerialization() throws IOException {
final RoleDescriptorsIntersection roleDescriptorsIntersection = new RoleDescriptorsIntersection(
randomList(0, 3, () -> Set.copyOf(randomUniquelyNamedRoleDescriptors(0, 3)))
);
final NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(
List.of(
new NamedWriteableRegistry.Entry(
ConfigurableClusterPrivilege.class,
ConfigurableClusterPrivileges.ManageApplicationPrivileges.WRITEABLE_NAME,
ConfigurableClusterPrivileges.ManageApplicationPrivileges::createFrom
),
new NamedWriteableRegistry.Entry(
ConfigurableClusterPrivilege.class,
ConfigurableClusterPrivileges.WriteProfileDataPrivileges.WRITEABLE_NAME,
ConfigurableClusterPrivileges.WriteProfileDataPrivileges::createFrom
),
new NamedWriteableRegistry.Entry(
ConfigurableClusterPrivilege.class,
ConfigurableClusterPrivileges.ManageRolesPrivilege.WRITEABLE_NAME,
ConfigurableClusterPrivileges.ManageRolesPrivilege::createFrom
)
)
);
try (BytesStreamOutput output = new BytesStreamOutput()) {
roleDescriptorsIntersection.writeTo(output);
try (StreamInput input = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
RoleDescriptorsIntersection deserialized = new RoleDescriptorsIntersection(input);
assertThat(deserialized.roleDescriptorsList(), equalTo(roleDescriptorsIntersection.roleDescriptorsList()));
}
}
}
public void testXContent() throws IOException {
final RoleDescriptorsIntersection roleDescriptorsIntersection = new RoleDescriptorsIntersection(
List.of(
Set.of(new RoleDescriptor("role_0", new String[] { "monitor" }, null, null)),
Set.of(new RoleDescriptor("role_1", new String[] { "all" }, null, null))
)
);
final XContentBuilder builder = XContentFactory.jsonBuilder();
roleDescriptorsIntersection.toXContent(builder, ToXContent.EMPTY_PARAMS);
final String jsonString = Strings.toString(builder);
assertThat(jsonString, equalTo(XContentHelper.stripWhitespace("""
[
{
"role_0": {
"cluster": ["monitor"],
"indices": [],
"applications": [],
"run_as": [],
"metadata": {},
"transient_metadata": {"enabled": true}
}
},
{
"role_1": {
"cluster": ["all"],
"indices": [],
"applications": [],
"run_as": [],
"metadata": {},
"transient_metadata": {"enabled": true}
}
}
]""")));
try (XContentParser p = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY, jsonString)) {
assertThat(RoleDescriptorsIntersection.fromXContent(p), equalTo(roleDescriptorsIntersection));
}
}
}
|
RoleDescriptorsIntersectionTests
|
java
|
apache__flink
|
flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/SavepointWriterWindowITCase.java
|
{
"start": 16710,
"end": 17673
}
|
class ____
implements AggregateFunction<
Tuple2<String, Integer>, Tuple2<String, Integer>, Tuple2<String, Integer>> {
@Override
public Tuple2<String, Integer> createAccumulator() {
return null;
}
@Override
public Tuple2<String, Integer> add(
Tuple2<String, Integer> value, Tuple2<String, Integer> accumulator) {
if (accumulator == null) {
return Tuple2.of(value.f0, value.f1);
}
accumulator.f1 += value.f1;
return accumulator;
}
@Override
public Tuple2<String, Integer> getResult(Tuple2<String, Integer> accumulator) {
return accumulator;
}
@Override
public Tuple2<String, Integer> merge(Tuple2<String, Integer> a, Tuple2<String, Integer> b) {
a.f1 += b.f1;
return a;
}
}
private static
|
Aggregator
|
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/TimelineKeyValueFilter.java
|
{
"start": 1029,
"end": 1182
}
|
class ____ represents filter to be applied based on key-value pair
* being equal or not to the values in back-end store.
*/
@Private
@Unstable
public
|
which
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/checkpointing/UnalignedCheckpointFailureHandlingITCase.java
|
{
"start": 9337,
"end": 10527
}
|
class ____ implements CheckpointStorage {
private final CheckpointStorage delegate;
private final SharedReference<AtomicBoolean> failOnCloseRef;
private final SharedReference<TemporaryFolder> tempFolderRef;
private TestCheckpointStorage(
CheckpointStorage delegate,
SharedReference<AtomicBoolean> failOnCloseRef,
SharedReference<TemporaryFolder> tempFolderRef) {
this.delegate = delegate;
this.failOnCloseRef = failOnCloseRef;
this.tempFolderRef = tempFolderRef;
}
@Override
public CheckpointStorageAccess createCheckpointStorage(JobID jobId) throws IOException {
return new TestCheckpointStorageAccess(
delegate.createCheckpointStorage(jobId),
failOnCloseRef.get(),
tempFolderRef.get().newFolder());
}
@Override
public CompletedCheckpointStorageLocation resolveCheckpoint(String externalPointer)
throws IOException {
return delegate.resolveCheckpoint(externalPointer);
}
}
private static
|
TestCheckpointStorage
|
java
|
apache__dubbo
|
dubbo-plugin/dubbo-spring6-security/src/main/java/org/apache/dubbo/spring/security/oauth2/jackson/OAuth2ObjectMapperCodecCustomer.java
|
{
"start": 1220,
"end": 1700
}
|
class ____ implements ObjectMapperCodecCustomer {
@Override
public void customize(ObjectMapperCodec objectMapperCodec) {
objectMapperCodec.configureMapper(mapper -> {
mapper.registerModule(new OAuth2SecurityModule());
List<Module> securityModules =
SecurityJackson2Modules.getModules(this.getClass().getClassLoader());
mapper.registerModules(securityModules);
});
}
}
|
OAuth2ObjectMapperCodecCustomer
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/store/TestDataBlocks.java
|
{
"start": 1600,
"end": 5302
}
|
class ____ {
private final Configuration configuration = new Configuration();
private static final int ONE_KB = 1024;
private static final Logger LOG =
LoggerFactory.getLogger(TestDataBlocks.class);
/**
* Test to verify different DataBlocks factories, different operations.
*/
@Test
public void testDataBlocksFactory() throws Exception {
testCreateFactory(DATA_BLOCKS_BUFFER_DISK);
testCreateFactory(DATA_BLOCKS_BUFFER_ARRAY);
testCreateFactory(DATA_BLOCKS_BYTEBUFFER);
}
/**
* Verify creation of a data block factory and its operations.
*
* @param nameOfFactory Name of the DataBlock factory to be created.
* @throws IOException Throw IOE in case of failure while creating a block.
*/
public void testCreateFactory(String nameOfFactory) throws Exception {
LOG.info("Testing: {}", nameOfFactory);
DataBlocks.BlockFactory blockFactory =
DataBlocks.createFactory("Dir", configuration, nameOfFactory);
DataBlocks.DataBlock dataBlock = blockFactory.create(0, ONE_KB, null);
assertWriteBlock(dataBlock);
assertToByteArray(dataBlock);
assertCloseBlock(dataBlock);
}
/**
* Verify Writing of a dataBlock.
*
* @param dataBlock DataBlock to be tested.
* @throws IOException Throw Exception in case of failures.
*/
private void assertWriteBlock(DataBlocks.DataBlock dataBlock)
throws IOException {
byte[] oneKbBuff = new byte[ONE_KB];
new Random().nextBytes(oneKbBuff);
dataBlock.write(oneKbBuff, 0, ONE_KB);
// Verify DataBlock state is at Writing.
dataBlock.verifyState(DataBlocks.DataBlock.DestState.Writing);
// Verify that the DataBlock has data written.
assertTrue(dataBlock.hasData(), "Expected Data block to have data");
// Verify the size of data.
assertEquals(ONE_KB, dataBlock.dataSize(), "Mismatch in data size in block");
// Verify that no capacity is left in the data block to write more.
assertFalse(dataBlock.hasCapacity(1),
"Expected the data block to have no capacity to write 1 byte of data");
}
/**
* Verify the Conversion of Data blocks into byte[].
*
* @param dataBlock data block to be tested.
* @throws Exception Throw Exception in case of failures.
*/
private void assertToByteArray(DataBlocks.DataBlock dataBlock)
throws Exception {
DataBlocks.BlockUploadData blockUploadData = dataBlock.startUpload();
// Verify that the current state is in upload.
dataBlock.verifyState(DataBlocks.DataBlock.DestState.Upload);
// Convert the DataBlock upload to byteArray.
byte[] bytesWritten = blockUploadData.toByteArray();
// Verify that we can call toByteArray() more than once and gives the
// same byte[].
assertEquals(bytesWritten, blockUploadData.toByteArray(),
"Mismatch in byteArray provided by toByteArray() the second time");
IOUtils.close(blockUploadData);
// Verify that after closing blockUploadData, we can't call toByteArray().
LambdaTestUtils.intercept(IllegalStateException.class,
"Block is closed",
"Expected to throw IllegalStateException.java after closing "
+ "blockUploadData and trying to call toByteArray()",
() -> {
blockUploadData.toByteArray();
});
}
/**
* Verify the close() of data blocks.
*
* @param dataBlock data block to be tested.
* @throws IOException Throw Exception in case of failures.
*/
private void assertCloseBlock(DataBlocks.DataBlock dataBlock)
throws IOException {
dataBlock.close();
// Verify that the current state is in Closed.
dataBlock.verifyState(DataBlocks.DataBlock.DestState.Closed);
}
}
|
TestDataBlocks
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/index/mapper/AbstractShapeGeometryFieldMapperTests.java
|
{
"start": 8174,
"end": 9019
}
|
class
____ new Rectangle(
encoder.decodeX(ints[0]),
encoder.decodeX(ints[1]),
encoder.decodeY(ints[2]),
encoder.decodeY(ints[3])
);
} else {
throw new IllegalArgumentException("Expected 4 or 6 integers");
}
}
throw new IllegalArgumentException("Expected an array of integers");
}
private static Rectangle makeGeoRectangle(CoordinateEncoder encoder, Object integers) {
if (integers instanceof ArrayList<?> list) {
int[] ints = list.stream().mapToInt(x -> (int) x).toArray();
if (list.size() != 6) {
throw new IllegalArgumentException("Expected 6 integers");
}
// Data in order defined by Extent
|
return
|
java
|
elastic__elasticsearch
|
server/src/internalClusterTest/java/org/elasticsearch/search/functionscore/FunctionScorePluginIT.java
|
{
"start": 4694,
"end": 5917
}
|
class ____ extends DecayFunctionBuilder<CustomDistanceScoreBuilder> {
public static final String NAME = "linear_mult";
public static final ScoreFunctionParser<CustomDistanceScoreBuilder> PARSER = new DecayFunctionParser<>(
CustomDistanceScoreBuilder::new
);
public CustomDistanceScoreBuilder(String fieldName, Object origin, Object scale) {
super(fieldName, origin, scale, null);
}
CustomDistanceScoreBuilder(String fieldName, BytesReference functionBytes) {
super(fieldName, functionBytes);
}
/**
* Read from a stream.
*/
CustomDistanceScoreBuilder(StreamInput in) throws IOException {
super(in);
}
@Override
public String getName() {
return NAME;
}
@Override
public DecayFunction getDecayFunction() {
return decayFunction;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersion.zero();
}
private static final DecayFunction decayFunction = new LinearMultScoreFunction();
private static
|
CustomDistanceScoreBuilder
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MybatisBeanComponentBuilderFactory.java
|
{
"start": 1421,
"end": 1952
}
|
interface ____ {
/**
* MyBatis Bean (camel-mybatis)
* Perform queries, inserts, updates or deletes in a relational database
* using MyBatis.
*
* Category: database
* Since: 2.22
* Maven coordinates: org.apache.camel:camel-mybatis
*
* @return the dsl builder
*/
static MybatisBeanComponentBuilder mybatisBean() {
return new MybatisBeanComponentBuilderImpl();
}
/**
* Builder for the MyBatis Bean component.
*/
|
MybatisBeanComponentBuilderFactory
|
java
|
google__gson
|
gson/src/test/java/com/google/gson/FieldNamingPolicyTest.java
|
{
"start": 3483,
"end": 4587
}
|
class ____ {
@SuppressWarnings({"unused", "ConstantField"})
int I;
}
FieldNamingPolicy[] policies = {
FieldNamingPolicy.LOWER_CASE_WITH_DASHES,
FieldNamingPolicy.LOWER_CASE_WITH_DOTS,
FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES,
};
Field field = Dummy.class.getDeclaredField("I");
String name = field.getName();
String expected = name.toLowerCase(Locale.ROOT);
Locale oldLocale = Locale.getDefault();
// Set Turkish as Locale which has special case conversion rules
Locale.setDefault(new Locale("tr"));
try {
// Verify that default Locale has different case conversion rules
assertWithMessage("Test setup is broken")
.that(name.toLowerCase(Locale.getDefault()))
.doesNotMatch(expected);
for (FieldNamingPolicy policy : policies) {
// Should ignore default Locale
assertWithMessage("Unexpected conversion for %s", policy)
.that(policy.translateName(field))
.matches(expected);
}
} finally {
Locale.setDefault(oldLocale);
}
}
}
|
Dummy
|
java
|
apache__camel
|
core/camel-api/src/main/java/org/apache/camel/spi/CompilePostProcessor.java
|
{
"start": 1256,
"end": 1873
}
|
class ____ been compiled
*
* @param camelContext the camel context
* @param name the name of the resource/class
* @param clazz the class
* @param byteCode byte code that was compiled from the source as the class (only supported on some DSLs)
* @param instance the object created as instance of the class (if any)
* @throws Exception is thrown if error during post-processing
*/
void postCompile(
CamelContext camelContext, String name,
Class<?> clazz, byte[] byteCode, Object instance)
throws Exception;
}
|
has
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/pytorch/results/PyTorchResultTests.java
|
{
"start": 460,
"end": 1631
}
|
class ____ extends AbstractXContentTestCase<PyTorchResult> {
@Override
protected PyTorchResult createTestInstance() {
String requestId = randomAlphaOfLength(5);
int type = randomIntBetween(0, 3);
return switch (type) {
case 0 -> new PyTorchResult(
requestId,
randomBoolean(),
randomNonNegativeLong(),
PyTorchInferenceResultTests.createRandom(),
null,
null,
null
);
case 1 -> new PyTorchResult(requestId, null, null, null, ThreadSettingsTests.createRandom(), null, null);
case 2 -> new PyTorchResult(requestId, null, null, null, null, AckResultTests.createRandom(), null);
default -> new PyTorchResult(requestId, null, null, null, null, null, ErrorResultTests.createRandom());
};
}
@Override
protected PyTorchResult doParseInstance(XContentParser parser) throws IOException {
return PyTorchResult.PARSER.parse(parser, null);
}
@Override
protected boolean supportsUnknownFields() {
return false;
}
}
|
PyTorchResultTests
|
java
|
grpc__grpc-java
|
core/src/main/java/io/grpc/internal/ForwardingNameResolver.java
|
{
"start": 786,
"end": 869
}
|
class ____ ensure non overridden methods are forwarded to the delegate.
*/
abstract
|
to
|
java
|
apache__commons-lang
|
src/main/java/org/apache/commons/lang3/SystemUtils.java
|
{
"start": 45159,
"end": 45679
}
|
class ____ loaded.
* </p>
*
* @since 3.15.0
*/
public static final boolean IS_JAVA_22 = getJavaVersionMatches("22");
/**
* The constant {@code true} if this is Java version 23 (also 23.x versions).
* <p>
* The result depends on the value of the {@link #JAVA_SPECIFICATION_VERSION} constant.
* </p>
* <p>
* The field will return {@code false} if {@link #JAVA_SPECIFICATION_VERSION} is {@code null}.
* </p>
* <p>
* This value is initialized when the
|
is
|
java
|
apache__flink
|
flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/network/ClientHandlerCallback.java
|
{
"start": 1032,
"end": 1810
}
|
interface ____<RESP extends MessageBody> {
/**
* Called on a successful request.
*
* @param requestId ID of the request
* @param response The received response
*/
void onRequestResult(long requestId, RESP response);
/**
* Called on a failed request.
*
* @param requestId ID of the request
* @param cause Cause of the request failure
*/
void onRequestFailure(long requestId, Throwable cause);
/**
* Called on any failure, which is not related to a specific request.
*
* <p>This can be for example a caught Exception in the channel pipeline or an unexpected
* channel close.
*
* @param cause Cause of the failure
*/
void onFailure(Throwable cause);
}
|
ClientHandlerCallback
|
java
|
google__auto
|
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
|
{
"start": 8733,
"end": 9429
}
|
class ____ {
abstract Builder setNumberClass(Class<? extends Number> x);
abstract ClassPropertyWithBuilder build();
}
}
@Test
public void testClassPropertyWithBuilder() {
ClassPropertyWithBuilder instance =
ClassPropertyWithBuilder.builder().setNumberClass(Integer.class).build();
assertThat(instance.numberClass()).isEqualTo(Integer.class);
try {
ClassPropertyWithBuilder.builder().build();
fail();
} catch (IllegalStateException expected) {
}
try {
ClassPropertyWithBuilder.builder().setNumberClass(null);
fail();
} catch (NullPointerException expected) {
}
}
@AutoValue
public abstract static
|
Builder
|
java
|
google__auto
|
factory/src/test/resources/expected/SimpleClassNullableParametersFactory.java
|
{
"start": 905,
"end": 2111
}
|
class ____ {
private final Provider<String> providedNullableProvider;
private final Provider<String> providedQualifiedNullableProvider;
@Inject
SimpleClassNullableParametersFactory(
Provider<String> providedNullableProvider,
@BQualifier Provider<String> providedQualifiedNullableProvider) {
this.providedNullableProvider = checkNotNull(providedNullableProvider, 1, 2);
this.providedQualifiedNullableProvider = checkNotNull(providedQualifiedNullableProvider, 2, 2);
}
SimpleClassNullableParameters create(
@Nullable String nullable, @Nullable @AQualifier String qualifiedNullable) {
return new SimpleClassNullableParameters(
nullable,
qualifiedNullable,
providedNullableProvider.get(),
providedQualifiedNullableProvider.get());
}
private static <T> T checkNotNull(T reference, int argumentNumber, int argumentCount) {
if (reference == null) {
throw new NullPointerException(
"@AutoFactory method argument is null but is not marked @Nullable. Argument "
+ argumentNumber
+ " of "
+ argumentCount);
}
return reference;
}
}
|
SimpleClassNullableParametersFactory
|
java
|
quarkusio__quarkus
|
independent-projects/qute/core/src/test/java/io/quarkus/qute/ParserTest.java
|
{
"start": 27262,
"end": 27957
}
|
class ____ implements ErrorInitializer, WithOrigin {
@Override
public Origin getOrigin() {
return null;
}
@Override
public Builder error(String message) {
return TemplateException.builder().message(message);
}
}
Iterator<String> iter = Parser.splitSectionParams(content, new Dummy());
List<String> params = new ArrayList<>();
while (iter.hasNext()) {
params.add(iter.next());
}
assertTrue(params.containsAll(Arrays.asList(expectedParams)),
params + " should contain " + Arrays.toString(expectedParams));
}
}
|
Dummy
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/PreferInstanceofOverGetKind.java
|
{
"start": 2470,
"end": 2818
}
|
class ____ extends BugChecker
implements BinaryTreeMatcher, MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> GET_KIND =
Matchers.instanceMethod().onDescendantOf(Tree.class.getName()).named("getKind");
/**
* A map from {@link Kind} to the {@link Class} of tree it denotes, iff that
|
PreferInstanceofOverGetKind
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_as_with_description_text_supplier_Test.java
|
{
"start": 1074,
"end": 2985
}
|
class ____ {
@Test
void descriptionText_should_evaluate_lazy_description() {
// GIVEN
ConcreteAssert assertions = new ConcreteAssert("foo");
// WHEN
assertions.as(() -> "description");
// THEN
then(assertions.descriptionText()).isEqualTo("description");
}
@Test
void should_not_evaluate_description_when_assertion_succeeds() {
// GIVEN
final AtomicBoolean evaluated = new AtomicBoolean(false);
Supplier<String> descriptionSupplier = spiedSupplier(evaluated);
// WHEN
assertThat(true).as(descriptionSupplier).isTrue();
// THEN
then(evaluated).isFalse();
}
@Test
void should_evaluate_description_when_assertion_fails() {
// GIVEN
final AtomicBoolean evaluated = new AtomicBoolean(false);
Supplier<String> descriptionSupplier = spiedSupplier(evaluated);
// WHEN
expectAssertionError(() -> assertThat(true).as(descriptionSupplier).isFalse());
// THEN
then(evaluated).isTrue();
}
@Test
void should_return_this() {
// GIVEN
ConcreteAssert assertions = new ConcreteAssert("foo");
// WHEN
ConcreteAssert returnedAssertions = assertions.as(() -> "description");
// THEN
then(returnedAssertions).isSameAs(assertions);
}
@Test
void should_throw_evaluate_lazy_description() {
// GIVEN
ConcreteAssert assertions = new ConcreteAssert("foo");
Supplier<String> descriptionSupplier = null;
// WHEN
Throwable throwable = catchThrowable(() -> assertions.as(descriptionSupplier).descriptionText());
// THEN
then(throwable).isInstanceOf(IllegalStateException.class)
.hasMessage("the descriptionSupplier should not be null");
}
private static Supplier<String> spiedSupplier(final AtomicBoolean evaluated) {
return () -> {
evaluated.set(true);
return "description";
};
}
}
|
AbstractAssert_as_with_description_text_supplier_Test
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/package-info.java
|
{
"start": 1499,
"end": 2565
}
|
interface
____ the even simpler and more concise and declarative metrics annotations.
The consumers of metrics just need to implement the simple
{@link org.apache.hadoop.metrics2.MetricsSink} interface. Producers
register the metrics sources with a metrics system, while consumers
register the sinks. A default metrics system is provided to marshal
metrics from sources to sinks based on (per source/sink) configuration
options. All the metrics are also published and queryable via the
standard JMX MBean interface. This document targets the framework users.
Framework developers could also consult the
<a href="http://wiki.apache.org/hadoop/HADOOP-6728-MetricsV2">design
document</a> for architecture and implementation notes.
</p>
<h4>Sub-packages</h4>
<dl>
<dt><code>org.apache.hadoop.metrics2.annotation</code></dt>
<dd>Public annotation interfaces for simpler metrics instrumentation.
</dd>
<dt><code>org.apache.hadoop.metrics2.impl</code></dt>
<dd>Implementation classes of the framework for
|
or
|
java
|
resilience4j__resilience4j
|
resilience4j-rxjava2/src/main/java/io/github/resilience4j/AbstractObserver.java
|
{
"start": 180,
"end": 1283
}
|
class ____<T> extends AbstractDisposable implements Observer<T> {
protected final AtomicBoolean eventWasEmitted = new AtomicBoolean(false);
private final Observer<? super T> downstreamObserver;
public AbstractObserver(Observer<? super T> downstreamObserver) {
this.downstreamObserver = requireNonNull(downstreamObserver);
}
@Override
protected void hookOnSubscribe() {
downstreamObserver.onSubscribe(this);
}
@Override
public void onNext(T item) {
whenNotDisposed(() -> {
eventWasEmitted.set(true);
downstreamObserver.onNext(item);
});
}
@Override
public void onError(Throwable e) {
whenNotCompleted(() -> {
hookOnError(e);
downstreamObserver.onError(e);
});
}
protected abstract void hookOnError(Throwable e);
@Override
public void onComplete() {
whenNotCompleted(() -> {
hookOnComplete();
downstreamObserver.onComplete();
});
}
protected abstract void hookOnComplete();
}
|
AbstractObserver
|
java
|
apache__camel
|
components/camel-smb/src/test/java/org/apache/camel/component/smb/SmbServerTestSupport.java
|
{
"start": 1442,
"end": 1503
}
|
class ____ unit testing using a SMBServer
*/
public abstract
|
for
|
java
|
spring-projects__spring-security
|
core/src/main/java/org/springframework/security/authentication/event/AuthenticationSuccessEvent.java
|
{
"start": 871,
"end": 1120
}
|
class ____ extends AbstractAuthenticationEvent {
@Serial
private static final long serialVersionUID = 2537206344128673963L;
public AuthenticationSuccessEvent(Authentication authentication) {
super(authentication);
}
}
|
AuthenticationSuccessEvent
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/dancing/DancingLinks.java
|
{
"start": 1512,
"end": 1821
}
|
class ____<ColumnName> {
private static final Logger LOG = LoggerFactory.getLogger(DancingLinks.class);
/**
* A cell in the table with up/down and left/right links that form doubly
* linked lists in both directions. It also includes a link to the column
* head.
*/
private static
|
DancingLinks
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/action/admin/cluster/hotthreads/NodesHotThreadsResponseTests.java
|
{
"start": 1103,
"end": 2206
}
|
class ____ extends ESTestCase {
public void testGetTextChunks() {
final var node0 = DiscoveryNodeUtils.create("node-0");
final var node1 = DiscoveryNodeUtils.create("node-1");
final var response = new NodesHotThreadsResponse(
ClusterName.DEFAULT,
List.of(
new NodeHotThreads(node0, ReleasableBytesReference.wrap(new BytesArray("""
node 0 line 1
node 0 line 2"""))),
new NodeHotThreads(node1, ReleasableBytesReference.wrap(new BytesArray("""
node 1 line 1
node 1 line 2""")))
),
List.of()
);
try {
assertEquals(Strings.format("""
::: %s
node 0 line 1
node 0 line 2
::: %s
node 1 line 1
node 1 line 2
""", node0, node1), getTextBodyContent(response.getTextChunks()));
} finally {
response.decRef();
}
}
}
|
NodesHotThreadsResponseTests
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/wall/WallSqlTableStat.java
|
{
"start": 656,
"end": 3646
}
|
class ____ {
private int selectCount;
private int selectIntoCount;
private int insertCount;
private int updateCount;
private int deleteCount;
private int truncateCount;
private int createCount;
private int alterCount;
private int dropCount;
private int replaceCount;
private int showCount;
private String sample;
public String getSample() {
return sample;
}
public void setSample(String sample) {
this.sample = sample;
}
public int getReplaceCount() {
return replaceCount;
}
public int incrementReplaceCount() {
return replaceCount++;
}
public void addReplaceCount(int value) {
this.replaceCount += value;
}
public int getSelectCount() {
return selectCount;
}
public void incrementSelectCount() {
this.selectCount++;
}
public void addSelectCount(int value) {
this.selectCount += value;
}
public int getSelectIntoCount() {
return selectIntoCount;
}
public void incrementSelectIntoCount() {
this.selectIntoCount++;
}
public void addSelectIntoCount(int value) {
this.selectIntoCount += value;
}
public int getInsertCount() {
return insertCount;
}
public void incrementInsertCount() {
this.insertCount++;
}
public void addInsertCount(int value) {
this.insertCount += value;
}
public int getUpdateCount() {
return updateCount;
}
public void incrementUpdateCount() {
this.updateCount++;
}
public void addUpdateCount(int value) {
this.deleteCount += value;
}
public int getDeleteCount() {
return deleteCount;
}
public void incrementDeleteCount() {
this.deleteCount++;
}
public void addDeleteCount(int value) {
this.deleteCount += value;
}
public int getTruncateCount() {
return truncateCount;
}
public void incrementTruncateCount() {
this.truncateCount++;
}
public void addTruncateCount(int value) {
this.truncateCount += value;
}
public int getCreateCount() {
return createCount;
}
public void incrementCreateCount() {
this.createCount++;
}
public void addCreateCount(int value) {
this.createCount += value;
}
public int getAlterCount() {
return alterCount;
}
public void incrementAlterCount() {
this.alterCount++;
}
public void addAlterCount(int value) {
this.alterCount += value;
}
public int getDropCount() {
return dropCount;
}
public void incrementDropCount() {
this.dropCount++;
}
public void addDropCount(int value) {
this.dropCount += value;
}
public int getShowCount() {
return showCount;
}
public void incrementShowCount() {
this.showCount++;
}
}
|
WallSqlTableStat
|
java
|
apache__dubbo
|
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter2Impl.java
|
{
"start": 861,
"end": 1201
}
|
class ____ implements IGreeter2 {
@Override
public String echo(String request) throws IGreeterException {
throw new IGreeterException("I am self define exception");
}
@Override
public Exception echoException(String request) {
return new IGreeterException("I am self define exception");
}
}
|
IGreeter2Impl
|
java
|
spring-projects__spring-boot
|
module/spring-boot-tomcat/src/test/java/org/springframework/boot/tomcat/autoconfigure/TomcatVirtualThreadsWebServerFactoryCustomizerTests.java
|
{
"start": 1222,
"end": 2102
}
|
class ____ {
private final TomcatVirtualThreadsWebServerFactoryCustomizer customizer = new TomcatVirtualThreadsWebServerFactoryCustomizer();
@Test
@EnabledForJreRange(min = JRE.JAVA_21)
void shouldSetVirtualThreadExecutor() {
withWebServer((webServer) -> assertThat(webServer.getTomcat().getConnector().getProtocolHandler().getExecutor())
.isInstanceOf(VirtualThreadExecutor.class));
}
private TomcatWebServer getWebServer() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0);
this.customizer.customize(factory);
return (TomcatWebServer) factory.getWebServer();
}
private void withWebServer(Consumer<TomcatWebServer> callback) {
TomcatWebServer webServer = getWebServer();
webServer.start();
try {
callback.accept(webServer);
}
finally {
webServer.stop();
}
}
}
|
TomcatVirtualThreadsWebServerFactoryCustomizerTests
|
java
|
grpc__grpc-java
|
interop-testing/src/test/java/io/grpc/testing/integration/CascadingTest.java
|
{
"start": 2354,
"end": 7119
}
|
class ____ {
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Mock
TestServiceGrpc.TestServiceImplBase service;
private ManagedChannel channel;
private Server server;
private CountDownLatch observedCancellations;
private CountDownLatch receivedCancellations;
private TestServiceGrpc.TestServiceBlockingStub blockingStub;
private TestServiceGrpc.TestServiceStub asyncStub;
private TestServiceGrpc.TestServiceFutureStub futureStub;
private ExecutorService otherWork;
@Before
public void setUp() throws Exception {
// Use a cached thread pool as we need a thread for each blocked call
otherWork = Executors.newCachedThreadPool();
channel = InProcessChannelBuilder.forName("channel").executor(otherWork).build();
blockingStub = TestServiceGrpc.newBlockingStub(channel);
asyncStub = TestServiceGrpc.newStub(channel);
futureStub = TestServiceGrpc.newFutureStub(channel);
}
@After
public void tearDown() {
channel.shutdownNow();
server.shutdownNow();
otherWork.shutdownNow();
}
/**
* Test {@link Context} cancellation propagates from the first node in the call chain all the way
* to the last.
*/
@Test
public void testCascadingCancellationViaOuterContextCancellation() throws Exception {
observedCancellations = new CountDownLatch(2);
receivedCancellations = new CountDownLatch(3);
Future<?> chainReady = startChainingServer(3);
CancellableContext context = Context.current().withCancellation();
Future<SimpleResponse> future;
Context prevContext = context.attach();
try {
future = futureStub.unaryCall(SimpleRequest.getDefaultInstance());
} finally {
context.detach(prevContext);
}
chainReady.get(5, TimeUnit.SECONDS);
context.cancel(null);
try {
future.get(5, TimeUnit.SECONDS);
fail("Expected cancellation");
} catch (ExecutionException ex) {
Status status = Status.fromThrowable(ex);
assertEquals(Status.Code.CANCELLED, status.getCode());
// Should have observed 2 cancellations responses from downstream servers
if (!observedCancellations.await(5, TimeUnit.SECONDS)) {
fail("Expected number of cancellations not observed by clients");
}
if (!receivedCancellations.await(5, TimeUnit.SECONDS)) {
fail("Expected number of cancellations to be received by servers not observed");
}
}
}
/**
* Test that cancellation via call cancellation propagates down the call.
*/
@Test
public void testCascadingCancellationViaRpcCancel() throws Exception {
observedCancellations = new CountDownLatch(2);
receivedCancellations = new CountDownLatch(3);
Future<?> chainReady = startChainingServer(3);
Future<SimpleResponse> future = futureStub.unaryCall(SimpleRequest.getDefaultInstance());
chainReady.get(5, TimeUnit.SECONDS);
future.cancel(true);
assertTrue(future.isCancelled());
if (!observedCancellations.await(5, TimeUnit.SECONDS)) {
fail("Expected number of cancellations not observed by clients");
}
if (!receivedCancellations.await(5, TimeUnit.SECONDS)) {
fail("Expected number of cancellations to be received by servers not observed");
}
}
/**
* Test that when RPC cancellation propagates up a call chain, the cancellation of the parent
* RPC triggers cancellation of all of its children.
*/
@Test
public void testCascadingCancellationViaLeafFailure() throws Exception {
// All nodes (15) except one edge of the tree (4) will be cancelled.
observedCancellations = new CountDownLatch(11);
receivedCancellations = new CountDownLatch(11);
startCallTreeServer(3);
try {
// Use response size limit to control tree nodeCount.
blockingStub.unaryCall(Messages.SimpleRequest.newBuilder().setResponseSize(3).build());
fail("Expected abort");
} catch (StatusRuntimeException sre) {
// Wait for the workers to finish
Status status = sre.getStatus();
// Outermost caller observes ABORTED propagating up from the failing leaf,
// The descendant RPCs are cancelled so they receive CANCELLED.
assertEquals(Status.Code.ABORTED, status.getCode());
if (!observedCancellations.await(5, TimeUnit.SECONDS)) {
fail("Expected number of cancellations not observed by clients");
}
if (!receivedCancellations.await(5, TimeUnit.SECONDS)) {
fail("Expected number of cancellations to be received by servers not observed");
}
}
}
@Test
public void testDeadlinePropagation() throws Exception {
final AtomicInteger recursionDepthRemaining = new AtomicInteger(3);
final SettableFuture<Deadline> finalDeadline = SettableFuture.create();
|
CascadingTest
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/error/ShouldBeInstance.java
|
{
"start": 842,
"end": 2662
}
|
class ____ extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldBeInstance}</code>.
*
* @param object the object value in the failed assertion.
* @param type the type {@code object} is \nExpecting:\n to belong to.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldBeInstance(Object object, Class<?> type) {
return object instanceof Throwable throwable ? new ShouldBeInstance(throwable, type) : new ShouldBeInstance(object, type);
}
/**
* Creates a new <code>{@link ShouldBeInstance}</code> when object we want to check type is null.
*
* @param objectDescription the description of the null object we wanted to check type.
* @param type the \nExpecting:\n type.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldBeInstanceButWasNull(String objectDescription, Class<?> type) {
return new ShouldBeInstance(objectDescription, type);
}
private ShouldBeInstance(Object object, Class<?> type) {
super("%n" +
"Expecting actual:%n" +
" %s%n" +
"to be an instance of:%n" +
" %s%n" +
"but was instance of:%n" +
" %s",
object, type, object.getClass());
}
private ShouldBeInstance(Throwable throwable, Class<?> type) {
super("%n" +
"Expecting actual throwable to be an instance of:%n" +
" %s%n" +
"but was:%n" +
" %s",
type, throwable);
}
private ShouldBeInstance(String objectDescription, Class<?> type) {
super("%n" +
"Expecting object:%n" +
" %s%n" +
"to be an instance of:%n" +
" <%s>%n" +
"but was null",
objectDescription, type);
}
}
|
ShouldBeInstance
|
java
|
apache__camel
|
components/camel-telemetry/src/test/java/org/apache/camel/telemetry/SpanTestSupport.java
|
{
"start": 928,
"end": 1517
}
|
class ____ {
protected static MockSpanAdapter getSpan(List<Span> trace, String uri, Op op) {
for (Span span : trace) {
MockSpanAdapter mockSpanAdapter = (MockSpanAdapter) span;
if (mockSpanAdapter.getTag("camel.uri") != null && mockSpanAdapter.getTag("camel.uri").equals(uri)) {
if (mockSpanAdapter.getTag(TagConstants.OP).equals(op.toString())) {
return mockSpanAdapter;
}
}
}
throw new IllegalArgumentException("Trying to get a non existing span!");
}
}
|
SpanTestSupport
|
java
|
apache__dubbo
|
dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/BaseCommand.java
|
{
"start": 987,
"end": 1142
}
|
interface ____ {
default boolean logResult() {
return true;
}
String execute(CommandContext commandContext, String[] args);
}
|
BaseCommand
|
java
|
reactor__reactor-core
|
reactor-core/src/jcstress/java/reactor/core/publisher/FluxSwitchMapStressTest.java
|
{
"start": 8340,
"end": 9858
}
|
class ____ extends FluxSwitchMapStressTest {
final TestPublisher<Object> testPublisher =
TestPublisher.createColdNonCompliant(false, TestPublisher.Violation.CLEANUP_ON_TERMINATE, TestPublisher.Violation.DEFER_CANCELLATION);
{
switchMapMain.onSubscribe(stressSubscription);
}
@Override
Publisher<Object> handle(Object value) {
return testPublisher;
}
@Actor
public void outerProducer() {
for (int i = 0; i < 10; i++) {
switchMapMain.onNext(i);
}
switchMapMain.onComplete();
}
@Actor
public void innerProducer() {
for (int i = 0; i < 200; i++) {
testPublisher.next(i);
}
testPublisher.complete();
}
@Actor
public void outerRequest() {
for (int i = 0; i < 200; i++) {
switchMapMain.request(1);
}
}
@Arbiter
public void arbiter(III_Result r) {
r.r1 = stressSubscriber.onNextCalls.get();
r.r2 = (int) switchMapMain.requested;
r.r3 = stressSubscriber.onCompleteCalls.get();
switch (r.toString()) {
case "200, 0, 0":
case "200, 0, 1":
break;
default: throw new IllegalStateException(r + " " + fastLogger);
}
if (stressSubscriber.onNextCalls.get() < 200 && stressSubscriber.onNextDiscarded.get() < switchMapMain.requested) {
throw new IllegalStateException(r + " " + fastLogger);
}
}
}
@JCStressTest
@Outcome(id = {"200, 1"}, expect = ACCEPTABLE, desc = "Should produced and remaining requested result in total requested number of elements")
@State
public static
|
RequestAndProduceStressTest2
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java
|
{
"start": 5181,
"end": 5373
}
|
class ____ {
@Bean
TestAuthorizationAuditListener authorizationAuditListener() {
return new TestAuthorizationAuditListener();
}
}
static
|
CustomAuthorizationAuditListenerConfiguration
|
java
|
micronaut-projects__micronaut-core
|
core/src/main/java/io/micronaut/core/cli/CommandLine.java
|
{
"start": 813,
"end": 2902
}
|
interface ____ {
/**
* @return The remaining arguments after the command name
*/
List<String> getRemainingArgs();
/**
* @return The system properties specified
*/
Properties getSystemProperties();
/**
* @return The declared option values
*/
Map<Option, Object> getOptions();
/**
* @param name The name of the option
* @return Whether the given option is specified
*/
boolean hasOption(String name);
/**
* The value of an option.
*
* @param name The option
* @return The value
*/
Object optionValue(String name);
/**
* @return The last specified option
*/
Map.Entry<String, Object> lastOption();
/**
* @return The remaining args as one big string
*/
String getRemainingArgsString();
/**
* @return The remaining args as one big string without undeclared options
*/
String getRemainingArgsWithOptionsString();
/**
* @return Any undeclared options
*/
Map<String, Object> getUndeclaredOptions();
/**
* Parses a new {@link CommandLine} instance that combines this instance with the given arguments.
*
* @param args The arguments
* @return A new {@link CommandLine} instance
*/
CommandLine parseNew(String[] args);
/**
* @return The raw unparsed arguments
*/
String[] getRawArguments();
/**
* Build and parse a new command line.
*
* @return The builder
*/
static Builder build() {
return new CommandLineParser();
}
/**
* Parse a new command line with the default options.
*
* @param args The arguments
* @return The command line
*/
static CommandLine parse(String... args) {
if (args == null || args.length == 0) {
return new DefaultCommandLine();
}
return new CommandLineParser().parse(args);
}
/**
* A build for constructing a command line parser.
*
* @param <T> The concrete type of the builder
*/
|
CommandLine
|
java
|
apache__commons-lang
|
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
|
{
"start": 22441,
"end": 22528
}
|
interface ____ found: " + midType);
}
// check if this
|
type
|
java
|
alibaba__nacos
|
client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java
|
{
"start": 1835,
"end": 12087
}
|
class ____ {
private NacosNamingMaintainService nacosNamingMaintainService;
private NamingHttpClientProxy serverProxy;
private NamingServerListManager serverListManager;
private SecurityProxy securityProxy;
private ScheduledExecutorService executorService;
@BeforeEach
void setUp() throws Exception {
Properties prop = new Properties();
prop.setProperty(PropertyKeyConst.NAMESPACE, "public");
prop.setProperty("serverAddr", "localhost");
nacosNamingMaintainService = new NacosNamingMaintainService(prop);
serverProxy = mock(NamingHttpClientProxy.class);
serverListManager = mock(NamingServerListManager.class);
securityProxy = mock(SecurityProxy.class);
executorService = mock(ScheduledExecutorService.class);
Field serverProxyField = NacosNamingMaintainService.class.getDeclaredField("serverProxy");
serverProxyField.setAccessible(true);
serverProxyField.set(nacosNamingMaintainService, serverProxy);
Field serverListManagerField = NacosNamingMaintainService.class.getDeclaredField("serverListManager");
serverListManagerField.setAccessible(true);
serverListManagerField.set(nacosNamingMaintainService, serverListManager);
Field securityProxyFiled = NacosNamingMaintainService.class.getDeclaredField("securityProxy");
securityProxyFiled.setAccessible(true);
securityProxyFiled.set(nacosNamingMaintainService, securityProxy);
Field executorServiceField = NacosNamingMaintainService.class.getDeclaredField("executorService");
executorServiceField.setAccessible(true);
executorServiceField.set(nacosNamingMaintainService, executorService);
}
@AfterEach
void tearDown() throws Exception {
}
@Test
void testConstructor() throws NacosException {
NacosNamingMaintainService client = new NacosNamingMaintainService("localhost");
assertNotNull(client);
}
@Test
void testUpdateInstance1() throws NacosException {
//given
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
//when
nacosNamingMaintainService.updateInstance(serviceName, groupName, instance);
//then
verify(serverProxy, times(1)).updateInstance(serviceName, groupName, instance);
}
@Test
void testUpdateInstance2() throws NacosException {
//given
String serviceName = "service1";
Instance instance = new Instance();
//when
nacosNamingMaintainService.updateInstance(serviceName, instance);
//then
verify(serverProxy, times(1)).updateInstance(serviceName, Constants.DEFAULT_GROUP, instance);
}
@Test
void testQueryService1() throws NacosException {
//given
String serviceName = "service1";
String groupName = "group1";
//when
nacosNamingMaintainService.queryService(serviceName, groupName);
//then
verify(serverProxy, times(1)).queryService(serviceName, groupName);
}
@Test
void testQueryService2() throws NacosException {
//given
String serviceName = "service1";
Instance instance = new Instance();
//when
nacosNamingMaintainService.queryService(serviceName);
//then
verify(serverProxy, times(1)).queryService(serviceName, Constants.DEFAULT_GROUP);
}
@Test
void testCreateService1() throws NacosException {
//given
String serviceName = "service1";
//when
nacosNamingMaintainService.createService(serviceName);
//then
verify(serverProxy, times(1)).createService(argThat(new ArgumentMatcher<Service>() {
@Override
public boolean matches(Service service) {
return service.getName().equals(serviceName) && service.getGroupName().equals(Constants.DEFAULT_GROUP)
&& Math.abs(service.getProtectThreshold() - Constants.DEFAULT_PROTECT_THRESHOLD) < 0.1f
&& service.getMetadata().size() == 0;
}
}), argThat(o -> o instanceof NoneSelector));
}
@Test
void testCreateService2() throws NacosException {
//given
String serviceName = "service1";
String groupName = "groupName";
//when
nacosNamingMaintainService.createService(serviceName, groupName);
//then
verify(serverProxy, times(1)).createService(argThat(new ArgumentMatcher<Service>() {
@Override
public boolean matches(Service service) {
return service.getName().equals(serviceName) && service.getGroupName().equals(groupName)
&& Math.abs(service.getProtectThreshold() - Constants.DEFAULT_PROTECT_THRESHOLD) < 0.1f
&& service.getMetadata().size() == 0;
}
}), argThat(o -> o instanceof NoneSelector));
}
@Test
void testCreateService3() throws NacosException {
//given
String serviceName = "service1";
String groupName = "groupName";
float protectThreshold = 0.1f;
//when
nacosNamingMaintainService.createService(serviceName, groupName, protectThreshold);
//then
verify(serverProxy, times(1)).createService(argThat(new ArgumentMatcher<Service>() {
@Override
public boolean matches(Service service) {
return service.getName().equals(serviceName) && service.getGroupName().equals(groupName)
&& Math.abs(service.getProtectThreshold() - protectThreshold) < 0.1f
&& service.getMetadata().size() == 0;
}
}), argThat(o -> o instanceof NoneSelector));
}
@Test
void testCreateService5() throws NacosException {
//given
String serviceName = "service1";
String groupName = "groupName";
float protectThreshold = 0.1f;
String expression = "k=v";
//when
nacosNamingMaintainService.createService(serviceName, groupName, protectThreshold, expression);
//then
verify(serverProxy, times(1)).createService(argThat(new ArgumentMatcher<Service>() {
@Override
public boolean matches(Service service) {
return service.getName().equals(serviceName) && service.getGroupName().equals(groupName)
&& Math.abs(service.getProtectThreshold() - protectThreshold) < 0.1f
&& service.getMetadata().size() == 0;
}
}), argThat(o -> ((ExpressionSelector) o).getExpression().equals(expression)));
}
@Test
void testCreateService4() throws NacosException {
//given
Service service = new Service();
AbstractSelector selector = new NoneSelector();
//when
nacosNamingMaintainService.createService(service, selector);
//then
verify(serverProxy, times(1)).createService(service, selector);
}
@Test
void testDeleteService1() throws NacosException {
//given
String serviceName = "service1";
//when
nacosNamingMaintainService.deleteService(serviceName);
//then
verify(serverProxy, times(1)).deleteService(serviceName, Constants.DEFAULT_GROUP);
}
@Test
void testDeleteService2() throws NacosException {
//given
String serviceName = "service1";
String groupName = "groupName";
//when
nacosNamingMaintainService.deleteService(serviceName, groupName);
//then
verify(serverProxy, times(1)).deleteService(serviceName, groupName);
}
@Test
void testUpdateService1() throws NacosException {
//given
String serviceName = "service1";
String groupName = "groupName";
float protectThreshold = 0.1f;
//when
nacosNamingMaintainService.updateService(serviceName, groupName, protectThreshold);
//then
verify(serverProxy, times(1)).updateService(argThat(new ArgumentMatcher<Service>() {
@Override
public boolean matches(Service service) {
return service.getName().equals(serviceName) && service.getGroupName().equals(groupName)
&& Math.abs(service.getProtectThreshold() - protectThreshold) < 0.1f;
}
}), argThat(o -> o instanceof NoneSelector));
}
@Test
void testUpdateService2() throws NacosException {
//given
String serviceName = "service1";
String groupName = "groupName";
float protectThreshold = 0.1f;
Map<String, String> meta = new HashMap<>();
meta.put("k", "v");
//when
nacosNamingMaintainService.updateService(serviceName, groupName, protectThreshold, meta);
//then
verify(serverProxy, times(1)).updateService(argThat(new ArgumentMatcher<Service>() {
@Override
public boolean matches(Service service) {
return service.getName().equals(serviceName) && service.getGroupName().equals(groupName)
&& Math.abs(service.getProtectThreshold() - protectThreshold) < 0.1f
&& service.getMetadata().size() == 1;
}
}), argThat(o -> o instanceof NoneSelector));
}
@Test
void testUpdateService3() throws NacosException {
//given
Service service = new Service();
AbstractSelector selector = new NoneSelector();
//when
nacosNamingMaintainService.updateService(service, selector);
//then
verify(serverProxy, times(1)).updateService(service, selector);
}
@Test
void testShutDown() throws NacosException {
//when
nacosNamingMaintainService.shutDown();
//then
verify(serverProxy, times(1)).shutdown();
verify(serverListManager, times(1)).shutdown();
verify(executorService, times(1)).shutdown();
}
}
|
NacosNamingMaintainServiceTest
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAsyncTest.java
|
{
"start": 1259,
"end": 6965
}
|
class ____ extends ContextTestSupport {
@Override
public boolean isUseRouteBuilder() {
return false;
}
@Test
public void testAsyncComplete() throws Exception {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
onCompletion().parallelProcessing().to("mock:before").delay(250).setBody(simple("OnComplete:${body}"))
.to("mock:after");
from("direct:start").process(new MyProcessor()).to("mock:result");
}
});
context.start();
getMockEndpoint("mock:before").expectedBodiesReceived("Bye World");
getMockEndpoint("mock:before").expectedPropertyReceived(Exchange.ON_COMPLETION, true);
getMockEndpoint("mock:after").expectedBodiesReceived("OnComplete:Bye World");
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Bye World");
String out = template.requestBody("direct:start", "Hello World", String.class);
assertEquals("Bye World", out);
assertMockEndpointsSatisfied();
}
@Test
public void testAsyncFailure() throws Exception {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
onCompletion().parallelProcessing().to("mock:before").delay(250).setBody(simple("OnComplete:${body}"))
.to("mock:after");
from("direct:start").process(new MyProcessor()).to("mock:result");
}
});
context.start();
getMockEndpoint("mock:before").expectedBodiesReceived("Kaboom");
getMockEndpoint("mock:before").expectedPropertyReceived(Exchange.ON_COMPLETION, true);
getMockEndpoint("mock:after").expectedBodiesReceived("OnComplete:Kaboom");
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(0);
try {
template.requestBody("direct:start", "Kaboom");
fail("Should throw exception");
} catch (CamelExecutionException e) {
assertEquals("Kaboom", e.getCause().getMessage());
}
assertMockEndpointsSatisfied();
}
@Test
public void testAsyncCompleteUseOriginalBody() throws Exception {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
onCompletion().useOriginalBody().parallelProcessing().to("mock:before").delay(250)
.setBody(simple("OnComplete:${body}")).to("mock:after");
from("direct:start").process(new MyProcessor()).to("mock:result");
}
});
context.start();
getMockEndpoint("mock:before").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:before").expectedPropertyReceived(Exchange.ON_COMPLETION, true);
getMockEndpoint("mock:after").expectedBodiesReceived("OnComplete:Hello World");
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Bye World");
String out = template.requestBody("direct:start", "Hello World", String.class);
assertEquals("Bye World", out);
assertMockEndpointsSatisfied();
}
@Test
public void testAsyncFailureUseOriginalBody() throws Exception {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
onCompletion().useOriginalBody().parallelProcessing().to("mock:before").delay(250)
.setBody(simple("OnComplete:${body}")).to("mock:after");
from("direct:start").transform(body().prepend("Before:${body}")).process(new MyProcessor()).to("mock:result");
}
});
context.start();
getMockEndpoint("mock:before").expectedBodiesReceived("Kaboom");
getMockEndpoint("mock:before").expectedPropertyReceived(Exchange.ON_COMPLETION, true);
getMockEndpoint("mock:after").expectedBodiesReceived("OnComplete:Kaboom");
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(0);
try {
template.requestBody("direct:start", "Kaboom");
fail("Should throw exception");
} catch (CamelExecutionException e) {
assertEquals("Kaboom", e.getCause().getMessage());
}
assertMockEndpointsSatisfied();
}
@Test
public void testAsyncCompleteOnCompleteFail() throws Exception {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
onCompletion().parallelProcessing().to("mock:before").delay(250).setBody(simple("OnComplete:${body}"))
// this exception does not cause any side effect as we are
// in async mode
.throwException(new IllegalAccessException("From onComplete")).to("mock:after");
from("direct:start").process(new MyProcessor()).to("mock:result");
}
});
context.start();
getMockEndpoint("mock:before").expectedBodiesReceived("Bye World");
getMockEndpoint("mock:before").expectedPropertyReceived(Exchange.ON_COMPLETION, true);
getMockEndpoint("mock:after").expectedMessageCount(0);
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Bye World");
String out = template.requestBody("direct:start", "Hello World", String.class);
assertEquals("Bye World", out);
assertMockEndpointsSatisfied();
}
public static
|
OnCompletionAsyncTest
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/slot/DefaultTimerService.java
|
{
"start": 1464,
"end": 4566
}
|
class ____<K> implements TimerService<K> {
/** Executor service for the scheduled timeouts. */
private final ScheduledExecutorService scheduledExecutorService;
/** Timeout for the shutdown of the service. */
private final long shutdownTimeout;
/** Map of currently active timeouts. */
private final Map<K, Timeout<K>> timeouts;
/** Listener which is notified about occurring timeouts. */
private TimeoutListener<K> timeoutListener;
public DefaultTimerService(
final ScheduledExecutorService scheduledExecutorService, final long shutdownTimeout) {
this.scheduledExecutorService = Preconditions.checkNotNull(scheduledExecutorService);
Preconditions.checkArgument(
shutdownTimeout >= 0L,
"The shut down timeout must be larger than or equal than 0.");
this.shutdownTimeout = shutdownTimeout;
this.timeouts = CollectionUtil.newHashMapWithExpectedSize(16);
this.timeoutListener = null;
}
@Override
public void start(TimeoutListener<K> initialTimeoutListener) {
// sanity check; We only allow to assign a timeout listener once
Preconditions.checkState(!scheduledExecutorService.isShutdown());
Preconditions.checkState(timeoutListener == null);
this.timeoutListener = Preconditions.checkNotNull(initialTimeoutListener);
}
@Override
public void stop() {
unregisterAllTimeouts();
timeoutListener = null;
ExecutorUtils.gracefulShutdown(
shutdownTimeout, TimeUnit.MILLISECONDS, scheduledExecutorService);
}
@Override
public void registerTimeout(final K key, final long delay, final TimeUnit unit) {
Preconditions.checkState(
timeoutListener != null,
"The " + getClass().getSimpleName() + " has not been started.");
if (timeouts.containsKey(key)) {
unregisterTimeout(key);
}
timeouts.put(
key, new Timeout<>(timeoutListener, key, delay, unit, scheduledExecutorService));
}
@Override
public void unregisterTimeout(K key) {
Timeout<K> timeout = timeouts.remove(key);
if (timeout != null) {
timeout.cancel();
}
}
/** Unregister all timeouts. */
protected void unregisterAllTimeouts() {
for (Timeout<K> timeout : timeouts.values()) {
timeout.cancel();
}
timeouts.clear();
}
@Override
public boolean isValid(K key, UUID ticket) {
if (timeouts.containsKey(key)) {
Timeout<K> timeout = timeouts.get(key);
return timeout.getTicket().equals(ticket);
} else {
return false;
}
}
@VisibleForTesting
Map<K, Timeout<K>> getTimeouts() {
return timeouts;
}
// ---------------------------------------------------------------------
// Static utility classes
// ---------------------------------------------------------------------
@VisibleForTesting
static final
|
DefaultTimerService
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/analysis/PreBuiltAnalyzerProviderFactory.java
|
{
"start": 3516,
"end": 4926
}
|
class ____ implements PreBuiltCacheFactory.PreBuiltCache<AnalyzerProvider<?>> {
private final String name;
private final PreBuiltAnalyzers preBuiltAnalyzer;
private PreBuiltAnalyzersDelegateCache(String name, PreBuiltAnalyzers preBuiltAnalyzer) {
this.name = name;
this.preBuiltAnalyzer = preBuiltAnalyzer;
}
@Override
public AnalyzerProvider<?> get(IndexVersion version) {
return new PreBuiltAnalyzerProvider(name, AnalyzerScope.INDICES, preBuiltAnalyzer.getAnalyzer(version));
}
@Override
public void put(IndexVersion version, AnalyzerProvider<?> analyzerProvider) {
// No need to put, because we delegate in get() directly to PreBuiltAnalyzers which already caches.
}
@Override
public Collection<AnalyzerProvider<?>> values() {
return preBuiltAnalyzer.getCache()
.values()
.stream()
// Wrap the analyzer instance in a PreBuiltAnalyzerProvider, this is what PreBuiltAnalyzerProviderFactory#close expects
// (other caches are not directly caching analyzers, but analyzer provider instead)
.<AnalyzerProvider<?>>map(analyzer -> new PreBuiltAnalyzerProvider(name, AnalyzerScope.INDICES, analyzer))
.toList();
}
}
}
|
PreBuiltAnalyzersDelegateCache
|
java
|
spring-projects__spring-security
|
web/src/main/java/org/springframework/security/web/method/annotation/CurrentSecurityContextArgumentResolver.java
|
{
"start": 2404,
"end": 2731
}
|
class ____ {
* @RequestMapping("/im")
* public void security(@CurrentSecurityContext SecurityContext context) {
* // do something with context
* }
* }
* </pre>
*
* it can also support the spring SPEL expression to get the value from SecurityContext
* <pre>
* @Controller
* public
|
MyController
|
java
|
hibernate__hibernate-orm
|
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/typeliteral/TypeLiteralTest.java
|
{
"start": 775,
"end": 1643
}
|
class ____ {
@Test
@WithClasses(value = {},
sources = {
"org.hibernate.processor.test.typeliteral.Account",
"org.hibernate.processor.test.typeliteral.CreditAccount",
"org.hibernate.processor.test.typeliteral.DebitAccount"
})
@TestForIssue(jiraKey = "HHH-18358")
void inheritance() {
final var entityClass = "org.hibernate.processor.test.typeliteral.Account";
System.out.println( getMetaModelSourceAsString( entityClass ) );
assertMetamodelClassGeneratedFor( entityClass );
assertPresenceOfFieldInMetamodelFor( entityClass, "QUERY_DEBIT_ACCOUNTS" );
assertPresenceOfFieldInMetamodelFor( entityClass, "QUERY_CREDIT_ACCOUNTS" );
assertPresenceOfMethodInMetamodelFor( entityClass, "debitAccounts", EntityManager.class );
assertPresenceOfMethodInMetamodelFor( entityClass, "creditAccounts", EntityManager.class );
}
}
|
TypeLiteralTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/normalizer/NormalizerProcessFactory.java
|
{
"start": 453,
"end": 864
}
|
interface ____ {
/**
* Create an implementation of {@link NormalizerProcess}
*
* @param executorService Executor service used to start the async tasks a job needs to operate the analytical process
* @return The process
*/
NormalizerProcess createNormalizerProcess(String jobId, String quantilesState, Integer bucketSpan, ExecutorService executorService);
}
|
NormalizerProcessFactory
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/UndefinedEqualsTest.java
|
{
"start": 13518,
"end": 13904
}
|
class ____ {
void f(Iterable a, Iterable b) {
assertThat(a).containsExactlyElementsIn(b);
}
}
""")
.doTest();
}
@Test
public void positiveSparseArray() {
compilationHelper
.addSourceLines(
"SparseArray.java",
"""
package android.util;
public
|
Test
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/catalog/ModelChange.java
|
{
"start": 2150,
"end": 3441
}
|
class ____ implements ModelChange {
private final String key;
private final String value;
public SetOption(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ModelChange.SetOption)) {
return false;
}
ModelChange.SetOption setOption = (ModelChange.SetOption) o;
return Objects.equals(key, setOption.key) && Objects.equals(value, setOption.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public String toString() {
return "SetOption{" + "key='" + key + '\'' + ", value='" + value + '\'' + '}';
}
}
/**
* A model change to reset the model option.
*
* <p>It is equal to the following statement:
*
* <pre>
* ALTER MODEL <model_name> RESET (key);
* </pre>
*/
@PublicEvolving
|
SetOption
|
java
|
quarkusio__quarkus
|
extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/ProvidedKeyStoreWithJavaNetSslNameTest.java
|
{
"start": 1012,
"end": 1781
}
|
class ____ {
private static final String configuration = """
# no configuration by default
""";
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.add(new StringAsset(configuration), "application.properties"))
.assertException(t -> {
assertThat(t).hasMessageContaining("%s is reserved", TlsConfig.JAVA_NET_SSL_TLS_CONFIGURATION_NAME);
});
@Test
void shouldNotBeCalled() {
fail("This test should not be called");
}
@ApplicationScoped
@Identifier(TlsConfig.JAVA_NET_SSL_TLS_CONFIGURATION_NAME)
static
|
ProvidedKeyStoreWithJavaNetSslNameTest
|
java
|
elastic__elasticsearch
|
libs/entitlement/src/main/java/org/elasticsearch/entitlement/initialization/DynamicInstrumentation.java
|
{
"start": 5463,
"end": 14869
}
|
class ____ the time to get detailed diagnostic
transformer.enableClassVerification();
for (var classToRetransform : classesToRetransform) {
inst.retransformClasses(classToRetransform);
}
// We should have failed already in the loop above, but just in case we did not, rethrow.
throw e;
}
if (transformer.hadErrors()) {
throw new RuntimeException("Failed to transform JDK classes for entitlements");
}
}
static Map<MethodKey, CheckMethod> getMethodsToInstrument(Class<?> checkerInterface) throws ClassNotFoundException,
NoSuchMethodException {
Map<MethodKey, CheckMethod> checkMethods = new HashMap<>(INSTRUMENTATION_SERVICE.lookupMethods(checkerInterface));
Stream.of(fileSystemProviderChecks(), fileStoreChecks(), pathChecks(), selectorProviderChecks())
.flatMap(Function.identity())
.forEach(instrumentation -> checkMethods.put(instrumentation.targetMethod(), instrumentation.checkMethod()));
return checkMethods;
}
private static Stream<InstrumentationService.InstrumentationInfo> fileSystemProviderChecks() throws ClassNotFoundException,
NoSuchMethodException {
var fileSystemProviderClass = FileSystems.getDefault().provider().getClass();
var instrumentation = new InstrumentationInfoFactory() {
@Override
public InstrumentationService.InstrumentationInfo of(String methodName, Class<?>... parameterTypes)
throws ClassNotFoundException, NoSuchMethodException {
return INSTRUMENTATION_SERVICE.lookupImplementationMethod(
FileSystemProvider.class,
methodName,
fileSystemProviderClass,
EntitlementChecker.class,
"check" + Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1),
parameterTypes
);
}
};
return Stream.of(
instrumentation.of("newFileSystem", URI.class, Map.class),
instrumentation.of("newFileSystem", Path.class, Map.class),
instrumentation.of("newInputStream", Path.class, OpenOption[].class),
instrumentation.of("newOutputStream", Path.class, OpenOption[].class),
instrumentation.of("newFileChannel", Path.class, Set.class, FileAttribute[].class),
instrumentation.of("newAsynchronousFileChannel", Path.class, Set.class, ExecutorService.class, FileAttribute[].class),
instrumentation.of("newByteChannel", Path.class, Set.class, FileAttribute[].class),
instrumentation.of("newDirectoryStream", Path.class, DirectoryStream.Filter.class),
instrumentation.of("createDirectory", Path.class, FileAttribute[].class),
instrumentation.of("createSymbolicLink", Path.class, Path.class, FileAttribute[].class),
instrumentation.of("createLink", Path.class, Path.class),
instrumentation.of("delete", Path.class),
instrumentation.of("deleteIfExists", Path.class),
instrumentation.of("readSymbolicLink", Path.class),
instrumentation.of("copy", Path.class, Path.class, CopyOption[].class),
instrumentation.of("move", Path.class, Path.class, CopyOption[].class),
instrumentation.of("isSameFile", Path.class, Path.class),
instrumentation.of("isHidden", Path.class),
instrumentation.of("getFileStore", Path.class),
instrumentation.of("checkAccess", Path.class, AccessMode[].class),
instrumentation.of("getFileAttributeView", Path.class, Class.class, LinkOption[].class),
instrumentation.of("readAttributes", Path.class, Class.class, LinkOption[].class),
instrumentation.of("readAttributes", Path.class, String.class, LinkOption[].class),
instrumentation.of("readAttributesIfExists", Path.class, Class.class, LinkOption[].class),
instrumentation.of("setAttribute", Path.class, String.class, Object.class, LinkOption[].class),
instrumentation.of("exists", Path.class, LinkOption[].class)
);
}
private static Stream<InstrumentationService.InstrumentationInfo> fileStoreChecks() {
var fileStoreClasses = StreamSupport.stream(FileSystems.getDefault().getFileStores().spliterator(), false)
.map(FileStore::getClass)
.distinct();
return fileStoreClasses.flatMap(fileStoreClass -> {
var instrumentation = new InstrumentationInfoFactory() {
@Override
public InstrumentationService.InstrumentationInfo of(String methodName, Class<?>... parameterTypes)
throws ClassNotFoundException, NoSuchMethodException {
return INSTRUMENTATION_SERVICE.lookupImplementationMethod(
FileStore.class,
methodName,
fileStoreClass,
EntitlementChecker.class,
"check" + Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1),
parameterTypes
);
}
};
try {
return Stream.of(
instrumentation.of("getFileStoreAttributeView", Class.class),
instrumentation.of("getAttribute", String.class),
instrumentation.of("getBlockSize"),
instrumentation.of("getTotalSpace"),
instrumentation.of("getUnallocatedSpace"),
instrumentation.of("getUsableSpace"),
instrumentation.of("isReadOnly"),
instrumentation.of("name"),
instrumentation.of("type")
);
} catch (NoSuchMethodException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
});
}
private static Stream<InstrumentationService.InstrumentationInfo> pathChecks() {
var pathClasses = StreamSupport.stream(FileSystems.getDefault().getRootDirectories().spliterator(), false)
.map(Path::getClass)
.distinct();
return pathClasses.flatMap(pathClass -> {
InstrumentationInfoFactory instrumentation = (String methodName, Class<?>... parameterTypes) -> INSTRUMENTATION_SERVICE
.lookupImplementationMethod(
Path.class,
methodName,
pathClass,
EntitlementChecker.class,
"checkPath" + Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1),
parameterTypes
);
try {
return Stream.of(
instrumentation.of("toRealPath", LinkOption[].class),
instrumentation.of("register", WatchService.class, WatchEvent.Kind[].class),
instrumentation.of("register", WatchService.class, WatchEvent.Kind[].class, WatchEvent.Modifier[].class)
);
} catch (NoSuchMethodException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
});
}
private static Stream<InstrumentationService.InstrumentationInfo> selectorProviderChecks() {
var selectorProviderClass = SelectorProvider.provider().getClass();
var instrumentation = new InstrumentationInfoFactory() {
@Override
public InstrumentationService.InstrumentationInfo of(String methodName, Class<?>... parameterTypes)
throws ClassNotFoundException, NoSuchMethodException {
return INSTRUMENTATION_SERVICE.lookupImplementationMethod(
SelectorProvider.class,
methodName,
selectorProviderClass,
EntitlementChecker.class,
"checkSelectorProvider" + Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1),
parameterTypes
);
}
};
try {
return Stream.of(
instrumentation.of("inheritedChannel"),
instrumentation.of("openDatagramChannel"),
instrumentation.of("openDatagramChannel", java.net.ProtocolFamily.class),
instrumentation.of("openServerSocketChannel"),
instrumentation.of("openServerSocketChannel", java.net.ProtocolFamily.class),
instrumentation.of("openSocketChannel"),
instrumentation.of("openSocketChannel", java.net.ProtocolFamily.class)
);
} catch (NoSuchMethodException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private static Class<?>[] findClassesToRetransform(Class<?>[] loadedClasses, Set<String> classesToTransform) {
List<Class<?>> retransform = new ArrayList<>();
for (Class<?> loadedClass : loadedClasses) {
if (classesToTransform.contains(loadedClass.getName().replace(".", "/"))) {
retransform.add(loadedClass);
}
}
return retransform.toArray(new Class<?>[0]);
}
}
|
at
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SlotSharingExecutionSlotAllocator.java
|
{
"start": 18063,
"end": 18766
}
|
class ____ {
private final ExecutionVertexID executionVertexId;
private final CompletableFuture<LogicalSlot> logicalSlotFuture;
SlotExecutionVertexAssignment(
ExecutionVertexID executionVertexId,
CompletableFuture<LogicalSlot> logicalSlotFuture) {
this.executionVertexId = checkNotNull(executionVertexId);
this.logicalSlotFuture = checkNotNull(logicalSlotFuture);
}
ExecutionVertexID getExecutionVertexId() {
return executionVertexId;
}
CompletableFuture<LogicalSlot> getLogicalSlotFuture() {
return logicalSlotFuture;
}
}
}
|
SlotExecutionVertexAssignment
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/gateway/PersistedClusterStateService.java
|
{
"start": 74671,
"end": 74819
}
|
interface ____ {
void consumePage(BytesRef bytesRef, int pageIndex, boolean isLastPage) throws IOException;
}
private static
|
PageWriter
|
java
|
apache__camel
|
components/camel-mllp/src/test/java/org/apache/camel/test/stub/tcp/SocketOutputStreamStub.java
|
{
"start": 947,
"end": 2564
}
|
class ____ extends OutputStream {
public boolean failOnWrite;
public boolean failOnWriteArray;
public Byte writeFailOn;
public byte[] writeArrayFailOn;
ByteArrayOutputStream fakeOutputStream = new ByteArrayOutputStream();
@Override
public void write(int b) throws IOException {
if (failOnWrite) {
throw new IOException("Faking write failure");
} else if (writeFailOn != null && writeFailOn == b) {
throw new IOException("Faking write failure");
}
if (fakeOutputStream == null) {
fakeOutputStream = new ByteArrayOutputStream();
}
fakeOutputStream.write(b);
}
@Override
public void write(byte[] array, int off, int len) throws IOException {
if (failOnWriteArray) {
throw new IOException("Faking write array failure");
}
if (writeArrayFailOn != null) {
if (writeArrayFailOn == array) {
throw new IOException("Faking write array failure");
}
for (int i = 0; i < Math.min(len, writeArrayFailOn.length); ++i) {
if (array[off + i] != writeArrayFailOn[i]) {
super.write(array, off, len);
return;
}
}
throw new IOException("Faking write array failure");
} else {
super.write(array, off, len);
}
}
public byte[] getPayload() {
if (fakeOutputStream != null) {
return fakeOutputStream.toByteArray();
}
return null;
}
}
|
SocketOutputStreamStub
|
java
|
bumptech__glide
|
library/src/main/java/com/bumptech/glide/load/resource/drawable/AnimatedWebpDecoder.java
|
{
"start": 4175,
"end": 4926
}
|
class ____
implements ResourceDecoder<InputStream, Drawable> {
private final AnimatedWebpDecoder delegate;
StreamAnimatedWebpDecoder(AnimatedWebpDecoder delegate) {
this.delegate = delegate;
}
@Override
public boolean handles(@NonNull InputStream source, @NonNull Options options)
throws IOException {
return delegate.handles(source);
}
@Override
public Resource<Drawable> decode(
@NonNull InputStream is, int width, int height, @NonNull Options options)
throws IOException {
Source source = ImageDecoder.createSource(ByteBufferUtil.fromStream(is));
return delegate.decode(source, width, height, options);
}
}
private static final
|
StreamAnimatedWebpDecoder
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/web/servlet/assertj/MockMvcTesterIntegrationTests.java
|
{
"start": 21767,
"end": 22085
}
|
class ____ {
@GetMapping(path = "/greet", produces = "text/plain")
String greet() {
return "hello";
}
@GetMapping(path = "/message", produces = MediaType.APPLICATION_JSON_VALUE)
String message() {
return "{\"message\": \"hello\"}";
}
}
@Controller
@RequestMapping("/persons")
static
|
TestController
|
java
|
bumptech__glide
|
library/src/main/java/com/bumptech/glide/load/data/BufferedOutputStream.java
|
{
"start": 389,
"end": 2724
}
|
class ____ extends OutputStream {
@NonNull private final OutputStream out;
private byte[] buffer;
private ArrayPool arrayPool;
private int index;
public BufferedOutputStream(@NonNull OutputStream out, @NonNull ArrayPool arrayPool) {
this(out, arrayPool, ArrayPool.STANDARD_BUFFER_SIZE_BYTES);
}
@VisibleForTesting
BufferedOutputStream(@NonNull OutputStream out, ArrayPool arrayPool, int bufferSize) {
this.out = out;
this.arrayPool = arrayPool;
buffer = arrayPool.get(bufferSize, byte[].class);
}
@Override
public void write(int b) throws IOException {
buffer[index++] = (byte) b;
maybeFlushBuffer();
}
@Override
public void write(@NonNull byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(@NonNull byte[] b, int initialOffset, int length) throws IOException {
int writtenSoFar = 0;
do {
int remainingToWrite = length - writtenSoFar;
int currentOffset = initialOffset + writtenSoFar;
// If we still need to write at least the buffer size worth of bytes, we might as well do so
// directly and avoid the overhead of copying to the buffer first.
if (index == 0 && remainingToWrite >= buffer.length) {
out.write(b, currentOffset, remainingToWrite);
return;
}
int remainingSpaceInBuffer = buffer.length - index;
int totalBytesToWriteToBuffer = Math.min(remainingToWrite, remainingSpaceInBuffer);
System.arraycopy(b, currentOffset, buffer, index, totalBytesToWriteToBuffer);
index += totalBytesToWriteToBuffer;
writtenSoFar += totalBytesToWriteToBuffer;
maybeFlushBuffer();
} while (writtenSoFar < length);
}
@Override
public void flush() throws IOException {
flushBuffer();
out.flush();
}
private void flushBuffer() throws IOException {
if (index > 0) {
out.write(buffer, 0, index);
index = 0;
}
}
private void maybeFlushBuffer() throws IOException {
if (index == buffer.length) {
flushBuffer();
}
}
@Override
public void close() throws IOException {
try {
flush();
} finally {
out.close();
}
release();
}
private void release() {
if (buffer != null) {
arrayPool.put(buffer);
buffer = null;
}
}
}
|
BufferedOutputStream
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/manytomany/sametable/Child2Entity.java
|
{
"start": 655,
"end": 2428
}
|
class ____ {
@Id
@GeneratedValue
private Integer id;
private String child2Data;
public Child2Entity() {
}
public Child2Entity(String child2Data) {
this.child2Data = child2Data;
}
public Child2Entity(Integer id, String child2Data) {
this.id = id;
this.child2Data = child2Data;
}
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "children",
joinColumns = @JoinColumn(name = "child2_id"),
inverseJoinColumns = @JoinColumn(name = "parent_id", insertable = false, updatable = false)
)
@SQLJoinTableRestriction("child2_id is not null")
private List<ParentEntity> parents = new ArrayList<ParentEntity>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getChild2Data() {
return child2Data;
}
public void setChild2Data(String child2Data) {
this.child2Data = child2Data;
}
public List<ParentEntity> getParents() {
return parents;
}
public void setParents(List<ParentEntity> parents) {
this.parents = parents;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Child2Entity that = (Child2Entity) o;
if ( child2Data != null ? !child2Data.equals( that.child2Data ) : that.child2Data != null ) {
return false;
}
//noinspection RedundantIfStatement
if ( id != null ? !id.equals( that.id ) : that.id != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (child2Data != null ? child2Data.hashCode() : 0);
return result;
}
public String toString() {
return "C2E(id = " + id + ", child2Data = " + child2Data + ")";
}
}
|
Child2Entity
|
java
|
quarkusio__quarkus
|
extensions/spring-di/deployment/src/main/java/io/quarkus/spring/di/deployment/SpringDiBuildTimeConfig.java
|
{
"start": 320,
"end": 608
}
|
interface ____ {
/**
* Whether Spring DI is enabled **during the build**.
* <p>
* Turning this setting off will result in Quarkus completely ignoring beans annotated with Spring annotations
*/
@WithDefault("true")
boolean enabled();
}
|
SpringDiBuildTimeConfig
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/StructHelper.java
|
{
"start": 1412,
"end": 6887
}
|
class ____ {
public static StructAttributeValues getAttributeValues(
EmbeddableMappingType embeddableMappingType,
Object[] rawJdbcValues,
WrapperOptions options) throws SQLException {
final int numberOfAttributeMappings = embeddableMappingType.getNumberOfAttributeMappings();
final int size = numberOfAttributeMappings + ( embeddableMappingType.isPolymorphic() ? 1 : 0 );
final var attributeValues = new StructAttributeValues( numberOfAttributeMappings, rawJdbcValues );
int jdbcIndex = 0;
for ( int i = 0; i < size; i++ ) {
jdbcIndex += injectAttributeValue(
getSubPart( embeddableMappingType, i ),
attributeValues,
i,
rawJdbcValues,
jdbcIndex,
options
);
}
return attributeValues;
}
private static int injectAttributeValue(
ValuedModelPart modelPart,
StructAttributeValues attributeValues,
int attributeIndex,
Object[] rawJdbcValues,
int jdbcIndex,
WrapperOptions options) throws SQLException {
if ( modelPart.getMappedType() instanceof EmbeddableMappingType embeddableMappingType ) {
return injectAttributeValueEmbeddable(
attributeValues, attributeIndex,
rawJdbcValues, jdbcIndex,
options,
embeddableMappingType
);
}
else {
assert modelPart.getJdbcTypeCount() == 1;
return injectAttributeValueSimple(
modelPart,
attributeValues, attributeIndex,
rawJdbcValues, jdbcIndex,
options
);
}
}
private static int injectAttributeValueSimple(
ValuedModelPart modelPart,
StructAttributeValues attributeValues,
int attributeIndex,
Object[] rawJdbcValues,
int jdbcIndex,
WrapperOptions options) {
final var jdbcMapping = modelPart.getSingleJdbcMapping();
final Object jdbcValue = jdbcMapping.getJdbcJavaType().wrap( rawJdbcValues[jdbcIndex], options );
attributeValues.setAttributeValue( attributeIndex, jdbcMapping.convertToDomainValue( jdbcValue ) );
return 1;
}
private static int injectAttributeValueEmbeddable(
StructAttributeValues attributeValues,
int attributeIndex,
Object[] rawJdbcValues,
int jdbcIndex,
WrapperOptions options,
EmbeddableMappingType embeddableMappingType)
throws SQLException {
if ( embeddableMappingType.getAggregateMapping() != null ) {
attributeValues.setAttributeValue( attributeIndex, rawJdbcValues[jdbcIndex] );
return 1;
}
else {
final int jdbcValueCount = embeddableMappingType.getJdbcValueCount();
final Object[] subJdbcValues = new Object[jdbcValueCount];
System.arraycopy( rawJdbcValues, jdbcIndex, subJdbcValues, 0, subJdbcValues.length );
final var subValues = getAttributeValues( embeddableMappingType, subJdbcValues, options );
attributeValues.setAttributeValue( attributeIndex, instantiate( embeddableMappingType, subValues ) );
return jdbcValueCount;
}
}
public static Object[] getJdbcValues(
EmbeddableMappingType embeddableMappingType,
int[] orderMapping,
Object domainValue,
WrapperOptions options) throws SQLException {
final int jdbcValueCount = embeddableMappingType.getJdbcValueCount();
final int valueCount = jdbcValueCount + ( embeddableMappingType.isPolymorphic() ? 1 : 0 );
final Object[] values = embeddableMappingType.getValues( domainValue );
final Object[] jdbcValues =
valueCount != values.length || orderMapping != null ? new Object[valueCount] : values;
injectJdbcValues(
embeddableMappingType,
values,
jdbcValues,
0,
options
);
if ( orderMapping != null ) {
final Object[] originalJdbcValues = jdbcValues.clone();
for ( int i = 0; i < orderMapping.length; i++ ) {
jdbcValues[i] = originalJdbcValues[orderMapping[i]];
}
}
return jdbcValues;
}
private static int injectJdbcValues(
EmbeddableMappingType embeddableMappingType,
@Nullable Object domainValue,
Object[] jdbcValues,
int jdbcIndex,
WrapperOptions options) throws SQLException {
return injectJdbcValues(
embeddableMappingType,
domainValue == null ? null : embeddableMappingType.getValues( domainValue ),
jdbcValues,
jdbcIndex,
options
);
}
private static int injectJdbcValues(
EmbeddableMappingType embeddableMappingType,
@Nullable Object[] values,
Object[] jdbcValues,
int jdbcIndex,
WrapperOptions options) throws SQLException {
final int jdbcValueCount = embeddableMappingType.getJdbcValueCount();
final int valueCount = jdbcValueCount + ( embeddableMappingType.isPolymorphic() ? 1 : 0 );
if ( values == null ) {
return valueCount;
}
int offset = 0;
for ( int i = 0; i < values.length; i++ ) {
offset += injectJdbcValue(
getSubPart( embeddableMappingType, i ),
values,
i,
jdbcValues,
jdbcIndex + offset,
options
);
}
assert offset == valueCount;
return offset;
}
public static Object instantiate(
EmbeddableMappingType embeddableMappingType,
StructAttributeValues attributeValues) {
return embeddableInstantiator( embeddableMappingType, attributeValues ).instantiate( attributeValues );
}
private static EmbeddableInstantiator embeddableInstantiator(
EmbeddableMappingType embeddableMappingType,
StructAttributeValues attributeValues) {
final EmbeddableRepresentationStrategy representationStrategy = embeddableMappingType.getRepresentationStrategy();
if ( !embeddableMappingType.isPolymorphic() ) {
return representationStrategy.getInstantiator();
}
else {
// the discriminator here is the composite
|
StructHelper
|
java
|
google__auto
|
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
|
{
"start": 131812,
"end": 132631
}
|
interface ____ {",
" Class<?>[] values() default {};",
" }",
"}");
ImmutableList<String> annotations =
ImmutableList.of(
"@ReferenceClass(BarFoo.class)",
"@ReferenceClass(values = {Void.class, BarFoo.class})",
"@ReferenceClass(nested = @ReferenceClass.Nested(values = {Void.class,"
+ " BarFoo.class}))");
for (String annotation : annotations) {
JavaFileObject bazFileObject =
JavaFileObjects.forSourceLines(
"foo.bar.Baz",
"package foo.bar;",
"",
"import com.google.auto.value.AutoValue;",
"",
"@AutoValue",
"@AutoValue.CopyAnnotations",
annotation,
"public abstract
|
Nested
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/SubstringOfZeroTest.java
|
{
"start": 877,
"end": 1180
}
|
class ____ {
private final BugCheckerRefactoringTestHelper helper =
BugCheckerRefactoringTestHelper.newInstance(SubstringOfZero.class, getClass());
@Test
public void positiveJustVars() {
helper
.addInputLines(
"Test.java",
"""
|
SubstringOfZeroTest
|
java
|
mapstruct__mapstruct
|
core/src/main/java/org/mapstruct/ValueMappings.java
|
{
"start": 1349,
"end": 1407
}
|
interface ____ {
ValueMapping[] value();
}
|
ValueMappings
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/slowtaskdetector/SlowTaskDetector.java
|
{
"start": 1069,
"end": 1376
}
|
interface ____ {
/** Start detecting slow tasks periodically. */
void start(
ExecutionGraph executionGraph,
SlowTaskDetectorListener listener,
ComponentMainThreadExecutor mainThreadExecutor);
/** Stop detecting slow tasks. */
void stop();
}
|
SlowTaskDetector
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-nativetask/src/test/java/org/apache/hadoop/mapred/nativetask/handlers/TestNativeCollectorOnlyHandler.java
|
{
"start": 2136,
"end": 5536
}
|
class ____ {
private NativeCollectorOnlyHandler handler;
private INativeHandler nativeHandler;
private BufferPusher pusher;
private ICombineHandler combiner;
private TaskContext taskContext;
private static final String LOCAL_DIR = TestConstants.NATIVETASK_TEST_DIR + "/local";
@BeforeEach
public void setUp() throws IOException {
this.nativeHandler = Mockito.mock(INativeHandler.class);
this.pusher = Mockito.mock(BufferPusher.class);
this.combiner = Mockito.mock(ICombineHandler.class);
JobConf jobConf = new JobConf();
jobConf.set(OutputUtil.NATIVE_TASK_OUTPUT_MANAGER,
"org.apache.hadoop.mapred.nativetask.util.LocalJobOutputFiles");
jobConf.set("mapred.local.dir", LOCAL_DIR);
this.taskContext = new TaskContext(jobConf,
BytesWritable.class, BytesWritable.class,
BytesWritable.class,
BytesWritable.class,
null,
null);
Mockito.when(nativeHandler.getInputBuffer()).thenReturn(
new InputBuffer(BufferType.HEAP_BUFFER, 100));
}
@AfterEach
public void tearDown() throws IOException {
FileSystem.getLocal(new Configuration()).delete(new Path(LOCAL_DIR));
}
@Test
public void testCollect() throws IOException {
this.handler = new NativeCollectorOnlyHandler(taskContext, nativeHandler, pusher, combiner);
handler.collect(new BytesWritable(), new BytesWritable(), 100);
handler.close();
handler.close();
Mockito.verify(pusher, Mockito.times(1)).collect(any(BytesWritable.class),
any(BytesWritable.class), anyInt());
Mockito.verify(pusher, Mockito.times(1)).close();
Mockito.verify(combiner, Mockito.times(1)).close();
Mockito.verify(nativeHandler, Mockito.times(1)).close();
}
@Test
public void testGetCombiner() throws IOException {
this.handler = new NativeCollectorOnlyHandler(taskContext, nativeHandler, pusher, combiner);
Mockito.when(combiner.getId()).thenReturn(100L);
final ReadWriteBuffer result = handler.onCall(
NativeCollectorOnlyHandler.GET_COMBINE_HANDLER, null);
assertEquals(100L, result.readLong());
}
@Test
public void testOnCall() throws IOException {
this.handler = new NativeCollectorOnlyHandler(taskContext, nativeHandler, pusher, combiner);
boolean thrown = false;
try {
handler.onCall(new Command(-1), null);
} catch(final IOException e) {
thrown = true;
}
assertTrue(thrown, "exception thrown");
final String expectedOutputPath = StringUtils.join(File.separator,
new String[] {LOCAL_DIR, "output", "file.out"});
final String expectedOutputIndexPath = StringUtils.join(File.separator,
new String[] {LOCAL_DIR, "output", "file.out.index"});
final String expectedSpillPath = StringUtils.join(File.separator,
new String[] {LOCAL_DIR, "output", "spill0.out"});
final String outputPath = handler.onCall(
NativeCollectorOnlyHandler.GET_OUTPUT_PATH, null).readString();
assertEquals(expectedOutputPath, outputPath);
final String outputIndexPath = handler.onCall(
NativeCollectorOnlyHandler.GET_OUTPUT_INDEX_PATH, null).readString();
assertEquals(expectedOutputIndexPath, outputIndexPath);
final String spillPath = handler.onCall(
NativeCollectorOnlyHandler.GET_SPILL_PATH, null).readString();
assertEquals(expectedSpillPath, spillPath);
}
}
|
TestNativeCollectorOnlyHandler
|
java
|
spring-projects__spring-security
|
web/src/main/java/org/springframework/security/web/firewall/RequestRejectedHandler.java
|
{
"start": 1030,
"end": 1615
}
|
interface ____ {
/**
* Handles an request rejected failure.
* @param request that resulted in an <code>RequestRejectedException</code>
* @param response so that the user agent can be advised of the failure
* @param requestRejectedException that caused the invocation
* @throws IOException in the event of an IOException
* @throws ServletException in the event of a ServletException
*/
void handle(HttpServletRequest request, HttpServletResponse response,
RequestRejectedException requestRejectedException) throws IOException, ServletException;
}
|
RequestRejectedHandler
|
java
|
google__gson
|
gson/src/test/java/com/google/gson/functional/NullObjectAndFieldTest.java
|
{
"start": 6122,
"end": 6740
}
|
class ____ {
// Using a mix of no-args constructor and field initializers
// Also, some fields are initialized and some are not (so initialized per JVM spec)
public static final String MY_STRING_DEFAULT = "string";
private static final int MY_INT_DEFAULT = 2;
private static final boolean MY_BOOLEAN_DEFAULT = true;
int[] array;
String str1;
String str2;
int int1 = MY_INT_DEFAULT;
int int2;
boolean bool1 = MY_BOOLEAN_DEFAULT;
boolean bool2;
public ClassWithInitializedMembers() {
str1 = MY_STRING_DEFAULT;
}
}
private static
|
ClassWithInitializedMembers
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.