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 | bumptech__glide | library/test/src/test/java/com/bumptech/glide/load/engine/bitmap_recycle/SizeStrategyKeyTest.java | {
"start": 542,
"end": 1390
} | class ____ {
private SizeStrategy.KeyPool keyPool;
@Before
public void setUp() {
keyPool = mock(SizeStrategy.KeyPool.class);
}
@Test
public void testEquality() {
Key first = new Key(keyPool);
first.init(100);
Key second = new Key(keyPool);
second.init(100);
Key third = new Key(keyPool);
third.init(50);
new EqualsTester().addEqualityGroup(first, second).addEqualityGroup(third).testEquals();
}
@Test
public void testReturnsSelfToPoolOnOffer() {
Key key = new Key(keyPool);
key.offer();
verify(keyPool).offer(eq(key));
}
@Test
public void testInitSetsSize() {
Key key = new Key(keyPool);
key.init(100);
Key other = new Key(keyPool);
other.init(200);
assertNotEquals(key, other);
key.init(200);
assertEquals(key, other);
}
}
| SizeStrategyKeyTest |
java | quarkusio__quarkus | extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/i18n/AppMessages.java | {
"start": 215,
"end": 1249
} | interface ____ {
@Message("Hello world!")
String hello();
@Message("Hello {name}!")
String hello_name(String name);
@Message("Hello {name} {surname}!")
String hello_fullname(String name, String surname);
// key=hello_with_if_section
@Message(key = UNDERSCORED_ELEMENT_NAME, value = "{#if count eq 1}"
+ "{msg:hello_name('you guy')}"
+ "{#else}"
+ "{msg:hello_name('you guys')}"
+ "{/if}")
String helloWithIfSection(int count);
@Message("Item name: {item.name}, age: {item.age}")
String itemDetail(Item item);
@Message(key = "dot.test", value = "Dot test!")
String dotTest();
@Message("There {msg:fileStrings(numberOfFiles)} on {disk}.")
String files(int numberOfFiles, String disk);
@Message("{#when numberOfFiles}"
+ "{#is 0}are no files"
+ "{#is 1}is one file"
+ "{#else}are {numberOfFiles} files"
+ "{/when}")
String fileStrings(int numberOfFiles);
}
| AppMessages |
java | netty__netty | codec-base/src/test/java/io/netty/handler/codec/ByteToMessageDecoderTest.java | {
"start": 12595,
"end": 16687
} | class ____ extends UnpooledHeapByteBuf {
private final Error error = new Error();
private int untilFailure;
WriteFailingByteBuf(int untilFailure, int capacity) {
super(UnpooledByteBufAllocator.DEFAULT, capacity, capacity);
this.untilFailure = untilFailure;
}
@Override
public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {
if (--untilFailure <= 0) {
throw error;
}
return super.setBytes(index, src, srcIndex, length);
}
Error writeError() {
return error;
}
}
@Test
public void releaseWhenMergeCumulateThrows() {
WriteFailingByteBuf oldCumulation = new WriteFailingByteBuf(1, 64);
oldCumulation.writeZero(1);
ByteBuf in = Unpooled.buffer().writeZero(12);
Throwable thrown = null;
try {
ByteToMessageDecoder.MERGE_CUMULATOR.cumulate(UnpooledByteBufAllocator.DEFAULT, oldCumulation, in);
} catch (Throwable t) {
thrown = t;
}
assertSame(oldCumulation.writeError(), thrown);
assertEquals(0, in.refCnt());
assertEquals(1, oldCumulation.refCnt());
oldCumulation.release();
}
@Test
public void releaseWhenMergeCumulateThrowsInExpand() {
releaseWhenMergeCumulateThrowsInExpand(1, true);
releaseWhenMergeCumulateThrowsInExpand(2, true);
releaseWhenMergeCumulateThrowsInExpand(3, false); // sentinel test case
}
private void releaseWhenMergeCumulateThrowsInExpand(int untilFailure, boolean shouldFail) {
ByteBuf oldCumulation = UnpooledByteBufAllocator.DEFAULT.heapBuffer(8, 8).writeZero(1);
final WriteFailingByteBuf newCumulation = new WriteFailingByteBuf(untilFailure, 16);
ByteBufAllocator allocator = new AbstractByteBufAllocator(false) {
@Override
public boolean isDirectBufferPooled() {
return false;
}
@Override
protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
return newCumulation;
}
@Override
protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) {
throw new UnsupportedOperationException();
}
};
ByteBuf in = Unpooled.buffer().writeZero(12);
Throwable thrown = null;
try {
ByteToMessageDecoder.MERGE_CUMULATOR.cumulate(allocator, oldCumulation, in);
} catch (Throwable t) {
thrown = t;
}
assertEquals(0, in.refCnt());
if (shouldFail) {
assertSame(newCumulation.writeError(), thrown);
assertEquals(1, oldCumulation.refCnt());
oldCumulation.release();
assertEquals(0, newCumulation.refCnt());
} else {
assertNull(thrown);
assertEquals(0, oldCumulation.refCnt());
assertEquals(1, newCumulation.refCnt());
newCumulation.release();
}
}
@Test
public void releaseWhenCompositeCumulateThrows() {
final Error error = new Error();
ByteBuf cumulation = new CompositeByteBuf(UnpooledByteBufAllocator.DEFAULT, false, 64) {
@Override
public CompositeByteBuf addComponent(boolean increaseWriterIndex, ByteBuf buffer) {
throw error;
}
@Override
public CompositeByteBuf addFlattenedComponents(boolean increaseWriterIndex, ByteBuf buffer) {
throw error;
}
}.writeZero(1);
ByteBuf in = Unpooled.buffer().writeZero(12);
try {
ByteToMessageDecoder.COMPOSITE_CUMULATOR.cumulate(UnpooledByteBufAllocator.DEFAULT, cumulation, in);
fail();
} catch (Error expected) {
assertSame(error, expected);
assertEquals(0, in.refCnt());
cumulation.release();
}
}
private static final | WriteFailingByteBuf |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/context/AbstractInitializableBeanDefinition.java | {
"start": 116158,
"end": 116299
} | class ____ annotation injection information.
*/
@Internal
@SuppressWarnings("VisibilityModifier")
public static final | containing |
java | alibaba__nacos | common/src/main/java/com/alibaba/nacos/common/cache/decorators/SynchronizedCache.java | {
"start": 840,
"end": 1704
} | class ____<K, V> implements Cache<K, V> {
private final Cache<K, V> delegate;
public SynchronizedCache(Cache<K, V> delegate) {
this.delegate = delegate;
}
@Override
public synchronized void put(K key, V val) {
this.delegate.put(key, val);
}
@Override
public synchronized V get(K key) {
return this.delegate.get(key);
}
@Override
public V get(K key, Callable<? extends V> call) throws Exception {
return this.delegate.get(key, call);
}
@Override
public synchronized V remove(K key) {
return this.delegate.remove(key);
}
@Override
public synchronized void clear() {
this.delegate.clear();
}
@Override
public synchronized int getSize() {
return this.delegate.getSize();
}
}
| SynchronizedCache |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/inference/action/GetCCMConfigurationAction.java | {
"start": 585,
"end": 928
} | class ____ extends ActionType<CCMEnabledActionResponse> {
public static final GetCCMConfigurationAction INSTANCE = new GetCCMConfigurationAction();
public static final String NAME = "cluster:monitor/xpack/inference/ccm/get";
public GetCCMConfigurationAction() {
super(NAME);
}
public static | GetCCMConfigurationAction |
java | redisson__redisson | redisson/src/test/java/org/redisson/spring/cache/RedissonSpringCacheTest.java | {
"start": 2002,
"end": 3058
} | class ____ {
@Cacheable(cacheNames = "monoCache", sync = true)
public Mono<String> readMono() {
return Mono.delay(Duration.ofSeconds(1))
.map(i -> "Hello world")
.log();
}
@CachePut(cacheNames = "testMap", key = "#p0")
public SampleObject store(String key, SampleObject object) {
return object;
}
@CachePut(cacheNames = "testMap", key = "#p0")
public SampleObject storeNull(String key) {
return null;
}
@CacheEvict(cacheNames = "testMap", key = "#p0")
public void remove(String key) {
}
@Cacheable(cacheNames = "testMap", key = "#p0")
public SampleObject read(String key) {
throw new IllegalStateException();
}
@Cacheable(cacheNames = "testMap", key = "#p0")
public SampleObject readNull(String key) {
return null;
}
}
@Configuration
@ComponentScan
@EnableCaching
public static | SampleBean |
java | eclipse-vertx__vert.x | vertx-core/src/test/java/io/vertx/tests/timer/TimerTest.java | {
"start": 2439,
"end": 3292
} | class ____ extends AbstractVerticle {
AtomicInteger cnt = new AtomicInteger();
@Override
public void start() {
Thread thr = Thread.currentThread();
vertx.setTimer(1, id -> {
assertSame(thr, Thread.currentThread());
if (cnt.incrementAndGet() == 5) {
testComplete();
}
});
vertx.setPeriodic(2, id -> {
assertSame(thr, Thread.currentThread());
if (cnt.incrementAndGet() == 5) {
testComplete();
}
});
vertx.setPeriodic(3, 4, id -> {
assertSame(thr, Thread.currentThread());
if (cnt.incrementAndGet() == 5) {
testComplete();
}
});
}
}
MyVerticle verticle = new MyVerticle();
vertx.deployVerticle(verticle);
await();
}
static | MyVerticle |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/config/remote/request/ConfigQueryRequest.java | {
"start": 878,
"end": 1977
} | class ____ extends AbstractConfigRequest {
private String tag;
/**
* request builder.
*
* @param dataId dataId
* @param group group
* @param tenant tenant
* @return ConfigQueryRequest instance.
*/
public static ConfigQueryRequest build(String dataId, String group, String tenant) {
ConfigQueryRequest request = new ConfigQueryRequest();
request.setDataId(dataId);
request.setGroup(group);
request.setTenant(tenant);
return request;
}
/**
* Getter method for property <tt>tag</tt>.
*
* @return property value of tag
*/
public String getTag() {
return tag;
}
/**
* Setter method for property <tt>tag</tt>.
*
* @param tag value to be assigned to property tag
*/
public void setTag(String tag) {
this.tag = tag;
}
public boolean isNotify() {
String notify = getHeader(Constants.Config.NOTIFY_HEADER, Boolean.FALSE.toString());
return Boolean.parseBoolean(notify);
}
}
| ConfigQueryRequest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/fieldsel/FieldSelectionReducer.java | {
"start": 1278,
"end": 2592
} | class ____ can be used to perform field
* selections in a manner similar to unix cut.
*
* The input data is treated as fields separated by a user specified
* separator (the default value is "\t"). The user can specify a list of
* fields that form the reduce output keys, and a list of fields that form
* the reduce output values. The fields are the union of those from the key
* and those from the value.
*
* The field separator is under attribute "mapreduce.fieldsel.data.field.separator"
*
* The reduce output field list spec is under attribute
* "mapreduce.fieldsel.reduce.output.key.value.fields.spec".
* The value is expected to be like
* "keyFieldsSpec:valueFieldsSpec" key/valueFieldsSpec are comma (,)
* separated field spec: fieldSpec,fieldSpec,fieldSpec ... Each field spec
* can be a simple number (e.g. 5) specifying a specific field, or a range
* (like 2-5) to specify a range of fields, or an open range (like 3-)
* specifying all the fields starting from field 3. The open range field
* spec applies value fields only. They have no effect on the key fields.
*
* Here is an example: "4,3,0,1:6,5,1-3,7-". It specifies to use fields
* 4,3,0 and 1 for keys, and use fields 6,5,1,2,3,7 and above for values.
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public | that |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/metrics/OutlierDetector.java | {
"start": 1392,
"end": 2206
} | class ____ help detect resources (nodes/ disks) whose aggregate
* latency is an outlier within a given set.
*
* We use the median absolute deviation for outlier detection as
* described in the following publication:
*
* Leys, C., et al., Detecting outliers: Do not use standard deviation
* around the mean, use absolute deviation around the median.
* http://dx.doi.org/10.1016/j.jesp.2013.03.013
*
* We augment the above scheme with the following heuristics to be even
* more conservative:
*
* 1. Skip outlier detection if the sample size is too small.
* 2. Never flag resources whose aggregate latency is below a low threshold.
* 3. Never flag resources whose aggregate latency is less than a small
* multiple of the median.
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public | to |
java | google__dagger | javatests/dagger/internal/codegen/DelegateRequestRepresentationTest.java | {
"start": 3310,
"end": 3696
} | interface ____ {",
" Class<?> value();",
"}");
@Test
public void toDoubleCheck() throws Exception {
Source module =
CompilerTests.javaSource(
"test.TestModule",
"package test;",
"",
"import dagger.Binds;",
"import dagger.Module;",
"",
"@Module",
" | Qualifier |
java | apache__camel | test-infra/camel-test-infra-aws-v2/src/main/java/org/apache/camel/test/infra/aws2/services/AWSContainer.java | {
"start": 1655,
"end": 3851
} | class ____ extends GenericContainer<AWSContainer> {
private static final Logger LOG = LoggerFactory.getLogger(AWSLocalContainerInfraService.class);
private static final int SERVICE_PORT = 4566;
public AWSContainer() {
this(LocalPropertyResolver.getProperty(
AWSContainer.class,
AWSProperties.AWS_CONTAINER));
}
public AWSContainer(String imageName) {
super(imageName);
}
public AWSContainer(String imageName, boolean fixedPort, Service... services) {
super(imageName);
setupServices(services);
setupContainer(fixedPort);
}
@Deprecated
protected AWSContainer(String imageName, String serviceList) {
super(imageName);
setupServices(serviceList);
setupContainer(false);
}
public void setupServices(Service... services) {
String serviceList = Arrays.stream(services)
.map(Service::serviceName)
.collect(Collectors.joining(","));
setupServices(serviceList);
}
public void setupServices(String serviceList) {
LOG.debug("Creating services {}", serviceList);
withEnv("SERVICE", serviceList);
}
protected void setupContainer(boolean fixedPort) {
if (fixedPort) {
addFixedExposedPort(SERVICE_PORT, SERVICE_PORT);
} else {
withExposedPorts(SERVICE_PORT);
}
waitingFor(Wait.forLogMessage(".*Ready\\.\n", 1));
}
public AwsCredentialsProvider getCredentialsProvider() {
return TestAWSCredentialsProvider.CONTAINER_LOCAL_DEFAULT_PROVIDER;
}
protected String getAmazonHost() {
return getHost() + ":" + getMappedPort(SERVICE_PORT);
}
public URI getServiceEndpoint() {
try {
String address = String.format("http://%s:%d", getHost(), getMappedPort(SERVICE_PORT));
LOG.debug("Running on service endpoint: {}", address);
return new URI(address);
} catch (URISyntaxException e) {
throw new RuntimeException(String.format("Unable to determine the service endpoint: %s", e.getMessage()), e);
}
}
}
| AWSContainer |
java | apache__maven | impl/maven-core/src/main/java/org/apache/maven/plugin/PluginDescriptorParsingException.java | {
"start": 896,
"end": 1601
} | class ____ extends Exception {
public PluginDescriptorParsingException(Plugin plugin, String descriptorLocation, Throwable e) {
super(createMessage(plugin, descriptorLocation, e), e);
}
private static String createMessage(Plugin plugin, String descriptorLocation, Throwable e) {
String message = "Failed to parse plugin descriptor";
if (plugin != null) {
message += " for " + plugin.getId();
}
if (descriptorLocation != null) {
message += " (" + descriptorLocation + ")";
}
if (e != null) {
message += ": " + e.getMessage();
}
return message;
}
}
| PluginDescriptorParsingException |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateMultipleSourceTest.java | {
"start": 2502,
"end": 2999
} | class ____ implements AggregationStrategy {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
String body = oldExchange.getIn().getBody(String.class);
String newBody = newExchange.getIn().getBody(String.class);
oldExchange.getIn().setBody(body + newBody);
return oldExchange;
}
}
}
| MyAggregationStrategy |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/support/metrics/MetricCollector.java | {
"start": 667,
"end": 744
} | class ____ {
public void collect() throws Exception {
}
}
| MetricCollector |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/convert/Log.java | {
"start": 637,
"end": 1087
} | class ____ implements AttributeConverter<Date, Long> {
@Override
public Long convertToDatabaseColumn(Date date) {
if (null == date) {
return null;
}
return date.getTime();
}
@Override
public Date convertToEntityAttribute(Long dbDate) {
if (null == dbDate) {
return null;
}
return new Date( dbDate );
}
}
public Long getId() {
return id;
}
public Date getLastUpdate() {
return lastUpdate;
}
}
| DateConverter |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/SqlColumn.java | {
"start": 952,
"end": 2027
} | class ____ extends AbstractSqmSelfRenderingFunctionDescriptor {
private final String columnName;
public SqlColumn(String columnName, BasicType<?> type) {
super(
"column",
StandardArgumentsValidators.min( 1 ),
StandardFunctionReturnTypeResolvers.invariant( type == null ? JavaObjectType.INSTANCE : type ),
null
);
this.columnName = columnName;
}
@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> arguments,
ReturnableType<?> returnType,
SqlAstTranslator<?> walker) {
final SqlAstNode sqlAstNode = arguments.get(0);
final ColumnReference reference;
if ( sqlAstNode instanceof Assignable assignable ) {
reference = assignable.getColumnReferences().get(0);
}
else if ( sqlAstNode instanceof Expression expression ) {
reference = expression.getColumnReference();
}
else {
throw new HqlInterpretationException( "path did not map to a column" );
}
sqlAppender.appendSql( reference.getQualifier() );
sqlAppender.appendSql( '.' );
sqlAppender.appendSql( columnName );
}
}
| SqlColumn |
java | elastic__elasticsearch | modules/lang-painless/src/main/java/org/elasticsearch/painless/antlr/PainlessParser.java | {
"start": 122629,
"end": 125132
} | class ____ extends ChainContext {
public ArrayinitializerContext arrayinitializer() {
return getRuleContext(ArrayinitializerContext.class, 0);
}
public NewarrayContext(ChainContext ctx) {
copyFrom(ctx);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if (visitor instanceof PainlessParserVisitor) return ((PainlessParserVisitor<? extends T>) visitor).visitNewarray(this);
else return visitor.visitChildren(this);
}
}
public final ChainContext chain() throws RecognitionException {
ChainContext _localctx = new ChainContext(_ctx, getState());
enterRule(_localctx, 46, RULE_chain);
try {
int _alt;
setState(394);
_errHandler.sync(this);
switch (getInterpreter().adaptivePredict(_input, 36, _ctx)) {
case 1:
_localctx = new DynamicContext(_localctx);
enterOuterAlt(_localctx, 1); {
setState(386);
primary();
setState(390);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input, 35, _ctx);
while (_alt != 2 && _alt != org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER) {
if (_alt == 1) {
{
{
setState(387);
postfix();
}
}
}
setState(392);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input, 35, _ctx);
}
}
break;
case 2:
_localctx = new NewarrayContext(_localctx);
enterOuterAlt(_localctx, 2); {
setState(393);
arrayinitializer();
}
break;
}
} catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
} finally {
exitRule();
}
return _localctx;
}
@SuppressWarnings("CheckReturnValue")
public static | NewarrayContext |
java | quarkusio__quarkus | extensions/hibernate-envers/runtime/src/main/java/io/quarkus/hibernate/envers/HibernateEnversBuildTimeConfigPersistenceUnit.java | {
"start": 4820,
"end": 7401
} | class ____ of the audit strategy to be used.
*
* Maps to {@link org.hibernate.envers.configuration.EnversSettings#AUDIT_STRATEGY}.
*/
@WithDefault("org.hibernate.envers.strategy.DefaultAuditStrategy")
Optional<String> auditStrategy();
/**
* Defines the property name for the audit entity's composite primary key. Defaults to {@literal originalId}.
* Maps to {@link org.hibernate.envers.configuration.EnversSettings#ORIGINAL_ID_PROP_NAME}.
*/
@WithDefault("originalId")
Optional<String> originalIdPropName();
/**
* Defines the column name that holds the end revision number in audit entities. Defaults to {@literal REVEND}.
* Maps to {@link org.hibernate.envers.configuration.EnversSettings#AUDIT_STRATEGY_VALIDITY_END_REV_FIELD_NAME}.
*/
@WithDefault("REVEND")
Optional<String> auditStrategyValidityEndRevFieldName();
/**
* Enables the audit_strategy_validity_store_revend_timestamp feature.
* Maps to {@link org.hibernate.envers.configuration.EnversSettings#AUDIT_STRATEGY_VALIDITY_STORE_REVEND_TIMESTAMP}.
*/
@WithDefault("false")
boolean auditStrategyValidityStoreRevendTimestamp();
/**
* Defines the column name of the revision end timestamp in the audit tables. Defaults to {@literal REVEND_TSTMP}.
* Maps to {@link org.hibernate.envers.configuration.EnversSettings#AUDIT_STRATEGY_VALIDITY_REVEND_TIMESTAMP_FIELD_NAME}.
*/
@WithDefault("REVEND_TSTMP")
Optional<String> auditStrategyValidityRevendTimestampFieldName();
/**
* Defines the name of the column used for storing collection ordinal values for embeddable elements.
* Defaults to {@literal SETORDINAL}.
* Maps to {@link org.hibernate.envers.configuration.EnversSettings#EMBEDDABLE_SET_ORDINAL_FIELD_NAME}.
*/
@WithDefault("SETORDINAL")
Optional<String> embeddableSetOrdinalFieldName();
/**
* Enables the allow_identifier_reuse feature.
* Maps to {@link org.hibernate.envers.configuration.EnversSettings#ALLOW_IDENTIFIER_REUSE}.
*/
@WithDefault("false")
boolean allowIdentifierReuse();
/**
* Defines the naming strategy to be used for modified columns.
* Defaults to {@literal org.hibernate.envers.boot.internal.LegacyModifiedColumnNamingStrategy}.
* Maps to {@link org.hibernate.envers.configuration.EnversSettings#MODIFIED_COLUMN_NAMING_STRATEGY}.
*/
@WithDefault("org.hibernate.envers.boot.internal.LegacyModifiedColumnNamingStrategy")
Optional<String> modifiedColumnNamingStrategy();
}
| name |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/QueryHintJpaAnnotation.java | {
"start": 462,
"end": 1539
} | class ____ implements QueryHint {
private String name;
private String value;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public QueryHintJpaAnnotation(ModelsContext modelContext) {
}
/**
* Used in creating annotation instances from JDK variant
*/
public QueryHintJpaAnnotation(QueryHint annotation, ModelsContext modelContext) {
this.name = annotation.name();
this.value = annotation.value();
}
/**
* Used in creating annotation instances from Jandex variant
*/
public QueryHintJpaAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) {
this.name = (String) attributeValues.get( "name" );
this.value = (String) attributeValues.get( "value" );
}
@Override
public Class<? extends Annotation> annotationType() {
return QueryHint.class;
}
@Override
public String name() {
return name;
}
public void name(String value) {
this.name = value;
}
@Override
public String value() {
return value;
}
public void value(String value) {
this.value = value;
}
}
| QueryHintJpaAnnotation |
java | apache__camel | components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/integration/EventHubsConsumerIT.java | {
"start": 2561,
"end": 6548
} | class ____ extends CamelTestSupport {
@EndpointInject("mock:result")
private MockEndpoint result;
private String containerName;
private BlobContainerAsyncClient containerAsyncClient;
private EventHubsConfiguration configuration;
@BeforeAll
public void prepare() throws Exception {
containerName = RandomStringUtils.randomAlphabetic(5).toLowerCase();
final Properties properties = TestUtils.loadAzureAccessFromJvmEnv();
configuration = new EventHubsConfiguration();
configuration.setBlobAccessKey(properties.getProperty(TestUtils.BLOB_ACCESS_KEY));
configuration.setBlobAccountName(properties.getProperty(TestUtils.BLOB_ACCOUNT_NAME));
configuration.setBlobContainerName(containerName);
configuration.setConnectionString(properties.getProperty(TestUtils.CONNECTION_STRING));
containerAsyncClient = EventHubsClientFactory.createBlobContainerClient(configuration);
// create test container
containerAsyncClient.create().block();
}
@Test
public void testConsumerEvents() throws InterruptedException {
// send test data
final EventHubProducerAsyncClient producerAsyncClient
= EventHubsClientFactory.createEventHubProducerAsyncClient(configuration);
final String messageBody = RandomStringUtils.randomAlphabetic(30);
final String messageKey = RandomStringUtils.randomAlphabetic(5);
producerAsyncClient
.send(Collections.singletonList(new EventData(messageBody)), new SendOptions().setPartitionKey(messageKey))
.block();
result.expectedMinimumMessageCount(1);
result.setAssertPeriod(20000);
final List<Exchange> exchanges = result.getExchanges();
result.assertIsSatisfied();
// now we check our messages
final Exchange returnedMessage = exchanges.stream()
.filter(Objects::nonNull)
.filter(exchange -> exchange.getMessage().getHeader(EventHubsConstants.PARTITION_KEY)
!= null
&& exchange.getMessage().getHeader(EventHubsConstants.PARTITION_KEY).equals(messageKey))
.findFirst()
.orElse(null);
assertNotNull(returnedMessage);
assertEquals(messageKey, returnedMessage.getMessage().getHeader(EventHubsConstants.PARTITION_KEY));
assertNotNull(returnedMessage.getMessage().getBody());
assertNotNull(returnedMessage.getMessage().getHeader(EventHubsConstants.PARTITION_ID));
assertNotNull(returnedMessage.getMessage().getHeader(EventHubsConstants.SEQUENCE_NUMBER));
assertNotNull(returnedMessage.getMessage().getHeader(EventHubsConstants.OFFSET));
assertNotNull(returnedMessage.getMessage().getHeader(EventHubsConstants.ENQUEUED_TIME));
}
@AfterAll
public void cleanup() {
// delete testing container
containerAsyncClient.delete().block();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("azure-eventhubs:?"
+ "connectionString=RAW({{connectionString}})"
+ "&blobContainerName=" + containerName + "&eventPosition=#eventPosition"
+ "&blobAccountName={{blobAccountName}}&blobAccessKey=RAW({{blobAccessKey}})")
.to(result);
}
};
}
@Override
protected CamelContext createCamelContext() throws Exception {
final Map<String, EventPosition> positionMap = new HashMap<>();
positionMap.put("0", EventPosition.earliest());
positionMap.put("1", EventPosition.earliest());
CamelContext context = super.createCamelContext();
context.getRegistry().bind("eventPosition", positionMap);
return context;
}
}
| EventHubsConsumerIT |
java | apache__camel | components/camel-crypto-pgp/src/main/java/org/apache/camel/converter/crypto/PGPPublicKeyAccessor.java | {
"start": 959,
"end": 2235
} | interface ____ {
/**
* Returns the encryption keys for the given user ID parts. This method is used for encryption.
*
* @param exchange exchange, can be <code>null</code>
* @param useridParts parts of User IDs, must not be <code>null</code>
* @return list of public keys, must not be <code>null</code>
*/
List<PGPPublicKey> getEncryptionKeys(Exchange exchange, List<String> useridParts) throws Exception;
/**
* Returns the public key with a certain key ID. This method is used for verifying the signature. The given User IDs
* are provided to filter the public key, further. If the User ID parts list is empty, then any public key can be
* returned which has the specified key ID. If the User ID parts list is not empty then the returned key must have a
* User ID which contains at least one User ID part.
*
* @param exchange exchange
* @param keyId key ID
* @param useridParts parts of User IDs, must not be <code>null</code>, but can be empty
* @return public key or <code>null</code> if the key cannot be found
*/
PGPPublicKey getPublicKey(Exchange exchange, long keyId, List<String> useridParts) throws Exception;
}
| PGPPublicKeyAccessor |
java | micronaut-projects__micronaut-core | retry/src/main/java/io/micronaut/retry/exception/RetryException.java | {
"start": 773,
"end": 1985
} | class ____ extends RuntimeException {
/**
* Constructs a new Retry exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public RetryException(String message) {
super(message);
}
/**
* Constructs a new Retry exception with the specified detail message and
* cause. <p>Note that the detail message associated with
* {@code cause} is <i>not</i> automatically incorporated in
* this exception's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public RetryException(String message, Throwable cause) {
super(message, cause);
}
}
| RetryException |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationToken.java | {
"start": 1407,
"end": 4447
} | class ____ extends AbstractAuthenticationToken {
@Serial
private static final long serialVersionUID = 9003173975452760956L;
private final String token;
private final Authentication clientPrincipal;
private final String tokenTypeHint;
private final Map<String, Object> additionalParameters;
private final OAuth2TokenIntrospection tokenClaims;
/**
* Constructs an {@code OAuth2TokenIntrospectionAuthenticationToken} using the
* provided parameters.
* @param token the token
* @param clientPrincipal the authenticated client principal
* @param tokenTypeHint the token type hint
* @param additionalParameters the additional parameters
*/
public OAuth2TokenIntrospectionAuthenticationToken(String token, Authentication clientPrincipal,
@Nullable String tokenTypeHint, @Nullable Map<String, Object> additionalParameters) {
super(Collections.emptyList());
Assert.hasText(token, "token cannot be empty");
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
this.token = token;
this.clientPrincipal = clientPrincipal;
this.tokenTypeHint = tokenTypeHint;
this.additionalParameters = Collections.unmodifiableMap(
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
this.tokenClaims = OAuth2TokenIntrospection.builder().build();
}
/**
* Constructs an {@code OAuth2TokenIntrospectionAuthenticationToken} using the
* provided parameters.
* @param token the token
* @param clientPrincipal the authenticated client principal
* @param tokenClaims the token claims
*/
public OAuth2TokenIntrospectionAuthenticationToken(String token, Authentication clientPrincipal,
OAuth2TokenIntrospection tokenClaims) {
super(Collections.emptyList());
Assert.hasText(token, "token cannot be empty");
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
Assert.notNull(tokenClaims, "tokenClaims cannot be null");
this.token = token;
this.clientPrincipal = clientPrincipal;
this.tokenTypeHint = null;
this.additionalParameters = Collections.emptyMap();
this.tokenClaims = tokenClaims;
// Indicates that the request was authenticated, even though the token might not
// be active
setAuthenticated(true);
}
@Override
public Object getPrincipal() {
return this.clientPrincipal;
}
@Override
public Object getCredentials() {
return "";
}
/**
* Returns the token.
* @return the token
*/
public String getToken() {
return this.token;
}
/**
* Returns the token type hint.
* @return the token type hint
*/
@Nullable
public String getTokenTypeHint() {
return this.tokenTypeHint;
}
/**
* Returns the additional parameters.
* @return the additional parameters
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
/**
* Returns the token claims.
* @return the {@link OAuth2TokenIntrospection}
*/
public OAuth2TokenIntrospection getTokenClaims() {
return this.tokenClaims;
}
}
| OAuth2TokenIntrospectionAuthenticationToken |
java | apache__camel | core/camel-main/src/generated/java/org/apache/camel/main/RouteControllerConfigurationPropertiesConfigurer.java | {
"start": 716,
"end": 6700
} | class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter {
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
map.put("BackOffDelay", long.class);
map.put("BackOffMaxAttempts", long.class);
map.put("BackOffMaxDelay", long.class);
map.put("BackOffMaxElapsedTime", long.class);
map.put("BackOffMultiplier", double.class);
map.put("Enabled", boolean.class);
map.put("ExcludeRoutes", java.lang.String.class);
map.put("IncludeRoutes", java.lang.String.class);
map.put("InitialDelay", long.class);
map.put("ThreadPoolSize", int.class);
map.put("UnhealthyOnExhausted", boolean.class);
map.put("UnhealthyOnRestarting", boolean.class);
ALL_OPTIONS = map;
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.main.RouteControllerConfigurationProperties target = (org.apache.camel.main.RouteControllerConfigurationProperties) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "backoffdelay":
case "backOffDelay": target.setBackOffDelay(property(camelContext, long.class, value)); return true;
case "backoffmaxattempts":
case "backOffMaxAttempts": target.setBackOffMaxAttempts(property(camelContext, long.class, value)); return true;
case "backoffmaxdelay":
case "backOffMaxDelay": target.setBackOffMaxDelay(property(camelContext, long.class, value)); return true;
case "backoffmaxelapsedtime":
case "backOffMaxElapsedTime": target.setBackOffMaxElapsedTime(property(camelContext, long.class, value)); return true;
case "backoffmultiplier":
case "backOffMultiplier": target.setBackOffMultiplier(property(camelContext, double.class, value)); return true;
case "enabled": target.setEnabled(property(camelContext, boolean.class, value)); return true;
case "excluderoutes":
case "excludeRoutes": target.setExcludeRoutes(property(camelContext, java.lang.String.class, value)); return true;
case "includeroutes":
case "includeRoutes": target.setIncludeRoutes(property(camelContext, java.lang.String.class, value)); return true;
case "initialdelay":
case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true;
case "threadpoolsize":
case "threadPoolSize": target.setThreadPoolSize(property(camelContext, int.class, value)); return true;
case "unhealthyonexhausted":
case "unhealthyOnExhausted": target.setUnhealthyOnExhausted(property(camelContext, boolean.class, value)); return true;
case "unhealthyonrestarting":
case "unhealthyOnRestarting": target.setUnhealthyOnRestarting(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Map<String, Object> getAllOptions(Object target) {
return ALL_OPTIONS;
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "backoffdelay":
case "backOffDelay": return long.class;
case "backoffmaxattempts":
case "backOffMaxAttempts": return long.class;
case "backoffmaxdelay":
case "backOffMaxDelay": return long.class;
case "backoffmaxelapsedtime":
case "backOffMaxElapsedTime": return long.class;
case "backoffmultiplier":
case "backOffMultiplier": return double.class;
case "enabled": return boolean.class;
case "excluderoutes":
case "excludeRoutes": return java.lang.String.class;
case "includeroutes":
case "includeRoutes": return java.lang.String.class;
case "initialdelay":
case "initialDelay": return long.class;
case "threadpoolsize":
case "threadPoolSize": return int.class;
case "unhealthyonexhausted":
case "unhealthyOnExhausted": return boolean.class;
case "unhealthyonrestarting":
case "unhealthyOnRestarting": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.main.RouteControllerConfigurationProperties target = (org.apache.camel.main.RouteControllerConfigurationProperties) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "backoffdelay":
case "backOffDelay": return target.getBackOffDelay();
case "backoffmaxattempts":
case "backOffMaxAttempts": return target.getBackOffMaxAttempts();
case "backoffmaxdelay":
case "backOffMaxDelay": return target.getBackOffMaxDelay();
case "backoffmaxelapsedtime":
case "backOffMaxElapsedTime": return target.getBackOffMaxElapsedTime();
case "backoffmultiplier":
case "backOffMultiplier": return target.getBackOffMultiplier();
case "enabled": return target.isEnabled();
case "excluderoutes":
case "excludeRoutes": return target.getExcludeRoutes();
case "includeroutes":
case "includeRoutes": return target.getIncludeRoutes();
case "initialdelay":
case "initialDelay": return target.getInitialDelay();
case "threadpoolsize":
case "threadPoolSize": return target.getThreadPoolSize();
case "unhealthyonexhausted":
case "unhealthyOnExhausted": return target.isUnhealthyOnExhausted();
case "unhealthyonrestarting":
case "unhealthyOnRestarting": return target.isUnhealthyOnRestarting();
default: return null;
}
}
}
| RouteControllerConfigurationPropertiesConfigurer |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/search/CountedCollector.java | {
"start": 983,
"end": 2480
} | class ____<R extends SearchPhaseResult> {
private final SearchPhaseResults<R> resultConsumer;
private final CountDown counter;
private final Runnable onFinish;
private final AbstractSearchAsyncAction<?> context;
CountedCollector(SearchPhaseResults<R> resultConsumer, int expectedOps, Runnable onFinish, AbstractSearchAsyncAction<?> context) {
this.resultConsumer = resultConsumer;
this.counter = new CountDown(expectedOps);
this.onFinish = onFinish;
this.context = context;
}
/**
* Forcefully counts down an operation and executes the provided runnable
* if all expected operations where executed
*/
void countDown() {
assert counter.isCountedDown() == false : "more operations executed than specified";
if (counter.countDown()) {
onFinish.run();
}
}
/**
* Sets the result to the given array index and then runs {@link #countDown()}
*/
void onResult(R result) {
resultConsumer.consumeResult(result, this::countDown);
}
/**
* Escalates the failure via {@link AbstractSearchAsyncAction#onShardFailure(int, SearchShardTarget, Exception)}
* and then runs {@link #countDown()}
*/
void onFailure(final int shardIndex, @Nullable SearchShardTarget shardTarget, Exception e) {
try {
context.onShardFailure(shardIndex, shardTarget, e);
} finally {
countDown();
}
}
}
| CountedCollector |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/aot/AotQuery.java | {
"start": 1025,
"end": 2631
} | class ____ {
private final List<ParameterBinding> parameterBindings;
AotQuery(List<ParameterBinding> parameterBindings) {
this.parameterBindings = parameterBindings;
}
static boolean hasConstructorExpressionOrDefaultProjection(EntityQuery query) {
return query.hasConstructorExpression() || query.isDefaultProjection();
}
/**
* @return whether the query is a {@link jakarta.persistence.EntityManager#createNativeQuery native} one.
*/
public abstract boolean isNative();
/**
* @return the list of parameter bindings.
*/
public List<ParameterBinding> getParameterBindings() {
return parameterBindings;
}
/**
* @return the preliminary query limit.
*/
public Limit getLimit() {
return Limit.unlimited();
}
/**
* @return whether the query is limited (e.g. {@code findTop10By}).
*/
public boolean isLimited() {
return getLimit().isLimited();
}
/**
* @return whether the query is derived.
* @since 4.0.1
*/
public boolean isDerived() {
return false;
}
/**
* @return whether the query a delete query.
*/
public boolean isDelete() {
return false;
}
/**
* @return whether the query is an exists query.
*/
public boolean isExists() {
return false;
}
/**
* @return {@literal true} if query is expected to return the declared method type directly; {@literal false} if the
* result requires projection post-processing. See also {@code NativeJpaQuery#getTypeToQueryFor}.
*/
public abstract boolean hasConstructorExpressionOrDefaultProjection();
/**
* Extension to describe a named query.
*
* @since 4.0.1
*/
| AotQuery |
java | resilience4j__resilience4j | resilience4j-micrometer/src/test/java/io/github/resilience4j/micrometer/tagged/TaggedBulkheadMetricsPublisherTest.java | {
"start": 1548,
"end": 8242
} | class ____ {
private MeterRegistry meterRegistry;
private Bulkhead bulkhead;
private BulkheadRegistry bulkheadRegistry;
private TaggedBulkheadMetricsPublisher taggedBulkheadMetricsPublisher;
@Before
public void setUp() {
meterRegistry = new SimpleMeterRegistry();
taggedBulkheadMetricsPublisher = new TaggedBulkheadMetricsPublisher(meterRegistry);
bulkheadRegistry = BulkheadRegistry
.of(BulkheadConfig.ofDefaults(), taggedBulkheadMetricsPublisher);
bulkhead = bulkheadRegistry.bulkhead("backendA");
// record some basic stats
bulkhead.tryAcquirePermission();
bulkhead.tryAcquirePermission();
}
@Test
public void shouldAddMetricsForANewlyCreatedRetry() {
Bulkhead newBulkhead = bulkheadRegistry.bulkhead("backendB");
assertThat(taggedBulkheadMetricsPublisher.meterIdMap).containsKeys("backendA", "backendB");
assertThat(taggedBulkheadMetricsPublisher.meterIdMap.get("backendA")).hasSize(2);
assertThat(taggedBulkheadMetricsPublisher.meterIdMap.get("backendB")).hasSize(2);
List<Meter> meters = meterRegistry.getMeters();
assertThat(meters).hasSize(4);
Collection<Gauge> gauges = meterRegistry
.get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges();
Optional<Gauge> successful = findMeterByNamesTag(gauges, newBulkhead.getName());
assertThat(successful).isPresent();
assertThat(successful.get().value())
.isEqualTo(newBulkhead.getMetrics().getMaxAllowedConcurrentCalls());
}
@Test
public void shouldRemovedMetricsForRemovedRetry() {
List<Meter> meters = meterRegistry.getMeters();
assertThat(meters).hasSize(2);
assertThat(taggedBulkheadMetricsPublisher.meterIdMap).containsKeys("backendA");
bulkheadRegistry.remove("backendA");
assertThat(taggedBulkheadMetricsPublisher.meterIdMap).isEmpty();
meters = meterRegistry.getMeters();
assertThat(meters).isEmpty();
}
@Test
public void shouldReplaceMetrics() {
Collection<Gauge> gauges = meterRegistry
.get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges();
Optional<Gauge> successful = findMeterByNamesTag(gauges, bulkhead.getName());
assertThat(successful).isPresent();
assertThat(successful.get().value())
.isEqualTo(bulkhead.getMetrics().getMaxAllowedConcurrentCalls());
Bulkhead newBulkhead = Bulkhead.of(bulkhead.getName(), BulkheadConfig.custom()
.maxConcurrentCalls(100).build());
bulkheadRegistry.replace(bulkhead.getName(), newBulkhead);
gauges = meterRegistry.get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME)
.gauges();
successful = findMeterByNamesTag(gauges, newBulkhead.getName());
assertThat(successful).isPresent();
assertThat(successful.get().value())
.isEqualTo(newBulkhead.getMetrics().getMaxAllowedConcurrentCalls());
}
@Test
public void availableConcurrentCallsGaugeIsRegistered() {
Gauge available = meterRegistry.get(DEFAULT_BULKHEAD_AVAILABLE_CONCURRENT_CALLS_METRIC_NAME)
.gauge();
assertThat(available).isNotNull();
assertThat(available.value())
.isEqualTo(bulkhead.getMetrics().getAvailableConcurrentCalls());
}
@Test
public void maxAllowedConcurrentCallsGaugeIsRegistered() {
Gauge maxAllowed = meterRegistry
.get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauge();
assertThat(maxAllowed).isNotNull();
assertThat(maxAllowed.value())
.isEqualTo(bulkhead.getMetrics().getMaxAllowedConcurrentCalls());
assertThat(maxAllowed.getId().getTag(TagNames.NAME)).isEqualTo(bulkhead.getName());
}
@Test
public void customMetricNamesGetApplied() {
MeterRegistry meterRegistry = new SimpleMeterRegistry();
TaggedBulkheadMetricsPublisher taggedBulkheadMetricsPublisher = new TaggedBulkheadMetricsPublisher(
BulkheadMetricNames.custom()
.availableConcurrentCallsMetricName("custom_available_calls")
.maxAllowedConcurrentCallsMetricName("custom_max_allowed_calls")
.build(), meterRegistry);
BulkheadRegistry bulkheadRegistry = BulkheadRegistry
.of(BulkheadConfig.ofDefaults(), taggedBulkheadMetricsPublisher);
bulkhead = bulkheadRegistry.bulkhead("backendA");
Set<String> metricNames = meterRegistry.getMeters()
.stream()
.map(Meter::getId)
.map(Meter.Id::getName)
.collect(Collectors.toSet());
assertThat(metricNames).hasSameElementsAs(Arrays.asList(
"custom_available_calls",
"custom_max_allowed_calls"
));
}
@Test
public void testReplaceNewMeter(){
Bulkhead oldOne = Bulkhead.of("backendC", BulkheadConfig.ofDefaults());
// add meters of old
taggedBulkheadMetricsPublisher.addMetrics(meterRegistry, oldOne);
// one success call
oldOne.tryAcquirePermission();
assertThat(taggedBulkheadMetricsPublisher.meterIdMap).containsKeys("backendC");
assertThat(taggedBulkheadMetricsPublisher.meterIdMap.get("backendC")).hasSize(2);
Collection<Gauge> gauges = meterRegistry
.get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges();
Optional<Gauge> successful = findMeterByNamesTag(gauges, oldOne.getName());
assertThat(successful).isPresent();
assertThat(successful.get().value())
.isEqualTo(oldOne.getMetrics().getMaxAllowedConcurrentCalls());
Bulkhead newOne = Bulkhead.of("backendC", BulkheadConfig.ofDefaults());
// add meters of new
taggedBulkheadMetricsPublisher.addMetrics(meterRegistry, newOne);
// three success call
newOne.tryAcquirePermission();
newOne.tryAcquirePermission();
newOne.tryAcquirePermission();
assertThat(taggedBulkheadMetricsPublisher.meterIdMap).containsKeys("backendC");
assertThat(taggedBulkheadMetricsPublisher.meterIdMap.get("backendC")).hasSize(2);
gauges = meterRegistry
.get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges();
successful = findMeterByNamesTag(gauges, newOne.getName());
assertThat(successful).isPresent();
assertThat(successful.get().value())
.isEqualTo(newOne.getMetrics().getMaxAllowedConcurrentCalls());
}
} | TaggedBulkheadMetricsPublisherTest |
java | google__guice | extensions/dagger-adapter/test/com/google/inject/daggeradapter/IntoMapTest.java | {
"start": 3747,
"end": 3863
} | interface ____ {
int i();
long l();
String defaultValue() default "";
}
@dagger.Module
static | Wrapped |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/search/SearchTimeoutIT.java | {
"start": 17455,
"end": 23028
} | class ____ extends AbstractQueryBuilder<BulkScorerTimeoutQuery> {
private final boolean partialResults;
BulkScorerTimeoutQuery(boolean partialResults) {
this.partialResults = partialResults;
}
BulkScorerTimeoutQuery(StreamInput in) throws IOException {
super(in);
this.partialResults = in.readBoolean();
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
out.writeBoolean(partialResults);
}
@Override
protected void doXContent(XContentBuilder builder, Params params) {}
@Override
protected Query doToQuery(SearchExecutionContext context) {
return new Query() {
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) {
return new ConstantScoreWeight(this, boost) {
@Override
public boolean isCacheable(LeafReaderContext ctx) {
return false;
}
@Override
public ScorerSupplier scorerSupplier(LeafReaderContext context) {
return new ScorerSupplier() {
@Override
public BulkScorer bulkScorer() {
if (partialResults == false) {
((ContextIndexSearcher) searcher).throwTimeExceededException();
}
final int maxDoc = context.reader().maxDoc();
return new BulkScorer() {
@Override
public int score(LeafCollector collector, Bits acceptDocs, int min, int max) throws IOException {
max = Math.min(max, maxDoc);
collector.setScorer(new Scorable() {
@Override
public float score() {
return 1f;
}
});
for (int doc = min; doc < max; ++doc) {
if (acceptDocs == null || acceptDocs.get(doc)) {
collector.collect(doc);
// collect one doc per segment, only then throw a timeout: this ensures partial
// results are returned
((ContextIndexSearcher) searcher).throwTimeExceededException();
}
}
// there is a slight chance that no docs are scored for a specific segment.
// other shards / slices will throw the timeout anyway, one is enough.
return max == maxDoc ? DocIdSetIterator.NO_MORE_DOCS : max;
}
@Override
public long cost() {
return maxDoc;
}
};
}
@Override
public Scorer get(long leadCost) {
assert false;
return new ConstantScoreScorer(score(), scoreMode, DocIdSetIterator.all(context.reader().maxDoc()));
}
@Override
public long cost() {
assert false;
return context.reader().maxDoc();
}
};
}
};
}
@Override
public String toString(String field) {
return "timeout query";
}
@Override
public void visit(QueryVisitor visitor) {
visitor.visitLeaf(this);
}
@Override
public boolean equals(Object obj) {
return sameClassAs(obj);
}
@Override
public int hashCode() {
return classHash();
}
};
}
@Override
protected boolean doEquals(BulkScorerTimeoutQuery other) {
return false;
}
@Override
protected int doHashCode() {
return 0;
}
@Override
public String getWriteableName() {
return "timeout";
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return null;
}
}
/**
* Suggestion builder that triggers a timeout as part of its execution
*/
private static final | BulkScorerTimeoutQuery |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/dataframe/process/AnalyticsProcessManager.java | {
"start": 2502,
"end": 18283
} | class ____ {
private static final Logger LOGGER = LogManager.getLogger(AnalyticsProcessManager.class);
private final Settings settings;
private final Client client;
private final ExecutorService executorServiceForJob;
private final ExecutorService executorServiceForProcess;
private final AnalyticsProcessFactory<AnalyticsResult> processFactory;
private final ConcurrentMap<Long, ProcessContext> processContextByAllocation = new ConcurrentHashMap<>();
private final DataFrameAnalyticsAuditor auditor;
private final TrainedModelProvider trainedModelProvider;
private final ResultsPersisterService resultsPersisterService;
private final int numAllocatedProcessors;
public AnalyticsProcessManager(
Settings settings,
Client client,
ThreadPool threadPool,
AnalyticsProcessFactory<AnalyticsResult> analyticsProcessFactory,
DataFrameAnalyticsAuditor auditor,
TrainedModelProvider trainedModelProvider,
ResultsPersisterService resultsPersisterService,
int numAllocatedProcessors
) {
this(
settings,
client,
threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME),
threadPool.executor(MachineLearning.JOB_COMMS_THREAD_POOL_NAME),
analyticsProcessFactory,
auditor,
trainedModelProvider,
resultsPersisterService,
numAllocatedProcessors
);
}
// Visible for testing
public AnalyticsProcessManager(
Settings settings,
Client client,
ExecutorService executorServiceForJob,
ExecutorService executorServiceForProcess,
AnalyticsProcessFactory<AnalyticsResult> analyticsProcessFactory,
DataFrameAnalyticsAuditor auditor,
TrainedModelProvider trainedModelProvider,
ResultsPersisterService resultsPersisterService,
int numAllocatedProcessors
) {
this.settings = Objects.requireNonNull(settings);
this.client = Objects.requireNonNull(client);
this.executorServiceForJob = Objects.requireNonNull(executorServiceForJob);
this.executorServiceForProcess = Objects.requireNonNull(executorServiceForProcess);
this.processFactory = Objects.requireNonNull(analyticsProcessFactory);
this.auditor = Objects.requireNonNull(auditor);
this.trainedModelProvider = Objects.requireNonNull(trainedModelProvider);
this.resultsPersisterService = Objects.requireNonNull(resultsPersisterService);
this.numAllocatedProcessors = numAllocatedProcessors;
}
public void runJob(
DataFrameAnalyticsTask task,
DataFrameAnalyticsConfig config,
DataFrameDataExtractorFactory dataExtractorFactory,
ActionListener<StepResponse> listener
) {
executorServiceForJob.execute(() -> {
ProcessContext processContext = new ProcessContext(config);
synchronized (processContextByAllocation) {
if (task.isStopping()) {
LOGGER.debug("[{}] task is stopping. Marking as complete before creating process context.", task.getParams().getId());
// The task was requested to stop before we created the process context
auditor.info(config.getId(), Messages.DATA_FRAME_ANALYTICS_AUDIT_FINISHED_ANALYSIS);
listener.onResponse(new StepResponse(true));
return;
}
if (processContextByAllocation.putIfAbsent(task.getAllocationId(), processContext) != null) {
listener.onFailure(
ExceptionsHelper.serverError("[" + config.getId() + "] Could not create process as one already exists")
);
return;
}
}
// Fetch existing model state (if any)
final boolean hasState = hasModelState(config);
boolean isProcessStarted;
try {
isProcessStarted = processContext.startProcess(dataExtractorFactory, task, hasState);
} catch (Exception e) {
processContext.stop();
processContextByAllocation.remove(task.getAllocationId());
listener.onFailure(
processContext.getFailureReason() == null ? e : ExceptionsHelper.serverError(processContext.getFailureReason())
);
return;
}
if (isProcessStarted) {
executorServiceForProcess.execute(() -> processContext.resultProcessor.get().process(processContext.process.get()));
executorServiceForProcess.execute(() -> processData(task, processContext, hasState, listener));
} else {
processContextByAllocation.remove(task.getAllocationId());
auditor.info(config.getId(), Messages.DATA_FRAME_ANALYTICS_AUDIT_FINISHED_ANALYSIS);
listener.onResponse(new StepResponse(true));
}
});
}
private boolean hasModelState(DataFrameAnalyticsConfig config) {
if (config.getAnalysis().persistsState() == false) {
return false;
}
try (ThreadContext.StoredContext ignore = client.threadPool().getThreadContext().stashWithOrigin(ML_ORIGIN)) {
SearchResponse searchResponse = client.prepareSearch(AnomalyDetectorsIndex.jobStateIndexPattern())
.setSize(1)
.setFetchSource(false)
.setQuery(QueryBuilders.idsQuery().addIds(config.getAnalysis().getStateDocIdPrefix(config.getId()) + "1"))
.get();
try {
return searchResponse.getHits().getHits().length == 1;
} finally {
searchResponse.decRef();
}
}
}
private void processData(
DataFrameAnalyticsTask task,
ProcessContext processContext,
boolean hasState,
ActionListener<StepResponse> listener
) {
LOGGER.info("[{}] Started loading data", processContext.config.getId());
auditor.info(processContext.config.getId(), Messages.getMessage(Messages.DATA_FRAME_ANALYTICS_AUDIT_STARTED_LOADING_DATA));
DataFrameAnalyticsConfig config = processContext.config;
DataFrameDataExtractor dataExtractor = processContext.dataExtractor.get();
AnalyticsProcess<AnalyticsResult> process = processContext.process.get();
AnalyticsResultProcessor resultProcessor = processContext.resultProcessor.get();
try {
writeHeaderRecord(dataExtractor, process, task);
writeDataRows(dataExtractor, process, task);
process.writeEndOfDataMessage();
LOGGER.debug(() -> "[" + processContext.config.getId() + "] Flushing input stream");
process.flushStream();
LOGGER.debug(() -> "[" + processContext.config.getId() + "] Flushing input stream completed");
restoreState(config, process, hasState);
LOGGER.info("[{}] Started analyzing", processContext.config.getId());
auditor.info(processContext.config.getId(), Messages.getMessage(Messages.DATA_FRAME_ANALYTICS_AUDIT_STARTED_ANALYZING));
LOGGER.info("[{}] Waiting for result processor to complete", config.getId());
resultProcessor.awaitForCompletion();
processContext.setFailureReason(resultProcessor.getFailure());
LOGGER.info("[{}] Result processor has completed", config.getId());
} catch (Exception e) {
if (task.isStopping()) {
// Errors during task stopping are expected but we still want to log them just in case.
String errorMsg = format("[%s] Error while processing data [%s]; task is stopping", config.getId(), e.getMessage());
LOGGER.debug(errorMsg, e);
} else {
String errorMsg = format("[%s] Error while processing data [%s]", config.getId(), e.getMessage());
LOGGER.error(errorMsg, e);
processContext.setFailureReason(errorMsg);
}
} finally {
closeProcess(task);
processContextByAllocation.remove(task.getAllocationId());
LOGGER.debug(
"Removed process context for task [{}]; [{}] processes still running",
config.getId(),
processContextByAllocation.size()
);
if (processContext.getFailureReason() == null) {
auditor.info(config.getId(), Messages.DATA_FRAME_ANALYTICS_AUDIT_FINISHED_ANALYSIS);
listener.onResponse(new StepResponse(false));
} else {
LOGGER.error("[{}] Marking task failed; {}", config.getId(), processContext.getFailureReason());
listener.onFailure(ExceptionsHelper.serverError(processContext.getFailureReason()));
// Note: We are not marking the task as failed here as we want the user to be able to inspect the failure reason.
}
}
}
private static void writeDataRows(
DataFrameDataExtractor dataExtractor,
AnalyticsProcess<AnalyticsResult> process,
DataFrameAnalyticsTask task
) throws IOException {
ProgressTracker progressTracker = task.getStatsHolder().getProgressTracker();
DataCountsTracker dataCountsTracker = task.getStatsHolder().getDataCountsTracker();
// The extra fields are for the doc hash and the control field (should be an empty string)
String[] record = new String[dataExtractor.getFieldNames().size() + 2];
// The value of the control field should be an empty string for data frame rows
record[record.length - 1] = "";
long totalRows = process.getConfig().rows();
long rowsProcessed = 0;
while (dataExtractor.hasNext()) {
Optional<SearchHit[]> rows = dataExtractor.next();
if (rows.isPresent()) {
for (SearchHit searchHit : rows.get()) {
if (dataExtractor.isCancelled()) {
break;
}
rowsProcessed++;
DataFrameDataExtractor.Row row = dataExtractor.createRow(searchHit);
if (row.shouldSkip()) {
dataCountsTracker.incrementSkippedDocsCount();
} else {
String[] rowValues = row.getValues();
System.arraycopy(rowValues, 0, record, 0, rowValues.length);
record[record.length - 2] = String.valueOf(row.getChecksum());
if (row.isTraining()) {
dataCountsTracker.incrementTrainingDocsCount();
process.writeRecord(record);
}
}
}
progressTracker.updateLoadingDataProgress(rowsProcessed >= totalRows ? 100 : (int) (rowsProcessed * 100.0 / totalRows));
}
}
}
private static void writeHeaderRecord(
DataFrameDataExtractor dataExtractor,
AnalyticsProcess<AnalyticsResult> process,
DataFrameAnalyticsTask task
) throws IOException {
List<String> fieldNames = dataExtractor.getFieldNames();
LOGGER.debug(() -> format("[%s] header row fields %s", task.getParams().getId(), fieldNames));
// We add 2 extra fields, both named dot:
// - the document hash
// - the control message
String[] headerRecord = new String[fieldNames.size() + 2];
for (int i = 0; i < fieldNames.size(); i++) {
headerRecord[i] = fieldNames.get(i);
}
headerRecord[headerRecord.length - 2] = ".";
headerRecord[headerRecord.length - 1] = ".";
process.writeRecord(headerRecord);
}
private void restoreState(DataFrameAnalyticsConfig config, AnalyticsProcess<AnalyticsResult> process, boolean hasState) {
if (config.getAnalysis().persistsState() == false) {
LOGGER.debug("[{}] Analysis does not support state", config.getId());
return;
}
if (hasState == false) {
LOGGER.debug("[{}] No model state available to restore", config.getId());
return;
}
LOGGER.debug("[{}] Restoring from previous model state", config.getId());
auditor.info(config.getId(), Messages.DATA_FRAME_ANALYTICS_AUDIT_RESTORING_STATE);
try (ThreadContext.StoredContext ignore = client.threadPool().getThreadContext().stashWithOrigin(ML_ORIGIN)) {
process.restoreState(client, config.getAnalysis().getStateDocIdPrefix(config.getId()));
} catch (Exception e) {
LOGGER.error(() -> "[" + process.getConfig().jobId() + "] Failed to restore state", e);
throw ExceptionsHelper.serverError("Failed to restore state: " + e.getMessage());
}
}
private AnalyticsProcess<AnalyticsResult> createProcess(
DataFrameAnalyticsTask task,
DataFrameAnalyticsConfig config,
AnalyticsProcessConfig analyticsProcessConfig,
boolean hasState
) {
AnalyticsProcess<AnalyticsResult> process = processFactory.createAnalyticsProcess(
config,
analyticsProcessConfig,
hasState,
executorServiceForProcess,
onProcessCrash(task)
);
if (process.isProcessAlive() == false) {
throw ExceptionsHelper.serverError("Failed to start data frame analytics process");
}
return process;
}
private Consumer<String> onProcessCrash(DataFrameAnalyticsTask task) {
return reason -> {
ProcessContext processContext = processContextByAllocation.get(task.getAllocationId());
if (processContext != null) {
processContext.setFailureReason(reason);
processContext.stop();
}
};
}
private void closeProcess(DataFrameAnalyticsTask task) {
String configId = task.getParams().getId();
LOGGER.info("[{}] Closing process", configId);
ProcessContext processContext = processContextByAllocation.get(task.getAllocationId());
try {
processContext.process.get().close();
LOGGER.info("[{}] Closed process", configId);
} catch (Exception e) {
if (task.isStopping()) {
LOGGER.debug(
() -> format("[%s] Process closing was interrupted by kill request due to the task being stopped", configId),
e
);
LOGGER.info("[{}] Closed process", configId);
} else {
LOGGER.error("[" + configId + "] Error closing data frame analyzer process", e);
String errorMsg = format("[%s] Error closing data frame analyzer process [%s]", configId, e.getMessage());
processContext.setFailureReason(errorMsg);
}
}
}
public void stop(DataFrameAnalyticsTask task) {
ProcessContext processContext;
synchronized (processContextByAllocation) {
processContext = processContextByAllocation.get(task.getAllocationId());
}
if (processContext != null) {
LOGGER.debug("[{}] Stopping process", task.getParams().getId());
processContext.stop();
} else {
LOGGER.debug("[{}] No process context to stop", task.getParams().getId());
}
}
// Visible for testing
int getProcessContextCount() {
return processContextByAllocation.size();
}
| AnalyticsProcessManager |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java | {
"start": 74731,
"end": 75009
} | class ____ {
private char @Nullable [] chars;
char @Nullable [] getChars() {
return this.chars;
}
void setChars(char @Nullable [] chars) {
this.chars = chars;
}
}
@EnableConfigurationProperties
@ConfigurationProperties("test")
static | WithCharArrayProperties |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/security/modules/TestSecurityModuleFactory.java | {
"start": 1271,
"end": 1615
} | class ____ implements SecurityModule {
public boolean installed;
@Override
public void install() throws SecurityInstallException {
installed = true;
}
@Override
public void uninstall() throws SecurityInstallException {
installed = false;
}
}
}
| TestSecurityModule |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationClassLoaderTests.java | {
"start": 5149,
"end": 5442
} | interface ____ {
@AliasFor("d")
String c() default "";
@AliasFor("c")
String d() default "";
Class<?> classValue();
TestEnum enumValue();
}
@TestMetaAnnotation(classValue = TestReference.class, enumValue = TestEnum.TWO)
@Retention(RetentionPolicy.RUNTIME)
@ | TestMetaAnnotation |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/shard/DenseVectorStats.java | {
"start": 7442,
"end": 7623
} | class ____ {
static final String NAME = "dense_vector";
static final String VALUE_COUNT = "value_count";
static final String FIELDS = "fielddata";
}
}
| Fields |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/jobmanager/slots/TaskManagerGateway.java | {
"start": 1833,
"end": 6214
} | interface ____ extends TaskExecutorOperatorEventGateway {
/**
* Return the address of the task manager with which the gateway is associated.
*
* @return Address of the task manager with which this gateway is associated.
*/
String getAddress();
/**
* Submit a task to the task manager.
*
* @param tdd describing the task to submit
* @param timeout of the submit operation
* @return Future acknowledge of the successful operation
*/
CompletableFuture<Acknowledge> submitTask(TaskDeploymentDescriptor tdd, Duration timeout);
/**
* Cancel the given task.
*
* @param executionAttemptID identifying the task
* @param timeout of the submit operation
* @return Future acknowledge if the task is successfully canceled
*/
CompletableFuture<Acknowledge> cancelTask(
ExecutionAttemptID executionAttemptID, Duration timeout);
/**
* Update the task where the given partitions can be found.
*
* @param executionAttemptID identifying the task
* @param partitionInfos telling where the partition can be retrieved from
* @param timeout of the submit operation
* @return Future acknowledge if the partitions have been successfully updated
*/
CompletableFuture<Acknowledge> updatePartitions(
ExecutionAttemptID executionAttemptID,
Iterable<PartitionInfo> partitionInfos,
Duration timeout);
/**
* Batch release intermediate result partitions.
*
* @param jobId id of the job that the partitions belong to
* @param partitionIds partition ids to release
*/
void releasePartitions(JobID jobId, Set<ResultPartitionID> partitionIds);
/**
* Notify the given task about a completed checkpoint and the last subsumed checkpoint id if
* possible.
*
* @param executionAttemptID identifying the task
* @param jobId identifying the job to which the task belongs
* @param completedCheckpointId of the completed checkpoint
* @param completedTimestamp of the completed checkpoint
* @param lastSubsumedCheckpointId of the last subsumed checkpoint id,
*/
void notifyCheckpointOnComplete(
ExecutionAttemptID executionAttemptID,
JobID jobId,
long completedCheckpointId,
long completedTimestamp,
long lastSubsumedCheckpointId);
/**
* Notify the given task about a aborted checkpoint.
*
* @param executionAttemptID identifying the task
* @param jobId identifying the job to which the task belongs
* @param checkpointId of the subsumed checkpoint
* @param latestCompletedCheckpointId of the latest completed checkpoint
* @param timestamp of the subsumed checkpoint
*/
void notifyCheckpointAborted(
ExecutionAttemptID executionAttemptID,
JobID jobId,
long checkpointId,
long latestCompletedCheckpointId,
long timestamp);
/**
* Trigger for the given task a checkpoint.
*
* @param executionAttemptID identifying the task
* @param jobId identifying the job to which the task belongs
* @param checkpointId of the checkpoint to trigger
* @param timestamp of the checkpoint to trigger
* @param checkpointOptions of the checkpoint to trigger
* @return Future acknowledge which is returned once the checkpoint has been triggered
*/
CompletableFuture<Acknowledge> triggerCheckpoint(
ExecutionAttemptID executionAttemptID,
JobID jobId,
long checkpointId,
long timestamp,
CheckpointOptions checkpointOptions);
/**
* Frees the slot with the given allocation ID.
*
* @param allocationId identifying the slot to free
* @param cause of the freeing operation
* @param timeout for the operation
* @return Future acknowledge which is returned once the slot has been freed
*/
CompletableFuture<Acknowledge> freeSlot(
final AllocationID allocationId,
final Throwable cause,
@RpcTimeout final Duration timeout);
@Override
CompletableFuture<Acknowledge> sendOperatorEventToTask(
ExecutionAttemptID task, OperatorID operator, SerializedValue<OperatorEvent> evt);
}
| TaskManagerGateway |
java | alibaba__nacos | config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpServiceTest.java | {
"start": 2442,
"end": 9285
} | class ____ {
private static final String BETA_TABLE_NAME = "config_info_beta";
private static final String TAG_TABLE_NAME = "config_info_tag";
@Mock
DefaultHistoryConfigCleaner defaultHistoryConfigCleaner = new DefaultHistoryConfigCleaner();
@Mock
ConfigInfoPersistService configInfoPersistService;
@Mock
NamespacePersistService namespacePersistService;
@Mock
HistoryConfigInfoPersistService historyConfigInfoPersistService;
@Mock
ConfigInfoGrayPersistService configInfoGrayPersistService;
@Mock
ServerMemberManager memberManager;
@Mock
ConfigMigrateService configMigrateService;
MockedStatic<EnvUtil> envUtilMockedStatic;
MockedStatic<ConfigExecutor> configExecutorMocked;
MockedStatic<PropertyUtil> propertyUtilMockedStatic;
MockedStatic<HistoryConfigCleanerManager> historyConfigCleanerManagerMockedStatic;
@Mock
private DataSourceService dataSourceService;
private DumpService dumpService;
@Mock
private TaskManager dumpTaskMgr;
@BeforeEach
void setUp() {
envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class);
propertyUtilMockedStatic = Mockito.mockStatic(PropertyUtil.class);
propertyUtilMockedStatic.when(() -> PropertyUtil.getAllDumpPageSize()).thenReturn(100);
propertyUtilMockedStatic.when(() -> PropertyUtil.getDumpChangeWorkerInterval()).thenReturn(1000 * 60L);
ReflectionTestUtils.setField(DynamicDataSource.getInstance(), "localDataSourceService", dataSourceService);
ReflectionTestUtils.setField(DynamicDataSource.getInstance(), "basicDataSourceService", dataSourceService);
dumpService = new ExternalDumpService(configInfoPersistService, namespacePersistService,
historyConfigInfoPersistService, configInfoGrayPersistService, memberManager, configMigrateService);
configExecutorMocked = Mockito.mockStatic(ConfigExecutor.class);
historyConfigCleanerManagerMockedStatic = Mockito.mockStatic(HistoryConfigCleanerManager.class);
historyConfigCleanerManagerMockedStatic.when(
() -> HistoryConfigCleanerManager.getHistoryConfigCleaner(anyString()))
.thenReturn(defaultHistoryConfigCleaner);
}
@AfterEach
void after() {
envUtilMockedStatic.close();
configExecutorMocked.close();
propertyUtilMockedStatic.close();
historyConfigCleanerManagerMockedStatic.close();
}
@Test
void dumpRequest() throws Throwable {
String dataId = "12345667dataId";
String group = "234445group";
DumpRequest dumpRequest = DumpRequest.create(dataId, group, "testtenant", System.currentTimeMillis(),
"127.0.0.1");
// TaskManager dumpTaskMgr;
ReflectionTestUtils.setField(dumpService, "dumpTaskMgr", dumpTaskMgr);
Mockito.doNothing().when(dumpTaskMgr).addTask(any(), any());
dumpService.dump(dumpRequest);
Mockito.verify(dumpTaskMgr, times(1))
.addTask(eq(GroupKey.getKeyTenant(dataId, group, dumpRequest.getTenant())), any(DumpTask.class));
dumpRequest.setGrayName("tag_123");
dumpService.dump(dumpRequest);
Mockito.verify(dumpTaskMgr, times(1)).addTask(
eq(GroupKey.getKeyTenant(dataId, group, dumpRequest.getTenant()) + "+gray+"
+ dumpRequest.getGrayName()), any(DumpTask.class));
}
@Test
void dumpOperate() throws Throwable {
configExecutorMocked.when(
() -> ConfigExecutor.scheduleConfigTask(any(Runnable.class), anyInt(), anyInt(), any(TimeUnit.class)))
.thenAnswer(invocation -> null);
configExecutorMocked.when(
() -> ConfigExecutor.scheduleConfigChangeTask(any(Runnable.class), anyInt(), any(TimeUnit.class)))
.thenAnswer(invocation -> null);
Mockito.when(namespacePersistService.isExistTable(BETA_TABLE_NAME)).thenReturn(true);
Mockito.when(namespacePersistService.isExistTable(TAG_TABLE_NAME)).thenReturn(true);
Mockito.when(configInfoPersistService.findConfigMaxId()).thenReturn(300L);
dumpService.dumpOperate();
// expect dump
Mockito.verify(configInfoPersistService, times(1)).findAllConfigInfoFragment(0, 100, true);
Mockito.verify(configInfoPersistService, times(1)).findConfigMaxId();
Mockito.verify(configInfoGrayPersistService, times(1)).configInfoGrayCount();
// expect dump formal,beta,tag,history clear,config change task to be scheduled.
// expect config clear history task be scheduled.
configExecutorMocked.verify(
() -> ConfigExecutor.scheduleConfigTask(any(DumpService.DumpAllProcessorRunner.class), anyLong(),
anyLong(), eq(TimeUnit.MINUTES)), times(1));
configExecutorMocked.verify(
() -> ConfigExecutor.scheduleConfigTask(any(DumpService.DumpAllGrayProcessorRunner.class), anyLong(),
anyLong(), eq(TimeUnit.MINUTES)), times(1));
configExecutorMocked.verify(
() -> ConfigExecutor.scheduleConfigChangeTask(any(DumpChangeConfigWorker.class), anyLong(),
eq(TimeUnit.MILLISECONDS)), times(1));
configExecutorMocked.verify(
() -> ConfigExecutor.scheduleConfigTask(any(DumpService.ConfigHistoryClear.class), anyLong(), anyLong(),
eq(TimeUnit.MINUTES)), times(1));
}
@Test
void clearHistory() {
envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("nacos.config.retention.days"))).thenReturn("10");
Mockito.when(memberManager.isFirstIp()).thenReturn(true);
DumpService.ConfigHistoryClear configHistoryClear = dumpService.new ConfigHistoryClear(
defaultHistoryConfigCleaner);
configHistoryClear.run();
Mockito.verify(defaultHistoryConfigCleaner, times(1)).cleanHistoryConfig();
}
@Test
void testHandleConfigDataChange() {
ConfigDataChangeEvent configDataChangeEvent = new ConfigDataChangeEvent("dataId", "group", null,
System.currentTimeMillis());
ReflectionTestUtils.setField(dumpService, "dumpTaskMgr", dumpTaskMgr);
Mockito.doNothing().when(dumpTaskMgr).addTask(any(), any());
dumpService.handleConfigDataChange(configDataChangeEvent);
Mockito.verify(dumpTaskMgr, times(1)).addTask(
eq(GroupKey.getKeyTenant(configDataChangeEvent.dataId, configDataChangeEvent.group,
configDataChangeEvent.tenant)), any(DumpTask.class));
}
}
| DumpServiceTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/LongFieldTest_4.java | {
"start": 310,
"end": 1051
} | class ____ extends TestCase {
public void test_min() throws Exception {
Random random = new Random();
Model[] array = new Model[2048];
for (int i = 0; i < array.length; ++i) {
array[i] = new Model();
array[i].value = random.nextLong();
}
String text = JSON.toJSONString(array);
Model[] array2 = JSON.parseObject(text, Model[].class);
Assert.assertEquals(array.length, array2.length);
for (int i = 0; i < array.length; ++i) {
Assert.assertEquals(array[i].value, array2[i].value);
}
}
@JSONType(serialzeFeatures = SerializerFeature.BeanToArray, parseFeatures = Feature.SupportArrayToBean)
public static | LongFieldTest_4 |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/JupiterTestDescriptorTests.java | {
"start": 15946,
"end": 16008
} | class ____ {
}
}
private abstract static | StaticTestCaseLevel2 |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/common/serialization/SerializerConfigImplTest.java | {
"start": 1675,
"end": 9574
} | class ____ {
@Test
void testReadingDefaultConfig() {
SerializerConfig config = new SerializerConfigImpl();
Configuration configuration = new Configuration();
// mutate config according to configuration
config.configure(configuration, SerializerConfigImplTest.class.getClassLoader());
assertThat(config).isEqualTo(new SerializerConfigImpl());
}
@Test
void testDoubleTypeRegistration() {
SerializerConfigImpl config = new SerializerConfigImpl();
List<Class<?>> types = Arrays.asList(Double.class, Integer.class, Double.class);
List<Class<?>> expectedTypes = Arrays.asList(Double.class, Integer.class);
for (Class<?> tpe : types) {
config.registerKryoType(tpe);
}
int counter = 0;
for (Class<?> tpe : config.getRegisteredKryoTypes()) {
assertThat(tpe).isEqualTo(expectedTypes.get(counter++));
}
assertThat(expectedTypes).hasSize(counter);
}
@Test
void testNotOverridingRegisteredKryoTypesWithDefaultsFromConfiguration() {
SerializerConfigImpl config = new SerializerConfigImpl();
config.registerKryoType(SerializerConfigImplTest.class);
config.registerKryoType(SerializerConfigImplTest.TestSerializer1.class);
Configuration configuration = new Configuration();
// mutate config according to configuration
config.configure(configuration, Thread.currentThread().getContextClassLoader());
LinkedHashSet<Object> set = new LinkedHashSet<>();
set.add(SerializerConfigImplTest.class);
set.add(SerializerConfigImplTest.TestSerializer1.class);
assertThat(config.getRegisteredKryoTypes()).isEqualTo(set);
}
@Test
void testNotOverridingRegisteredPojoTypesWithDefaultsFromConfiguration() {
SerializerConfigImpl config = new SerializerConfigImpl();
config.registerPojoType(SerializerConfigImplTest.class);
config.registerPojoType(SerializerConfigImplTest.TestSerializer1.class);
Configuration configuration = new Configuration();
// mutate config according to configuration
config.configure(configuration, Thread.currentThread().getContextClassLoader());
LinkedHashSet<Object> set = new LinkedHashSet<>();
set.add(SerializerConfigImplTest.class);
set.add(SerializerConfigImplTest.TestSerializer1.class);
assertThat(config.getRegisteredPojoTypes()).isEqualTo(set);
}
@Test
void testNotOverridingDefaultKryoSerializersFromConfiguration() {
SerializerConfigImpl config = new SerializerConfigImpl();
config.addDefaultKryoSerializer(
SerializerConfigImplTest.class, SerializerConfigImplTest.TestSerializer1.class);
config.addDefaultKryoSerializer(
SerializerConfigImplTest.TestSerializer1.class,
SerializerConfigImplTest.TestSerializer2.class);
Configuration configuration = new Configuration();
// mutate config according to configuration
config.configure(configuration, Thread.currentThread().getContextClassLoader());
LinkedHashMap<Class<?>, Class<? extends Serializer>> serializers = new LinkedHashMap<>();
serializers.put(
SerializerConfigImplTest.class, SerializerConfigImplTest.TestSerializer1.class);
serializers.put(
SerializerConfigImplTest.TestSerializer1.class,
SerializerConfigImplTest.TestSerializer2.class);
assertThat(config.getDefaultKryoSerializerClasses()).isEqualTo(serializers);
}
@Test
void testLoadingPojoTypesFromSerializationConfig() {
String serializationConfigStr =
"[org.apache.flink.api.common.serialization.SerializerConfigImplTest:"
+ " {type: pojo},"
+ " org.apache.flink.api.common.serialization.SerializerConfigImplTest$TestSerializer1:"
+ " {type: pojo},"
+ " org.apache.flink.api.common.serialization.SerializerConfigImplTest$TestSerializer2:"
+ " {type: pojo}]";
SerializerConfig serializerConfig = getConfiguredSerializerConfig(serializationConfigStr);
assertThat(serializerConfig.getRegisteredPojoTypes())
.containsExactly(
SerializerConfigImplTest.class,
TestSerializer1.class,
TestSerializer2.class);
}
@Test
void testLoadingKryoTypesFromSerializationConfig() {
String serializationConfigStr =
"{org.apache.flink.api.common.serialization.SerializerConfigImplTest:"
+ " {type: kryo},"
+ " org.apache.flink.api.common.serialization.SerializerConfigImplTest$TestSerializer1:"
+ " {type: kryo, kryo-type: default, class: org.apache.flink.api.common.serialization.SerializerConfigImplTest$TestSerializer2},"
+ " org.apache.flink.api.common.serialization.SerializerConfigImplTest$TestSerializer2:"
+ " {type: kryo, kryo-type: registered, class: org.apache.flink.api.common.serialization.SerializerConfigImplTest$TestSerializer3}}";
SerializerConfig serializerConfig = getConfiguredSerializerConfig(serializationConfigStr);
assertThat(serializerConfig.getRegisteredKryoTypes())
.containsExactly(SerializerConfigImplTest.class);
assertThat(serializerConfig.getDefaultKryoSerializerClasses())
.containsExactly(
new AbstractMap.SimpleEntry<>(
TestSerializer1.class, TestSerializer2.class));
assertThat(serializerConfig.getRegisteredTypesWithKryoSerializerClasses())
.containsExactly(
new AbstractMap.SimpleEntry<>(
TestSerializer2.class, TestSerializer3.class));
}
@Test
void testLoadingTypeInfoFactoriesFromSerializationConfig() {
String serializationConfigStr =
"{org.apache.flink.api.common.serialization.SerializerConfigImplTest:"
+ " {type: typeinfo, class: org.apache.flink.api.common.serialization.SerializerConfigImplTest$TestTypeInfoFactory}}";
SerializerConfig serializerConfig = getConfiguredSerializerConfig(serializationConfigStr);
assertThat(serializerConfig.getRegisteredTypeInfoFactories())
.containsExactly(
new AbstractMap.SimpleEntry<>(
SerializerConfigImplTest.class, TestTypeInfoFactory.class));
}
@Test
void testLoadingIllegalSerializationConfig() {
String duplicateClassConfigStr =
"[org.apache.flink.api.common.serialization.SerializerConfigImplTest:"
+ " {type: pojo},"
+ " org.apache.flink.api.common.serialization.SerializerConfigImplTest:"
+ " {type: pojo}]";
assertThatThrownBy(() -> getConfiguredSerializerConfig(duplicateClassConfigStr))
.isInstanceOf(IllegalArgumentException.class)
.hasRootCauseMessage("Duplicated serializer for the same class.");
String nullTypeConfigStr =
"{org.apache.flink.api.common.serialization.SerializerConfigImplTest:"
+ " {class: org.apache.flink.api.common.serialization.SerializerConfigImplTest$TestTypeInfoFactory}}";
assertThatThrownBy(() -> getConfiguredSerializerConfig(nullTypeConfigStr))
.isInstanceOf(IllegalArgumentException.class)
.hasRootCauseMessage(
"Serializer type not specified for"
+ " | SerializerConfigImplTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/createTable/OracleCreateTableTest80.java | {
"start": 875,
"end": 2595
} | class ____ extends OracleTest {
public void test_types() throws Exception {
String sql = //
"CREATE TABLE KTV.ALI_KTV_VISIT_TBD20150401 (\n" +
"\tKEY VARCHAR(20),\n" +
"\tVALUE VARCHAR(400),\n" +
"\tTYPE VARCHAR(20),\n" +
"\tID VARCHAR(50)\n" +
")";
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE);
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
//
assertEquals("CREATE TABLE KTV.ALI_KTV_VISIT_TBD20150401 (\n" +
"\tKEY VARCHAR(20),\n" +
"\tVALUE VARCHAR(400),\n" +
"\tTYPE VARCHAR(20),\n" +
"\tID VARCHAR(50)\n" +
")",
SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE));
//
// SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ORACLE);
// stmt.accept(visitor);
//
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("relationships : " + visitor.getRelationships());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
//
// assertEquals(1, visitor.getTables().size());
//
// assertEquals(3, visitor.getColumns().size());
//
// assertTrue(visitor.getColumns().contains(new TableStat.Column("JWGZPT.A", "XM")));
}
}
| OracleCreateTableTest80 |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSEditLogOp.java | {
"start": 84562,
"end": 89374
} | class ____ extends FSEditLogOp {
int length;
String src;
String dst;
long timestamp;
Rename[] options;
RenameOp() {
super(OP_RENAME);
}
static RenameOp getInstance(OpInstanceCache cache) {
return cache.get(OP_RENAME);
}
@Override
void resetSubFields() {
length = 0;
src = null;
dst = null;
timestamp = 0L;
options = null;
}
RenameOp setSource(String src) {
this.src = src;
return this;
}
RenameOp setDestination(String dst) {
this.dst = dst;
return this;
}
RenameOp setTimestamp(long timestamp) {
this.timestamp = timestamp;
return this;
}
RenameOp setOptions(Rename[] options) {
this.options = options;
return this;
}
@Override
public
void writeFields(DataOutputStream out) throws IOException {
FSImageSerialization.writeString(src, out);
FSImageSerialization.writeString(dst, out);
FSImageSerialization.writeLong(timestamp, out);
toBytesWritable(options).write(out);
writeRpcIds(rpcClientId, rpcCallId, out);
}
@Override
void readFields(DataInputStream in, int logVersion)
throws IOException {
if (!NameNodeLayoutVersion.supports(
LayoutVersion.Feature.EDITLOG_OP_OPTIMIZATION, logVersion)) {
this.length = in.readInt();
if (this.length != 3) {
throw new IOException("Incorrect data format. " + "Rename operation.");
}
}
this.src = FSImageSerialization.readString(in);
this.dst = FSImageSerialization.readString(in);
if (NameNodeLayoutVersion.supports(
LayoutVersion.Feature.EDITLOG_OP_OPTIMIZATION, logVersion)) {
this.timestamp = FSImageSerialization.readLong(in);
} else {
this.timestamp = readLong(in);
}
this.options = readRenameOptions(in);
// read RPC ids if necessary
readRpcIds(in, logVersion);
}
private static Rename[] readRenameOptions(DataInputStream in) throws IOException {
BytesWritable writable = new BytesWritable();
writable.readFields(in);
byte[] bytes = writable.getBytes();
int len = writable.getLength();
Rename[] options = new Rename[len];
for (int i = 0; i < len; i++) {
options[i] = Rename.valueOf(bytes[i]);
}
return options;
}
static BytesWritable toBytesWritable(Rename... options) {
byte[] bytes = new byte[options.length];
for (int i = 0; i < options.length; i++) {
bytes[i] = options[i].value();
}
return new BytesWritable(bytes);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RenameOp [length=")
.append(length)
.append(", src=")
.append(src)
.append(", dst=")
.append(dst)
.append(", timestamp=")
.append(timestamp)
.append(", options=")
.append(Arrays.toString(options));
appendRpcIdsToString(builder, rpcClientId, rpcCallId);
builder.append(", opCode=")
.append(opCode)
.append(", txid=")
.append(txid)
.append("]");
return builder.toString();
}
@Override
protected void toXml(ContentHandler contentHandler) throws SAXException {
XMLUtils.addSaxString(contentHandler, "LENGTH",
Integer.toString(length));
XMLUtils.addSaxString(contentHandler, "SRC", src);
XMLUtils.addSaxString(contentHandler, "DST", dst);
XMLUtils.addSaxString(contentHandler, "TIMESTAMP",
Long.toString(timestamp));
StringBuilder bld = new StringBuilder();
String prefix = "";
for (Rename r : options) {
bld.append(prefix).append(r.toString());
prefix = "|";
}
XMLUtils.addSaxString(contentHandler, "OPTIONS", bld.toString());
appendRpcIdsToXml(contentHandler, rpcClientId, rpcCallId);
}
@Override void fromXml(Stanza st) throws InvalidXmlException {
this.length = Integer.parseInt(st.getValue("LENGTH"));
this.src = st.getValue("SRC");
this.dst = st.getValue("DST");
this.timestamp = Long.parseLong(st.getValue("TIMESTAMP"));
String opts = st.getValue("OPTIONS");
String o[] = opts.split("\\|");
this.options = new Rename[o.length];
for (int i = 0; i < o.length; i++) {
if (o[i].equals(""))
continue;
try {
this.options[i] = Rename.valueOf(o[i]);
} finally {
if (this.options[i] == null) {
System.err.println("error parsing Rename value: \"" + o[i] + "\"");
}
}
}
readRpcIdsFromXml(st);
}
}
static | RenameOp |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/cache/config/ExpressionCachingIntegrationTests.java | {
"start": 2468,
"end": 2659
} | class ____ {
private final String id;
public User(String id) {
this.id = id;
}
@SuppressWarnings("unused")
public String getId() {
return this.id;
}
}
private static | User |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryDefaultInEnumSwitchTest.java | {
"start": 25344,
"end": 25909
} | enum ____ {
ONE
}
boolean m(Case c) {
switch (c) {
case ONE:
return true;
// BUG: Diagnostic contains: after the switch statement
default:
throw new AssertionError(c);
}
}
}
""")
.doTest();
}
@Test
public void messageRemovedAssertion() {
compilationHelper
.addSourceLines(
"in/Test.java",
"""
| Case |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceVerificationAuthenticationConverterTests.java | {
"start": 2031,
"end": 8468
} | class ____ {
private static final String VERIFICATION_URI = "/oauth2/device_verification";
private static final String USER_CODE = "BCDF-GHJK";
private OAuth2DeviceVerificationAuthenticationConverter converter;
@BeforeEach
public void setUp() {
this.converter = new OAuth2DeviceVerificationAuthenticationConverter();
}
@AfterEach
public void tearDown() {
SecurityContextHolder.clearContext();
}
@Test
public void convertWhenPutThenReturnNull() {
MockHttpServletRequest request = createRequest();
request.setMethod(HttpMethod.PUT.name());
Authentication authentication = this.converter.convert(request);
assertThat(authentication).isNull();
}
@Test
public void convertWhenStateThenReturnNull() {
MockHttpServletRequest request = createRequest();
request.addParameter(OAuth2ParameterNames.STATE, "abc123");
updateQueryString(request);
Authentication authentication = this.converter.convert(request);
assertThat(authentication).isNull();
}
@Test
public void convertWhenMissingUserCodeThenReturnNull() {
MockHttpServletRequest request = createRequest();
Authentication authentication = this.converter.convert(request);
assertThat(authentication).isNull();
}
@Test
public void convertWhenEmptyUserCodeParameterThenInvalidRequestError() {
MockHttpServletRequest request = createRequest();
request.addParameter(OAuth2ParameterNames.USER_CODE, "");
updateQueryString(request);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.converter.convert(request))
.withMessageContaining(OAuth2ParameterNames.USER_CODE)
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
// @formatter:on
}
@Test
public void convertWhenInvalidUserCodeParameterThenInvalidRequestError() {
MockHttpServletRequest request = createRequest();
request.addParameter(OAuth2ParameterNames.USER_CODE, "LONG-USER-CODE");
updateQueryString(request);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.converter.convert(request))
.withMessageContaining(OAuth2ParameterNames.USER_CODE)
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
// @formatter:on
}
@Test
public void convertWhenMultipleUserCodeParameterThenInvalidRequestError() {
MockHttpServletRequest request = createRequest();
request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE);
request.addParameter(OAuth2ParameterNames.USER_CODE, "another");
updateQueryString(request);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.converter.convert(request))
.withMessageContaining(OAuth2ParameterNames.USER_CODE)
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
// @formatter:on
}
@Test
public void convertWhenMissingPrincipalThenReturnDeviceVerificationAuthentication() {
MockHttpServletRequest request = createRequest();
request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE.toLowerCase().replace("-", " . "));
updateQueryString(request);
OAuth2DeviceVerificationAuthenticationToken authentication = (OAuth2DeviceVerificationAuthenticationToken) this.converter
.convert(request);
assertThat(authentication).isNotNull();
assertThat(authentication.getPrincipal()).isInstanceOf(AnonymousAuthenticationToken.class);
assertThat(authentication.getUserCode()).isEqualTo(USER_CODE);
assertThat(authentication.getAdditionalParameters()).isEmpty();
}
@Test
public void convertWhenNonNormalizedUserCodeThenReturnDeviceVerificationAuthentication() {
MockHttpServletRequest request = createRequest();
request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE.toLowerCase().replace("-", " . "));
updateQueryString(request);
SecurityContextImpl securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new TestingAuthenticationToken("user", null));
SecurityContextHolder.setContext(securityContext);
OAuth2DeviceVerificationAuthenticationToken authentication = (OAuth2DeviceVerificationAuthenticationToken) this.converter
.convert(request);
assertThat(authentication).isNotNull();
assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class);
assertThat(authentication.getUserCode()).isEqualTo(USER_CODE);
assertThat(authentication.getAdditionalParameters()).isEmpty();
}
@Test
public void convertWhenAllParametersThenReturnDeviceVerificationAuthentication() {
MockHttpServletRequest request = createRequest();
request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE);
request.addParameter("param-1", "value-1");
request.addParameter("param-2", "value-1", "value-2");
updateQueryString(request);
SecurityContextImpl securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new TestingAuthenticationToken("user", null));
SecurityContextHolder.setContext(securityContext);
OAuth2DeviceVerificationAuthenticationToken authentication = (OAuth2DeviceVerificationAuthenticationToken) this.converter
.convert(request);
assertThat(authentication).isNotNull();
assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class);
assertThat(authentication.getUserCode()).isEqualTo(USER_CODE);
assertThat(authentication.getAdditionalParameters()).containsExactly(Map.entry("param-1", "value-1"),
Map.entry("param-2", new String[] { "value-1", "value-2" }));
}
private static MockHttpServletRequest createRequest() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod(HttpMethod.GET.name());
request.setRequestURI(VERIFICATION_URI);
return request;
}
private static void updateQueryString(MockHttpServletRequest request) {
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(request.getRequestURI());
request.getParameterMap().forEach((key, values) -> {
if (values.length > 0) {
for (String value : values) {
uriBuilder.queryParam(key, value);
}
}
});
request.setQueryString(uriBuilder.build().getQuery());
}
}
| OAuth2DeviceVerificationAuthenticationConverterTests |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_516/Issue516Test.java | {
"start": 518,
"end": 905
} | class ____ {
@ProcessorTest
@WithClasses( { SourceTargetMapper.class, Source.class, Target.class } )
public void shouldAddNullPtrCheckAroundSourceForAdder() {
Source source = new Source();
Target target = SourceTargetMapper.STM.map( source );
assertThat( target ).isNotNull();
assertThat( target.getElements() ).isNull();
}
}
| Issue516Test |
java | junit-team__junit5 | junit-start/src/main/java/org/junit/start/JUnit.java | {
"start": 1339,
"end": 1620
} | class ____ {
/// Run all tests defined in the caller class.
public static void run() {
var walker = StackWalker.getInstance(RETAIN_CLASS_REFERENCE);
run(selectClass(walker.getCallerClass()));
}
/// Run all tests defined in the given test class.
/// @param testClass the | JUnit |
java | apache__camel | core/camel-util/src/main/java21/org/apache/camel/util/concurrent/CamelThreadFactory.java | {
"start": 1123,
"end": 2340
} | class ____ implements ThreadFactoryTypeAware {
private static final Logger LOG = LoggerFactory.getLogger(CamelThreadFactory.class);
private static final ThreadFactoryType TYPE = ThreadFactoryType.current();
private final String pattern;
private final String name;
private final boolean daemon;
private final ThreadFactoryType threadType;
public CamelThreadFactory(String pattern, String name, boolean daemon) {
this.pattern = pattern;
this.name = name;
this.daemon = daemon;
this.threadType = daemon ? TYPE : ThreadFactoryType.PLATFORM;
}
@Override
public boolean isVirtual() {
return threadType == ThreadFactoryType.VIRTUAL;
}
@Override
public Thread newThread(Runnable runnable) {
String threadName = ThreadHelper.resolveThreadName(pattern, name);
Thread answer = threadType.newThread(threadName, daemon, runnable);
LOG.trace("Created thread[{}] -> {}", threadName, answer);
return answer;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "CamelThreadFactory[" + name + "]";
}
private | CamelThreadFactory |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/codec/HttpMessageWriter.java | {
"start": 1513,
"end": 4816
} | interface ____<T> {
/**
* Return the list of media types supported by this Writer. The list may not
* apply to every possible target element type and calls to this method should
* typically be guarded via {@link #canWrite(ResolvableType, MediaType)
* canWrite(elementType, null)}. The list may also exclude media types
* supported only for a specific element type. Alternatively, use
* {@link #getWritableMediaTypes(ResolvableType)} for a more precise list.
* @return the general list of supported media types
*/
List<MediaType> getWritableMediaTypes();
/**
* Return the list of media types supported by this Writer for the given type
* of element. This list may differ from {@link #getWritableMediaTypes()}
* if the Writer doesn't support the element type, or if it supports it
* only for a subset of media types.
* @param elementType the type of element to encode
* @return the list of media types supported for the given class
* @since 5.3.4
*/
default List<MediaType> getWritableMediaTypes(ResolvableType elementType) {
return (canWrite(elementType, null) ? getWritableMediaTypes() : Collections.emptyList());
}
/**
* Whether the given object type is supported by this writer.
* @param elementType the type of object to check
* @param mediaType the media type for the write (possibly {@code null})
* @return {@code true} if writable, {@code false} otherwise
*/
boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType);
/**
* Write a given stream of object to the output message.
* @param inputStream the objects to write
* @param elementType the type of objects in the stream which must have been
* previously checked via {@link #canWrite(ResolvableType, MediaType)}
* @param mediaType the content type for the write (possibly {@code null} to
* indicate that the default content type of the writer must be used)
* @param message the message to write to
* @param hints additional information about how to encode and write
* @return indicates completion or error
*/
Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType elementType,
@Nullable MediaType mediaType, ReactiveHttpOutputMessage message, Map<String, Object> hints);
/**
* Server-side only alternative to
* {@link #write(Publisher, ResolvableType, MediaType, ReactiveHttpOutputMessage, Map)}
* with additional context available.
* @param actualType the actual return type of the method that returned the
* value; for annotated controllers, the {@link MethodParameter} can be
* accessed via {@link ResolvableType#getSource()}.
* @param elementType the type of Objects in the input stream
* @param mediaType the content type to use (possibly {@code null} indicating
* the default content type of the writer should be used)
* @param request the current request
* @param response the current response
* @return a {@link Mono} that indicates completion of writing or error
*/
default Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType actualType,
ResolvableType elementType, @Nullable MediaType mediaType, ServerHttpRequest request,
ServerHttpResponse response, Map<String, Object> hints) {
return write(inputStream, elementType, mediaType, response, hints);
}
}
| HttpMessageWriter |
java | spring-projects__spring-security | cas/src/test/java/org/springframework/security/cas/authentication/NullStatelessTicketCacheTests.java | {
"start": 889,
"end": 1410
} | class ____ extends AbstractStatelessTicketCacheTests {
private StatelessTicketCache cache = new NullStatelessTicketCache();
@Test
public void testGetter() {
assertThat(this.cache.getByTicketId(null)).isNull();
assertThat(this.cache.getByTicketId("test")).isNull();
}
@Test
public void testInsertAndGet() {
final CasAuthenticationToken token = getToken();
this.cache.putTicketInCache(token);
assertThat(this.cache.getByTicketId((String) token.getCredentials())).isNull();
}
}
| NullStatelessTicketCacheTests |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/JmsLoadBalanceFailOverIT.java | {
"start": 1708,
"end": 3710
} | class ____ extends CamelTestSupport {
@RegisterExtension
public static ArtemisService service = ArtemisServiceFactory.createVMService();
@BeforeEach
void configureTest() {
getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:bar").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");
}
@Test
public void testFailover() throws Exception {
String out = template.requestBody("direct:start", "Hello World", String.class);
assertEquals("Bye World", out);
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.loadBalance().failover()
.to("jms:queue:fooJmsLoadBalanceFailoverTest?transferException=true")
.to("jms:queue:barJmsLoadBalanceFailoverTest?transferException=true")
.end()
.to("mock:result");
from("jms:queue:fooJmsLoadBalanceFailoverTest?transferException=true")
.to("mock:foo")
.throwException(new IllegalArgumentException("Damn"));
from("jms:queue:barJmsLoadBalanceFailoverTest?transferException=true")
.to("mock:bar")
.transform().simple("Bye World");
}
};
}
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
ConnectionFactory connectionFactory = ConnectionFactoryHelper.createConnectionFactory(service);
camelContext.addComponent("jms", jmsComponentAutoAcknowledge(connectionFactory));
return camelContext;
}
}
| JmsLoadBalanceFailOverIT |
java | elastic__elasticsearch | build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/BuildPlugin.java | {
"start": 1460,
"end": 5472
} | class ____ implements Plugin<Project> {
public static final String LICENSE_PATH = "licenses/AGPL-3.0+SSPL-1.0+ELASTIC-LICENSE-2.0.txt";
private final BuildLayout buildLayout;
private final ObjectFactory objectFactory;
private final ProviderFactory providerFactory;
private final ProjectLayout projectLayout;
@Inject
BuildPlugin(BuildLayout buildLayout, ObjectFactory objectFactory, ProviderFactory providerFactory, ProjectLayout projectLayout) {
this.buildLayout = buildLayout;
this.objectFactory = objectFactory;
this.providerFactory = providerFactory;
this.projectLayout = projectLayout;
}
@Override
public void apply(final Project project) {
// make sure the global build info plugin is applied to the root project
project.getRootProject().getPluginManager().apply(GlobalBuildInfoPlugin.class);
if (project.getPluginManager().hasPlugin("elasticsearch.standalone-rest-test")) {
throw new InvalidUserDataException(
"elasticsearch.standalone-test, " + "elasticsearch.standalone-rest-test, and elasticsearch.build are mutually exclusive"
);
}
project.getPluginManager().apply("elasticsearch.java");
project.getPluginManager().apply(ElasticsearchJavadocPlugin.class);
project.getPluginManager().apply(DependenciesInfoPlugin.class);
project.getPluginManager().apply(LicensingPlugin.class);
project.getPluginManager().apply(SnykDependencyMonitoringGradlePlugin.class);
project.getPluginManager().apply(ClusterFeaturesMetadataPlugin.class);
InternalPrecommitTasks.create(project, true);
configureLicenseAndNotice(project);
}
public void configureLicenseAndNotice(final Project project) {
final ExtraPropertiesExtension ext = project.getExtensions().getByType(ExtraPropertiesExtension.class);
RegularFileProperty licenseFileProperty = objectFactory.fileProperty();
RegularFileProperty noticeFileProperty = objectFactory.fileProperty();
ext.set("licenseFile", licenseFileProperty);
ext.set("noticeFile", noticeFileProperty);
configureLicenseDefaultConvention(licenseFileProperty);
configureNoticeDefaultConvention(noticeFileProperty);
updateJarTasksMetaInf(project);
}
private void updateJarTasksMetaInf(Project project) {
final ExtraPropertiesExtension ext = project.getExtensions().getByType(ExtraPropertiesExtension.class);
project.getTasks().withType(Jar.class).configureEach(jar -> {
final RegularFileProperty licenseFileExtProperty = (RegularFileProperty) ext.get("licenseFile");
final RegularFileProperty noticeFileExtProperty = (RegularFileProperty) ext.get("noticeFile");
File licenseFile = licenseFileExtProperty.getAsFile().get();
File noticeFile = noticeFileExtProperty.getAsFile().get();
jar.metaInf(spec -> {
spec.from(licenseFile.getParent(), from -> {
from.include(licenseFile.getName());
from.rename(s -> "LICENSE.txt");
});
spec.from(noticeFile.getParent(), from -> {
from.include(noticeFile.getName());
from.rename(s -> "NOTICE.txt");
});
});
});
}
private void configureLicenseDefaultConvention(RegularFileProperty licenseFileProperty) {
File licenseFileDefault = new File(buildLayout.getRootDirectory(), LICENSE_PATH);
licenseFileProperty.convention(projectLayout.file(providerFactory.provider(() -> licenseFileDefault)));
}
private void configureNoticeDefaultConvention(RegularFileProperty noticeFileProperty) {
File noticeFileDefault = new File(buildLayout.getRootDirectory(), "NOTICE.txt");
noticeFileProperty.convention(projectLayout.file(providerFactory.provider(() -> noticeFileDefault)));
}
}
| BuildPlugin |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeMap.java | {
"start": 1366,
"end": 4210
} | class ____ {
static INodeMap newInstance(INodeDirectory rootDir) {
// Compute the map capacity by allocating 1% of total memory
int capacity = LightWeightGSet.computeCapacity(1, "INodeMap");
GSet<INode, INodeWithAdditionalFields> map =
new LightWeightGSet<>(capacity);
map.put(rootDir);
return new INodeMap(map);
}
/** Synchronized by external lock. */
private final GSet<INode, INodeWithAdditionalFields> map;
public Iterator<INodeWithAdditionalFields> getMapIterator() {
return map.iterator();
}
private INodeMap(GSet<INode, INodeWithAdditionalFields> map) {
Preconditions.checkArgument(map != null);
this.map = map;
}
/**
* Add an {@link INode} into the {@link INode} map. Replace the old value if
* necessary.
* @param inode The {@link INode} to be added to the map.
*/
public final void put(INode inode) {
if (inode instanceof INodeWithAdditionalFields) {
map.put((INodeWithAdditionalFields)inode);
}
}
/**
* Remove a {@link INode} from the map.
* @param inode The {@link INode} to be removed.
*/
public final void remove(INode inode) {
map.remove(inode);
}
/**
* @return The size of the map.
*/
public int size() {
return map.size();
}
/**
* Get the {@link INode} with the given id from the map.
* @param id ID of the {@link INode}.
* @return The {@link INode} in the map with the given id. Return null if no
* such {@link INode} in the map.
*/
public INode get(long id) {
INode inode = new INodeWithAdditionalFields(id, null, new PermissionStatus(
"", "", new FsPermission((short) 0)), 0, 0) {
@Override
void recordModification(int latestSnapshotId) {
}
@Override
public void destroyAndCollectBlocks(ReclaimContext reclaimContext) {
// Nothing to do
}
@Override
public QuotaCounts computeQuotaUsage(
BlockStoragePolicySuite bsps, byte blockStoragePolicyId,
boolean useCache, int lastSnapshotId) {
return null;
}
@Override
public ContentSummaryComputationContext computeContentSummary(
int snapshotId, ContentSummaryComputationContext summary) {
return null;
}
@Override
public void cleanSubtree(
ReclaimContext reclaimContext, int snapshotId, int priorSnapshotId) {
}
@Override
public byte getStoragePolicyID(){
return HdfsConstants.BLOCK_STORAGE_POLICY_ID_UNSPECIFIED;
}
@Override
public byte getLocalStoragePolicyID() {
return HdfsConstants.BLOCK_STORAGE_POLICY_ID_UNSPECIFIED;
}
};
return map.get(inode);
}
/**
* Clear the {@link #map}
*/
public void clear() {
map.clear();
}
}
| INodeMap |
java | quarkusio__quarkus | extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/JsonObjectScalarTest.java | {
"start": 2079,
"end": 2210
} | class ____ {
@Query
public JsonObject echo(JsonObject input) {
return input;
}
}
}
| ObjectApi |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAlterTableSetComment.java | {
"start": 812,
"end": 1348
} | class ____ extends SQLObjectImpl implements SQLAlterTableItem {
private SQLExpr comment;
public SQLExpr getComment() {
return comment;
}
public void setComment(SQLExpr comment) {
if (comment != null) {
comment.setParent(this);
}
this.comment = comment;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, comment);
}
visitor.endVisit(this);
}
}
| SQLAlterTableSetComment |
java | spring-projects__spring-framework | spring-expression/src/test/java/org/springframework/expression/spel/ParsingTests.java | {
"start": 8962,
"end": 10033
} | class ____ {
@Test
void mathOperatorsAddIntegers() {
parseCheck("2+4", "(2 + 4)");
}
@Test
void mathOperatorsSubtract() {
parseCheck("5-4", "(5 - 4)");
}
@Test
void mathOperatorsMultiply() {
parseCheck("7*4", "(7 * 4)");
}
@Test
void mathOperatorsDivide() {
parseCheck("8/4", "(8 / 4)");
}
@Test
void mathOperatorModulus() {
parseCheck("7 % 4", "(7 % 4)");
}
@Test
void mathOperatorIncrementPrefix() {
parseCheck("++foo", "++foo");
}
@Test
void mathOperatorIncrementPostfix() {
parseCheck("foo++", "foo++");
}
@Test
void mathOperatorDecrementPrefix() {
parseCheck("--foo", "--foo");
}
@Test
void mathOperatorDecrementPostfix() {
parseCheck("foo--", "foo--");
}
@Test
void mathOperatorPower() {
parseCheck("3^2", "(3 ^ 2)");
parseCheck("3.0d^2.0d", "(3.0 ^ 2.0)");
parseCheck("3L^2L", "(3 ^ 2)");
parseCheck("(2^32)^2", "((2 ^ 32) ^ 2)");
parseCheck("new java.math.BigDecimal('5') ^ 3", "(new java.math.BigDecimal('5') ^ 3)");
}
}
@Nested
| MathematicalOperators |
java | grpc__grpc-java | core/src/main/java/io/grpc/internal/DelayedClientCall.java | {
"start": 13972,
"end": 14375
} | class ____ extends ContextRunnable {
final Listener<RespT> listener;
final Status status;
CloseListenerRunnable(Listener<RespT> listener, Status status) {
super(context);
this.listener = listener;
this.status = status;
}
@Override
public void runInContext() {
listener.onClose(status, new Metadata());
}
}
private static final | CloseListenerRunnable |
java | spring-projects__spring-boot | documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/data/sql/r2dbc/MyR2dbcConfiguration.java | {
"start": 985,
"end": 1189
} | class ____ {
@Bean
public ConnectionFactoryOptionsBuilderCustomizer connectionFactoryPortCustomizer() {
return (builder) -> builder.option(ConnectionFactoryOptions.PORT, 5432);
}
}
| MyR2dbcConfiguration |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/engine/LiveVersionMapTests.java | {
"start": 1922,
"end": 24419
} | class ____ extends ESTestCase {
public void testRamBytesUsed() throws Exception {
LiveVersionMap map = new LiveVersionMap();
for (int i = 0; i < 100000; ++i) {
BytesRefBuilder uid = new BytesRefBuilder();
uid.copyChars(TestUtil.randomSimpleString(random(), 10, 20));
try (Releasable r = map.acquireLock(uid.toBytesRef())) {
map.putIndexUnderLock(uid.toBytesRef(), randomIndexVersionValue());
}
}
long actualRamBytesUsed = RamUsageTester.ramUsed(map);
long estimatedRamBytesUsed = map.ramBytesUsed();
// less than 50% off
assertEquals(actualRamBytesUsed, estimatedRamBytesUsed, actualRamBytesUsed / 2);
// now refresh
map.beforeRefresh();
map.afterRefresh(true);
for (int i = 0; i < 100000; ++i) {
BytesRefBuilder uid = new BytesRefBuilder();
uid.copyChars(TestUtil.randomSimpleString(random(), 10, 20));
try (Releasable r = map.acquireLock(uid.toBytesRef())) {
map.putIndexUnderLock(uid.toBytesRef(), randomIndexVersionValue());
}
}
actualRamBytesUsed = RamUsageTester.ramUsed(map);
estimatedRamBytesUsed = map.ramBytesUsed();
// Since Java 9, RamUsageTester computes the memory usage of maps as
// the memory usage of an array that would contain exactly all keys
// and values. This is an under-estimation of the actual memory
// usage since it ignores the impact of the load factor and of the
// linked list/tree that is used to resolve collisions. So we use a
// bigger tolerance.
// less than 50% off
long tolerance = actualRamBytesUsed / 2;
assertEquals(actualRamBytesUsed, estimatedRamBytesUsed, tolerance);
}
public void testRefreshingBytes() throws IOException {
LiveVersionMap map = new LiveVersionMap();
BytesRefBuilder uid = new BytesRefBuilder();
uid.copyChars(TestUtil.randomSimpleString(random(), 10, 20));
try (Releasable r = map.acquireLock(uid.toBytesRef())) {
map.putIndexUnderLock(uid.toBytesRef(), randomIndexVersionValue());
}
map.beforeRefresh();
assertThat(map.getRefreshingBytes(), greaterThan(0L));
map.afterRefresh(true);
assertThat(map.getRefreshingBytes(), equalTo(0L));
}
private BytesRef uid(String string) {
BytesRefBuilder builder = new BytesRefBuilder();
builder.copyChars(string);
// length of the array must be the same as the len of the ref... there is an assertion in LiveVersionMap#putUnderLock
return BytesRef.deepCopyOf(builder.get());
}
public void testBasics() throws IOException {
LiveVersionMap map = new LiveVersionMap();
try (Releasable r = map.acquireLock(uid("test"))) {
Translog.Location tlogLoc = randomTranslogLocation();
map.putIndexUnderLock(uid("test"), new IndexVersionValue(tlogLoc, 1, 1, 1));
assertEquals(new IndexVersionValue(tlogLoc, 1, 1, 1), map.getUnderLock(uid("test")));
map.beforeRefresh();
assertEquals(new IndexVersionValue(tlogLoc, 1, 1, 1), map.getUnderLock(uid("test")));
map.afterRefresh(randomBoolean());
assertNull(map.getUnderLock(uid("test")));
map.putDeleteUnderLock(uid("test"), new DeleteVersionValue(1, 1, 1, 1));
assertEquals(new DeleteVersionValue(1, 1, 1, 1), map.getUnderLock(uid("test")));
map.beforeRefresh();
assertEquals(new DeleteVersionValue(1, 1, 1, 1), map.getUnderLock(uid("test")));
map.afterRefresh(randomBoolean());
assertEquals(new DeleteVersionValue(1, 1, 1, 1), map.getUnderLock(uid("test")));
map.pruneTombstones(2, 0);
assertEquals(new DeleteVersionValue(1, 1, 1, 1), map.getUnderLock(uid("test")));
map.pruneTombstones(2, 1);
assertNull(map.getUnderLock(uid("test")));
}
}
public void testConcurrently() throws IOException, InterruptedException {
HashSet<BytesRef> keySet = new HashSet<>();
int numKeys = randomIntBetween(50, 200);
for (int i = 0; i < numKeys; i++) {
keySet.add(uid(TestUtil.randomSimpleString(random(), 10, 20)));
}
List<BytesRef> keyList = new ArrayList<>(keySet);
ConcurrentHashMap<BytesRef, VersionValue> values = new ConcurrentHashMap<>();
ConcurrentHashMap<BytesRef, DeleteVersionValue> deletes = new ConcurrentHashMap<>();
LiveVersionMap map = new LiveVersionMap();
int numThreads = randomIntBetween(2, 5);
Thread[] threads = new Thread[numThreads];
CountDownLatch startGun = new CountDownLatch(numThreads);
CountDownLatch done = new CountDownLatch(numThreads);
int randomValuesPerThread = randomIntBetween(5000, 20000);
final AtomicLong clock = new AtomicLong(0);
final AtomicLong lastPrunedTimestamp = new AtomicLong(-1);
final AtomicLong maxSeqNo = new AtomicLong();
final AtomicLong lastPrunedSeqNo = new AtomicLong();
for (int j = 0; j < threads.length; j++) {
threads[j] = new Thread(() -> {
startGun.countDown();
try {
startGun.await();
} catch (InterruptedException e) {
done.countDown();
throw new AssertionError(e);
}
try {
for (int i = 0; i < randomValuesPerThread; ++i) {
BytesRef bytesRef = randomFrom(random(), keyList);
try (Releasable r = map.acquireLock(bytesRef)) {
VersionValue versionValue = values.computeIfAbsent(
bytesRef,
v -> new IndexVersionValue(randomTranslogLocation(), randomLong(), maxSeqNo.incrementAndGet(), randomLong())
);
boolean isDelete = versionValue instanceof DeleteVersionValue;
if (isDelete) {
map.removeTombstoneUnderLock(bytesRef);
deletes.remove(bytesRef);
}
if (isDelete == false && rarely()) {
versionValue = new DeleteVersionValue(
versionValue.version + 1,
maxSeqNo.incrementAndGet(),
versionValue.term,
clock.getAndIncrement()
);
deletes.put(bytesRef, (DeleteVersionValue) versionValue);
map.putDeleteUnderLock(bytesRef, (DeleteVersionValue) versionValue);
} else {
versionValue = new IndexVersionValue(
randomTranslogLocation(),
versionValue.version + 1,
maxSeqNo.incrementAndGet(),
versionValue.term
);
map.putIndexUnderLock(bytesRef, (IndexVersionValue) versionValue);
}
values.put(bytesRef, versionValue);
}
if (rarely()) {
final long pruneSeqNo = randomLongBetween(0, maxSeqNo.get());
final long clockTick = randomLongBetween(0, clock.get());
map.pruneTombstones(clockTick, pruneSeqNo);
// make sure we track the latest timestamp and seqno we pruned the deletes
lastPrunedTimestamp.updateAndGet(prev -> Math.max(clockTick, prev));
lastPrunedSeqNo.updateAndGet(prev -> Math.max(pruneSeqNo, prev));
}
}
} finally {
done.countDown();
}
});
threads[j].start();
}
do {
final Map<BytesRef, VersionValue> valueMap = new HashMap<>(map.getAllCurrent());
map.beforeRefresh();
valueMap.forEach((k, v) -> {
try (Releasable r = map.acquireLock(k)) {
VersionValue actualValue = map.getUnderLock(k);
assertNotNull(actualValue);
assertTrue(v.version <= actualValue.version);
}
});
map.afterRefresh(randomBoolean());
valueMap.forEach((k, v) -> {
try (Releasable r = map.acquireLock(k)) {
VersionValue actualValue = map.getUnderLock(k);
if (actualValue != null) {
if (actualValue instanceof DeleteVersionValue) {
assertTrue(v.version <= actualValue.version); // deletes can be the same version
} else {
assertTrue(v.version < actualValue.version);
}
}
}
});
if (randomBoolean()) {
Thread.yield();
}
} while (done.getCount() != 0);
for (int j = 0; j < threads.length; j++) {
threads[j].join();
}
map.getAllCurrent().forEach((k, v) -> {
VersionValue versionValue = values.get(k);
assertNotNull(versionValue);
assertEquals(v, versionValue);
});
Runnable assertTombstones = () -> map.getAllTombstones().entrySet().forEach(e -> {
VersionValue versionValue = values.get(e.getKey());
assertNotNull(versionValue);
assertEquals(e.getValue(), versionValue);
assertTrue(versionValue instanceof DeleteVersionValue);
});
assertTombstones.run();
map.beforeRefresh();
assertTombstones.run();
map.afterRefresh(false);
assertTombstones.run();
deletes.entrySet().forEach(e -> {
try (Releasable r = map.acquireLock(e.getKey())) {
VersionValue value = map.getUnderLock(e.getKey());
// here we keep track of the deletes and ensure that all deletes that are not visible anymore ie. not in the map
// have a timestamp that is smaller or equal to the maximum timestamp that we pruned on
final DeleteVersionValue delete = e.getValue();
if (value == null) {
assertTrue(
delete.time + " > " + lastPrunedTimestamp.get() + "," + delete.seqNo + " > " + lastPrunedSeqNo.get(),
delete.time <= lastPrunedTimestamp.get() && delete.seqNo <= lastPrunedSeqNo.get()
);
} else {
assertEquals(value, delete);
}
}
});
map.pruneTombstones(clock.incrementAndGet(), maxSeqNo.get());
assertThat(map.getAllTombstones().entrySet(), empty());
}
public void testCarryOnSafeAccess() throws IOException {
LiveVersionMap map = new LiveVersionMap();
assertFalse(map.isUnsafe());
assertFalse(map.isSafeAccessRequired());
map.enforceSafeAccess();
assertTrue(map.isSafeAccessRequired());
assertFalse(map.isUnsafe());
int numIters = randomIntBetween(1, 5);
for (int i = 0; i < numIters; i++) { // if we don't do anything ie. no adds etc we will stay with the safe access required
map.beforeRefresh();
map.afterRefresh(randomBoolean());
assertTrue("failed in iter: " + i, map.isSafeAccessRequired());
}
try (Releasable r = map.acquireLock(uid(""))) {
map.maybePutIndexUnderLock(new BytesRef(""), randomIndexVersionValue());
}
assertFalse(map.isUnsafe());
assertEquals(1, map.getAllCurrent().size());
map.beforeRefresh();
map.afterRefresh(randomBoolean());
assertFalse(map.isUnsafe());
assertFalse(map.isSafeAccessRequired());
try (Releasable r = map.acquireLock(uid(""))) {
map.maybePutIndexUnderLock(new BytesRef(""), randomIndexVersionValue());
}
assertTrue(map.isUnsafe());
assertFalse(map.isSafeAccessRequired());
assertEquals(0, map.getAllCurrent().size());
}
public void testRefreshTransition() throws IOException {
LiveVersionMap map = new LiveVersionMap();
try (Releasable r = map.acquireLock(uid("1"))) {
map.maybePutIndexUnderLock(uid("1"), randomIndexVersionValue());
assertTrue(map.isUnsafe());
assertNull(map.getUnderLock(uid("1")));
map.beforeRefresh();
assertTrue(map.isUnsafe());
assertNull(map.getUnderLock(uid("1")));
map.afterRefresh(randomBoolean());
assertNull(map.getUnderLock(uid("1")));
assertFalse(map.isUnsafe());
map.enforceSafeAccess();
map.maybePutIndexUnderLock(uid("1"), randomIndexVersionValue());
assertFalse(map.isUnsafe());
assertNotNull(map.getUnderLock(uid("1")));
map.beforeRefresh();
assertFalse(map.isUnsafe());
assertTrue(map.isSafeAccessRequired());
assertNotNull(map.getUnderLock(uid("1")));
map.afterRefresh(randomBoolean());
assertNull(map.getUnderLock(uid("1")));
assertFalse(map.isUnsafe());
assertTrue(map.isSafeAccessRequired());
}
}
public void testAddAndDeleteRefreshConcurrently() throws IOException, InterruptedException {
LiveVersionMap map = new LiveVersionMap();
int numIters = randomIntBetween(1000, 5000);
AtomicBoolean done = new AtomicBoolean(false);
AtomicLong version = new AtomicLong();
CountDownLatch start = new CountDownLatch(2);
BytesRef uid = uid("1");
VersionValue initialVersion;
try (Releasable ignore = map.acquireLock(uid)) {
initialVersion = new IndexVersionValue(randomTranslogLocation(), version.incrementAndGet(), 1, 1);
map.putIndexUnderLock(uid, (IndexVersionValue) initialVersion);
}
Thread t = new Thread(() -> {
start.countDown();
try {
start.await();
VersionValue nextVersionValue = initialVersion;
for (int i = 0; i < numIters; i++) {
try (Releasable ignore = map.acquireLock(uid)) {
VersionValue underLock = map.getUnderLock(uid);
if (underLock != null) {
assertEquals(underLock, nextVersionValue);
} else {
underLock = nextVersionValue;
}
if (underLock.isDelete() || randomBoolean()) {
nextVersionValue = new IndexVersionValue(randomTranslogLocation(), version.incrementAndGet(), 1, 1);
map.putIndexUnderLock(uid, (IndexVersionValue) nextVersionValue);
} else {
nextVersionValue = new DeleteVersionValue(version.incrementAndGet(), 1, 1, 0);
map.putDeleteUnderLock(uid, (DeleteVersionValue) nextVersionValue);
}
}
}
} catch (Exception e) {
throw new AssertionError(e);
} finally {
done.set(true);
}
});
t.start();
start.countDown();
while (done.get() == false) {
map.beforeRefresh();
Thread.yield();
map.afterRefresh(false);
}
t.join();
try (Releasable ignore = map.acquireLock(uid)) {
VersionValue underLock = map.getUnderLock(uid);
if (underLock != null) {
assertEquals(version.get(), underLock.version);
}
}
}
public void testPruneTombstonesWhileLocked() throws InterruptedException, IOException {
LiveVersionMap map = new LiveVersionMap();
BytesRef uid = uid("1");
try (Releasable ignore = map.acquireLock(uid)) {
map.putDeleteUnderLock(uid, new DeleteVersionValue(0, 0, 0, 0));
map.beforeRefresh(); // refresh otherwise we won't prune since it's tracked by the current map
map.afterRefresh(false);
Thread thread = new Thread(() -> { map.pruneTombstones(Long.MAX_VALUE, 0); });
thread.start();
thread.join();
assertEquals(1, map.getAllTombstones().size());
}
Thread thread = new Thread(() -> { map.pruneTombstones(Long.MAX_VALUE, 0); });
thread.start();
thread.join();
assertEquals(0, map.getAllTombstones().size());
}
public void testRandomlyIndexDeleteAndRefresh() throws Exception {
final LiveVersionMap versionMap = new LiveVersionMap();
final BytesRef uid = uid("1");
final long versions = between(10, 1000);
VersionValue latestVersion = null;
for (long i = 0; i < versions; i++) {
if (randomBoolean()) {
versionMap.beforeRefresh();
versionMap.afterRefresh(randomBoolean());
}
if (randomBoolean()) {
versionMap.enforceSafeAccess();
}
try (Releasable ignore = versionMap.acquireLock(uid)) {
if (randomBoolean()) {
latestVersion = new DeleteVersionValue(randomNonNegativeLong(), randomLong(), randomLong(), randomLong());
versionMap.putDeleteUnderLock(uid, (DeleteVersionValue) latestVersion);
assertThat(versionMap.getUnderLock(uid), equalTo(latestVersion));
} else if (randomBoolean()) {
latestVersion = new IndexVersionValue(randomTranslogLocation(), randomNonNegativeLong(), randomLong(), randomLong());
versionMap.maybePutIndexUnderLock(uid, (IndexVersionValue) latestVersion);
if (versionMap.isSafeAccessRequired()) {
assertThat(versionMap.getUnderLock(uid), equalTo(latestVersion));
} else {
assertThat(versionMap.getUnderLock(uid), nullValue());
}
}
if (versionMap.getUnderLock(uid) != null) {
assertThat(versionMap.getUnderLock(uid), equalTo(latestVersion));
}
}
}
}
public void testVersionLookupRamBytesUsed() {
var vl = new LiveVersionMap.VersionLookup(newConcurrentMapWithAggressiveConcurrency());
assertEquals(0, vl.ramBytesUsed());
Set<BytesRef> existingKeys = new HashSet<>();
Supplier<Tuple<BytesRef, IndexVersionValue>> randomEntry = () -> {
var key = randomBoolean() || existingKeys.isEmpty() ? uid(randomIdentifier()) : randomFrom(existingKeys);
return tuple(key, randomIndexVersionValue());
};
IntStream.range(0, randomIntBetween(10, 100)).forEach(i -> {
switch (randomIntBetween(0, 2)) {
case 0: // put
var entry = randomEntry.get();
var previousValue = vl.put(entry.v1(), entry.v2());
if (existingKeys.contains(entry.v1())) {
assertNotNull(previousValue);
} else {
assertNull(previousValue);
existingKeys.add(entry.v1());
}
break;
case 1: // remove
if (existingKeys.isEmpty() == false) {
var key = randomFrom(existingKeys);
assertNotNull(vl.remove(key));
existingKeys.remove(key);
}
break;
case 2: // merge
var toMerge = new LiveVersionMap.VersionLookup(ConcurrentCollections.newConcurrentMapWithAggressiveConcurrency());
IntStream.range(0, randomIntBetween(1, 100))
.mapToObj(n -> randomEntry.get())
.forEach(kv -> toMerge.put(kv.v1(), kv.v2()));
vl.merge(toMerge);
existingKeys.addAll(toMerge.getMap().keySet());
break;
default:
throw new IllegalStateException("branch value unexpected");
}
});
long actualRamBytesUsed = vl.getMap()
.entrySet()
.stream()
.mapToLong(entry -> LiveVersionMap.VersionLookup.mapEntryBytesUsed(entry.getKey(), entry.getValue()))
.sum();
assertEquals(actualRamBytesUsed, vl.ramBytesUsed());
}
public void testVersionMapReclaimableRamBytes() throws IOException {
LiveVersionMap map = new LiveVersionMap();
assertEquals(map.ramBytesUsedForRefresh(), 0L);
assertEquals(map.reclaimableRefreshRamBytes(), 0L);
IntStream.range(0, randomIntBetween(10, 100)).forEach(i -> {
BytesRefBuilder uid = new BytesRefBuilder();
uid.copyChars(TestUtil.randomSimpleString(random(), 10, 20));
try (Releasable r = map.acquireLock(uid.toBytesRef())) {
map.putIndexUnderLock(uid.toBytesRef(), randomIndexVersionValue());
}
});
assertThat(map.reclaimableRefreshRamBytes(), greaterThan(0L));
assertEquals(map.reclaimableRefreshRamBytes(), map.ramBytesUsedForRefresh());
map.beforeRefresh();
assertEquals(map.reclaimableRefreshRamBytes(), 0L);
assertThat(map.ramBytesUsedForRefresh(), greaterThan(0L));
map.afterRefresh(randomBoolean());
assertEquals(map.reclaimableRefreshRamBytes(), 0L);
assertEquals(map.ramBytesUsedForRefresh(), 0L);
}
}
| LiveVersionMapTests |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/math/CopySignDoubleEvaluator.java | {
"start": 1089,
"end": 5105
} | class ____ implements EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(CopySignDoubleEvaluator.class);
private final Source source;
private final EvalOperator.ExpressionEvaluator magnitude;
private final EvalOperator.ExpressionEvaluator sign;
private final DriverContext driverContext;
private Warnings warnings;
public CopySignDoubleEvaluator(Source source, EvalOperator.ExpressionEvaluator magnitude,
EvalOperator.ExpressionEvaluator sign, DriverContext driverContext) {
this.source = source;
this.magnitude = magnitude;
this.sign = sign;
this.driverContext = driverContext;
}
@Override
public Block eval(Page page) {
try (DoubleBlock magnitudeBlock = (DoubleBlock) magnitude.eval(page)) {
try (DoubleBlock signBlock = (DoubleBlock) sign.eval(page)) {
DoubleVector magnitudeVector = magnitudeBlock.asVector();
if (magnitudeVector == null) {
return eval(page.getPositionCount(), magnitudeBlock, signBlock);
}
DoubleVector signVector = signBlock.asVector();
if (signVector == null) {
return eval(page.getPositionCount(), magnitudeBlock, signBlock);
}
return eval(page.getPositionCount(), magnitudeVector, signVector).asBlock();
}
}
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += magnitude.baseRamBytesUsed();
baseRamBytesUsed += sign.baseRamBytesUsed();
return baseRamBytesUsed;
}
public DoubleBlock eval(int positionCount, DoubleBlock magnitudeBlock, DoubleBlock signBlock) {
try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
switch (magnitudeBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
switch (signBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
double magnitude = magnitudeBlock.getDouble(magnitudeBlock.getFirstValueIndex(p));
double sign = signBlock.getDouble(signBlock.getFirstValueIndex(p));
result.appendDouble(CopySign.processDouble(magnitude, sign));
}
return result.build();
}
}
public DoubleVector eval(int positionCount, DoubleVector magnitudeVector,
DoubleVector signVector) {
try(DoubleVector.FixedBuilder result = driverContext.blockFactory().newDoubleVectorFixedBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
double magnitude = magnitudeVector.getDouble(p);
double sign = signVector.getDouble(p);
result.appendDouble(p, CopySign.processDouble(magnitude, sign));
}
return result.build();
}
}
@Override
public String toString() {
return "CopySignDoubleEvaluator[" + "magnitude=" + magnitude + ", sign=" + sign + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(magnitude, sign);
}
private Warnings warnings() {
if (warnings == null) {
this.warnings = Warnings.createWarnings(
driverContext.warningsMode(),
source.source().getLineNumber(),
source.source().getColumnNumber(),
source.text()
);
}
return warnings;
}
static | CopySignDoubleEvaluator |
java | grpc__grpc-java | xds/src/main/java/io/grpc/xds/HttpConnectionManager.java | {
"start": 981,
"end": 2596
} | class ____ {
// Total number of nanoseconds to keep alive an HTTP request/response stream.
abstract long httpMaxStreamDurationNano();
// Name of the route configuration to be used for RDS resource discovery.
@Nullable
abstract String rdsName();
// List of virtual hosts that make up the route table.
@Nullable
abstract ImmutableList<VirtualHost> virtualHosts();
// List of http filter configs. Null if HttpFilter support is not enabled.
@Nullable
abstract ImmutableList<NamedFilterConfig> httpFilterConfigs();
static HttpConnectionManager forRdsName(long httpMaxStreamDurationNano, String rdsName,
@Nullable List<NamedFilterConfig> httpFilterConfigs) {
checkNotNull(rdsName, "rdsName");
return create(httpMaxStreamDurationNano, rdsName, null, httpFilterConfigs);
}
static HttpConnectionManager forVirtualHosts(long httpMaxStreamDurationNano,
List<VirtualHost> virtualHosts, @Nullable List<NamedFilterConfig> httpFilterConfigs) {
checkNotNull(virtualHosts, "virtualHosts");
return create(httpMaxStreamDurationNano, null, virtualHosts,
httpFilterConfigs);
}
private static HttpConnectionManager create(long httpMaxStreamDurationNano,
@Nullable String rdsName, @Nullable List<VirtualHost> virtualHosts,
@Nullable List<NamedFilterConfig> httpFilterConfigs) {
return new AutoValue_HttpConnectionManager(
httpMaxStreamDurationNano, rdsName,
virtualHosts == null ? null : ImmutableList.copyOf(virtualHosts),
httpFilterConfigs == null ? null : ImmutableList.copyOf(httpFilterConfigs));
}
}
| HttpConnectionManager |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java | {
"start": 146293,
"end": 148991
} | interface ____<T> {
void accept(StatisticsData data);
T aggregate();
}
private final String scheme;
/**
* rootData is data that doesn't belong to any thread, but will be added
* to the totals. This is useful for making copies of Statistics objects,
* and for storing data that pertains to threads that have been garbage
* collected. Protected by the Statistics lock.
*/
private final StatisticsData rootData;
/**
* Thread-local data.
*/
@SuppressWarnings("ThreadLocalNotStaticFinal")
private final ThreadLocal<StatisticsData> threadData;
/**
* Set of all thread-local data areas. Protected by the Statistics lock.
* The references to the statistics data are kept using weak references
* to the associated threads. Proper clean-up is performed by the cleaner
* thread when the threads are garbage collected.
*/
private final Set<StatisticsDataReference> allData;
/**
* Global reference queue and a cleaner thread that manage statistics data
* references from all filesystem instances.
*/
private static final ReferenceQueue<Thread> STATS_DATA_REF_QUEUE;
private static final Thread STATS_DATA_CLEANER;
static {
STATS_DATA_REF_QUEUE = new ReferenceQueue<>();
// start a single daemon cleaner thread
STATS_DATA_CLEANER = new SubjectInheritingThread(new StatisticsDataReferenceCleaner());
STATS_DATA_CLEANER.
setName(StatisticsDataReferenceCleaner.class.getName());
STATS_DATA_CLEANER.setDaemon(true);
STATS_DATA_CLEANER.setContextClassLoader(null);
STATS_DATA_CLEANER.start();
}
public Statistics(String scheme) {
this.scheme = scheme;
this.rootData = new StatisticsData();
this.threadData = new ThreadLocal<>();
this.allData = new HashSet<>();
}
/**
* Copy constructor.
*
* @param other The input Statistics object which is cloned.
*/
public Statistics(Statistics other) {
this.scheme = other.scheme;
this.rootData = new StatisticsData();
other.visitAll(new StatisticsAggregator<Void>() {
@Override
public void accept(StatisticsData data) {
rootData.add(data);
}
public Void aggregate() {
return null;
}
});
this.threadData = new ThreadLocal<>();
this.allData = new HashSet<>();
}
/**
* A weak reference to a thread that also includes the data associated
* with that thread. On the thread being garbage collected, it is enqueued
* to the reference queue for clean-up.
*/
private final | StatisticsAggregator |
java | quarkusio__quarkus | extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/security/DuplicatedContextSecurityIdentityAssociation.java | {
"start": 602,
"end": 2787
} | class ____ extends AbstractSecurityIdentityAssociation {
private IdentityProviderManager identityProviderManager;
@Inject
public DuplicatedContextSecurityIdentityAssociation setIdentityProviderManager(
IdentityProviderManager identityProviderManager) {
this.identityProviderManager = identityProviderManager;
return this;
}
@Override
protected IdentityProviderManager getIdentityProviderManager() {
return identityProviderManager;
}
@Override
public Uni<SecurityIdentity> getDeferredIdentity() {
RoutingContext routingContext = getRoutingContext();
if (routingContext != null) {
SecurityIdentity securityIdentity = getSecurityIdentityFromCtx(routingContext);
if (securityIdentity != null) {
return Uni.createFrom().item(securityIdentity);
}
Uni<SecurityIdentity> identityUni = routingContext.get(DEFERRED_IDENTITY_KEY);
if (identityUni != null) {
return identityUni;
}
}
return super.getDeferredIdentity();
}
@Override
public SecurityIdentity getIdentity() {
RoutingContext routingContext = getRoutingContext();
if (routingContext != null) {
SecurityIdentity securityIdentity = getSecurityIdentityFromCtx(routingContext);
if (securityIdentity != null) {
return securityIdentity;
}
securityIdentity = QuarkusHttpUser.getSecurityIdentityBlocking(routingContext, null);
if (securityIdentity != null) {
return securityIdentity;
}
}
return super.getIdentity();
}
private static SecurityIdentity getSecurityIdentityFromCtx(RoutingContext routingContext) {
if (routingContext.user() instanceof QuarkusHttpUser quarkusHttpUser) {
return quarkusHttpUser.getSecurityIdentity();
}
return null;
}
private static RoutingContext getRoutingContext() {
return ContextLocals.get(HttpSecurityUtils.ROUTING_CONTEXT_ATTRIBUTE, null);
}
}
| DuplicatedContextSecurityIdentityAssociation |
java | dropwizard__dropwizard | dropwizard-metrics/src/main/java/io/dropwizard/metrics/common/MetricsFactory.java | {
"start": 1359,
"end": 3909
} | class ____ {
private static final Logger LOGGER = LoggerFactory.getLogger(MetricsFactory.class);
@Valid
@NotNull
private Duration frequency = Duration.minutes(1);
@Valid
@NotNull
private List<ReporterFactory> reporters = Collections.emptyList();
private boolean reportOnStop = false;
@JsonProperty
public List<ReporterFactory> getReporters() {
return reporters;
}
@JsonProperty
public void setReporters(List<ReporterFactory> reporters) {
this.reporters = new ArrayList<>(reporters);
}
@JsonProperty
public Duration getFrequency() {
return frequency;
}
@JsonProperty
public void setFrequency(Duration frequency) {
this.frequency = frequency;
}
/**
* @since 2.0
*/
@JsonProperty
public boolean isReportOnStop() {
return reportOnStop;
}
/**
* @since 2.0
*/
@JsonProperty
public void setReportOnStop(boolean reportOnStop) {
this.reportOnStop = reportOnStop;
}
/**
* Configures the given lifecycle with the {@link com.codahale.metrics.ScheduledReporter
* reporters} configured for the given registry.
* <p />
* The reporters are tied in to the given lifecycle, such that their {@link #getFrequency()
* frequency} for reporting metrics begins when the lifecycle {@link
* io.dropwizard.lifecycle.Managed#start() starts}, and stops when the lifecycle
* {@link io.dropwizard.lifecycle.Managed#stop() stops}.
*
* @param environment the lifecycle to manage the reporters.
* @param registry the metric registry to report metrics from.
*/
public void configure(LifecycleEnvironment environment, MetricRegistry registry) {
for (ReporterFactory reporter : reporters) {
try {
final ScheduledReporterManager manager =
new ScheduledReporterManager(reporter.build(registry),
reporter.getFrequency().orElseGet(this::getFrequency),
isReportOnStop());
environment.manage(manager);
} catch (Exception e) {
LOGGER.warn("Failed to create reporter, metrics may not be properly reported.", e);
}
}
}
@Override
public String toString() {
return "MetricsFactory{frequency=" + frequency + ", reporters=" + reporters + ", reportOnStop=" + reportOnStop + '}';
}
}
| MetricsFactory |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebProperties.java | {
"start": 7438,
"end": 8563
} | class ____ {
private boolean customized;
/**
* Whether to enable the fixed Version Strategy.
*/
private boolean enabled;
/**
* List of patterns to apply to the fixed Version Strategy.
*/
private String[] paths = new String[] { "/**" };
/**
* Version string to use for the fixed Version Strategy.
*/
private @Nullable String version;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.customized = true;
this.enabled = enabled;
}
public String[] getPaths() {
return this.paths;
}
public void setPaths(String[] paths) {
this.customized = true;
this.paths = paths;
}
public @Nullable String getVersion() {
return this.version;
}
public void setVersion(@Nullable String version) {
this.customized = true;
this.version = version;
}
private boolean hasBeenCustomized() {
return this.customized;
}
}
}
}
/**
* Cache configuration.
*/
public static | Fixed |
java | apache__camel | test-infra/camel-test-infra-kafka/src/main/java/org/apache/camel/test/infra/kafka/services/RemoteKafkaInfraService.java | {
"start": 987,
"end": 1687
} | class ____ implements KafkaInfraService {
private static final Logger LOG = LoggerFactory.getLogger(RemoteKafkaInfraService.class);
@Override
public String getBootstrapServers() {
return System.getProperty(KafkaProperties.KAFKA_BOOTSTRAP_SERVERS);
}
@Override
public String brokers() {
return getBootstrapServers();
}
@Override
public void registerProperties() {
// NO-OP
}
@Override
public void initialize() {
registerProperties();
LOG.info("Kafka bootstrap server running at address {}", getBootstrapServers());
}
@Override
public void shutdown() {
// NO-OP
}
}
| RemoteKafkaInfraService |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/testers/ListAddAllAtIndexTester.java | {
"start": 1993,
"end": 6593
} | class ____<E> extends AbstractListTester<E> {
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAllAtIndex_supportedAllPresent() {
assertTrue(
"addAll(n, allPresent) should return true",
getList().addAll(0, MinimalCollection.of(e0())));
expectAdded(0, e0());
}
@ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAllAtIndex_unsupportedAllPresent() {
assertThrows(
UnsupportedOperationException.class, () -> getList().addAll(0, MinimalCollection.of(e0())));
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAllAtIndex_supportedSomePresent() {
assertTrue(
"addAll(n, allPresent) should return true",
getList().addAll(0, MinimalCollection.of(e0(), e3())));
expectAdded(0, e0(), e3());
}
@ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAllAtIndex_unsupportedSomePresent() {
assertThrows(
UnsupportedOperationException.class,
() -> getList().addAll(0, MinimalCollection.of(e0(), e3())));
expectUnchanged();
expectMissing(e3());
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAllAtIndex_supportedNothing() {
assertFalse("addAll(n, nothing) should return false", getList().addAll(0, emptyCollection()));
expectUnchanged();
}
@ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX)
public void testAddAllAtIndex_unsupportedNothing() {
try {
assertFalse(
"addAll(n, nothing) should return false or throw",
getList().addAll(0, emptyCollection()));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAllAtIndex_withDuplicates() {
MinimalCollection<E> elementsToAdd = MinimalCollection.of(e0(), e1(), e0(), e1());
assertTrue("addAll(n, hasDuplicates) should return true", getList().addAll(0, elementsToAdd));
expectAdded(0, e0(), e1(), e0(), e1());
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testAddAllAtIndex_nullSupported() {
List<E> containsNull = singletonList(null);
assertTrue("addAll(n, containsNull) should return true", getList().addAll(0, containsNull));
/*
* We need (E) to force interpretation of null as the single element of a
* varargs array, not the array itself
*/
expectAdded(0, (E) null);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testAddAllAtIndex_nullUnsupported() {
List<E> containsNull = singletonList(null);
assertThrows(NullPointerException.class, () -> getList().addAll(0, containsNull));
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported addAll(n, containsNull)");
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testAddAllAtIndex_middle() {
assertTrue(
"addAll(middle, disjoint) should return true",
getList().addAll(getNumElements() / 2, createDisjointCollection()));
expectAdded(getNumElements() / 2, createDisjointCollection());
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAllAtIndex_end() {
assertTrue(
"addAll(end, disjoint) should return true",
getList().addAll(getNumElements(), createDisjointCollection()));
expectAdded(getNumElements(), createDisjointCollection());
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAllAtIndex_nullCollectionReference() {
assertThrows(NullPointerException.class, () -> getList().addAll(0, null));
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAllAtIndex_negative() {
assertThrows(
IndexOutOfBoundsException.class, () -> getList().addAll(-1, MinimalCollection.of(e3())));
expectUnchanged();
expectMissing(e3());
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAllAtIndex_tooLarge() {
assertThrows(
IndexOutOfBoundsException.class,
() -> getList().addAll(getNumElements() + 1, MinimalCollection.of(e3())));
expectUnchanged();
expectMissing(e3());
}
}
| ListAddAllAtIndexTester |
java | apache__camel | components/camel-kubernetes/src/generated/java/org/apache/camel/component/kubernetes/persistent_volumes_claims/KubernetesPersistentVolumesClaimsEndpointUriFactory.java | {
"start": 546,
"end": 3464
} | class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = ":masterUrl";
private static final Set<String> PROPERTY_NAMES;
private static final Set<String> SECRET_PROPERTY_NAMES;
private static final Map<String, String> MULTI_VALUE_PREFIXES;
static {
Set<String> props = new HashSet<>(22);
props.add("apiVersion");
props.add("caCertData");
props.add("caCertFile");
props.add("clientCertData");
props.add("clientCertFile");
props.add("clientKeyAlgo");
props.add("clientKeyData");
props.add("clientKeyFile");
props.add("clientKeyPassphrase");
props.add("connectionTimeout");
props.add("dnsDomain");
props.add("kubernetesClient");
props.add("lazyStartProducer");
props.add("masterUrl");
props.add("namespace");
props.add("oauthToken");
props.add("operation");
props.add("password");
props.add("portName");
props.add("portProtocol");
props.add("trustCerts");
props.add("username");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
Set<String> secretProps = new HashSet<>(12);
secretProps.add("caCertData");
secretProps.add("caCertFile");
secretProps.add("clientCertData");
secretProps.add("clientCertFile");
secretProps.add("clientKeyAlgo");
secretProps.add("clientKeyData");
secretProps.add("clientKeyFile");
secretProps.add("clientKeyPassphrase");
secretProps.add("oauthToken");
secretProps.add("password");
secretProps.add("trustCerts");
secretProps.add("username");
SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps);
MULTI_VALUE_PREFIXES = Collections.emptyMap();
}
@Override
public boolean isEnabled(String scheme) {
return "kubernetes-persistent-volumes-claims".equals(scheme);
}
@Override
public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException {
String syntax = scheme + BASE;
String uri = syntax;
Map<String, Object> copy = new HashMap<>(properties);
uri = buildPathParameter(syntax, uri, "masterUrl", null, true, copy);
uri = buildQueryParameters(uri, copy, encode);
return uri;
}
@Override
public Set<String> propertyNames() {
return PROPERTY_NAMES;
}
@Override
public Set<String> secretPropertyNames() {
return SECRET_PROPERTY_NAMES;
}
@Override
public Map<String, String> multiValuePrefixes() {
return MULTI_VALUE_PREFIXES;
}
@Override
public boolean isLenientProperties() {
return false;
}
}
| KubernetesPersistentVolumesClaimsEndpointUriFactory |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToRadians.java | {
"start": 1529,
"end": 3717
} | class ____ extends AbstractConvertFunction implements EvaluatorMapper {
public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(
Expression.class,
"ToRadians",
ToRadians::new
);
private static final Map<DataType, BuildFactory> EVALUATORS = Map.ofEntries(
Map.entry(DOUBLE, ToRadiansEvaluator.Factory::new),
Map.entry(INTEGER, (source, field) -> new ToRadiansEvaluator.Factory(source, new ToDoubleFromIntEvaluator.Factory(source, field))),
Map.entry(LONG, (source, field) -> new ToRadiansEvaluator.Factory(source, new ToDoubleFromLongEvaluator.Factory(source, field))),
Map.entry(
UNSIGNED_LONG,
(source, field) -> new ToRadiansEvaluator.Factory(source, new ToDoubleFromUnsignedLongEvaluator.Factory(source, field))
)
);
@FunctionInfo(
returnType = "double",
description = "Converts a number in {wikipedia}/Degree_(angle)[degrees] to {wikipedia}/Radian[radians].",
examples = @Example(file = "floats", tag = "to_radians")
)
public ToRadians(
Source source,
@Param(
name = "number",
type = { "double", "integer", "long", "unsigned_long" },
description = "Input value. The input can be a single- or multi-valued column or an expression."
) Expression field
) {
super(source, field);
}
private ToRadians(StreamInput in) throws IOException {
super(in);
}
@Override
public String getWriteableName() {
return ENTRY.name;
}
@Override
protected Map<DataType, BuildFactory> factories() {
return EVALUATORS;
}
@Override
public Expression replaceChildren(List<Expression> newChildren) {
return new ToRadians(source(), newChildren.get(0));
}
@Override
protected NodeInfo<? extends Expression> info() {
return NodeInfo.create(this, ToRadians::new, field());
}
@Override
public DataType dataType() {
return DOUBLE;
}
@ConvertEvaluator
static double process(double deg) {
return Math.toRadians(deg);
}
}
| ToRadians |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ElementCollectionMapUpdateTest.java | {
"start": 1234,
"end": 2550
} | class ____ {
private static final String NAME = "S&P500";
private static final Currency USD = Currency.getInstance( "USD" );
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final Company parent = new Company( 1L );
parent.add( new MarketData( NAME, new Amount( 1d, USD ), new Amount( 1_000d, USD ) ) );
session.persist( parent );
} );
}
@AfterAll
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction( session -> session.createMutationQuery( "delete from Company" ).executeUpdate() );
}
@Test
public void testElementCollectionUpdate(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final Company company = session.find( Company.class, 1L );
company.add( new MarketData( NAME, new Amount( 1d, USD ), new Amount( 1_000d, USD ) ) );
} );
scope.inTransaction( session -> {
final Company company = session.find( Company.class, 1L );
assertThat( company.getData() ).hasSize( 1 );
assertThat( company.getData() ).containsKey( NAME );
assertThat( company.getData().get( NAME ).getPrice().getValue() ).isEqualTo( 1d );
assertThat( company.getData().get( NAME ).getCapitalization().getValue() ).isEqualTo( 1_000d );
} );
}
@Entity( name = "Company" )
public static | ElementCollectionMapUpdateTest |
java | apache__camel | components/camel-openstack/src/main/java/org/apache/camel/component/openstack/swift/producer/ObjectProducer.java | {
"start": 1710,
"end": 6561
} | class ____ extends AbstractOpenstackProducer {
public ObjectProducer(SwiftEndpoint endpoint, OSClient client) {
super(endpoint, client);
}
@Override
public void process(Exchange exchange) throws Exception {
String operation = getOperation(exchange);
switch (operation) {
case OpenstackConstants.CREATE:
doCreate(exchange);
break;
case OpenstackConstants.GET:
doGet(exchange);
break;
case OpenstackConstants.GET_ALL:
doGetAll(exchange);
break;
case OpenstackConstants.DELETE:
doDelete(exchange);
break;
case SwiftConstants.GET_METADATA:
doGetMetadata(exchange);
break;
case SwiftConstants.CREATE_UPDATE_METADATA:
doUpdateMetadata(exchange);
break;
default:
throw new IllegalArgumentException("Unsupported operation " + operation);
}
}
private void doCreate(Exchange exchange) {
final Message msg = exchange.getIn();
final Payload payload = createPayload(msg);
final String containerName = msg.getHeader(SwiftConstants.CONTAINER_NAME, String.class);
final String objectName = msg.getHeader(SwiftConstants.OBJECT_NAME, String.class);
StringHelper.notEmpty(containerName, "Container name");
StringHelper.notEmpty(objectName, "Object name");
final String etag = os.objectStorage().objects().put(containerName, objectName, payload);
msg.setBody(etag);
}
private void doGet(Exchange exchange) {
final Message msg = exchange.getIn();
final String containerName = msg.getHeader(SwiftConstants.CONTAINER_NAME, String.class);
final String objectName = msg.getHeader(SwiftConstants.OBJECT_NAME, String.class);
StringHelper.notEmpty(containerName, "Container name");
StringHelper.notEmpty(objectName, "Object name");
final SwiftObject out = os.objectStorage().objects().get(containerName, objectName);
msg.setBody(out);
}
private void doGetAll(Exchange exchange) {
final Message msg = exchange.getIn();
final String name = msg.getHeader(SwiftConstants.CONTAINER_NAME, msg.getHeader(OpenstackConstants.NAME, String.class),
String.class);
StringHelper.notEmpty(name, "Container name");
final String path = msg.getHeader(SwiftConstants.PATH, String.class);
List<? extends SwiftObject> out;
if (path != null) {
StringHelper.notEmpty(path, "Path");
ObjectListOptions objectListOptions = ObjectListOptions.create();
objectListOptions.startsWith(path).delimiter('/');
out = os.objectStorage().objects().list(name, objectListOptions);
} else {
out = os.objectStorage().objects().list(name);
}
exchange.getIn().setBody(out);
}
private void doDelete(Exchange exchange) {
final Message msg = exchange.getIn();
final String containerName = msg.getHeader(SwiftConstants.CONTAINER_NAME, String.class);
final String objectName = msg.getHeader(SwiftConstants.OBJECT_NAME, String.class);
StringHelper.notEmpty(containerName, "Container name");
StringHelper.notEmpty(objectName, "Object name");
final ActionResponse out = os.objectStorage().objects().delete(containerName, objectName);
checkFailure(out, exchange, "Delete container");
}
private void doGetMetadata(Exchange exchange) {
final Message msg = exchange.getIn();
final String containerName = msg.getHeader(SwiftConstants.CONTAINER_NAME, String.class);
final String objectName = msg.getHeader(SwiftConstants.OBJECT_NAME, String.class);
StringHelper.notEmpty(containerName, "Container name");
StringHelper.notEmpty(objectName, "Object name");
msg.setBody(os.objectStorage().objects().getMetadata(containerName, objectName));
}
private void doUpdateMetadata(Exchange exchange) {
final Message msg = exchange.getIn();
final String containerName = msg.getHeader(SwiftConstants.CONTAINER_NAME, String.class);
final String objectName = msg.getHeader(SwiftConstants.OBJECT_NAME, String.class);
StringHelper.notEmpty(containerName, "Container name");
StringHelper.notEmpty(objectName, "Object name");
final boolean success = os.objectStorage().objects().updateMetadata(ObjectLocation.create(containerName, objectName),
msg.getBody(Map.class));
if (!success) {
exchange.setException(new OpenstackException("Updating metadata was not successful"));
}
}
}
| ObjectProducer |
java | google__gson | gson/src/test/java/com/google/gson/ParameterizedTypeFixtures.java | {
"start": 3391,
"end": 5416
} | class ____<T>
implements JsonSerializer<MyParameterizedType<T>>, JsonDeserializer<MyParameterizedType<T>> {
@SuppressWarnings("unchecked")
public static <T> String getExpectedJson(MyParameterizedType<T> obj) {
Class<T> clazz = (Class<T>) obj.value.getClass();
boolean addQuotes = !clazz.isArray() && !Primitives.unwrap(clazz).isPrimitive();
StringBuilder sb = new StringBuilder("{\"");
sb.append(obj.value.getClass().getSimpleName()).append("\":");
if (addQuotes) {
sb.append("\"");
}
sb.append(obj.value.toString());
if (addQuotes) {
sb.append("\"");
}
sb.append("}");
return sb.toString();
}
@Override
public JsonElement serialize(
MyParameterizedType<T> src, Type classOfSrc, JsonSerializationContext context) {
JsonObject json = new JsonObject();
T value = src.getValue();
json.add(value.getClass().getSimpleName(), context.serialize(value));
return json;
}
@SuppressWarnings("unchecked")
@Override
public MyParameterizedType<T> deserialize(
JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
Type genericClass = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
Class<?> rawType = GsonTypes.getRawType(genericClass);
String className = rawType.getSimpleName();
JsonElement jsonElement = json.getAsJsonObject().get(className);
T value;
if (genericClass == Integer.class) {
value = (T) Integer.valueOf(jsonElement.getAsInt());
} else if (genericClass == String.class) {
value = (T) jsonElement.getAsString();
} else {
value = (T) jsonElement;
}
if (Primitives.isPrimitive(genericClass)) {
PrimitiveTypeAdapter typeAdapter = new PrimitiveTypeAdapter();
value = (T) typeAdapter.adaptType(value, rawType);
}
return new MyParameterizedType<>(value);
}
}
}
| MyParameterizedTypeAdapter |
java | spring-projects__spring-framework | spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java | {
"start": 2045,
"end": 7505
} | class ____ extends AbstractRequestMappingIntegrationTests {
private final HttpHeaders headers = new HttpHeaders();
@Override
protected void startServer(HttpServer httpServer) throws Exception {
super.startServer(httpServer);
this.headers.setOrigin("http://localhost:9000");
}
@Override
protected ApplicationContext initApplicationContext() {
return new AnnotationConfigApplicationContext(WebConfig.class);
}
@Override
protected RestTemplate initRestTemplate() {
// JDK default HTTP client disallowed headers like Origin
return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
@ParameterizedHttpServerTest
void actualRequestWithCorsEnabled(HttpServer httpServer) throws Exception {
startServer(httpServer);
ResponseEntity<String> entity = performGet("/cors", this.headers, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("*");
assertThat(entity.getBody()).isEqualTo("cors");
}
@ParameterizedHttpServerTest
void actualRequestWithCorsRejected(HttpServer httpServer) throws Exception {
startServer(httpServer);
assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() ->
performGet("/cors-restricted", this.headers, String.class))
.satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN));
}
@ParameterizedHttpServerTest
void actualRequestWithoutCorsEnabled(HttpServer httpServer) throws Exception {
startServer(httpServer);
ResponseEntity<String> entity = performGet("/welcome", this.headers, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isNull();
assertThat(entity.getBody()).isEqualTo("welcome");
}
@ParameterizedHttpServerTest
void actualRequestWithAmbiguousMapping(HttpServer httpServer) throws Exception {
startServer(httpServer);
this.headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE);
ResponseEntity<String> entity = performGet("/ambiguous", this.headers, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("*");
}
@ParameterizedHttpServerTest
void preFlightRequestWithCorsEnabled(HttpServer httpServer) throws Exception {
startServer(httpServer);
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
ResponseEntity<String> entity = performOptions("/cors", this.headers, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("*");
assertThat(entity.getHeaders().getAccessControlAllowMethods())
.containsExactly(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.POST);
}
@ParameterizedHttpServerTest
void preFlightRequestWithCorsRejected(HttpServer httpServer) throws Exception {
startServer(httpServer);
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() ->
performOptions("/cors-restricted", this.headers, String.class))
.satisfies(ex -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN));
}
@ParameterizedHttpServerTest
void preFlightRequestWithoutCorsEnabled(HttpServer httpServer) throws Exception {
startServer(httpServer);
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
ResponseEntity<String> entity = performOptions("/welcome", this.headers, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isNull();
assertThat(entity.getHeaders().getAccessControlAllowMethods()).isEmpty();
}
@ParameterizedHttpServerTest
void preFlightRequestWithCorsRestricted(HttpServer httpServer) throws Exception {
startServer(httpServer);
this.headers.set(HttpHeaders.ORIGIN, "https://foo");
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
ResponseEntity<String> entity = performOptions("/cors-restricted", this.headers, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("https://foo");
assertThat(entity.getHeaders().getAccessControlAllowMethods())
.containsExactly(HttpMethod.GET, HttpMethod.POST);
}
@ParameterizedHttpServerTest
void preFlightRequestWithAmbiguousMapping(HttpServer httpServer) throws Exception {
startServer(httpServer);
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
ResponseEntity<String> entity = performOptions("/ambiguous", this.headers, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("*");
assertThat(entity.getHeaders().getAccessControlAllowMethods()).containsExactly(HttpMethod.GET, HttpMethod.POST);
assertThat(entity.getHeaders().getAccessControlAllowCredentials()).isFalse();
assertThat(entity.getHeaders().get(HttpHeaders.VARY))
.containsExactly(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD,
HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
}
@Configuration
@ComponentScan(resourcePattern = "**/GlobalCorsConfigIntegrationTests*.class")
@SuppressWarnings({"unused", "WeakerAccess"})
static | GlobalCorsConfigIntegrationTests |
java | quarkusio__quarkus | devtools/maven/src/main/java/io/quarkus/maven/ListCategoriesMojo.java | {
"start": 493,
"end": 1644
} | class ____ extends QuarkusProjectMojoBase {
private static final String DEFAULT_FORMAT = "concise";
/**
* Select the output format among 'name' (display the name only) and 'full'
* (includes a verbose name and a description).
*/
@Parameter(property = "format", defaultValue = DEFAULT_FORMAT)
protected String format;
@Override
public void doExecute(final QuarkusProject quarkusProject, final MessageWriter log) throws MojoExecutionException {
try {
ListCategories listExtensions = new ListCategories(quarkusProject)
.format(format);
listExtensions.execute();
if (DEFAULT_FORMAT.equalsIgnoreCase(format)) {
log.info("");
log.info(ListCategories.MORE_INFO_HINT, "-Dformat=full");
}
log.info("");
log.info(ListCategories.LIST_EXTENSIONS_HINT,
"`./mvnw quarkus:list-extensions -Dcategory=\"categoryId\"`");
} catch (Exception e) {
throw new MojoExecutionException("Failed to list extension categories", e);
}
}
}
| ListCategoriesMojo |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/CustomSdkSigner.java | {
"start": 5668,
"end": 6293
} | class ____ implements AwsSignerInitializer {
@Override
public void registerStore(
final String bucketName,
final Configuration storeConf,
final DelegationTokenProvider dtProvider,
final UserGroupInformation storeUgi) {
LOG.debug("Registering store for bucket {}", bucketName);
}
@Override
public void unregisterStore(final String bucketName,
final Configuration storeConf,
final DelegationTokenProvider dtProvider,
final UserGroupInformation storeUgi) {
LOG.debug("Unregistering store for bucket {}", bucketName);
}
}
}
| Initializer |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/enums/EnumDefaultReadTest.java | {
"start": 1168,
"end": 1222
} | enum ____ {
A, B, C, Z;
}
| BaseEnumDefault |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-api/src/test/java/org/apache/hadoop/yarn/service/client/TestApiServiceClient.java | {
"start": 1816,
"end": 2080
} | class ____ {
private static ApiServiceClient asc;
private static ApiServiceClient badAsc;
private static Server server;
/**
* A mocked version of API Service for testing purpose.
*
*/
@SuppressWarnings("serial")
public static | TestApiServiceClient |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/protocol/ReplicaRecoveryInfo.java | {
"start": 1205,
"end": 1860
} | class ____ extends Block {
private final ReplicaState originalState;
public ReplicaRecoveryInfo(long blockId, long diskLen, long gs, ReplicaState rState) {
set(blockId, diskLen, gs);
originalState = rState;
}
public ReplicaState getOriginalReplicaState() {
return originalState;
}
@Override
public boolean equals(Object o) {
return super.equals(o);
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
return super.toString() + "[numBytes=" + this.getNumBytes() +
",originalReplicaState=" + this.originalState.name() + "]";
}
}
| ReplicaRecoveryInfo |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/vectors/DiversifyingParentBlockQuery.java | {
"start": 1388,
"end": 3103
} | class ____ extends Query {
private final BitSetProducer parentFilter;
private final Query innerQuery;
public DiversifyingParentBlockQuery(BitSetProducer parentFilter, Query innerQuery) {
this.parentFilter = Objects.requireNonNull(parentFilter);
this.innerQuery = Objects.requireNonNull(innerQuery);
}
@Override
public Query rewrite(IndexSearcher indexSearcher) throws IOException {
Query rewritten = innerQuery.rewrite(indexSearcher);
if (rewritten != innerQuery) {
return new DiversifyingParentBlockQuery(parentFilter, rewritten);
}
return this;
}
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
Weight innerWeight = innerQuery.createWeight(searcher, scoreMode, boost);
return new DiversifyingParentBlockWeight(this, innerWeight, parentFilter);
}
@Override
public String toString(String field) {
return "DiversifyingBlockQuery(inner=" + innerQuery.toString(field) + ")";
}
@Override
public void visit(QueryVisitor visitor) {
innerQuery.visit(visitor.getSubVisitor(BooleanClause.Occur.MUST, this));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DiversifyingParentBlockQuery that = (DiversifyingParentBlockQuery) o;
return Objects.equals(innerQuery, that.innerQuery) && parentFilter == that.parentFilter;
}
@Override
public int hashCode() {
return Objects.hash(innerQuery, parentFilter);
}
private static | DiversifyingParentBlockQuery |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/PromqlBaseParser.java | {
"start": 72981,
"end": 73961
} | class ____ extends NumberContext {
public TerminalNode DECIMAL_VALUE() { return getToken(PromqlBaseParser.DECIMAL_VALUE, 0); }
@SuppressWarnings("this-escape")
public DecimalLiteralContext(NumberContext ctx) { copyFrom(ctx); }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof PromqlBaseParserListener ) ((PromqlBaseParserListener)listener).enterDecimalLiteral(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof PromqlBaseParserListener ) ((PromqlBaseParserListener)listener).exitDecimalLiteral(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof PromqlBaseParserVisitor ) return ((PromqlBaseParserVisitor<? extends T>)visitor).visitDecimalLiteral(this);
else return visitor.visitChildren(this);
}
}
@SuppressWarnings("CheckReturnValue")
public static | DecimalLiteralContext |
java | elastic__elasticsearch | x-pack/plugin/old-lucene-versions/src/main/java/org/elasticsearch/xpack/lucene/bwc/codecs/lucene70/fst/FSTCompiler.java | {
"start": 25270,
"end": 29272
} | class ____<T> implements Node {
final FSTCompiler<T> owner;
int numArcs;
Arc<T>[] arcs;
// TODO: instead of recording isFinal/output on the
// node, maybe we should use -1 arc to mean "end" (like
// we do when reading the FST). Would simplify much
// code here...
T output;
boolean isFinal;
long inputCount;
/** This node's depth, starting from the automaton root. */
final int depth;
/**
* @param depth The node's depth starting from the automaton root. Needed for LUCENE-2934 (node
* expansion based on conditions other than the fanout size).
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
UnCompiledNode(FSTCompiler<T> owner, int depth) {
this.owner = owner;
arcs = (Arc<T>[]) new Arc[1];
arcs[0] = new Arc<>();
output = owner.NO_OUTPUT;
this.depth = depth;
}
@Override
public boolean isCompiled() {
return false;
}
void clear() {
numArcs = 0;
isFinal = false;
output = owner.NO_OUTPUT;
inputCount = 0;
// We don't clear the depth here because it never changes
// for nodes on the frontier (even when reused).
}
T getLastOutput(int labelToMatch) {
assert numArcs > 0;
assert arcs[numArcs - 1].label == labelToMatch;
return arcs[numArcs - 1].output;
}
void addArc(int label, Node target) {
assert label >= 0;
assert numArcs == 0 || label > arcs[numArcs - 1].label
: "arc[numArcs-1].label=" + arcs[numArcs - 1].label + " new label=" + label + " numArcs=" + numArcs;
if (numArcs == arcs.length) {
final Arc<T>[] newArcs = ArrayUtil.grow(arcs);
for (int arcIdx = numArcs; arcIdx < newArcs.length; arcIdx++) {
newArcs[arcIdx] = new Arc<>();
}
arcs = newArcs;
}
final Arc<T> arc = arcs[numArcs++];
arc.label = label;
arc.target = target;
arc.output = arc.nextFinalOutput = owner.NO_OUTPUT;
arc.isFinal = false;
}
void replaceLast(int labelToMatch, Node target, T nextFinalOutput, boolean isFinal) {
assert numArcs > 0;
final Arc<T> arc = arcs[numArcs - 1];
assert arc.label == labelToMatch : "arc.label=" + arc.label + " vs " + labelToMatch;
arc.target = target;
// assert target.node != -2;
arc.nextFinalOutput = nextFinalOutput;
arc.isFinal = isFinal;
}
void deleteLast(int label, Node target) {
assert numArcs > 0;
assert label == arcs[numArcs - 1].label;
assert target == arcs[numArcs - 1].target;
numArcs--;
}
void setLastOutput(int labelToMatch, T newOutput) {
assert owner.validOutput(newOutput);
assert numArcs > 0;
final Arc<T> arc = arcs[numArcs - 1];
assert arc.label == labelToMatch;
arc.output = newOutput;
}
// pushes an output prefix forward onto all arcs
void prependOutput(T outputPrefix) {
assert owner.validOutput(outputPrefix);
for (int arcIdx = 0; arcIdx < numArcs; arcIdx++) {
arcs[arcIdx].output = owner.fst.outputs.add(outputPrefix, arcs[arcIdx].output);
assert owner.validOutput(arcs[arcIdx].output);
}
if (isFinal) {
output = owner.fst.outputs.add(outputPrefix, output);
assert owner.validOutput(output);
}
}
}
/**
* Reusable buffer for building nodes with fixed length arcs (binary search or direct addressing).
*/
static | UnCompiledNode |
java | apache__camel | components/camel-consul/src/test/java/org/apache/camel/component/consul/ConsulEventIT.java | {
"start": 1364,
"end": 2514
} | class ____ extends ConsulTestSupport {
@Test
public void testFireEvent() throws Exception {
String key = generateRandomString();
String val = generateRandomString();
MockEndpoint mock = getMockEndpoint("mock:event");
mock.expectedMinimumMessageCount(1);
mock.expectedHeaderReceived(ConsulConstants.CONSUL_RESULT, true);
fluentTemplate().withHeader(ConsulConstants.CONSUL_ACTION, ConsulEventActions.FIRE)
.withHeader(ConsulConstants.CONSUL_KEY, key).withBody(val).to("direct:event").send();
mock.assertIsSatisfied();
EventResponse response = getConsul().eventClient().listEvents(key);
List<Event> events = response.getEvents();
assertFalse(events.isEmpty());
assertTrue(events.get(0).getPayload().isPresent());
assertEquals(val, events.get(0).getPayload().get());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:event").to("consul:event").to("mock:event");
}
};
}
}
| ConsulEventIT |
java | spring-projects__spring-boot | module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/IssuerUriCondition.java | {
"start": 1318,
"end": 2204
} | class ____ extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("OpenID Connect Issuer URI Condition");
Environment environment = context.getEnvironment();
String issuerUri = environment.getProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri");
if (!StringUtils.hasText(issuerUri)) {
return ConditionOutcome.noMatch(message.didNotFind("issuer-uri property").atAll());
}
String jwkSetUri = environment.getProperty("spring.security.oauth2.resourceserver.jwt.jwk-set-uri");
if (StringUtils.hasText(jwkSetUri)) {
return ConditionOutcome.noMatch(message.found("jwk-set-uri property").items(jwkSetUri));
}
return ConditionOutcome.match(message.foundExactly("issuer-uri property"));
}
}
| IssuerUriCondition |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/volume/csi/lifecycle/VolumeImpl.java | {
"start": 6913,
"end": 8455
} | class ____
implements MultipleArcTransition<VolumeImpl, VolumeEvent, VolumeState> {
@Override
public VolumeState transition(VolumeImpl volume,
VolumeEvent volumeEvent) {
// this call could cross node, we should keep the message tight
return VolumeState.NODE_READY;
}
}
@Override
public void handle(VolumeEvent event) {
this.writeLock.lock();
try {
VolumeId volumeId = event.getVolumeId();
if (volumeId == null) {
// This should not happen, safely ignore the event
LOG.warn("Unexpected volume event received, event type is "
+ event.getType().name() + ", but the volumeId is null.");
return;
}
LOG.info("Processing volume event, type=" + event.getType().name()
+ ", volumeId=" + volumeId.toString());
VolumeState oldState = null;
VolumeState newState = null;
try {
oldState = stateMachine.getCurrentState();
newState = stateMachine.doTransition(event.getType(), event);
} catch (InvalidStateTransitionException e) {
LOG.warn("Can't handle this event at current state: Current: ["
+ oldState + "], eventType: [" + event.getType() + "]," +
" volumeId: [" + volumeId + "]", e);
}
if (newState != null && oldState != newState) {
LOG.info("VolumeImpl " + volumeId + " transitioned from " + oldState
+ " to " + newState);
}
}finally {
this.writeLock.unlock();
}
}
}
| ControllerPublishVolumeTransition |
java | spring-projects__spring-security | core/src/test/java/org/springframework/security/authentication/ott/OneTimeTokenAuthenticationProviderTests.java | {
"start": 1966,
"end": 5210
} | class ____ {
private static final String TOKEN = "token";
private static final String USERNAME = "Max";
private static final String PASSWORD = "password";
@Mock
private OneTimeTokenService oneTimeTokenService;
@Mock
private UserDetailsService userDetailsService;
@InjectMocks
private OneTimeTokenAuthenticationProvider provider;
@Test
void authenticateWhenAuthenticationTokenIsPresentThenAuthenticates() {
given(this.oneTimeTokenService.consume(any()))
.willReturn(new DefaultOneTimeToken(TOKEN, USERNAME, Instant.now().plusSeconds(120)));
given(this.userDetailsService.loadUserByUsername(anyString()))
.willReturn(new User(USERNAME, PASSWORD, List.of()));
OneTimeTokenAuthenticationToken token = new OneTimeTokenAuthenticationToken(TOKEN);
Authentication authentication = this.provider.authenticate(token);
User user = (User) authentication.getPrincipal();
assertThat(authentication.isAuthenticated()).isTrue();
assertThat(user.getUsername()).isEqualTo(USERNAME);
assertThat(user.getPassword()).isEqualTo(PASSWORD);
assertThat(CollectionUtils.isEmpty(user.getAuthorities())).isTrue();
}
@Test
void authenticateWhenOneTimeTokenIsNotFoundThenFails() {
given(this.oneTimeTokenService.consume(any())).willReturn(null);
OneTimeTokenAuthenticationToken token = new OneTimeTokenAuthenticationToken(TOKEN);
assertThatExceptionOfType(InvalidOneTimeTokenException.class)
.isThrownBy(() -> this.provider.authenticate(token));
}
@Test
void authenticateWhenUserIsNotFoundThenFails() {
given(this.oneTimeTokenService.consume(any()))
.willReturn(new DefaultOneTimeToken(TOKEN, USERNAME, Instant.now().plusSeconds(120)));
given(this.userDetailsService.loadUserByUsername(anyString())).willThrow(UsernameNotFoundException.class);
OneTimeTokenAuthenticationToken token = new OneTimeTokenAuthenticationToken(TOKEN);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(token));
}
@Test
void authenticateWhenSuccessThenIssuesFactor() {
given(this.oneTimeTokenService.consume(any()))
.willReturn(new DefaultOneTimeToken(TOKEN, USERNAME, Instant.now().plusSeconds(120)));
given(this.userDetailsService.loadUserByUsername(anyString()))
.willReturn(new User(USERNAME, PASSWORD, List.of()));
OneTimeTokenAuthenticationToken token = new OneTimeTokenAuthenticationToken(TOKEN);
Authentication authentication = this.provider.authenticate(token);
SecurityAssertions.assertThat(authentication).hasAuthority(FactorGrantedAuthority.OTT_AUTHORITY);
}
@Test
void constructorWhenOneTimeTokenServiceIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new OneTimeTokenAuthenticationProvider(null, this.userDetailsService))
.withMessage("oneTimeTokenService cannot be null");
// @formatter:on
}
@Test
void constructorWhenUserDetailsServiceIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new OneTimeTokenAuthenticationProvider(this.oneTimeTokenService, null))
.withMessage("userDetailsService cannot be null");
// @formatter:on
}
}
| OneTimeTokenAuthenticationProviderTests |
java | spring-projects__spring-security | crypto/src/main/java/org/springframework/security/crypto/keygen/HexEncodingStringKeyGenerator.java | {
"start": 914,
"end": 1250
} | class ____ implements StringKeyGenerator {
private final BytesKeyGenerator keyGenerator;
HexEncodingStringKeyGenerator(BytesKeyGenerator keyGenerator) {
this.keyGenerator = keyGenerator;
}
@Override
public String generateKey() {
return new String(Hex.encode(this.keyGenerator.generateKey()));
}
}
| HexEncodingStringKeyGenerator |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/ref/RefTest_for_huanxige.java | {
"start": 185,
"end": 824
} | class ____ extends TestCase {
public void test_for_ref() throws Exception {
//字符串通过其它对象序列化而来,当中涉及循环引用,因此存在$ref
String jsonStr="{\"displayName\":\"灰度发布\",\"id\":221," +
"\"name\":\"灰度\",\"processInsId\":48,\"processInstance\":{\"$ref\":\"$" +
".lastSubProcessInstence.parentProcess\"},\"status\":1,\"success\":true," +
"\"tail\":true,\"type\":\"gray\"}";
ProcessNodeInstanceDto a = JSON.parseObject(jsonStr, ProcessNodeInstanceDto.class);//status为空!!!
assertNotNull(a.status);
assertEquals(1, a.status.intValue());
}
public static | RefTest_for_huanxige |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/VariableWidthHistogramAggregatorSupplier.java | {
"start": 923,
"end": 1328
} | interface ____ {
Aggregator build(
String name,
AggregatorFactories factories,
int numBuckets,
int shardSize,
int initialBuffer,
@Nullable ValuesSourceConfig valuesSourceConfig,
AggregationContext aggregationContext,
Aggregator parent,
Map<String, Object> metadata
) throws IOException;
}
| VariableWidthHistogramAggregatorSupplier |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/resource/PlacementConstraint.java | {
"start": 18998,
"end": 19869
} | class ____<R extends Visitable>
extends AbstractConstraint {
/**
* Get the children of this composite constraint.
*
* @return the children of the composite constraint
*/
public abstract List<R> getChildren();
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return getChildren() != null ? getChildren().equals(
((CompositeConstraint)o).getChildren()) :
((CompositeConstraint)o).getChildren() == null;
}
@Override
public int hashCode() {
return getChildren() != null ? getChildren().hashCode() : 0;
}
}
/**
* Class that represents a composite constraint that is a conjunction of other
* constraints.
*/
public static | CompositeConstraint |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/repositories/RepositoriesServiceIT.java | {
"start": 1491,
"end": 4789
} | class ____ extends ESIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Collections.singletonList(MockRepository.Plugin.class);
}
public void testUpdateRepository() {
final InternalTestCluster cluster = internalCluster();
final String repositoryName = "test-repo";
final Client client = client();
final RepositoriesService repositoriesService = cluster.getDataOrMasterNodeInstances(RepositoriesService.class).iterator().next();
final Settings.Builder repoSettings = Settings.builder().put("location", randomRepoPath());
assertAcked(
client.admin()
.cluster()
.preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, repositoryName)
.setType(FsRepository.TYPE)
.setSettings(repoSettings)
);
final GetRepositoriesResponse originalGetRepositoriesResponse = client.admin()
.cluster()
.prepareGetRepositories(TEST_REQUEST_TIMEOUT, repositoryName)
.get();
assertThat(originalGetRepositoriesResponse.repositories(), hasSize(1));
RepositoryMetadata originalRepositoryMetadata = originalGetRepositoriesResponse.repositories().get(0);
assertThat(originalRepositoryMetadata.type(), equalTo(FsRepository.TYPE));
final Repository originalRepository = repositoriesService.repository(ProjectId.DEFAULT, repositoryName);
assertThat(originalRepository, instanceOf(FsRepository.class));
final boolean updated = randomBoolean();
final String updatedRepositoryType = updated ? "mock" : FsRepository.TYPE;
assertAcked(
client.admin()
.cluster()
.preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, repositoryName)
.setType(updatedRepositoryType)
.setSettings(repoSettings)
);
final GetRepositoriesResponse updatedGetRepositoriesResponse = client.admin()
.cluster()
.prepareGetRepositories(TEST_REQUEST_TIMEOUT, repositoryName)
.get();
assertThat(updatedGetRepositoriesResponse.repositories(), hasSize(1));
final RepositoryMetadata updatedRepositoryMetadata = updatedGetRepositoriesResponse.repositories().get(0);
assertThat(updatedRepositoryMetadata.type(), equalTo(updatedRepositoryType));
final Repository updatedRepository = repositoriesService.repository(ProjectId.DEFAULT, repositoryName);
assertThat(updatedRepository, updated ? not(sameInstance(originalRepository)) : sameInstance(originalRepository));
// check that a noop update does not verify. Since the new data node does not share the same `path.repo`, verification will fail if
// it runs.
internalCluster().startDataOnlyNode(Settings.builder().put(Environment.PATH_REPO_SETTING.getKey(), createTempDir()).build());
assertAcked(
client.admin()
.cluster()
.preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, repositoryName)
.setType(updatedRepositoryType)
.setSettings(repoSettings)
);
}
}
| RepositoriesServiceIT |
java | FasterXML__jackson-core | src/test/java/tools/jackson/core/unittest/tofix/async/AsyncTokenBranchNumberErrorTest.java | {
"start": 563,
"end": 1722
} | class ____ extends AsyncTestBase
{
private final JsonFactory JSON_F = newStreamFactory();
@JacksonTestFailureExpected
@Test
void mangledNonRootInts() throws Exception
{
try (AsyncReaderWrapper p = _createParser("[ 123true ]")) {
assertToken(JsonToken.START_ARRAY, p.nextToken());
JsonToken t = p.nextToken();
fail("Should have gotten an exception; instead got token: "+t);
} catch (StreamReadException e) {
verifyException(e, "expected space");
}
}
@JacksonTestFailureExpected
@Test
void mangledNonRootFloats() throws Exception
{
try (AsyncReaderWrapper p = _createParser("[ 1.5false ]")) {
assertToken(JsonToken.START_ARRAY, p.nextToken());
JsonToken t = p.nextToken();
fail("Should have gotten an exception; instead got token: "+t);
} catch (StreamReadException e) {
verifyException(e, "expected space");
}
}
private AsyncReaderWrapper _createParser(String doc)
{
return asyncForBytes(JSON_F, 1, _jsonDoc(doc), 1);
}
}
| AsyncTokenBranchNumberErrorTest |
java | apache__flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/sink/filesystem/StreamingFileSinkHelper.java | {
"start": 1820,
"end": 4440
} | class ____<IN> implements ProcessingTimeCallback {
// -------------------------- state descriptors ---------------------------
private static final ListStateDescriptor<byte[]> BUCKET_STATE_DESC =
new ListStateDescriptor<>("bucket-states", BytePrimitiveArraySerializer.INSTANCE);
private static final ListStateDescriptor<Long> MAX_PART_COUNTER_STATE_DESC =
new ListStateDescriptor<>("max-part-counter", LongSerializer.INSTANCE);
// --------------------------- fields -----------------------------
private final long bucketCheckInterval;
private final ProcessingTimeService procTimeService;
private final Buckets<IN, ?> buckets;
private final ListState<byte[]> bucketStates;
private final ListState<Long> maxPartCountersState;
public StreamingFileSinkHelper(
Buckets<IN, ?> buckets,
boolean isRestored,
OperatorStateStore stateStore,
ProcessingTimeService procTimeService,
long bucketCheckInterval)
throws Exception {
this.bucketCheckInterval = bucketCheckInterval;
this.buckets = buckets;
this.bucketStates = stateStore.getListState(BUCKET_STATE_DESC);
this.maxPartCountersState = stateStore.getUnionListState(MAX_PART_COUNTER_STATE_DESC);
this.procTimeService = procTimeService;
if (isRestored) {
buckets.initializeState(bucketStates, maxPartCountersState);
}
long currentProcessingTime = procTimeService.getCurrentProcessingTime();
procTimeService.registerTimer(currentProcessingTime + bucketCheckInterval, this);
}
public void commitUpToCheckpoint(long checkpointId) throws Exception {
buckets.commitUpToCheckpoint(checkpointId);
}
public void snapshotState(long checkpointId) throws Exception {
buckets.snapshotState(checkpointId, bucketStates, maxPartCountersState);
}
@Override
public void onProcessingTime(long timestamp) throws Exception {
final long currentTime = procTimeService.getCurrentProcessingTime();
buckets.onProcessingTime(currentTime);
procTimeService.registerTimer(currentTime + bucketCheckInterval, this);
}
public void onElement(
IN value,
long currentProcessingTime,
@Nullable Long elementTimestamp,
long currentWatermark)
throws Exception {
buckets.onElement(value, currentProcessingTime, elementTimestamp, currentWatermark);
}
public void close() {
this.buckets.close();
}
}
| StreamingFileSinkHelper |
java | elastic__elasticsearch | distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/cli/RemovePluginCommand.java | {
"start": 917,
"end": 1827
} | class ____ extends EnvironmentAwareCommand {
private final OptionSpec<Void> purgeOption;
private final OptionSpec<String> arguments;
RemovePluginCommand() {
super("removes plugins from Elasticsearch");
this.purgeOption = parser.acceptsAll(Arrays.asList("p", "purge"), "Purge plugin configuration files");
this.arguments = parser.nonOptions("plugin id");
}
@Override
public void execute(final Terminal terminal, final OptionSet options, final Environment env, ProcessInfo processInfo) throws Exception {
SyncPluginsAction.ensureNoConfigFile(env);
final List<InstallablePlugin> plugins = arguments.values(options).stream().map(InstallablePlugin::new).collect(Collectors.toList());
final RemovePluginAction action = new RemovePluginAction(terminal, env, options.has(purgeOption));
action.execute(plugins);
}
}
| RemovePluginCommand |
java | netty__netty | codec-compression/src/main/java/io/netty/handler/codec/compression/ZlibDecoder.java | {
"start": 1011,
"end": 3752
} | class ____ extends ByteToMessageDecoder {
/**
* Maximum allowed size of the decompression buffer.
*/
protected final int maxAllocation;
/**
* Same as {@link #ZlibDecoder(int)} with maxAllocation = 0.
*/
public ZlibDecoder() {
this(0);
}
/**
* Construct a new ZlibDecoder.
* @param maxAllocation
* Maximum size of the decompression buffer. Must be >= 0.
* If zero, maximum size is decided by the {@link ByteBufAllocator}.
*/
public ZlibDecoder(int maxAllocation) {
this.maxAllocation = checkPositiveOrZero(maxAllocation, "maxAllocation");
}
/**
* Returns {@code true} if and only if the end of the compressed stream
* has been reached.
*/
public abstract boolean isClosed();
/**
* Allocate or expand the decompression buffer, without exceeding the maximum allocation.
* Calls {@link #decompressionBufferExhausted(ByteBuf)} if the buffer is full and cannot be expanded further.
*/
protected ByteBuf prepareDecompressBuffer(ChannelHandlerContext ctx, ByteBuf buffer, int preferredSize) {
if (buffer == null) {
if (maxAllocation == 0) {
return ctx.alloc().heapBuffer(preferredSize);
}
return ctx.alloc().heapBuffer(Math.min(preferredSize, maxAllocation), maxAllocation);
}
// this always expands the buffer if possible, even if the expansion is less than preferredSize
// we throw the exception only if the buffer could not be expanded at all
// this means that one final attempt to deserialize will always be made with the buffer at maxAllocation
if (buffer.ensureWritable(preferredSize, true) == 1) {
// buffer must be consumed so subclasses don't add it to output
// we therefore duplicate it when calling decompressionBufferExhausted() to guarantee non-interference
// but wait until after to consume it so the subclass can tell how much output is really in the buffer
decompressionBufferExhausted(buffer.duplicate());
buffer.skipBytes(buffer.readableBytes());
throw new DecompressionException("Decompression buffer has reached maximum size: " + buffer.maxCapacity());
}
return buffer;
}
/**
* Called when the decompression buffer cannot be expanded further.
* Default implementation is a no-op, but subclasses can override in case they want to
* do something before the {@link DecompressionException} is thrown, such as log the
* data that was decompressed so far.
*/
protected void decompressionBufferExhausted(ByteBuf buffer) {
}
}
| ZlibDecoder |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/AbstractServiceConnectionManagerTest.java | {
"start": 2357,
"end": 2458
} | class ____
extends AbstractServiceConnectionManager<Object> {}
}
| TestServiceConnectionManager |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/blockaliasmap/impl/TextFileRegionAliasMap.java | {
"start": 12744,
"end": 12854
} | class ____ used as a writer for block maps which
* are stored as delimited text files.
*/
public static | is |
java | micronaut-projects__micronaut-core | management/src/main/java/io/micronaut/management/endpoint/EndpointDefaultConfiguration.java | {
"start": 1031,
"end": 4044
} | class ____ {
/**
* The prefix for endpoints settings.
*/
public static final String PREFIX = "endpoints.all";
/**
* The path for endpoints settings.
*/
public static final String PATH = "endpoints.all.path";
/**
* The context for endpoints settings.
*/
public static final String CONTEXT_PATH = "endpoints.all.context.path";
/**
* The path for endpoints settings.
*/
public static final String PORT = "endpoints.all.port";
/**
* The default base path.
*/
public static final String DEFAULT_ENDPOINT_BASE_PATH = "/";
/**
* The default context path.
*/
public static final String DEFAULT_ENDPOINT_CONTEXT_PATH = null;
private Boolean enabled;
private Boolean sensitive;
private Integer port;
private String path = DEFAULT_ENDPOINT_BASE_PATH;
private String contextPath = DEFAULT_ENDPOINT_CONTEXT_PATH;
/**
* @return endpoints Base Path (defaults to: {@value #DEFAULT_ENDPOINT_BASE_PATH})
*/
public String getPath() {
return path;
}
/**
* @return endpoints Context Path (defaults is null)
*/
public @Nullable String getContextPath() {
return contextPath;
}
/**
* @return Whether the endpoint is enabled
*/
public Optional<Boolean> isEnabled() {
return Optional.ofNullable(enabled);
}
/**
* @return Does the endpoint expose sensitive information
*/
public Optional<Boolean> isSensitive() {
return Optional.ofNullable(sensitive);
}
/**
* Sets whether the endpoint is enabled.
*
* @param enabled True it is enabled, null for the default behaviour
*/
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
/**
* Sets whether the endpoint is sensitive.
*
* @param sensitive True it is sensitive, null for the default behaviour
*/
public void setSensitive(Boolean sensitive) {
this.sensitive = sensitive;
}
/**
* The endpoints base path. It must include a leading and trailing '/'. Default value ({@value #DEFAULT_ENDPOINT_BASE_PATH}).
*
* @param path The path
*/
public void setPath(String path) {
if (StringUtils.isNotEmpty(path)) {
this.path = path;
}
}
/**
* The endpoints context path. Default value is null.
*
* @param contextPath The Context Path
*/
public void setContextPath(String contextPath) {
if (StringUtils.isNotEmpty(contextPath)) {
this.contextPath = contextPath;
}
}
/**
* @return The port to expose endpoints via.
*/
public Optional<Integer> getPort() {
return Optional.ofNullable(port);
}
/**
* Sets the port to expose endpoints via.
*
* @param port The port
*/
public void setPort(@Nullable Integer port) {
this.port = port;
}
}
| EndpointDefaultConfiguration |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/type/format/jaxb/JaxbXmlFormatMapper.java | {
"start": 21742,
"end": 21970
} | interface ____ {
JAXBElement<?> toJAXBElement(Object o);
Object fromJAXBElement(Object element, Unmarshaller unmarshaller) throws JAXBException;
Object fromXmlContent(String content);
}
private static | JAXBElementTransformer |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/web/accept/MediaTypeParamApiVersionResolverTests.java | {
"start": 1069,
"end": 2582
} | class ____ {
private final MediaType mediaType = MediaType.parseMediaType("application/x.abc+json");
private final ApiVersionResolver resolver = new MediaTypeParamApiVersionResolver(mediaType, "version");
private final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/path");
@Test
void resolveFromAccept() {
String version = "3";
this.request.addHeader("Accept", getMediaType(version));
testResolve(this.resolver, this.request, version);
}
@Test
void resolveFromContentType() {
String version = "3";
this.request.setContentType(getMediaType(version).toString());
testResolve(this.resolver, this.request, version);
}
@Test
void wildcard() {
MediaType compatibleMediaType = MediaType.parseMediaType("application/*+json");
ApiVersionResolver resolver = new MediaTypeParamApiVersionResolver(compatibleMediaType, "version");
String version = "3";
this.request.addHeader("Accept", getMediaType(version));
testResolve(resolver, this.request, version);
}
private MediaType getMediaType(String version) {
return new MediaType(this.mediaType, Map.of("version", version));
}
private void testResolve(ApiVersionResolver resolver, MockHttpServletRequest request, String expected) {
try {
ServletRequestPathUtils.parseAndCache(request);
String actual = resolver.resolveVersion(request);
assertThat(actual).isEqualTo(expected);
}
finally {
ServletRequestPathUtils.clearParsedRequestPath(request);
}
}
}
| MediaTypeParamApiVersionResolverTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.