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
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/EntityUseJoinedSubclassOptimizationTest.java
|
{
"start": 19113,
"end": 19238
}
|
class ____ extends Thing {
private Integer nr;
public Building() {
}
}
@Entity(name = "House")
public static
|
Building
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/bug/Bug_for_happyday517_3.java
|
{
"start": 869,
"end": 1837
}
|
class ____ extends TestCase {
private DruidDataSource dataSource;
private MockDriver driver;
private int originalDataSourceCount;
protected void setUp() throws Exception {
originalDataSourceCount = DruidDataSourceStatManager.getInstance().getDataSourceList().size();
driver = new MockDriver();
dataSource = new DruidDataSource();
dataSource.setDriver(driver);
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setFilters("stat,trace,log4j,encoding");
dataSource.setDefaultAutoCommit(false);
}
protected void tearDown() throws Exception {
dataSource.close();
assertEquals(originalDataSourceCount, DruidDataSourceStatManager.getInstance().getDataSourceList().size());
}
public void test_bug() throws Exception {
Connection conn = dataSource.getConnection();
assertEquals(false, conn.getAutoCommit());
conn.close();
}
}
|
Bug_for_happyday517_3
|
java
|
spring-projects__spring-framework
|
spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/AnnotationJCacheOperationSource.java
|
{
"start": 1753,
"end": 10066
}
|
class ____ extends AbstractFallbackJCacheOperationSource {
private static final Set<Class<? extends Annotation>> JCACHE_OPERATION_ANNOTATIONS =
Set.of(CacheResult.class, CachePut.class, CacheRemove.class, CacheRemoveAll.class);
@Override
public boolean isCandidateClass(Class<?> targetClass) {
return AnnotationUtils.isCandidateClass(targetClass, JCACHE_OPERATION_ANNOTATIONS);
}
@Override
protected @Nullable JCacheOperation<?> findCacheOperation(Method method, @Nullable Class<?> targetType) {
CacheResult cacheResult = method.getAnnotation(CacheResult.class);
CachePut cachePut = method.getAnnotation(CachePut.class);
CacheRemove cacheRemove = method.getAnnotation(CacheRemove.class);
CacheRemoveAll cacheRemoveAll = method.getAnnotation(CacheRemoveAll.class);
int found = countNonNull(cacheResult, cachePut, cacheRemove, cacheRemoveAll);
if (found == 0) {
return null;
}
if (found > 1) {
throw new IllegalStateException("More than one cache annotation found on '" + method + "'");
}
CacheDefaults defaults = getCacheDefaults(method, targetType);
if (cacheResult != null) {
return createCacheResultOperation(method, defaults, cacheResult);
}
else if (cachePut != null) {
return createCachePutOperation(method, defaults, cachePut);
}
else if (cacheRemove != null) {
return createCacheRemoveOperation(method, defaults, cacheRemove);
}
else {
return createCacheRemoveAllOperation(method, defaults, cacheRemoveAll);
}
}
protected @Nullable CacheDefaults getCacheDefaults(Method method, @Nullable Class<?> targetType) {
CacheDefaults annotation = method.getDeclaringClass().getAnnotation(CacheDefaults.class);
if (annotation != null) {
return annotation;
}
return (targetType != null ? targetType.getAnnotation(CacheDefaults.class) : null);
}
protected CacheResultOperation createCacheResultOperation(Method method, @Nullable CacheDefaults defaults, CacheResult ann) {
String cacheName = determineCacheName(method, defaults, ann.cacheName());
CacheResolverFactory cacheResolverFactory =
determineCacheResolverFactory(defaults, ann.cacheResolverFactory());
KeyGenerator keyGenerator = determineKeyGenerator(defaults, ann.cacheKeyGenerator());
CacheMethodDetails<CacheResult> methodDetails = createMethodDetails(method, ann, cacheName);
CacheResolver cacheResolver = getCacheResolver(cacheResolverFactory, methodDetails);
CacheResolver exceptionCacheResolver = null;
final String exceptionCacheName = ann.exceptionCacheName();
if (StringUtils.hasText(exceptionCacheName)) {
exceptionCacheResolver = getExceptionCacheResolver(cacheResolverFactory, methodDetails);
}
return new CacheResultOperation(methodDetails, cacheResolver, keyGenerator, exceptionCacheResolver);
}
protected CachePutOperation createCachePutOperation(Method method, @Nullable CacheDefaults defaults, CachePut ann) {
String cacheName = determineCacheName(method, defaults, ann.cacheName());
CacheResolverFactory cacheResolverFactory =
determineCacheResolverFactory(defaults, ann.cacheResolverFactory());
KeyGenerator keyGenerator = determineKeyGenerator(defaults, ann.cacheKeyGenerator());
CacheMethodDetails<CachePut> methodDetails = createMethodDetails(method, ann, cacheName);
CacheResolver cacheResolver = getCacheResolver(cacheResolverFactory, methodDetails);
return new CachePutOperation(methodDetails, cacheResolver, keyGenerator);
}
protected CacheRemoveOperation createCacheRemoveOperation(Method method, @Nullable CacheDefaults defaults, CacheRemove ann) {
String cacheName = determineCacheName(method, defaults, ann.cacheName());
CacheResolverFactory cacheResolverFactory =
determineCacheResolverFactory(defaults, ann.cacheResolverFactory());
KeyGenerator keyGenerator = determineKeyGenerator(defaults, ann.cacheKeyGenerator());
CacheMethodDetails<CacheRemove> methodDetails = createMethodDetails(method, ann, cacheName);
CacheResolver cacheResolver = getCacheResolver(cacheResolverFactory, methodDetails);
return new CacheRemoveOperation(methodDetails, cacheResolver, keyGenerator);
}
protected CacheRemoveAllOperation createCacheRemoveAllOperation(Method method, @Nullable CacheDefaults defaults, CacheRemoveAll ann) {
String cacheName = determineCacheName(method, defaults, ann.cacheName());
CacheResolverFactory cacheResolverFactory =
determineCacheResolverFactory(defaults, ann.cacheResolverFactory());
CacheMethodDetails<CacheRemoveAll> methodDetails = createMethodDetails(method, ann, cacheName);
CacheResolver cacheResolver = getCacheResolver(cacheResolverFactory, methodDetails);
return new CacheRemoveAllOperation(methodDetails, cacheResolver);
}
private <A extends Annotation> CacheMethodDetails<A> createMethodDetails(Method method, A annotation, String cacheName) {
return new DefaultCacheMethodDetails<>(method, annotation, cacheName);
}
protected CacheResolver getCacheResolver(
@Nullable CacheResolverFactory factory, CacheMethodDetails<?> details) {
if (factory != null) {
javax.cache.annotation.CacheResolver cacheResolver = factory.getCacheResolver(details);
return new CacheResolverAdapter(cacheResolver);
}
else {
return getDefaultCacheResolver();
}
}
protected CacheResolver getExceptionCacheResolver(
@Nullable CacheResolverFactory factory, CacheMethodDetails<CacheResult> details) {
if (factory != null) {
javax.cache.annotation.CacheResolver cacheResolver = factory.getExceptionCacheResolver(details);
return new CacheResolverAdapter(cacheResolver);
}
else {
return getDefaultExceptionCacheResolver();
}
}
protected @Nullable CacheResolverFactory determineCacheResolverFactory(
@Nullable CacheDefaults defaults, Class<? extends CacheResolverFactory> candidate) {
if (candidate != CacheResolverFactory.class) {
return getBean(candidate);
}
else if (defaults != null && defaults.cacheResolverFactory() != CacheResolverFactory.class) {
return getBean(defaults.cacheResolverFactory());
}
else {
return null;
}
}
protected KeyGenerator determineKeyGenerator(
@Nullable CacheDefaults defaults, Class<? extends CacheKeyGenerator> candidate) {
if (candidate != CacheKeyGenerator.class) {
return new KeyGeneratorAdapter(this, getBean(candidate));
}
else if (defaults != null && CacheKeyGenerator.class != defaults.cacheKeyGenerator()) {
return new KeyGeneratorAdapter(this, getBean(defaults.cacheKeyGenerator()));
}
else {
return getDefaultKeyGenerator();
}
}
protected String determineCacheName(Method method, @Nullable CacheDefaults defaults, String candidate) {
if (StringUtils.hasText(candidate)) {
return candidate;
}
if (defaults != null && StringUtils.hasText(defaults.cacheName())) {
return defaults.cacheName();
}
return generateDefaultCacheName(method);
}
/**
* Generate a default cache name for the specified {@link Method}.
* @param method the annotated method
* @return the default cache name, according to JSR-107
*/
protected String generateDefaultCacheName(Method method) {
Class<?>[] parameterTypes = method.getParameterTypes();
List<String> parameters = new ArrayList<>(parameterTypes.length);
for (Class<?> parameterType : parameterTypes) {
parameters.add(parameterType.getName());
}
return method.getDeclaringClass().getName() + '.' + method.getName() +
'(' + StringUtils.collectionToCommaDelimitedString(parameters) + ')';
}
private int countNonNull(Object... instances) {
int result = 0;
for (Object instance : instances) {
if (instance != null) {
result += 1;
}
}
return result;
}
/**
* Locate or create an instance of the specified cache strategy {@code type}.
* @param type the type of the bean to manage
* @return the required bean
*/
protected abstract <T> T getBean(Class<T> type);
/**
* Return the default {@link CacheResolver} if none is set.
*/
protected abstract CacheResolver getDefaultCacheResolver();
/**
* Return the default exception {@link CacheResolver} if none is set.
*/
protected abstract CacheResolver getDefaultExceptionCacheResolver();
/**
* Return the default {@link KeyGenerator} if none is set.
*/
protected abstract KeyGenerator getDefaultKeyGenerator();
}
|
AnnotationJCacheOperationSource
|
java
|
elastic__elasticsearch
|
modules/analysis-common/src/test/java/org/elasticsearch/analysis/common/LimitTokenCountFilterFactoryTests.java
|
{
"start": 1092,
"end": 5356
}
|
class ____ extends ESTokenStreamTestCase {
public void testDefault() throws IOException {
Settings settings = Settings.builder()
.put("index.analysis.filter.limit_default.type", "limit")
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
ESTestCase.TestAnalysis analysis = createTestAnalysisFromSettings(settings);
{
TokenFilterFactory tokenFilter = analysis.tokenFilter.get("limit_default");
String source = "the quick brown fox";
String[] expected = new String[] { "the" };
Tokenizer tokenizer = new WhitespaceTokenizer();
tokenizer.setReader(new StringReader(source));
assertTokenStreamContents(tokenFilter.create(tokenizer), expected);
}
{
TokenFilterFactory tokenFilter = analysis.tokenFilter.get("limit");
String source = "the quick brown fox";
String[] expected = new String[] { "the" };
Tokenizer tokenizer = new WhitespaceTokenizer();
tokenizer.setReader(new StringReader(source));
assertTokenStreamContents(tokenFilter.create(tokenizer), expected);
}
}
public void testSettings() throws IOException {
{
Settings settings = Settings.builder()
.put("index.analysis.filter.limit_1.type", "limit")
.put("index.analysis.filter.limit_1.max_token_count", 3)
.put("index.analysis.filter.limit_1.consume_all_tokens", true)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
ESTestCase.TestAnalysis analysis = createTestAnalysisFromSettings(settings);
TokenFilterFactory tokenFilter = analysis.tokenFilter.get("limit_1");
String source = "the quick brown fox";
String[] expected = new String[] { "the", "quick", "brown" };
Tokenizer tokenizer = new WhitespaceTokenizer();
tokenizer.setReader(new StringReader(source));
assertTokenStreamContents(tokenFilter.create(tokenizer), expected);
}
{
Settings settings = Settings.builder()
.put("index.analysis.filter.limit_1.type", "limit")
.put("index.analysis.filter.limit_1.max_token_count", 3)
.put("index.analysis.filter.limit_1.consume_all_tokens", false)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
ESTestCase.TestAnalysis analysis = createTestAnalysisFromSettings(settings);
TokenFilterFactory tokenFilter = analysis.tokenFilter.get("limit_1");
String source = "the quick brown fox";
String[] expected = new String[] { "the", "quick", "brown" };
Tokenizer tokenizer = new WhitespaceTokenizer();
tokenizer.setReader(new StringReader(source));
assertTokenStreamContents(tokenFilter.create(tokenizer), expected);
}
{
Settings settings = Settings.builder()
.put("index.analysis.filter.limit_1.type", "limit")
.put("index.analysis.filter.limit_1.max_token_count", 17)
.put("index.analysis.filter.limit_1.consume_all_tokens", true)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
ESTestCase.TestAnalysis analysis = createTestAnalysisFromSettings(settings);
TokenFilterFactory tokenFilter = analysis.tokenFilter.get("limit_1");
String source = "the quick brown fox";
String[] expected = new String[] { "the", "quick", "brown", "fox" };
Tokenizer tokenizer = new WhitespaceTokenizer();
tokenizer.setReader(new StringReader(source));
assertTokenStreamContents(tokenFilter.create(tokenizer), expected);
}
}
private static ESTestCase.TestAnalysis createTestAnalysisFromSettings(Settings settings) throws IOException {
return AnalysisTestsHelper.createTestAnalysisFromSettings(settings, new CommonAnalysisPlugin());
}
}
|
LimitTokenCountFilterFactoryTests
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/OAIPMHEndpointBuilderFactory.java
|
{
"start": 41243,
"end": 46371
}
|
interface ____
extends
OAIPMHEndpointConsumerBuilder,
OAIPMHEndpointProducerBuilder {
default AdvancedOAIPMHEndpointBuilder advanced() {
return (AdvancedOAIPMHEndpointBuilder) this;
}
/**
* Specifies a lower bound for datestamp-based selective harvesting. UTC
* DateTime value.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param from the value to set
* @return the dsl builder
*/
default OAIPMHEndpointBuilder from(String from) {
doSetProperty("from", from);
return this;
}
/**
* Identifier of the requested resources. Applicable only with certain
* verbs.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param identifier the value to set
* @return the dsl builder
*/
default OAIPMHEndpointBuilder identifier(String identifier) {
doSetProperty("identifier", identifier);
return this;
}
/**
* Specifies the metadataPrefix of the format that should be included in
* the metadata part of the returned records.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: oai_dc
* Group: common
*
* @param metadataPrefix the value to set
* @return the dsl builder
*/
default OAIPMHEndpointBuilder metadataPrefix(String metadataPrefix) {
doSetProperty("metadataPrefix", metadataPrefix);
return this;
}
/**
* Specifies membership as a criteria for set-based selective
* harvesting.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param set the value to set
* @return the dsl builder
*/
default OAIPMHEndpointBuilder set(String set) {
doSetProperty("set", set);
return this;
}
/**
* Specifies an upper bound for datestamp-based selective harvesting.
* UTC DateTime value.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param until the value to set
* @return the dsl builder
*/
default OAIPMHEndpointBuilder until(String until) {
doSetProperty("until", until);
return this;
}
/**
* Request name supported by OAI-PMh protocol.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: ListRecords
* Group: common
*
* @param verb the value to set
* @return the dsl builder
*/
default OAIPMHEndpointBuilder verb(String verb) {
doSetProperty("verb", verb);
return this;
}
/**
* Ignore SSL certificate warnings.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param ignoreSSLWarnings the value to set
* @return the dsl builder
*/
default OAIPMHEndpointBuilder ignoreSSLWarnings(boolean ignoreSSLWarnings) {
doSetProperty("ignoreSSLWarnings", ignoreSSLWarnings);
return this;
}
/**
* Ignore SSL certificate warnings.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param ignoreSSLWarnings the value to set
* @return the dsl builder
*/
default OAIPMHEndpointBuilder ignoreSSLWarnings(String ignoreSSLWarnings) {
doSetProperty("ignoreSSLWarnings", ignoreSSLWarnings);
return this;
}
/**
* Causes the defined url to make an https request.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param ssl the value to set
* @return the dsl builder
*/
default OAIPMHEndpointBuilder ssl(boolean ssl) {
doSetProperty("ssl", ssl);
return this;
}
/**
* Causes the defined url to make an https request.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param ssl the value to set
* @return the dsl builder
*/
default OAIPMHEndpointBuilder ssl(String ssl) {
doSetProperty("ssl", ssl);
return this;
}
}
/**
* Advanced builder for endpoint for the OAI-PMH component.
*/
public
|
OAIPMHEndpointBuilder
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/WatsonDiscoveryEndpointBuilderFactory.java
|
{
"start": 1606,
"end": 5397
}
|
interface ____
extends
EndpointProducerBuilder {
default AdvancedWatsonDiscoveryEndpointBuilder advanced() {
return (AdvancedWatsonDiscoveryEndpointBuilder) this;
}
/**
* The Watson Discovery project ID.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: common
*
* @param projectId the value to set
* @return the dsl builder
*/
default WatsonDiscoveryEndpointBuilder projectId(String projectId) {
doSetProperty("projectId", projectId);
return this;
}
/**
* The service endpoint URL. If not specified, the default URL will be
* used.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param serviceUrl the value to set
* @return the dsl builder
*/
default WatsonDiscoveryEndpointBuilder serviceUrl(String serviceUrl) {
doSetProperty("serviceUrl", serviceUrl);
return this;
}
/**
* The API version date (format: YYYY-MM-DD).
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: 2023-03-31
* Group: common
*
* @param version the value to set
* @return the dsl builder
*/
default WatsonDiscoveryEndpointBuilder version(String version) {
doSetProperty("version", version);
return this;
}
/**
* The collection ID for operations that require it.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param collectionId the value to set
* @return the dsl builder
*/
default WatsonDiscoveryEndpointBuilder collectionId(String collectionId) {
doSetProperty("collectionId", collectionId);
return this;
}
/**
* The operation to perform.
*
* The option is a:
* <code>org.apache.camel.component.ibm.watson.discovery.WatsonDiscoveryOperations</code> type.
*
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default WatsonDiscoveryEndpointBuilder operation(org.apache.camel.component.ibm.watson.discovery.WatsonDiscoveryOperations operation) {
doSetProperty("operation", operation);
return this;
}
/**
* The operation to perform.
*
* The option will be converted to a
* <code>org.apache.camel.component.ibm.watson.discovery.WatsonDiscoveryOperations</code> type.
*
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default WatsonDiscoveryEndpointBuilder operation(String operation) {
doSetProperty("operation", operation);
return this;
}
/**
* The IBM Cloud API key for authentication.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: security
*
* @param apiKey the value to set
* @return the dsl builder
*/
default WatsonDiscoveryEndpointBuilder apiKey(String apiKey) {
doSetProperty("apiKey", apiKey);
return this;
}
}
/**
* Advanced builder for endpoint for the IBM Watson Discovery component.
*/
public
|
WatsonDiscoveryEndpointBuilder
|
java
|
micronaut-projects__micronaut-core
|
http-netty/src/main/java/io/micronaut/http/netty/stream/EmptyHttpRequest.java
|
{
"start": 1310,
"end": 4350
}
|
class ____ extends DelegateHttpRequest implements FullHttpRequest {
/**
* @param request The Http request
*/
public EmptyHttpRequest(HttpRequest request) {
super(request);
}
@Override
public FullHttpRequest setUri(String uri) {
super.setUri(uri);
return this;
}
@Override
public FullHttpRequest setMethod(HttpMethod method) {
super.setMethod(method);
return this;
}
@Override
public FullHttpRequest setProtocolVersion(HttpVersion version) {
super.setProtocolVersion(version);
return this;
}
@Override
public FullHttpRequest copy() {
if (request instanceof FullHttpRequest httpRequest) {
return new EmptyHttpRequest(httpRequest.copy());
} else {
DefaultHttpRequest copy = new DefaultHttpRequest(protocolVersion(), method(), uri());
copy.headers().set(headers());
return new EmptyHttpRequest(copy);
}
}
@Override
public FullHttpRequest retain(int increment) {
ReferenceCountUtil.retain(message, increment);
return this;
}
@Override
public FullHttpRequest retain() {
ReferenceCountUtil.retain(message);
return this;
}
@Override
public FullHttpRequest touch() {
if (request instanceof FullHttpRequest httpRequest) {
return httpRequest.touch();
} else {
return this;
}
}
@Override
public FullHttpRequest touch(Object o) {
if (request instanceof FullHttpRequest httpRequest) {
return httpRequest.touch(o);
} else {
return this;
}
}
@Override
public HttpHeaders trailingHeaders() {
return new DefaultHttpHeaders();
}
@Override
public FullHttpRequest duplicate() {
if (request instanceof FullHttpRequest httpRequest) {
return httpRequest.duplicate();
} else {
return this;
}
}
@Override
public FullHttpRequest retainedDuplicate() {
if (request instanceof FullHttpRequest httpRequest) {
return httpRequest.retainedDuplicate();
} else {
return this;
}
}
@Override
public FullHttpRequest replace(ByteBuf byteBuf) {
if (message instanceof FullHttpRequest) {
return ((FullHttpRequest) request).replace(byteBuf);
} else {
return this;
}
}
@Override
public ByteBuf content() {
return Unpooled.EMPTY_BUFFER;
}
@Override
public int refCnt() {
if (message instanceof ReferenceCounted counted) {
return counted.refCnt();
} else {
return 1;
}
}
@Override
public boolean release() {
return ReferenceCountUtil.release(message);
}
@Override
public boolean release(int decrement) {
return ReferenceCountUtil.release(message, decrement);
}
}
|
EmptyHttpRequest
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/BiDirectionalResourceToRequirementMappingTest.java
|
{
"start": 1158,
"end": 2747
}
|
class ____ {
@Test
void testIncrement() {
BiDirectionalResourceToRequirementMapping mapping =
new BiDirectionalResourceToRequirementMapping();
ResourceProfile requirement = ResourceProfile.UNKNOWN;
ResourceProfile resource = ResourceProfile.ANY;
mapping.incrementCount(requirement, resource, 1);
assertThat(mapping.getRequirementsFulfilledBy(resource))
.isEqualTo(ResourceCounter.withResource(requirement, 1));
assertThat(mapping.getResourcesFulfilling(requirement))
.isEqualTo(ResourceCounter.withResource(resource, 1));
assertThat(mapping.getAllRequirementProfiles()).contains(requirement);
assertThat(mapping.getAllResourceProfiles()).contains(resource);
}
@Test
void testDecrement() {
BiDirectionalResourceToRequirementMapping mapping =
new BiDirectionalResourceToRequirementMapping();
ResourceProfile requirement = ResourceProfile.UNKNOWN;
ResourceProfile resource = ResourceProfile.ANY;
mapping.incrementCount(requirement, resource, 1);
mapping.decrementCount(requirement, resource, 1);
assertThat(mapping.getRequirementsFulfilledBy(resource).isEmpty()).isTrue();
assertThat(mapping.getResourcesFulfilling(requirement).isEmpty()).isTrue();
assertThat(mapping.getAllRequirementProfiles()).isEmpty();
assertThat(mapping.getAllResourceProfiles()).isEmpty();
assertThat(mapping.isEmpty()).isTrue();
}
}
|
BiDirectionalResourceToRequirementMappingTest
|
java
|
apache__camel
|
components/camel-zookeeper-master/src/main/java/org/apache/camel/component/zookeepermaster/group/DefaultManagedGroupFactory.java
|
{
"start": 1135,
"end": 2422
}
|
class ____ implements ManagedGroupFactory {
private final CuratorFramework curator;
private final boolean shouldClose;
public DefaultManagedGroupFactory(CuratorFramework curator, boolean shouldClose) {
this.curator = curator;
this.shouldClose = shouldClose;
}
@Override
public CuratorFramework getCurator() {
return curator;
}
@Override
public <T extends NodeState> Group<T> createGroup(String path, Class<T> clazz) {
return new ZooKeeperGroup<>(curator, path, clazz);
}
@Override
public <T extends NodeState> Group<T> createGroup(String path, Class<T> clazz, ThreadFactory threadFactory) {
return new ZooKeeperGroup<>(curator, path, clazz, threadFactory);
}
@Override
public <T extends NodeState> Group<T> createMultiGroup(String path, Class<T> clazz) {
return new ZooKeeperMultiGroup<>(curator, path, clazz);
}
@Override
public <T extends NodeState> Group<T> createMultiGroup(String path, Class<T> clazz, ThreadFactory threadFactory) {
return new ZooKeeperMultiGroup<>(curator, path, clazz, threadFactory);
}
@Override
public void close() {
if (shouldClose) {
curator.close();
}
}
}
|
DefaultManagedGroupFactory
|
java
|
netty__netty
|
codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker13Test.java
|
{
"start": 2160,
"end": 10598
}
|
class ____ extends WebSocketServerHandshakerTest {
@Override
protected WebSocketServerHandshaker newHandshaker(String webSocketURL, String subprotocols,
WebSocketDecoderConfig decoderConfig) {
return new WebSocketServerHandshaker13(webSocketURL, subprotocols, decoderConfig);
}
@Override
protected WebSocketVersion webSocketVersion() {
return WebSocketVersion.V13;
}
@Test
public void testPerformOpeningHandshake() {
testPerformOpeningHandshake0(true);
}
@Test
public void testPerformOpeningHandshakeSubProtocolNotSupported() {
testPerformOpeningHandshake0(false);
}
private static void testPerformOpeningHandshake0(boolean subProtocol) {
EmbeddedChannel ch = new EmbeddedChannel(
new HttpObjectAggregator(42), new HttpResponseEncoder(), new HttpRequestDecoder());
if (subProtocol) {
testUpgrade0(ch, new WebSocketServerHandshaker13(
"ws://example.com/chat", "chat", false, Integer.MAX_VALUE, false));
} else {
testUpgrade0(ch, new WebSocketServerHandshaker13(
"ws://example.com/chat", null, false, Integer.MAX_VALUE, false));
}
assertFalse(ch.finish());
}
@Test
public void testCloseReasonWithEncoderAndDecoder() {
testCloseReason0(new HttpResponseEncoder(), new HttpRequestDecoder());
}
@Test
public void testCloseReasonWithCodec() {
testCloseReason0(new HttpServerCodec());
}
@Test
public void testHandshakeExceptionWhenConnectionHeaderIsAbsent() {
final WebSocketServerHandshaker serverHandshaker = newHandshaker("ws://example.com/chat",
"chat", WebSocketDecoderConfig.DEFAULT);
final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
"ws://example.com/chat");
request.headers()
.set(HttpHeaderNames.HOST, "server.example.com")
.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
.set(HttpHeaderNames.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==")
.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, "http://example.com")
.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat")
.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "13");
Throwable exception = assertThrows(WebSocketServerHandshakeException.class, new Executable() {
@Override
public void execute() throws Throwable {
serverHandshaker.handshake(null, request, null, null);
}
});
assertEquals("not a WebSocket request: a |Connection| header must includes a token 'Upgrade'",
exception.getMessage());
assertTrue(request.release());
}
@Test
public void testHandshakeExceptionWhenInvalidConnectionHeader() {
final WebSocketServerHandshaker serverHandshaker = newHandshaker("ws://example.com/chat",
"chat", WebSocketDecoderConfig.DEFAULT);
final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
"ws://example.com/chat");
request.headers()
.set(HttpHeaderNames.HOST, "server.example.com")
.set(HttpHeaderNames.CONNECTION, "close")
.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
.set(HttpHeaderNames.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==")
.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, "http://example.com")
.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat")
.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "13");
Throwable exception = assertThrows(WebSocketServerHandshakeException.class, new Executable() {
@Override
public void execute() throws Throwable {
serverHandshaker.handshake(null, request, null, null);
}
});
assertEquals("not a WebSocket request: a |Connection| header must includes a token 'Upgrade'",
exception.getMessage());
assertTrue(request.release());
}
@Test
public void testHandshakeExceptionWhenInvalidUpgradeHeader() {
final WebSocketServerHandshaker serverHandshaker = newHandshaker("ws://example.com/chat",
"chat", WebSocketDecoderConfig.DEFAULT);
final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
"ws://example.com/chat");
request.headers()
.set(HttpHeaderNames.HOST, "server.example.com")
.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
.set(HttpHeaderNames.UPGRADE, "my_websocket")
.set(HttpHeaderNames.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==")
.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, "http://example.com")
.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat")
.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "13");
Throwable exception = assertThrows(WebSocketServerHandshakeException.class, new Executable() {
@Override
public void execute() throws Throwable {
serverHandshaker.handshake(null, request, null, null);
}
});
assertEquals("not a WebSocket request: a |Upgrade| header must containing the value 'websocket'",
exception.getMessage());
assertTrue(request.release());
}
private static void testCloseReason0(ChannelHandler... handlers) {
EmbeddedChannel ch = new EmbeddedChannel(
new HttpObjectAggregator(42));
ch.pipeline().addLast(handlers);
testUpgrade0(ch, new WebSocketServerHandshaker13("ws://example.com/chat", "chat",
WebSocketDecoderConfig.newBuilder().maxFramePayloadLength(4).closeOnProtocolViolation(true).build()));
ch.writeOutbound(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(new byte[8])));
ByteBuf buffer = ch.readOutbound();
try {
ch.writeInbound(buffer);
fail();
} catch (CorruptedWebSocketFrameException expected) {
// expected
}
ReferenceCounted closeMessage = ch.readOutbound();
assertInstanceOf(ByteBuf.class, closeMessage);
closeMessage.release();
assertFalse(ch.finish());
}
private static void testUpgrade0(EmbeddedChannel ch, WebSocketServerHandshaker13 handshaker) {
FullHttpRequest req = new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat");
req.headers().set(HttpHeaderNames.HOST, "server.example.com");
req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, "http://example.com");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "13");
handshaker.handshake(ch, req);
ByteBuf resBuf = ch.readOutbound();
EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
ch2.writeInbound(resBuf);
HttpResponse res = ch2.readInbound();
assertEquals(
"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT));
Iterator<String> subProtocols = handshaker.subprotocols().iterator();
if (subProtocols.hasNext()) {
assertEquals(subProtocols.next(),
res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
} else {
assertNull(res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
}
ReferenceCountUtil.release(res);
req.release();
}
}
|
WebSocketServerHandshaker13Test
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/job/GroupConfig.java
|
{
"start": 1586,
"end": 6445
}
|
class ____ implements Writeable, ToXContentObject {
public static final String NAME = "groups";
private static final ConstructingObjectParser<GroupConfig, Void> PARSER;
static {
PARSER = new ConstructingObjectParser<>(
NAME,
args -> new GroupConfig((DateHistogramGroupConfig) args[0], (HistogramGroupConfig) args[1], (TermsGroupConfig) args[2])
);
PARSER.declareObject(
constructorArg(),
(p, c) -> DateHistogramGroupConfig.fromXContent(p),
new ParseField(DateHistogramGroupConfig.NAME)
);
PARSER.declareObject(
optionalConstructorArg(),
(p, c) -> HistogramGroupConfig.fromXContent(p),
new ParseField(HistogramGroupConfig.NAME)
);
PARSER.declareObject(optionalConstructorArg(), (p, c) -> TermsGroupConfig.fromXContent(p), new ParseField(TermsGroupConfig.NAME));
}
private final DateHistogramGroupConfig dateHistogram;
private final @Nullable HistogramGroupConfig histogram;
private final @Nullable TermsGroupConfig terms;
public GroupConfig(final DateHistogramGroupConfig dateHistogram) {
this(dateHistogram, null, null);
}
public GroupConfig(
final DateHistogramGroupConfig dateHistogram,
final @Nullable HistogramGroupConfig histogram,
final @Nullable TermsGroupConfig terms
) {
if (dateHistogram == null) {
throw new IllegalArgumentException("Date histogram must not be null");
}
this.dateHistogram = dateHistogram;
this.histogram = histogram;
this.terms = terms;
}
public GroupConfig(final StreamInput in) throws IOException {
dateHistogram = DateHistogramGroupConfig.fromUnknownTimeUnit(in);
histogram = in.readOptionalWriteable(HistogramGroupConfig::new);
terms = in.readOptionalWriteable(TermsGroupConfig::new);
}
/**
* @return the configuration of the date histogram
*/
public DateHistogramGroupConfig getDateHistogram() {
return dateHistogram;
}
/**
* @return the configuration of the histogram
*/
@Nullable
public HistogramGroupConfig getHistogram() {
return histogram;
}
/**
* @return the configuration of the terms
*/
@Nullable
public TermsGroupConfig getTerms() {
return terms;
}
public Set<String> getAllFields() {
Set<String> fields = new HashSet<>();
fields.add(dateHistogram.getField());
if (histogram != null) {
fields.addAll(asList(histogram.getFields()));
}
if (terms != null) {
fields.addAll(asList(terms.getFields()));
}
return Collections.unmodifiableSet(fields);
}
public void validateMappings(
final Map<String, Map<String, FieldCapabilities>> fieldCapsResponse,
final ActionRequestValidationException validationException
) {
dateHistogram.validateMappings(fieldCapsResponse, validationException);
if (histogram != null) {
histogram.validateMappings(fieldCapsResponse, validationException);
}
if (terms != null) {
terms.validateMappings(fieldCapsResponse, validationException);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
{
builder.field(DateHistogramGroupConfig.NAME, dateHistogram);
if (histogram != null) {
builder.field(HistogramGroupConfig.NAME, histogram);
}
if (terms != null) {
builder.field(TermsGroupConfig.NAME, terms);
}
}
return builder.endObject();
}
@Override
public void writeTo(final StreamOutput out) throws IOException {
dateHistogram.writeTo(out);
out.writeOptionalWriteable(histogram);
out.writeOptionalWriteable(terms);
}
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
final GroupConfig that = (GroupConfig) other;
return Objects.equals(dateHistogram, that.dateHistogram)
&& Objects.equals(histogram, that.histogram)
&& Objects.equals(terms, that.terms);
}
@Override
public int hashCode() {
return Objects.hash(dateHistogram, histogram, terms);
}
@Override
public String toString() {
return Strings.toString(this, true, true);
}
public static GroupConfig fromXContent(final XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
}
|
GroupConfig
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/test/java/io/vertx/tests/json/jackson/HybridJacksonPoolTest.java
|
{
"start": 2631,
"end": 3331
}
|
class ____ {
static final MethodHandle virtualMh = findVirtualMH();
static MethodHandle findVirtualMH() {
try {
return MethodHandles.publicLookup().findStatic(Thread.class, "startVirtualThread",
MethodType.methodType(Thread.class, Runnable.class));
} catch (Exception e) {
return null;
}
}
static boolean hasVirtualThread() {
return virtualMh != null;
}
static void runOnVirtualThread(Runnable runnable) {
try {
VirtualThreadRunner.virtualMh.invoke(runnable);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
}
|
VirtualThreadRunner
|
java
|
apache__camel
|
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/CamelRouteGroupTop.java
|
{
"start": 1341,
"end": 4380
}
|
class ____ extends CamelRouteGroupStatus {
public CamelRouteGroupTop(CamelJBangMain main) {
super(main);
}
@Override
protected void printTable(List<Row> rows) {
printer().println(AsciiTable.getTable(AsciiTable.NO_BORDERS, rows, Arrays.asList(
new Column().header("PID").headerAlign(HorizontalAlign.CENTER).with(r -> r.pid),
new Column().header("NAME").dataAlign(HorizontalAlign.LEFT).maxWidth(30, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(r -> r.name),
new Column().header("GROUP").dataAlign(HorizontalAlign.LEFT)
.maxWidth(20, OverflowBehaviour.ELLIPSIS_RIGHT)
.with(this::getGroup),
new Column().header("ROUTES").dataAlign(HorizontalAlign.RIGHT).headerAlign(HorizontalAlign.CENTER)
.with(r -> "" + r.size),
new Column().header("STATUS").dataAlign(HorizontalAlign.LEFT).headerAlign(HorizontalAlign.CENTER)
.with(r -> r.state),
new Column().header("AGE").headerAlign(HorizontalAlign.CENTER).with(r -> r.age),
new Column().header("LOAD").headerAlign(HorizontalAlign.CENTER).dataAlign(HorizontalAlign.CENTER)
.with(this::getLoad),
new Column().header("TOTAL").with(this::getTotal),
new Column().header("FAIL").with(this::getFailed),
new Column().header("INFLIGHT").with(this::getInflight),
new Column().header("MEAN").with(r -> r.mean),
new Column().header("MIN").with(r -> r.min),
new Column().header("MAX").with(r -> r.max),
new Column().header("SINCE-LAST").with(this::getSinceLast))));
}
private String getLoad(Row r) {
String s1 = r.load01 != null ? r.load01 : "-";
String s2 = r.load05 != null ? r.load05 : "-";
String s3 = r.load15 != null ? r.load15 : "-";
if ("0.00".equals(s1)) {
s1 = "-";
}
if ("0.00".equals(s2)) {
s2 = "-";
}
if ("0.00".equals(s3)) {
s3 = "-";
}
if (s1.equals("-") && s2.equals("-") && s3.equals("-")) {
return "0/0/0";
}
return s1 + "/" + s2 + "/" + s3;
}
@Override
protected int sortRow(Row o1, Row o2) {
// use super to group by first
int answer = super.sortRow(o1, o2);
if (answer == 0) {
int negate = 1;
if (sort.startsWith("-")) {
negate = -1;
}
// sort for highest mean value as we want the slowest in the top
long m1 = o1.mean != null ? Long.parseLong(o1.mean) : 0;
long m2 = o2.mean != null ? Long.parseLong(o2.mean) : 0;
if (m1 < m2) {
answer = negate;
} else if (m1 > m2) {
answer = -1 * negate;
}
}
return answer;
}
}
|
CamelRouteGroupTop
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
|
{
"start": 64831,
"end": 65293
}
|
class ____ extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
return describeMatch(tree, SuggestedFixes.renameClassWithUses(tree, "Foo", state));
}
}
@Test
public void renameClass() {
BugCheckerRefactoringTestHelper.newInstance(RenameClassChecker.class, getClass())
.addInputLines(
"Test.java",
"""
|
RenameClassChecker
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/record/DefaultRecord.java
|
{
"start": 2393,
"end": 21509
}
|
class ____ implements Record {
// excluding key, value and headers: 5 bytes length + 10 bytes timestamp + 5 bytes offset + 1 byte attributes
public static final int MAX_RECORD_OVERHEAD = 21;
private static final int NULL_VARINT_SIZE_BYTES = ByteUtils.sizeOfVarint(-1);
private final int sizeInBytes;
private final byte attributes;
private final long offset;
private final long timestamp;
private final int sequence;
private final ByteBuffer key;
private final ByteBuffer value;
private final Header[] headers;
DefaultRecord(int sizeInBytes,
byte attributes,
long offset,
long timestamp,
int sequence,
ByteBuffer key,
ByteBuffer value,
Header[] headers) {
this.sizeInBytes = sizeInBytes;
this.attributes = attributes;
this.offset = offset;
this.timestamp = timestamp;
this.sequence = sequence;
this.key = key;
this.value = value;
this.headers = headers;
}
@Override
public long offset() {
return offset;
}
@Override
public int sequence() {
return sequence;
}
@Override
public int sizeInBytes() {
return sizeInBytes;
}
@Override
public long timestamp() {
return timestamp;
}
public byte attributes() {
return attributes;
}
@Override
public void ensureValid() {}
@Override
public int keySize() {
return key == null ? -1 : key.remaining();
}
@Override
public int valueSize() {
return value == null ? -1 : value.remaining();
}
@Override
public boolean hasKey() {
return key != null;
}
@Override
public ByteBuffer key() {
return key == null ? null : key.duplicate();
}
@Override
public boolean hasValue() {
return value != null;
}
@Override
public ByteBuffer value() {
return value == null ? null : value.duplicate();
}
@Override
public Header[] headers() {
return headers;
}
/**
* Write the record to `out` and return its size.
*/
public static int writeTo(DataOutputStream out,
int offsetDelta,
long timestampDelta,
ByteBuffer key,
ByteBuffer value,
Header[] headers) throws IOException {
int sizeInBytes = sizeOfBodyInBytes(offsetDelta, timestampDelta, key, value, headers);
ByteUtils.writeVarint(sizeInBytes, out);
byte attributes = 0; // there are no used record attributes at the moment
out.write(attributes);
ByteUtils.writeVarlong(timestampDelta, out);
ByteUtils.writeVarint(offsetDelta, out);
if (key == null) {
ByteUtils.writeVarint(-1, out);
} else {
int keySize = key.remaining();
ByteUtils.writeVarint(keySize, out);
Utils.writeTo(out, key, keySize);
}
if (value == null) {
ByteUtils.writeVarint(-1, out);
} else {
int valueSize = value.remaining();
ByteUtils.writeVarint(valueSize, out);
Utils.writeTo(out, value, valueSize);
}
if (headers == null)
throw new IllegalArgumentException("Headers cannot be null");
ByteUtils.writeVarint(headers.length, out);
for (Header header : headers) {
String headerKey = header.key();
if (headerKey == null)
throw new IllegalArgumentException("Invalid null header key found in headers");
byte[] utf8Bytes = Utils.utf8(headerKey);
ByteUtils.writeVarint(utf8Bytes.length, out);
out.write(utf8Bytes);
byte[] headerValue = header.value();
if (headerValue == null) {
ByteUtils.writeVarint(-1, out);
} else {
ByteUtils.writeVarint(headerValue.length, out);
out.write(headerValue);
}
}
return ByteUtils.sizeOfVarint(sizeInBytes) + sizeInBytes;
}
@Override
public boolean hasMagic(byte magic) {
return magic >= MAGIC_VALUE_V2;
}
@Override
public boolean isCompressed() {
return false;
}
@Override
public boolean hasTimestampType(TimestampType timestampType) {
return false;
}
@Override
public String toString() {
return String.format("DefaultRecord(offset=%d, timestamp=%d, key=%d bytes, value=%d bytes)",
offset,
timestamp,
key == null ? 0 : key.limit(),
value == null ? 0 : value.limit());
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
DefaultRecord that = (DefaultRecord) o;
return sizeInBytes == that.sizeInBytes &&
attributes == that.attributes &&
offset == that.offset &&
timestamp == that.timestamp &&
sequence == that.sequence &&
Objects.equals(key, that.key) &&
Objects.equals(value, that.value) &&
Arrays.equals(headers, that.headers);
}
@Override
public int hashCode() {
int result = sizeInBytes;
result = 31 * result + (int) attributes;
result = 31 * result + Long.hashCode(offset);
result = 31 * result + Long.hashCode(timestamp);
result = 31 * result + sequence;
result = 31 * result + (key != null ? key.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + Arrays.hashCode(headers);
return result;
}
public static DefaultRecord readFrom(InputStream input,
long baseOffset,
long baseTimestamp,
int baseSequence,
Long logAppendTime) throws IOException {
int sizeOfBodyInBytes = ByteUtils.readVarint(input);
ByteBuffer recordBuffer = ByteBuffer.allocate(sizeOfBodyInBytes);
int bytesRead = Utils.readFully(input, recordBuffer);
if (bytesRead != sizeOfBodyInBytes)
throw new InvalidRecordException("Invalid record size: expected " + sizeOfBodyInBytes +
" bytes in record payload, but the record payload reached EOF.");
recordBuffer.flip(); // prepare for reading
return readFrom(recordBuffer, sizeOfBodyInBytes, baseOffset, baseTimestamp,
baseSequence, logAppendTime);
}
public static DefaultRecord readFrom(ByteBuffer buffer,
long baseOffset,
long baseTimestamp,
int baseSequence,
Long logAppendTime) {
int sizeOfBodyInBytes = ByteUtils.readVarint(buffer);
return readFrom(buffer, sizeOfBodyInBytes, baseOffset, baseTimestamp,
baseSequence, logAppendTime);
}
private static DefaultRecord readFrom(ByteBuffer buffer,
int sizeOfBodyInBytes,
long baseOffset,
long baseTimestamp,
int baseSequence,
Long logAppendTime) {
if (buffer.remaining() < sizeOfBodyInBytes)
throw new InvalidRecordException("Invalid record size: expected " + sizeOfBodyInBytes +
" bytes in record payload, but instead the buffer has only " + buffer.remaining() +
" remaining bytes.");
try {
int recordStart = buffer.position();
byte attributes = buffer.get();
long timestampDelta = ByteUtils.readVarlong(buffer);
long timestamp = baseTimestamp + timestampDelta;
if (logAppendTime != null)
timestamp = logAppendTime;
int offsetDelta = ByteUtils.readVarint(buffer);
long offset = baseOffset + offsetDelta;
int sequence = baseSequence >= 0 ?
DefaultRecordBatch.incrementSequence(baseSequence, offsetDelta) :
RecordBatch.NO_SEQUENCE;
// read key
int keySize = ByteUtils.readVarint(buffer);
ByteBuffer key = Utils.readBytes(buffer, keySize);
// read value
int valueSize = ByteUtils.readVarint(buffer);
ByteBuffer value = Utils.readBytes(buffer, valueSize);
int numHeaders = ByteUtils.readVarint(buffer);
if (numHeaders < 0)
throw new InvalidRecordException("Found invalid number of record headers " + numHeaders);
if (numHeaders > buffer.remaining())
throw new InvalidRecordException("Found invalid number of record headers. " + numHeaders + " is larger than the remaining size of the buffer");
final Header[] headers;
if (numHeaders == 0)
headers = Record.EMPTY_HEADERS;
else
headers = readHeaders(buffer, numHeaders);
// validate whether we have read all header bytes in the current record
if (buffer.position() - recordStart != sizeOfBodyInBytes)
throw new InvalidRecordException("Invalid record size: expected to read " + sizeOfBodyInBytes +
" bytes in record payload, but instead read " + (buffer.position() - recordStart));
int totalSizeInBytes = ByteUtils.sizeOfVarint(sizeOfBodyInBytes) + sizeOfBodyInBytes;
return new DefaultRecord(totalSizeInBytes, attributes, offset, timestamp, sequence, key, value, headers);
} catch (BufferUnderflowException | IllegalArgumentException e) {
throw new InvalidRecordException("Found invalid record structure", e);
}
}
public static PartialDefaultRecord readPartiallyFrom(InputStream input,
long baseOffset,
long baseTimestamp,
int baseSequence,
Long logAppendTime) throws IOException {
int sizeOfBodyInBytes = ByteUtils.readVarint(input);
int totalSizeInBytes = ByteUtils.sizeOfVarint(sizeOfBodyInBytes) + sizeOfBodyInBytes;
return readPartiallyFrom(input, totalSizeInBytes, baseOffset, baseTimestamp,
baseSequence, logAppendTime);
}
private static PartialDefaultRecord readPartiallyFrom(InputStream input,
int sizeInBytes,
long baseOffset,
long baseTimestamp,
int baseSequence,
Long logAppendTime) throws IOException {
try {
byte attributes = (byte) input.read();
long timestampDelta = ByteUtils.readVarlong(input);
long timestamp = baseTimestamp + timestampDelta;
if (logAppendTime != null)
timestamp = logAppendTime;
int offsetDelta = ByteUtils.readVarint(input);
long offset = baseOffset + offsetDelta;
int sequence = baseSequence >= 0 ?
DefaultRecordBatch.incrementSequence(baseSequence, offsetDelta) :
RecordBatch.NO_SEQUENCE;
// skip key
int keySize = ByteUtils.readVarint(input);
skipBytes(input, keySize);
// skip value
int valueSize = ByteUtils.readVarint(input);
skipBytes(input, valueSize);
// skip header
int numHeaders = ByteUtils.readVarint(input);
if (numHeaders < 0)
throw new InvalidRecordException("Found invalid number of record headers " + numHeaders);
for (int i = 0; i < numHeaders; i++) {
int headerKeySize = ByteUtils.readVarint(input);
if (headerKeySize < 0)
throw new InvalidRecordException("Invalid negative header key size " + headerKeySize);
skipBytes(input, headerKeySize);
// headerValueSize
int headerValueSize = ByteUtils.readVarint(input);
skipBytes(input, headerValueSize);
}
return new PartialDefaultRecord(sizeInBytes, attributes, offset, timestamp, sequence, keySize, valueSize);
} catch (BufferUnderflowException | IllegalArgumentException e) {
throw new InvalidRecordException("Found invalid record structure", e);
}
}
/**
* Skips over and discards exactly {@code bytesToSkip} bytes from the input stream.
*
* We require a loop over {@link InputStream#skip(long)} because it is possible for InputStream to skip smaller
* number of bytes than expected (see javadoc for InputStream#skip).
*
* No-op for case where bytesToSkip <= 0. This could occur for cases where field is expected to be null.
* @throws InvalidRecordException if end of stream is encountered before we could skip required bytes.
* @throws IOException is an I/O error occurs while trying to skip from InputStream.
*
* @see java.io.InputStream#skip(long)
*/
private static void skipBytes(InputStream in, int bytesToSkip) throws IOException {
if (bytesToSkip <= 0) return;
// Starting JDK 12, this implementation could be replaced by InputStream#skipNBytes
while (bytesToSkip > 0) {
int ns = (int) in.skip(bytesToSkip);
if (ns > 0 && ns <= bytesToSkip) {
// adjust number to skip
bytesToSkip -= ns;
} else if (ns == 0) { // no bytes skipped
// read one byte to check for EOS
if (in.read() == -1) {
throw new InvalidRecordException("Reached end of input stream before skipping all bytes. " +
"Remaining bytes:" + bytesToSkip);
}
// one byte read so decrement number to skip
bytesToSkip--;
} else { // skipped negative or too many bytes
throw new IOException("Unable to skip exactly");
}
}
}
private static Header[] readHeaders(ByteBuffer buffer, int numHeaders) {
Header[] headers = new Header[numHeaders];
for (int i = 0; i < numHeaders; i++) {
int headerKeySize = ByteUtils.readVarint(buffer);
if (headerKeySize < 0)
throw new InvalidRecordException("Invalid negative header key size " + headerKeySize);
ByteBuffer headerKeyBuffer = Utils.readBytes(buffer, headerKeySize);
int headerValueSize = ByteUtils.readVarint(buffer);
ByteBuffer headerValue = Utils.readBytes(buffer, headerValueSize);
headers[i] = new RecordHeader(headerKeyBuffer, headerValue);
}
return headers;
}
public static int sizeInBytes(int offsetDelta,
long timestampDelta,
ByteBuffer key,
ByteBuffer value,
Header[] headers) {
int bodySize = sizeOfBodyInBytes(offsetDelta, timestampDelta, key, value, headers);
return bodySize + ByteUtils.sizeOfVarint(bodySize);
}
public static int sizeInBytes(int offsetDelta,
long timestampDelta,
int keySize,
int valueSize,
Header[] headers) {
int bodySize = sizeOfBodyInBytes(offsetDelta, timestampDelta, keySize, valueSize, headers);
return bodySize + ByteUtils.sizeOfVarint(bodySize);
}
private static int sizeOfBodyInBytes(int offsetDelta,
long timestampDelta,
ByteBuffer key,
ByteBuffer value,
Header[] headers) {
int keySize = key == null ? -1 : key.remaining();
int valueSize = value == null ? -1 : value.remaining();
return sizeOfBodyInBytes(offsetDelta, timestampDelta, keySize, valueSize, headers);
}
public static int sizeOfBodyInBytes(int offsetDelta,
long timestampDelta,
int keySize,
int valueSize,
Header[] headers) {
int size = 1; // always one byte for attributes
size += ByteUtils.sizeOfVarint(offsetDelta);
size += ByteUtils.sizeOfVarlong(timestampDelta);
size += sizeOf(keySize, valueSize, headers);
return size;
}
private static int sizeOf(int keySize, int valueSize, Header[] headers) {
int size = 0;
if (keySize < 0)
size += NULL_VARINT_SIZE_BYTES;
else
size += ByteUtils.sizeOfVarint(keySize) + keySize;
if (valueSize < 0)
size += NULL_VARINT_SIZE_BYTES;
else
size += ByteUtils.sizeOfVarint(valueSize) + valueSize;
if (headers == null)
throw new IllegalArgumentException("Headers cannot be null");
size += ByteUtils.sizeOfVarint(headers.length);
for (Header header : headers) {
String headerKey = header.key();
if (headerKey == null)
throw new IllegalArgumentException("Invalid null header key found in headers");
int headerKeySize = Utils.utf8Length(headerKey);
size += ByteUtils.sizeOfVarint(headerKeySize) + headerKeySize;
byte[] headerValue = header.value();
if (headerValue == null) {
size += NULL_VARINT_SIZE_BYTES;
} else {
size += ByteUtils.sizeOfVarint(headerValue.length) + headerValue.length;
}
}
return size;
}
static int recordSizeUpperBound(ByteBuffer key, ByteBuffer value, Header[] headers) {
int keySize = key == null ? -1 : key.remaining();
int valueSize = value == null ? -1 : value.remaining();
return MAX_RECORD_OVERHEAD + sizeOf(keySize, valueSize, headers);
}
}
|
DefaultRecord
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/issues/SplitterParallelRuntimeExceptionInHasNextOrNextTest.java
|
{
"start": 2846,
"end": 3214
}
|
class ____ {
public Iterator<String> errorInHasNext(InputStream request, Exchange exchange) {
return new CustomIterator(exchange, request, true);
}
public Iterator<String> errorInNext(InputStream request, Exchange exchange) {
return new CustomIterator(exchange, request, false);
}
}
static
|
SplitterImpl
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/security/oauthbearer/internals/secured/Retryable.java
|
{
"start": 936,
"end": 1098
}
|
interface ____ abstract out the call that is made so that it can be retried.
*
* @param <R> Result type
*
* @see Retry
* @see UnretryableException
*/
public
|
to
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest29.java
|
{
"start": 1016,
"end": 2377
}
|
class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "CREATE TABLE user" +
" (id INT, INDEX USING BTREE (id))" +
" MIN_ROWS 1024;";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
// print(statementList);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(1, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
assertTrue(visitor.getTables().containsKey(new TableStat.Name("user")));
String output = SQLUtils.toMySqlString(stmt);
assertEquals("CREATE TABLE user (" +
"\n\tid INT," +
"\n\tINDEX USING BTREE(id)" +
"\n) MIN_ROWS = 1024;", output);
}
}
|
MySqlCreateTableTest29
|
java
|
spring-projects__spring-boot
|
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java
|
{
"start": 3836,
"end": 4070
}
|
class ____ too long.
* @param listener the listener to add
*/
public void addMainClassTimeoutWarningListener(MainClassTimeoutWarningListener listener) {
this.mainClassTimeoutListeners.add(listener);
}
/**
* Sets the main
|
takes
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/ScoreOperator.java
|
{
"start": 3304,
"end": 3417
}
|
interface ____ extends Releasable {
/** A Factory for creating ExpressionScorers. */
|
ExpressionScorer
|
java
|
micronaut-projects__micronaut-core
|
core-processor/src/main/java/io/micronaut/inject/visitor/VisitorContext.java
|
{
"start": 8908,
"end": 9043
}
|
class ____ by name. If it cannot be found an empty optional will be returned.
*
* @param type The name
* @return The
|
element
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AbfsClientThrottlingAnalyzer.java
|
{
"start": 10376,
"end": 11467
}
|
class ____ extends TimerTask {
private AtomicInteger doingWork = new AtomicInteger(0);
/**
* Periodically analyzes a snapshot of the blob storage metrics and updates
* the sleepDuration in order to appropriately throttle storage operations.
*/
@Override
public void run() {
boolean doWork = false;
try {
doWork = doingWork.compareAndSet(0, 1);
// prevent concurrent execution of this task
if (!doWork) {
return;
}
long now = System.currentTimeMillis();
if (timerOrchestrator(TimerFunctionality.SUSPEND, this)) {
return;
}
if (now - blobMetrics.get().getStartTime() >= analysisPeriodMs) {
AbfsOperationMetrics oldMetrics = blobMetrics.getAndSet(
new AbfsOperationMetrics(now));
oldMetrics.setEndTime(now);
sleepDuration = analyzeMetricsAndUpdateSleepDuration(oldMetrics,
sleepDuration);
}
} finally {
if (doWork) {
doingWork.set(0);
}
}
}
}
}
|
TimerTaskImpl
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/action/search/CanMatchNodeRequest.java
|
{
"start": 2440,
"end": 11511
}
|
class ____ implements Writeable {
private final String[] indices;
private final ShardId shardId;
private final int shardRequestIndex;
private final AliasFilter aliasFilter;
private final float indexBoost;
private final ShardSearchContextId readerId;
private final TimeValue keepAlive;
private final long waitForCheckpoint;
private final SplitShardCountSummary reshardSplitShardCountSummary;
public Shard(
String[] indices,
ShardId shardId,
int shardRequestIndex,
AliasFilter aliasFilter,
float indexBoost,
ShardSearchContextId readerId,
TimeValue keepAlive,
long waitForCheckpoint,
SplitShardCountSummary reshardSplitShardCountSummary
) {
this.indices = indices;
this.shardId = shardId;
this.shardRequestIndex = shardRequestIndex;
this.aliasFilter = aliasFilter;
this.indexBoost = indexBoost;
this.readerId = readerId;
this.keepAlive = keepAlive;
this.waitForCheckpoint = waitForCheckpoint;
assert keepAlive == null || readerId != null : "readerId: " + readerId + " keepAlive: " + keepAlive;
this.reshardSplitShardCountSummary = reshardSplitShardCountSummary;
}
public Shard(StreamInput in) throws IOException {
indices = in.readStringArray();
shardId = new ShardId(in);
shardRequestIndex = in.readVInt();
aliasFilter = AliasFilter.readFrom(in);
indexBoost = in.readFloat();
readerId = in.readOptionalWriteable(ShardSearchContextId::new);
keepAlive = in.readOptionalTimeValue();
waitForCheckpoint = in.readLong();
assert keepAlive == null || readerId != null : "readerId: " + readerId + " keepAlive: " + keepAlive;
if (in.getTransportVersion().supports(ShardSearchRequest.SHARD_SEARCH_REQUEST_RESHARD_SHARD_COUNT_SUMMARY)) {
reshardSplitShardCountSummary = new SplitShardCountSummary(in);
} else {
reshardSplitShardCountSummary = SplitShardCountSummary.UNSET;
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeStringArray(indices);
shardId.writeTo(out);
out.writeVInt(shardRequestIndex);
aliasFilter.writeTo(out);
out.writeFloat(indexBoost);
out.writeOptionalWriteable(readerId);
out.writeOptionalTimeValue(keepAlive);
out.writeLong(waitForCheckpoint);
if (out.getTransportVersion().supports(ShardSearchRequest.SHARD_SEARCH_REQUEST_RESHARD_SHARD_COUNT_SUMMARY)) {
reshardSplitShardCountSummary.writeTo(out);
}
}
public int getShardRequestIndex() {
return shardRequestIndex;
}
public String[] getOriginalIndices() {
return indices;
}
public ShardId shardId() {
return shardId;
}
}
public CanMatchNodeRequest(
SearchRequest searchRequest,
IndicesOptions indicesOptions,
List<Shard> shards,
int numberOfShards,
long nowInMillis,
@Nullable String clusterAlias
) {
this.source = getCanMatchSource(searchRequest);
this.indicesOptions = indicesOptions;
this.shards = shards;
this.searchType = searchRequest.searchType();
this.requestCache = searchRequest.requestCache();
// If allowPartialSearchResults is unset (ie null), the cluster-level default should have been substituted
// at this stage. Any NPEs in the above are therefore an error in request preparation logic.
assert searchRequest.allowPartialSearchResults() != null;
this.allowPartialSearchResults = searchRequest.allowPartialSearchResults();
this.scroll = searchRequest.scroll();
this.numberOfShards = numberOfShards;
this.nowInMillis = nowInMillis;
this.clusterAlias = clusterAlias;
this.waitForCheckpointsTimeout = searchRequest.getWaitForCheckpointsTimeout();
indices = shards.stream().map(Shard::getOriginalIndices).flatMap(Arrays::stream).distinct().toArray(String[]::new);
}
private static void collectAggregationQueries(Collection<AggregationBuilder> aggregations, List<QueryBuilder> aggregationQueries) {
for (AggregationBuilder aggregation : aggregations) {
QueryBuilder aggregationQuery = aggregation.getQuery();
if (aggregationQuery != null) {
aggregationQueries.add(aggregationQuery);
}
collectAggregationQueries(aggregation.getSubAggregations(), aggregationQueries);
}
}
private SearchSourceBuilder getCanMatchSource(SearchRequest searchRequest) {
// Aggregations may use a different query than the top-level search query. An example is
// the significant terms aggregation, which also collects data over a background that
// typically much larger than the search query. To accommodate for this, we take the union
// of all queries to determine whether a request can match.
List<QueryBuilder> aggregationQueries = new ArrayList<>();
if (searchRequest.source() != null && searchRequest.source().aggregations() != null) {
collectAggregationQueries(searchRequest.source().aggregations().getAggregatorFactories(), aggregationQueries);
}
if (aggregationQueries.isEmpty()) {
return searchRequest.source();
} else {
List<SubSearchSourceBuilder> subSearches = new ArrayList<>(searchRequest.source().subSearches());
for (QueryBuilder aggregationQuery : aggregationQueries) {
subSearches.add(new SubSearchSourceBuilder(aggregationQuery));
}
return searchRequest.source().shallowCopy().subSearches(subSearches);
}
}
public CanMatchNodeRequest(StreamInput in) throws IOException {
super(in);
source = in.readOptionalWriteable(SearchSourceBuilder::new);
indicesOptions = IndicesOptions.readIndicesOptions(in);
searchType = SearchType.fromId(in.readByte());
scroll = in.readOptionalTimeValue();
requestCache = in.readOptionalBoolean();
allowPartialSearchResults = in.readBoolean();
numberOfShards = in.readVInt();
nowInMillis = in.readVLong();
clusterAlias = in.readOptionalString();
waitForCheckpointsTimeout = in.readTimeValue();
shards = in.readCollectionAsList(Shard::new);
indices = shards.stream().map(Shard::getOriginalIndices).flatMap(Arrays::stream).distinct().toArray(String[]::new);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalWriteable(source);
indicesOptions.writeIndicesOptions(out);
out.writeByte(searchType.id());
out.writeOptionalTimeValue(scroll);
out.writeOptionalBoolean(requestCache);
out.writeBoolean(allowPartialSearchResults);
out.writeVInt(numberOfShards);
out.writeVLong(nowInMillis);
out.writeOptionalString(clusterAlias);
out.writeTimeValue(waitForCheckpointsTimeout);
out.writeCollection(shards);
}
public List<Shard> getShardLevelRequests() {
return shards;
}
public ShardSearchRequest createShardSearchRequest(Shard r) {
ShardSearchRequest shardSearchRequest = new ShardSearchRequest(
new OriginalIndices(r.indices, indicesOptions),
r.shardId,
r.shardRequestIndex,
numberOfShards,
searchType,
source,
requestCache,
r.aliasFilter,
r.indexBoost,
allowPartialSearchResults,
scroll,
nowInMillis,
clusterAlias,
r.readerId,
r.keepAlive,
r.waitForCheckpoint,
waitForCheckpointsTimeout,
false,
r.reshardSplitShardCountSummary
);
shardSearchRequest.setParentTask(getParentTask());
return shardSearchRequest;
}
@Override
public String[] indices() {
return indices;
}
@Override
public IndicesOptions indicesOptions() {
return indicesOptions;
}
@Override
public Task createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) {
return new SearchShardTask(id, type, action, getDescription(), parentTaskId, headers);
}
@Override
public String getDescription() {
// Shard id is enough here, the request itself can be found by looking at the parent task description
return "shardIds[" + shards.stream().map(slr -> slr.shardId).toList() + "]";
}
}
|
Shard
|
java
|
apache__maven
|
compat/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/RequestTraceHelper.java
|
{
"start": 1664,
"end": 3229
}
|
class ____ to cover "most common" cases that are happening in Maven.
*/
public static String interpretTrace(boolean detailed, RequestTrace requestTrace) {
while (requestTrace != null) {
Object data = requestTrace.getData();
if (data instanceof DependencyRequest request) {
return "dependency resolution for " + request;
} else if (data instanceof CollectRequest request) {
return "dependency collection for " + request;
} else if (data instanceof CollectStepData stepData) {
String msg = "dependency collection step for " + stepData.getContext();
if (detailed) {
msg += ". Path to offending node from root:\n";
msg += stepData.getPath().stream()
.map(n -> " -> " + n.toString())
.collect(Collectors.joining("\n"));
msg += "\n => " + stepData.getNode();
}
return msg;
} else if (data instanceof ArtifactDescriptorRequest request) {
return "artifact descriptor request for " + request.getArtifact();
} else if (data instanceof ArtifactRequest request) {
return "artifact request for " + request.getArtifact();
} else if (data instanceof Plugin plugin) {
return "plugin request " + plugin.getId();
}
requestTrace = requestTrace.getParent();
}
return "n/a";
}
}
|
tries
|
java
|
apache__maven
|
api/maven-api-spi/src/main/java/org/apache/maven/api/spi/PackagingProvider.java
|
{
"start": 1049,
"end": 1132
}
|
interface ____ registering custom {@link Packaging} implementations.
* <p>
* This
|
for
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jdbc/GeneralWorkTest.java
|
{
"start": 849,
"end": 4076
}
|
class ____ {
@AfterEach
void cleanup(SessionFactoryScope factoryScope) {
factoryScope.dropData();
}
@Test
public void testGeneralUsage(SessionFactoryScope factoryScope) {
factoryScope.inTransaction( (session) -> session.doWork( (connection) -> {
// in this current form, users must handle try/catches themselves for proper resource release
Statement statement = null;
try {
statement = session.getJdbcCoordinator().getStatementPreparer().createStatement();
ResultSet resultSet = null;
try {
resultSet = session.getJdbcCoordinator().getResultSetReturn().extract( statement, "select * from T_JDBC_PERSON" );
}
finally {
releaseQuietly( session, resultSet, statement );
}
try {
session.getJdbcCoordinator().getResultSetReturn().extract( statement, "select * from T_JDBC_BOAT" );
}
finally {
releaseQuietly( session, resultSet, statement );
}
}
finally {
releaseQuietly( session, statement );
}
} ) );
}
@Test
public void testSQLExceptionThrowing(SessionFactoryScope factoryScope) {
factoryScope.inTransaction( (session) -> {
try {
session.doWork( (connection) -> {
Statement statement = null;
try {
statement = session.getJdbcCoordinator().getStatementPreparer().createStatement();
session.getJdbcCoordinator().getResultSetReturn().extract( statement, "select * from non_existent" );
}
finally {
releaseQuietly( session, statement );
}
fail( "expecting exception" );
} );
}
catch ( JDBCException expected ) {
// expected outcome
}
} );
}
@Test
public void testGeneralReturningUsage(SessionFactoryScope factoryScope) {
factoryScope.inTransaction( (session) -> {
var p = new Person( "Abe", "Lincoln" );
session.persist( p );
} );
factoryScope.inTransaction( (session) -> {
long count = session.doReturningWork( (connection) -> {
// in this current form, users must handle try/catches themselves for proper resource release
Statement statement = null;
long personCount = 0;
try {
statement = session.getJdbcCoordinator().getStatementPreparer().createStatement();
ResultSet resultSet = null;
try {
resultSet = session.getJdbcCoordinator().getResultSetReturn().extract( statement, "select count(*) from T_JDBC_PERSON" );
resultSet.next();
personCount = resultSet.getLong( 1 );
assertEquals( 1L, personCount );
}
finally {
releaseQuietly( session, resultSet, statement );
}
}
finally {
releaseQuietly( session, statement );
}
return personCount;
} );
} );
}
private void releaseQuietly(SessionImplementor s, Statement statement) {
if ( statement == null ) {
return;
}
try {
s.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( statement );
}
catch (Exception e) {
// ignore
}
}
private void releaseQuietly(SessionImplementor s, ResultSet resultSet, Statement statement) {
if ( resultSet == null ) {
return;
}
try {
s.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( resultSet, statement );
}
catch (Exception e) {
// ignore
}
}
}
|
GeneralWorkTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/RevertModelSnapshotAction.java
|
{
"start": 5694,
"end": 7203
}
|
class ____ extends ActionResponse implements ToXContentObject {
private static final ParseField MODEL = new ParseField("model");
private final ModelSnapshot model;
public Response(StreamInput in) throws IOException {
model = new ModelSnapshot(in);
}
public Response(ModelSnapshot modelSnapshot) {
model = modelSnapshot;
}
public ModelSnapshot getModel() {
return model;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
model.writeTo(out);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(MODEL.getPreferredName());
builder = model.toXContent(builder, params);
builder.endObject();
return builder;
}
@Override
public int hashCode() {
return Objects.hash(model);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Response other = (Response) obj;
return Objects.equals(model, other.model);
}
@Override
public final String toString() {
return Strings.toString(this);
}
}
}
|
Response
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/selection/qualifier/defaults/Folder.java
|
{
"start": 264,
"end": 551
}
|
class ____ {
private UUID id;
private Folder ancestor;
Folder(UUID id, Folder ancestor) {
this.id = id;
this.ancestor = ancestor;
}
public Folder getAncestor() {
return ancestor;
}
public UUID getId() {
return id;
}
}
|
Folder
|
java
|
netty__netty
|
codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java
|
{
"start": 12089,
"end": 58338
}
|
class ____ {
/**
* {@code "application/json"}
*/
public static final String APPLICATION_JSON = "application/json";
/**
* {@code "application/x-www-form-urlencoded"}
*/
public static final String APPLICATION_X_WWW_FORM_URLENCODED =
"application/x-www-form-urlencoded";
/**
* {@code "base64"}
*/
public static final String BASE64 = "base64";
/**
* {@code "binary"}
*/
public static final String BINARY = "binary";
/**
* {@code "boundary"}
*/
public static final String BOUNDARY = "boundary";
/**
* {@code "bytes"}
*/
public static final String BYTES = "bytes";
/**
* {@code "charset"}
*/
public static final String CHARSET = "charset";
/**
* {@code "chunked"}
*/
public static final String CHUNKED = "chunked";
/**
* {@code "close"}
*/
public static final String CLOSE = "close";
/**
* {@code "compress"}
*/
public static final String COMPRESS = "compress";
/**
* {@code "100-continue"}
*/
public static final String CONTINUE = "100-continue";
/**
* {@code "deflate"}
*/
public static final String DEFLATE = "deflate";
/**
* {@code "gzip"}
*/
public static final String GZIP = "gzip";
/**
* {@code "gzip,deflate"}
*/
public static final String GZIP_DEFLATE = "gzip,deflate";
/**
* {@code "identity"}
*/
public static final String IDENTITY = "identity";
/**
* {@code "keep-alive"}
*/
public static final String KEEP_ALIVE = "keep-alive";
/**
* {@code "max-age"}
*/
public static final String MAX_AGE = "max-age";
/**
* {@code "max-stale"}
*/
public static final String MAX_STALE = "max-stale";
/**
* {@code "min-fresh"}
*/
public static final String MIN_FRESH = "min-fresh";
/**
* {@code "multipart/form-data"}
*/
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
/**
* {@code "must-revalidate"}
*/
public static final String MUST_REVALIDATE = "must-revalidate";
/**
* {@code "no-cache"}
*/
public static final String NO_CACHE = "no-cache";
/**
* {@code "no-store"}
*/
public static final String NO_STORE = "no-store";
/**
* {@code "no-transform"}
*/
public static final String NO_TRANSFORM = "no-transform";
/**
* {@code "none"}
*/
public static final String NONE = "none";
/**
* {@code "only-if-cached"}
*/
public static final String ONLY_IF_CACHED = "only-if-cached";
/**
* {@code "private"}
*/
public static final String PRIVATE = "private";
/**
* {@code "proxy-revalidate"}
*/
public static final String PROXY_REVALIDATE = "proxy-revalidate";
/**
* {@code "public"}
*/
public static final String PUBLIC = "public";
/**
* {@code "quoted-printable"}
*/
public static final String QUOTED_PRINTABLE = "quoted-printable";
/**
* {@code "s-maxage"}
*/
public static final String S_MAXAGE = "s-maxage";
/**
* {@code "trailers"}
*/
public static final String TRAILERS = "trailers";
/**
* {@code "Upgrade"}
*/
public static final String UPGRADE = "Upgrade";
/**
* {@code "WebSocket"}
*/
public static final String WEBSOCKET = "WebSocket";
private Values() {
}
}
/**
* @deprecated Use {@link HttpUtil#isKeepAlive(HttpMessage)} instead.
*
* Returns {@code true} if and only if the connection can remain open and
* thus 'kept alive'. This methods respects the value of the
* {@code "Connection"} header first and then the return value of
* {@link HttpVersion#isKeepAliveDefault()}.
*/
@Deprecated
public static boolean isKeepAlive(HttpMessage message) {
return HttpUtil.isKeepAlive(message);
}
/**
* @deprecated Use {@link HttpUtil#setKeepAlive(HttpMessage, boolean)} instead.
*
* Sets the value of the {@code "Connection"} header depending on the
* protocol version of the specified message. This getMethod sets or removes
* the {@code "Connection"} header depending on what the default keep alive
* mode of the message's protocol version is, as specified by
* {@link HttpVersion#isKeepAliveDefault()}.
* <ul>
* <li>If the connection is kept alive by default:
* <ul>
* <li>set to {@code "close"} if {@code keepAlive} is {@code false}.</li>
* <li>remove otherwise.</li>
* </ul></li>
* <li>If the connection is closed by default:
* <ul>
* <li>set to {@code "keep-alive"} if {@code keepAlive} is {@code true}.</li>
* <li>remove otherwise.</li>
* </ul></li>
* </ul>
*/
@Deprecated
public static void setKeepAlive(HttpMessage message, boolean keepAlive) {
HttpUtil.setKeepAlive(message, keepAlive);
}
/**
* @deprecated Use {@link #get(CharSequence)} instead.
*/
@Deprecated
public static String getHeader(HttpMessage message, String name) {
return message.headers().get(name);
}
/**
* @deprecated Use {@link #get(CharSequence)} instead.
*
* Returns the header value with the specified header name. If there are
* more than one header value for the specified header name, the first
* value is returned.
*
* @return the header value or {@code null} if there is no such header
*/
@Deprecated
public static String getHeader(HttpMessage message, CharSequence name) {
return message.headers().get(name);
}
/**
* @deprecated Use {@link #get(CharSequence, String)} instead.
*
* @see #getHeader(HttpMessage, CharSequence, String)
*/
@Deprecated
public static String getHeader(HttpMessage message, String name, String defaultValue) {
return message.headers().get(name, defaultValue);
}
/**
* @deprecated Use {@link #get(CharSequence, String)} instead.
*
* Returns the header value with the specified header name. If there are
* more than one header value for the specified header name, the first
* value is returned.
*
* @return the header value or the {@code defaultValue} if there is no such
* header
*/
@Deprecated
public static String getHeader(HttpMessage message, CharSequence name, String defaultValue) {
return message.headers().get(name, defaultValue);
}
/**
* @deprecated Use {@link #set(CharSequence, Object)} instead.
*
* @see #setHeader(HttpMessage, CharSequence, Object)
*/
@Deprecated
public static void setHeader(HttpMessage message, String name, Object value) {
message.headers().set(name, value);
}
/**
* @deprecated Use {@link #set(CharSequence, Object)} instead.
*
* Sets a new header with the specified name and value. If there is an
* existing header with the same name, the existing header is removed.
* If the specified value is not a {@link String}, it is converted into a
* {@link String} by {@link Object#toString()}, except for {@link Date}
* and {@link Calendar} which are formatted to the date format defined in
* <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a>.
*/
@Deprecated
public static void setHeader(HttpMessage message, CharSequence name, Object value) {
message.headers().set(name, value);
}
/**
* @deprecated Use {@link #set(CharSequence, Iterable)} instead.
*
* @see #setHeader(HttpMessage, CharSequence, Iterable)
*/
@Deprecated
public static void setHeader(HttpMessage message, String name, Iterable<?> values) {
message.headers().set(name, values);
}
/**
* @deprecated Use {@link #set(CharSequence, Iterable)} instead.
*
* Sets a new header with the specified name and values. If there is an
* existing header with the same name, the existing header is removed.
* This getMethod can be represented approximately as the following code:
* <pre>
* removeHeader(message, name);
* for (Object v: values) {
* if (v == null) {
* break;
* }
* addHeader(message, name, v);
* }
* </pre>
*/
@Deprecated
public static void setHeader(HttpMessage message, CharSequence name, Iterable<?> values) {
message.headers().set(name, values);
}
/**
* @deprecated Use {@link #add(CharSequence, Object)} instead.
*
* @see #addHeader(HttpMessage, CharSequence, Object)
*/
@Deprecated
public static void addHeader(HttpMessage message, String name, Object value) {
message.headers().add(name, value);
}
/**
* @deprecated Use {@link #add(CharSequence, Object)} instead.
*
* Adds a new header with the specified name and value.
* If the specified value is not a {@link String}, it is converted into a
* {@link String} by {@link Object#toString()}, except for {@link Date}
* and {@link Calendar} which are formatted to the date format defined in
* <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a>.
*/
@Deprecated
public static void addHeader(HttpMessage message, CharSequence name, Object value) {
message.headers().add(name, value);
}
/**
* @deprecated Use {@link #remove(CharSequence)} instead.
*
* @see #removeHeader(HttpMessage, CharSequence)
*/
@Deprecated
public static void removeHeader(HttpMessage message, String name) {
message.headers().remove(name);
}
/**
* @deprecated Use {@link #remove(CharSequence)} instead.
*
* Removes the header with the specified name.
*/
@Deprecated
public static void removeHeader(HttpMessage message, CharSequence name) {
message.headers().remove(name);
}
/**
* @deprecated Use {@link #clear()} instead.
*
* Removes all headers from the specified message.
*/
@Deprecated
public static void clearHeaders(HttpMessage message) {
message.headers().clear();
}
/**
* @deprecated Use {@link #getInt(CharSequence)} instead.
*
* @see #getIntHeader(HttpMessage, CharSequence)
*/
@Deprecated
public static int getIntHeader(HttpMessage message, String name) {
return getIntHeader(message, (CharSequence) name);
}
/**
* @deprecated Use {@link #getInt(CharSequence)} instead.
*
* Returns the integer header value with the specified header name. If
* there are more than one header value for the specified header name, the
* first value is returned.
*
* @return the header value
* @throws NumberFormatException
* if there is no such header or the header value is not a number
*/
@Deprecated
public static int getIntHeader(HttpMessage message, CharSequence name) {
String value = message.headers().get(name);
if (value == null) {
throw new NumberFormatException("header not found: " + name);
}
return Integer.parseInt(value);
}
/**
* @deprecated Use {@link #getInt(CharSequence, int)} instead.
*
* @see #getIntHeader(HttpMessage, CharSequence, int)
*/
@Deprecated
public static int getIntHeader(HttpMessage message, String name, int defaultValue) {
return message.headers().getInt(name, defaultValue);
}
/**
* @deprecated Use {@link #getInt(CharSequence, int)} instead.
*
* Returns the integer header value with the specified header name. If
* there are more than one header value for the specified header name, the
* first value is returned.
*
* @return the header value or the {@code defaultValue} if there is no such
* header or the header value is not a number
*/
@Deprecated
public static int getIntHeader(HttpMessage message, CharSequence name, int defaultValue) {
return message.headers().getInt(name, defaultValue);
}
/**
* @deprecated Use {@link #setInt(CharSequence, int)} instead.
*
* @see #setIntHeader(HttpMessage, CharSequence, int)
*/
@Deprecated
public static void setIntHeader(HttpMessage message, String name, int value) {
message.headers().setInt(name, value);
}
/**
* @deprecated Use {@link #setInt(CharSequence, int)} instead.
*
* Sets a new integer header with the specified name and value. If there
* is an existing header with the same name, the existing header is removed.
*/
@Deprecated
public static void setIntHeader(HttpMessage message, CharSequence name, int value) {
message.headers().setInt(name, value);
}
/**
* @deprecated Use {@link #set(CharSequence, Iterable)} instead.
*
* @see #setIntHeader(HttpMessage, CharSequence, Iterable)
*/
@Deprecated
public static void setIntHeader(HttpMessage message, String name, Iterable<Integer> values) {
message.headers().set(name, values);
}
/**
* @deprecated Use {@link #set(CharSequence, Iterable)} instead.
*
* Sets a new integer header with the specified name and values. If there
* is an existing header with the same name, the existing header is removed.
*/
@Deprecated
public static void setIntHeader(HttpMessage message, CharSequence name, Iterable<Integer> values) {
message.headers().set(name, values);
}
/**
* @deprecated Use {@link #add(CharSequence, Iterable)} instead.
*
* @see #addIntHeader(HttpMessage, CharSequence, int)
*/
@Deprecated
public static void addIntHeader(HttpMessage message, String name, int value) {
message.headers().add(name, value);
}
/**
* @deprecated Use {@link #addInt(CharSequence, int)} instead.
*
* Adds a new integer header with the specified name and value.
*/
@Deprecated
public static void addIntHeader(HttpMessage message, CharSequence name, int value) {
message.headers().addInt(name, value);
}
/**
* @deprecated Use {@link #getTimeMillis(CharSequence)} instead.
*
* @see #getDateHeader(HttpMessage, CharSequence)
*/
@Deprecated
public static Date getDateHeader(HttpMessage message, String name) throws ParseException {
return getDateHeader(message, (CharSequence) name);
}
/**
* @deprecated Use {@link #getTimeMillis(CharSequence)} instead.
*
* Returns the date header value with the specified header name. If
* there are more than one header value for the specified header name, the
* first value is returned.
*
* @return the header value
* @throws ParseException
* if there is no such header or the header value is not a formatted date
*/
@Deprecated
public static Date getDateHeader(HttpMessage message, CharSequence name) throws ParseException {
String value = message.headers().get(name);
if (value == null) {
throw new ParseException("header not found: " + name, 0);
}
Date date = DateFormatter.parseHttpDate(value);
if (date == null) {
throw new ParseException("header can't be parsed into a Date: " + value, 0);
}
return date;
}
/**
* @deprecated Use {@link #getTimeMillis(CharSequence, long)} instead.
*
* @see #getDateHeader(HttpMessage, CharSequence, Date)
*/
@Deprecated
public static Date getDateHeader(HttpMessage message, String name, Date defaultValue) {
return getDateHeader(message, (CharSequence) name, defaultValue);
}
/**
* @deprecated Use {@link #getTimeMillis(CharSequence, long)} instead.
*
* Returns the date header value with the specified header name. If
* there are more than one header value for the specified header name, the
* first value is returned.
*
* @return the header value or the {@code defaultValue} if there is no such
* header or the header value is not a formatted date
*/
@Deprecated
public static Date getDateHeader(HttpMessage message, CharSequence name, Date defaultValue) {
final String value = getHeader(message, name);
Date date = DateFormatter.parseHttpDate(value);
return date != null ? date : defaultValue;
}
/**
* @deprecated Use {@link #set(CharSequence, Object)} instead.
*
* @see #setDateHeader(HttpMessage, CharSequence, Date)
*/
@Deprecated
public static void setDateHeader(HttpMessage message, String name, Date value) {
setDateHeader(message, (CharSequence) name, value);
}
/**
* @deprecated Use {@link #set(CharSequence, Object)} instead.
*
* Sets a new date header with the specified name and value. If there
* is an existing header with the same name, the existing header is removed.
* The specified value is formatted as defined in
* <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a>
*/
@Deprecated
public static void setDateHeader(HttpMessage message, CharSequence name, Date value) {
if (value != null) {
message.headers().set(name, DateFormatter.format(value));
} else {
message.headers().set(name, null);
}
}
/**
* @deprecated Use {@link #set(CharSequence, Iterable)} instead.
*
* @see #setDateHeader(HttpMessage, CharSequence, Iterable)
*/
@Deprecated
public static void setDateHeader(HttpMessage message, String name, Iterable<Date> values) {
message.headers().set(name, values);
}
/**
* @deprecated Use {@link #set(CharSequence, Iterable)} instead.
*
* Sets a new date header with the specified name and values. If there
* is an existing header with the same name, the existing header is removed.
* The specified values are formatted as defined in
* <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a>
*/
@Deprecated
public static void setDateHeader(HttpMessage message, CharSequence name, Iterable<Date> values) {
message.headers().set(name, values);
}
/**
* @deprecated Use {@link #add(CharSequence, Object)} instead.
*
* @see #addDateHeader(HttpMessage, CharSequence, Date)
*/
@Deprecated
public static void addDateHeader(HttpMessage message, String name, Date value) {
message.headers().add(name, value);
}
/**
* @deprecated Use {@link #add(CharSequence, Object)} instead.
*
* Adds a new date header with the specified name and value. The specified
* value is formatted as defined in
* <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a>
*/
@Deprecated
public static void addDateHeader(HttpMessage message, CharSequence name, Date value) {
message.headers().add(name, value);
}
/**
* @deprecated Use {@link HttpUtil#getContentLength(HttpMessage)} instead.
*
* Returns the length of the content. Please note that this value is
* not retrieved from {@link HttpContent#content()} but from the
* {@code "Content-Length"} header, and thus they are independent from each
* other.
*
* @return the content length
*
* @throws NumberFormatException
* if the message does not have the {@code "Content-Length"} header
* or its value is not a number
*/
@Deprecated
public static long getContentLength(HttpMessage message) {
return HttpUtil.getContentLength(message);
}
/**
* @deprecated Use {@link HttpUtil#getContentLength(HttpMessage, long)} instead.
*
* Returns the length of the content. Please note that this value is
* not retrieved from {@link HttpContent#content()} but from the
* {@code "Content-Length"} header, and thus they are independent from each
* other.
*
* @return the content length or {@code defaultValue} if this message does
* not have the {@code "Content-Length"} header or its value is not
* a number
*/
@Deprecated
public static long getContentLength(HttpMessage message, long defaultValue) {
return HttpUtil.getContentLength(message, defaultValue);
}
/**
* @deprecated Use {@link HttpUtil#setContentLength(HttpMessage, long)} instead.
*/
@Deprecated
public static void setContentLength(HttpMessage message, long length) {
HttpUtil.setContentLength(message, length);
}
/**
* @deprecated Use {@link #get(CharSequence)} instead.
*
* Returns the value of the {@code "Host"} header.
*/
@Deprecated
public static String getHost(HttpMessage message) {
return message.headers().get(HttpHeaderNames.HOST);
}
/**
* @deprecated Use {@link #get(CharSequence, String)} instead.
*
* Returns the value of the {@code "Host"} header. If there is no such
* header, the {@code defaultValue} is returned.
*/
@Deprecated
public static String getHost(HttpMessage message, String defaultValue) {
return message.headers().get(HttpHeaderNames.HOST, defaultValue);
}
/**
* @deprecated Use {@link #set(CharSequence, Object)} instead.
*
* @see #setHost(HttpMessage, CharSequence)
*/
@Deprecated
public static void setHost(HttpMessage message, String value) {
message.headers().set(HttpHeaderNames.HOST, value);
}
/**
* @deprecated Use {@link #set(CharSequence, Object)} instead.
*
* Sets the {@code "Host"} header.
*/
@Deprecated
public static void setHost(HttpMessage message, CharSequence value) {
message.headers().set(HttpHeaderNames.HOST, value);
}
/**
* @deprecated Use {@link #getTimeMillis(CharSequence)} instead.
*
* Returns the value of the {@code "Date"} header.
*
* @throws ParseException
* if there is no such header or the header value is not a formatted date
*/
@Deprecated
public static Date getDate(HttpMessage message) throws ParseException {
return getDateHeader(message, HttpHeaderNames.DATE);
}
/**
* @deprecated Use {@link #getTimeMillis(CharSequence, long)} instead.
*
* Returns the value of the {@code "Date"} header. If there is no such
* header or the header is not a formatted date, the {@code defaultValue}
* is returned.
*/
@Deprecated
public static Date getDate(HttpMessage message, Date defaultValue) {
return getDateHeader(message, HttpHeaderNames.DATE, defaultValue);
}
/**
* @deprecated Use {@link #set(CharSequence, Object)} instead.
*
* Sets the {@code "Date"} header.
*/
@Deprecated
public static void setDate(HttpMessage message, Date value) {
message.headers().set(HttpHeaderNames.DATE, value);
}
/**
* @deprecated Use {@link HttpUtil#is100ContinueExpected(HttpMessage)} instead.
*
* Returns {@code true} if and only if the specified message contains the
* {@code "Expect: 100-continue"} header.
*/
@Deprecated
public static boolean is100ContinueExpected(HttpMessage message) {
return HttpUtil.is100ContinueExpected(message);
}
/**
* @deprecated Use {@link HttpUtil#set100ContinueExpected(HttpMessage, boolean)} instead.
*
* Sets the {@code "Expect: 100-continue"} header to the specified message.
* If there is any existing {@code "Expect"} header, they are replaced with
* the new one.
*/
@Deprecated
public static void set100ContinueExpected(HttpMessage message) {
HttpUtil.set100ContinueExpected(message, true);
}
/**
* @deprecated Use {@link HttpUtil#set100ContinueExpected(HttpMessage, boolean)} instead.
*
* Sets or removes the {@code "Expect: 100-continue"} header to / from the
* specified message. If {@code set} is {@code true},
* the {@code "Expect: 100-continue"} header is set and all other previous
* {@code "Expect"} headers are removed. Otherwise, all {@code "Expect"}
* headers are removed completely.
*/
@Deprecated
public static void set100ContinueExpected(HttpMessage message, boolean set) {
HttpUtil.set100ContinueExpected(message, set);
}
/**
* @deprecated Use {@link HttpUtil#isTransferEncodingChunked(HttpMessage)} instead.
*
* Checks to see if the transfer encoding in a specified {@link HttpMessage} is chunked
*
* @param message The message to check
* @return True if transfer encoding is chunked, otherwise false
*/
@Deprecated
public static boolean isTransferEncodingChunked(HttpMessage message) {
return HttpUtil.isTransferEncodingChunked(message);
}
/**
* @deprecated Use {@link HttpUtil#setTransferEncodingChunked(HttpMessage, boolean)} instead.
*/
@Deprecated
public static void removeTransferEncodingChunked(HttpMessage m) {
HttpUtil.setTransferEncodingChunked(m, false);
}
/**
* @deprecated Use {@link HttpUtil#setTransferEncodingChunked(HttpMessage, boolean)} instead.
*/
@Deprecated
public static void setTransferEncodingChunked(HttpMessage m) {
HttpUtil.setTransferEncodingChunked(m, true);
}
/**
* @deprecated Use {@link HttpUtil#isContentLengthSet(HttpMessage)} instead.
*/
@Deprecated
public static boolean isContentLengthSet(HttpMessage m) {
return HttpUtil.isContentLengthSet(m);
}
/**
* @deprecated Use {@link AsciiString#contentEqualsIgnoreCase(CharSequence, CharSequence)} instead.
*/
@Deprecated
public static boolean equalsIgnoreCase(CharSequence name1, CharSequence name2) {
return contentEqualsIgnoreCase(name1, name2);
}
@Deprecated
public static void encodeAscii(CharSequence seq, ByteBuf buf) {
if (seq instanceof AsciiString) {
ByteBufUtil.copy((AsciiString) seq, 0, buf, seq.length());
} else {
buf.writeCharSequence(seq, CharsetUtil.US_ASCII);
}
}
/**
* @deprecated Use {@link AsciiString} instead.
* <p>
* Create a new {@link CharSequence} which is optimized for reuse as {@link HttpHeaders} name or value.
* So if you have a Header name or value that you want to reuse you should make use of this.
*/
@Deprecated
public static CharSequence newEntity(String name) {
return new AsciiString(name);
}
protected HttpHeaders() { }
/**
* @see #get(CharSequence)
*/
public abstract String get(String name);
/**
* Returns the value of a header with the specified name. If there are
* more than one values for the specified name, the first value is returned.
*
* @param name The name of the header to search
* @return The first header value or {@code null} if there is no such header
* @see #getAsString(CharSequence)
*/
public String get(CharSequence name) {
return get(name.toString());
}
/**
* Returns the value of a header with the specified name. If there are
* more than one values for the specified name, the first value is returned.
*
* @param name The name of the header to search
* @return The first header value or {@code defaultValue} if there is no such header
*/
public String get(CharSequence name, String defaultValue) {
String value = get(name);
if (value == null) {
return defaultValue;
}
return value;
}
/**
* Returns the integer value of a header with the specified name. If there are more than one values for the
* specified name, the first value is returned.
*
* @param name the name of the header to search
* @return the first header value if the header is found and its value is an integer. {@code null} if there's no
* such header or its value is not an integer.
*/
public abstract Integer getInt(CharSequence name);
/**
* Returns the integer value of a header with the specified name. If there are more than one values for the
* specified name, the first value is returned.
*
* @param name the name of the header to search
* @param defaultValue the default value
* @return the first header value if the header is found and its value is an integer. {@code defaultValue} if
* there's no such header or its value is not an integer.
*/
public abstract int getInt(CharSequence name, int defaultValue);
/**
* Returns the short value of a header with the specified name. If there are more than one values for the
* specified name, the first value is returned.
*
* @param name the name of the header to search
* @return the first header value if the header is found and its value is a short. {@code null} if there's no
* such header or its value is not a short.
*/
public abstract Short getShort(CharSequence name);
/**
* Returns the short value of a header with the specified name. If there are more than one values for the
* specified name, the first value is returned.
*
* @param name the name of the header to search
* @param defaultValue the default value
* @return the first header value if the header is found and its value is a short. {@code defaultValue} if
* there's no such header or its value is not a short.
*/
public abstract short getShort(CharSequence name, short defaultValue);
/**
* Returns the date value of a header with the specified name. If there are more than one values for the
* specified name, the first value is returned.
*
* @param name the name of the header to search
* @return the first header value if the header is found and its value is a date. {@code null} if there's no
* such header or its value is not a date.
*/
public abstract Long getTimeMillis(CharSequence name);
/**
* Returns the date value of a header with the specified name. If there are more than one values for the
* specified name, the first value is returned.
*
* @param name the name of the header to search
* @param defaultValue the default value
* @return the first header value if the header is found and its value is a date. {@code defaultValue} if
* there's no such header or its value is not a date.
*/
public abstract long getTimeMillis(CharSequence name, long defaultValue);
/**
* @see #getAll(CharSequence)
*/
public abstract List<String> getAll(String name);
/**
* Returns the values of headers with the specified name
*
* @param name The name of the headers to search
* @return A {@link List} of header values which will be empty if no values
* are found
* @see #getAllAsString(CharSequence)
*/
public List<String> getAll(CharSequence name) {
return getAll(name.toString());
}
/**
* Returns a new {@link List} that contains all headers in this object. Note that modifying the
* returned {@link List} will not affect the state of this object. If you intend to enumerate over the header
* entries only, use {@link #iterator()} instead, which has much less overhead.
* @see #iteratorCharSequence()
*/
public abstract List<Map.Entry<String, String>> entries();
/**
* @see #contains(CharSequence)
*/
public abstract boolean contains(String name);
/**
* @deprecated It is preferred to use {@link #iteratorCharSequence()} unless you need {@link String}.
* If {@link String} is required then use {@link #iteratorAsString()}.
*/
@Deprecated
@Override
public abstract Iterator<Entry<String, String>> iterator();
/**
* @return Iterator over the name/value header pairs.
*/
public abstract Iterator<Entry<CharSequence, CharSequence>> iteratorCharSequence();
/**
* Equivalent to {@link #getAll(String)} but it is possible that no intermediate list is generated.
* @param name the name of the header to retrieve
* @return an {@link Iterator} of header values corresponding to {@code name}.
*/
public Iterator<String> valueStringIterator(CharSequence name) {
return getAll(name).iterator();
}
/**
* Equivalent to {@link #getAll(String)} but it is possible that no intermediate list is generated.
* @param name the name of the header to retrieve
* @return an {@link Iterator} of header values corresponding to {@code name}.
*/
public Iterator<? extends CharSequence> valueCharSequenceIterator(CharSequence name) {
return valueStringIterator(name);
}
/**
* Checks to see if there is a header with the specified name
*
* @param name The name of the header to search for
* @return True if at least one header is found
*/
public boolean contains(CharSequence name) {
return contains(name.toString());
}
/**
* Checks if no header exists.
*/
public abstract boolean isEmpty();
/**
* Returns the number of headers in this object.
*/
public abstract int size();
/**
* Returns a new {@link Set} that contains the names of all headers in this object. Note that modifying the
* returned {@link Set} will not affect the state of this object. If you intend to enumerate over the header
* entries only, use {@link #iterator()} instead, which has much less overhead.
*/
public abstract Set<String> names();
/**
* @see #add(CharSequence, Object)
*/
public abstract HttpHeaders add(String name, Object value);
/**
* Adds a new header with the specified name and value.
*
* If the specified value is not a {@link String}, it is converted
* into a {@link String} by {@link Object#toString()}, except in the cases
* of {@link Date} and {@link Calendar}, which are formatted to the date
* format defined in <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a>.
*
* @param name The name of the header being added
* @param value The value of the header being added
*
* @return {@code this}
*/
public HttpHeaders add(CharSequence name, Object value) {
return add(name.toString(), value);
}
/**
* @see #add(CharSequence, Iterable)
*/
public abstract HttpHeaders add(String name, Iterable<?> values);
/**
* Adds a new header with the specified name and values.
*
* This getMethod can be represented approximately as the following code:
* <pre>
* for (Object v: values) {
* if (v == null) {
* break;
* }
* headers.add(name, v);
* }
* </pre>
*
* @param name The name of the headers being set
* @param values The values of the headers being set
* @return {@code this}
*/
public HttpHeaders add(CharSequence name, Iterable<?> values) {
return add(name.toString(), values);
}
/**
* Adds all header entries of the specified {@code headers}.
*
* @return {@code this}
*/
public HttpHeaders add(HttpHeaders headers) {
ObjectUtil.checkNotNull(headers, "headers");
for (Map.Entry<String, String> e: headers) {
add(e.getKey(), e.getValue());
}
return this;
}
/**
* Add the {@code name} to {@code value}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
public abstract HttpHeaders addInt(CharSequence name, int value);
/**
* Add the {@code name} to {@code value}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
public abstract HttpHeaders addShort(CharSequence name, short value);
/**
* @see #set(CharSequence, Object)
*/
public abstract HttpHeaders set(String name, Object value);
/**
* Sets a header with the specified name and value.
*
* If there is an existing header with the same name, it is removed.
* If the specified value is not a {@link String}, it is converted into a
* {@link String} by {@link Object#toString()}, except for {@link Date}
* and {@link Calendar}, which are formatted to the date format defined in
* <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a>.
*
* @param name The name of the header being set
* @param value The value of the header being set
* @return {@code this}
*/
public HttpHeaders set(CharSequence name, Object value) {
return set(name.toString(), value);
}
/**
* @see #set(CharSequence, Iterable)
*/
public abstract HttpHeaders set(String name, Iterable<?> values);
/**
* Sets a header with the specified name and values.
*
* If there is an existing header with the same name, it is removed.
* This getMethod can be represented approximately as the following code:
* <pre>
* headers.remove(name);
* for (Object v: values) {
* if (v == null) {
* break;
* }
* headers.add(name, v);
* }
* </pre>
*
* @param name The name of the headers being set
* @param values The values of the headers being set
* @return {@code this}
*/
public HttpHeaders set(CharSequence name, Iterable<?> values) {
return set(name.toString(), values);
}
/**
* Cleans the current header entries and copies all header entries of the specified {@code headers}.
*
* @return {@code this}
*/
public HttpHeaders set(HttpHeaders headers) {
checkNotNull(headers, "headers");
clear();
if (headers.isEmpty()) {
return this;
}
for (Entry<String, String> entry : headers) {
add(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Retains all current headers but calls {@link #set(String, Object)} for each entry in {@code headers}
*
* @param headers The headers used to {@link #set(String, Object)} values in this instance
* @return {@code this}
*/
public HttpHeaders setAll(HttpHeaders headers) {
checkNotNull(headers, "headers");
if (headers.isEmpty()) {
return this;
}
for (Entry<String, String> entry : headers) {
set(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Set the {@code name} to {@code value}. This will remove all previous values associated with {@code name}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
public abstract HttpHeaders setInt(CharSequence name, int value);
/**
* Set the {@code name} to {@code value}. This will remove all previous values associated with {@code name}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
public abstract HttpHeaders setShort(CharSequence name, short value);
/**
* @see #remove(CharSequence)
*/
public abstract HttpHeaders remove(String name);
/**
* Removes the header with the specified name.
*
* @param name The name of the header to remove
* @return {@code this}
*/
public HttpHeaders remove(CharSequence name) {
return remove(name.toString());
}
/**
* Removes all headers from this {@link HttpMessage}.
*
* @return {@code this}
*/
public abstract HttpHeaders clear();
/**
* @see #contains(CharSequence, CharSequence, boolean)
*/
public boolean contains(String name, String value, boolean ignoreCase) {
Iterator<String> valueIterator = valueStringIterator(name);
if (ignoreCase) {
while (valueIterator.hasNext()) {
if (valueIterator.next().equalsIgnoreCase(value)) {
return true;
}
}
} else {
while (valueIterator.hasNext()) {
if (valueIterator.next().equals(value)) {
return true;
}
}
}
return false;
}
/**
* Returns {@code true} if a header with the {@code name} and {@code value} exists, {@code false} otherwise.
* This also handles multiple values that are separated with a {@code ,}.
* <p>
* If {@code ignoreCase} is {@code true} then a case insensitive compare is done on the value.
* @param name the name of the header to find
* @param value the value of the header to find
* @param ignoreCase {@code true} then a case insensitive compare is run to compare values.
* otherwise a case sensitive compare is run to compare values.
*/
public boolean containsValue(CharSequence name, CharSequence value, boolean ignoreCase) {
Iterator<? extends CharSequence> itr = valueCharSequenceIterator(name);
while (itr.hasNext()) {
if (containsCommaSeparatedTrimmed(itr.next(), value, ignoreCase)) {
return true;
}
}
return false;
}
private static boolean containsCommaSeparatedTrimmed(CharSequence rawNext, CharSequence expected,
boolean ignoreCase) {
int begin = 0;
int end;
if (ignoreCase) {
if ((end = AsciiString.indexOf(rawNext, ',', begin)) == -1) {
if (contentEqualsIgnoreCase(trim(rawNext), expected)) {
return true;
}
} else {
do {
if (contentEqualsIgnoreCase(trim(rawNext.subSequence(begin, end)), expected)) {
return true;
}
begin = end + 1;
} while ((end = AsciiString.indexOf(rawNext, ',', begin)) != -1);
if (begin < rawNext.length()) {
if (contentEqualsIgnoreCase(trim(rawNext.subSequence(begin, rawNext.length())), expected)) {
return true;
}
}
}
} else {
if ((end = AsciiString.indexOf(rawNext, ',', begin)) == -1) {
if (contentEquals(trim(rawNext), expected)) {
return true;
}
} else {
do {
if (contentEquals(trim(rawNext.subSequence(begin, end)), expected)) {
return true;
}
begin = end + 1;
} while ((end = AsciiString.indexOf(rawNext, ',', begin)) != -1);
if (begin < rawNext.length()) {
if (contentEquals(trim(rawNext.subSequence(begin, rawNext.length())), expected)) {
return true;
}
}
}
}
return false;
}
/**
* {@link Headers#get(Object)} and convert the result to a {@link String}.
* @param name the name of the header to retrieve
* @return the first header value if the header is found. {@code null} if there's no such header.
*/
public final String getAsString(CharSequence name) {
return get(name);
}
/**
* {@link Headers#getAll(Object)} and convert each element of {@link List} to a {@link String}.
* @param name the name of the header to retrieve
* @return a {@link List} of header values or an empty {@link List} if no values are found.
*/
public final List<String> getAllAsString(CharSequence name) {
return getAll(name);
}
/**
* {@link Iterator} that converts each {@link Entry}'s key and value to a {@link String}.
*/
public final Iterator<Entry<String, String>> iteratorAsString() {
return iterator();
}
/**
* Returns {@code true} if a header with the {@code name} and {@code value} exists, {@code false} otherwise.
* <p>
* If {@code ignoreCase} is {@code true} then a case insensitive compare is done on the value.
* @param name the name of the header to find
* @param value the value of the header to find
* @param ignoreCase {@code true} then a case insensitive compare is run to compare values.
* otherwise a case sensitive compare is run to compare values.
*/
public boolean contains(CharSequence name, CharSequence value, boolean ignoreCase) {
return contains(name.toString(), value.toString(), ignoreCase);
}
@Override
public String toString() {
return HeadersUtils.toString(getClass(), iteratorCharSequence(), size());
}
/**
* Returns a deep copy of the passed in {@link HttpHeaders}.
*/
public HttpHeaders copy() {
return new DefaultHttpHeaders().set(this);
}
}
|
Values
|
java
|
reactor__reactor-core
|
reactor-core/src/main/java/reactor/util/Logger.java
|
{
"start": 761,
"end": 819
}
|
interface ____ for internal Reactor usage.
*/
public
|
designed
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/InstanceOfAssertFactoriesTest.java
|
{
"start": 19067,
"end": 19704
}
|
class ____ {
private final Object actual = Optional.of("something");
@Test
void createAssert() {
// WHEN
OptionalAssert<Object> result = OPTIONAL.createAssert(actual);
// THEN
result.isPresent();
}
@Test
void createAssert_with_ValueProvider() {
// GIVEN
ValueProvider<?> valueProvider = mockThatDelegatesTo(type -> actual);
// WHEN
OptionalAssert<Object> result = OPTIONAL.createAssert(valueProvider);
// THEN
result.isPresent();
verify(valueProvider).apply(parameterizedType(Optional.class, Object.class));
}
}
@Nested
|
Optional_Factory
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/cluster/serialization/DiffableTests.java
|
{
"start": 12946,
"end": 14610
}
|
class ____<V> extends MapDriver<ImmutableOpenMap<Integer, V>, V> {
@Override
protected ImmutableOpenMap<Integer, V> createMap(Map<Integer, V> values) {
return ImmutableOpenMap.<Integer, V>builder().putAllFromMap(values).build();
}
@Override
protected V get(ImmutableOpenMap<Integer, V> map, Integer key) {
return map.get(key);
}
@Override
protected int size(ImmutableOpenMap<Integer, V> map) {
return map.size();
}
}
private static <K> DiffableUtils.DiffableValueSerializer<K, TestDiffable> diffableValueSerializer() {
return new DiffableUtils.DiffableValueSerializer<K, TestDiffable>() {
@Override
public TestDiffable read(StreamInput in, K key) throws IOException {
return new TestDiffable(in.readString());
}
@Override
public Diff<TestDiffable> readDiff(StreamInput in, K key) throws IOException {
return SimpleDiffable.readDiffFrom(TestDiffable::readFrom, in);
}
};
}
private static <K> DiffableUtils.NonDiffableValueSerializer<K, String> nonDiffableValueSerializer() {
return new DiffableUtils.NonDiffableValueSerializer<K, String>() {
@Override
public void write(String value, StreamOutput out) throws IOException {
out.writeString(value);
}
@Override
public String read(StreamInput in, K key) throws IOException {
return in.readString();
}
};
}
public static
|
ImmutableOpenMapDriver
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/checkpointing/UnalignedCheckpointITCase.java
|
{
"start": 19531,
"end": 19876
}
|
class ____ extends VerifyingSinkStateBase {
private final long[] lastRecordInPartitions;
private State(int numberOfParallelSubtasks) {
lastRecordInPartitions = new long[numberOfParallelSubtasks];
Arrays.fill(lastRecordInPartitions, -1);
}
}
}
private static
|
State
|
java
|
mockito__mockito
|
mockito-core/src/test/java/org/mockitousage/puzzlers/OverloadingPuzzleTest.java
|
{
"start": 404,
"end": 573
}
|
class ____ extends TestBase {
private Super mock;
private void setMockWithDowncast(Super mock) {
this.mock = mock;
}
private
|
OverloadingPuzzleTest
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java
|
{
"start": 4060,
"end": 5875
}
|
class ____ extends TransportInstanceSingleOperationAction<Request, Response> {
private final Map<ShardId, Object> shards = new HashMap<>();
TestTransportInstanceSingleOperationAction(
String actionName,
TransportService transportService,
ActionFilters actionFilters,
IndexNameExpressionResolver indexNameExpressionResolver,
Writeable.Reader<Request> request
) {
super(
actionName,
THREAD_POOL,
TransportInstanceSingleOperationActionTests.this.clusterService,
TransportInstanceSingleOperationActionTests.this.projectResolver,
transportService,
actionFilters,
indexNameExpressionResolver,
request
);
}
public Map<ShardId, Object> getResults() {
return shards;
}
@Override
protected Executor executor(ShardId shardId) {
return EsExecutors.DIRECT_EXECUTOR_SERVICE;
}
@Override
protected void shardOperation(Request request, ActionListener<Response> listener) {
throw new UnsupportedOperationException("Not implemented in test class");
}
@Override
protected Response newResponse(StreamInput in) throws IOException {
return new Response();
}
@Override
protected void resolveRequest(ProjectState state, Request request) {}
@Override
protected ShardIterator shards(ProjectState projectState, Request request) {
return projectState.routingTable().index(request.concreteIndex()).shard(request.shardId.getId()).primaryShardIt();
}
}
static
|
TestTransportInstanceSingleOperationAction
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/cohere/CohereResponseHandlerTests.java
|
{
"start": 1198,
"end": 6812
}
|
class ____ extends ESTestCase {
public void testCheckForFailureStatusCode_DoesNotThrowFor200() {
callCheckForFailureStatusCode(200, "id");
}
public void testCheckForFailureStatusCode_ThrowsFor503() {
var exception = expectThrows(RetryException.class, () -> callCheckForFailureStatusCode(503, "id"));
assertFalse(exception.shouldRetry());
MatcherAssert.assertThat(
exception.getCause().getMessage(),
containsString("Received a server error status code for request from inference entity id [id] status [503]")
);
MatcherAssert.assertThat(((ElasticsearchStatusException) exception.getCause()).status(), is(RestStatus.BAD_REQUEST));
}
public void testCheckForFailureStatusCode_ThrowsFor500_WithShouldRetryTrue() {
var exception = expectThrows(RetryException.class, () -> callCheckForFailureStatusCode(500, "id"));
assertTrue(exception.shouldRetry());
MatcherAssert.assertThat(
exception.getCause().getMessage(),
containsString("Received a server error status code for request from inference entity id [id] status [500]")
);
MatcherAssert.assertThat(((ElasticsearchStatusException) exception.getCause()).status(), is(RestStatus.BAD_REQUEST));
}
public void testCheckForFailureStatusCode_ThrowsFor429() {
var exception = expectThrows(RetryException.class, () -> callCheckForFailureStatusCode(429, "id"));
assertTrue(exception.shouldRetry());
MatcherAssert.assertThat(
exception.getCause().getMessage(),
containsString("Received a rate limit status code for request from inference entity id [id] status [429]")
);
MatcherAssert.assertThat(((ElasticsearchStatusException) exception.getCause()).status(), is(RestStatus.TOO_MANY_REQUESTS));
}
public void testCheckForFailureStatusCode_ThrowsFor400() {
var exception = expectThrows(RetryException.class, () -> callCheckForFailureStatusCode(400, "id"));
assertFalse(exception.shouldRetry());
MatcherAssert.assertThat(
exception.getCause().getMessage(),
containsString("Received an unsuccessful status code for request from inference entity id [id] status [400]")
);
MatcherAssert.assertThat(((ElasticsearchStatusException) exception.getCause()).status(), is(RestStatus.BAD_REQUEST));
}
public void testCheckForFailureStatusCode_ThrowsFor400_TextsTooLarge() {
var exception = expectThrows(
RetryException.class,
() -> callCheckForFailureStatusCode(400, "invalid request: total number of texts must be at most 96 - received 100", "id")
);
assertFalse(exception.shouldRetry());
MatcherAssert.assertThat(
exception.getCause().getMessage(),
containsString("Received a texts array too large response for request from inference entity id [id] status [400]")
);
MatcherAssert.assertThat(((ElasticsearchStatusException) exception.getCause()).status(), is(RestStatus.BAD_REQUEST));
}
public void testCheckForFailureStatusCode_ThrowsFor401() {
var exception = expectThrows(RetryException.class, () -> callCheckForFailureStatusCode(401, "inferenceEntityId"));
assertFalse(exception.shouldRetry());
MatcherAssert.assertThat(
exception.getCause().getMessage(),
containsString(
"Received an authentication error status code for request from inference entity id [inferenceEntityId] status [401]"
)
);
MatcherAssert.assertThat(((ElasticsearchStatusException) exception.getCause()).status(), is(RestStatus.UNAUTHORIZED));
}
public void testCheckForFailureStatusCode_ThrowsFor300() {
var exception = expectThrows(RetryException.class, () -> callCheckForFailureStatusCode(300, "id"));
assertFalse(exception.shouldRetry());
MatcherAssert.assertThat(
exception.getCause().getMessage(),
containsString("Unhandled redirection for request from inference entity id [id] status [300]")
);
MatcherAssert.assertThat(((ElasticsearchStatusException) exception.getCause()).status(), is(RestStatus.MULTIPLE_CHOICES));
}
private static void callCheckForFailureStatusCode(int statusCode, String modelId) {
callCheckForFailureStatusCode(statusCode, null, modelId);
}
private static void callCheckForFailureStatusCode(int statusCode, @Nullable String errorMessage, String modelId) {
var statusLine = mock(StatusLine.class);
when(statusLine.getStatusCode()).thenReturn(statusCode);
var httpResponse = mock(HttpResponse.class);
when(httpResponse.getStatusLine()).thenReturn(statusLine);
var header = mock(Header.class);
when(header.getElements()).thenReturn(new HeaderElement[] {});
when(httpResponse.getFirstHeader(anyString())).thenReturn(header);
String responseJson = Strings.format("""
{
"message": "%s"
}
""", errorMessage);
var mockRequest = mock(Request.class);
when(mockRequest.getInferenceEntityId()).thenReturn(modelId);
var httpResult = new HttpResult(httpResponse, errorMessage == null ? new byte[] {} : responseJson.getBytes(StandardCharsets.UTF_8));
var handler = new CohereResponseHandler("", (request, result) -> null, false);
handler.checkForFailureStatusCode(mockRequest, httpResult);
}
}
|
CohereResponseHandlerTests
|
java
|
elastic__elasticsearch
|
test/framework/src/main/java/org/elasticsearch/test/EnumSerializationTestUtils.java
|
{
"start": 1404,
"end": 1533
}
|
class ____ {
private EnumSerializationTestUtils() {/* no instances */}
/**
* Assert that the
|
EnumSerializationTestUtils
|
java
|
mockito__mockito
|
mockito-core/src/main/java/org/mockito/Mockito.java
|
{
"start": 119962,
"end": 120511
}
|
class ____ used to execute the block with the mocked class. A mock
* maker might forbid mocking static methods of know classes that are known to cause problems.
* Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not
* explicitly forbidden.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param mockSettings the settings to use where only name and default answer are considered.
* @param reified don't pass any values to it. It's a trick to detect the class/
|
loaders
|
java
|
quarkusio__quarkus
|
independent-projects/qute/core/src/main/java/io/quarkus/qute/TemplateData.java
|
{
"start": 2624,
"end": 2689
}
|
interface ____ {
TemplateData[] value();
}
}
|
Container
|
java
|
quarkusio__quarkus
|
extensions/funqy/funqy-server-common/runtime/src/main/java/io/quarkus/funqy/runtime/query/QueryListReader.java
|
{
"start": 190,
"end": 447
}
|
class ____ extends BaseCollectionReader {
public QueryListReader(Type genericType, QueryObjectMapper mapper) {
super(genericType, mapper);
}
@Override
public Object create() {
return new LinkedList<>();
}
}
|
QueryListReader
|
java
|
quarkusio__quarkus
|
integration-tests/maven/src/test/resources-filtered/projects/rr-with-json-logging/src/main/java/org/acme/ClasspathResources.java
|
{
"start": 625,
"end": 2337
}
|
class ____ {
private static final String SUCCESS = "success";
@GET
public String readClassPathResources() {
return runAssertions(
() -> assertInvalidExactFileLocation(),
() -> assertCorrectExactFileLocation(),
() -> assertInvalidDirectory(),
() -> assertCorrectDirectory(),
() -> assertMultiRelease(),
() -> assertUniqueDirectories()
);
}
private String runAssertions(Supplier<String>... assertions) {
String result;
for (Supplier<String> assertion : assertions) {
result = assertion.get();
if (!SUCCESS.equals(result)) {
return result;
}
}
return SUCCESS;
}
private String assertInvalidExactFileLocation() {
final String testType = "invalid-exact-location";
try {
Enumeration<URL> exactFileLocationEnumeration = this.getClass().getClassLoader().getResources("db/location/test2.sql");
List<URL> exactFileLocationList = urlList(exactFileLocationEnumeration);
if (exactFileLocationList.size() != 0) {
return errorResult(testType, "wrong number of urls");
}
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
return errorResult(testType, "exception during resolution of resource");
}
}
private String assertMultiRelease() {
final String testType = "assert-multi-release-jar";
if (System.getProperty("java.version").startsWith("1.")) {
return SUCCESS;
}
try {
//this
|
ClasspathResources
|
java
|
apache__dubbo
|
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolMetric.java
|
{
"start": 1558,
"end": 4071
}
|
class ____ implements Metric {
private String applicationName;
private String threadPoolName;
private ThreadPoolExecutor threadPoolExecutor;
public ThreadPoolMetric(String applicationName, String threadPoolName, ThreadPoolExecutor threadPoolExecutor) {
this.applicationName = applicationName;
this.threadPoolExecutor = threadPoolExecutor;
this.threadPoolName = threadPoolName;
}
public String getThreadPoolName() {
return threadPoolName;
}
public void setThreadPoolName(String threadPoolName) {
this.threadPoolName = threadPoolName;
}
public ThreadPoolExecutor getThreadPoolExecutor() {
return threadPoolExecutor;
}
public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
this.threadPoolExecutor = threadPoolExecutor;
}
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ThreadPoolMetric that = (ThreadPoolMetric) o;
return Objects.equals(applicationName, that.applicationName)
&& Objects.equals(threadPoolName, that.threadPoolName);
}
@Override
public int hashCode() {
return Objects.hash(applicationName, threadPoolName);
}
@Override
public Map<String, String> getTags() {
Map<String, String> tags = new HashMap<>();
tags.put(TAG_IP, getLocalHost());
tags.put(TAG_PID, ConfigUtils.getPid() + "");
tags.put(TAG_HOSTNAME, getLocalHostName());
tags.put(TAG_APPLICATION_NAME, applicationName);
tags.put(TAG_THREAD_NAME, threadPoolName);
return tags;
}
public double getCorePoolSize() {
return threadPoolExecutor.getCorePoolSize();
}
public double getLargestPoolSize() {
return threadPoolExecutor.getLargestPoolSize();
}
public double getMaximumPoolSize() {
return threadPoolExecutor.getMaximumPoolSize();
}
public double getActiveCount() {
return threadPoolExecutor.getActiveCount();
}
public double getPoolSize() {
return threadPoolExecutor.getPoolSize();
}
public double getQueueSize() {
return threadPoolExecutor.getQueue().size();
}
}
|
ThreadPoolMetric
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/api/stream/StreamTrimLimitArgs.java
|
{
"start": 736,
"end": 1094
}
|
interface ____<T> {
/**
* Defines no limit of evicted objects for trim command.
*
* @return arguments object
*/
T noLimit();
/**
* Defines limit of evicted objects for trim command.
*
* @param size max amount of evicted objects
* @return arguments object
*/
T limit(int size);
}
|
StreamTrimLimitArgs
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsRepeatableAnnotationTests.java
|
{
"start": 17220,
"end": 17547
}
|
interface ____ {
String value() default "";
}
@ContainerWithMultipleAttributes(name = "enigma", value = {
@RepeatableWithContainerWithMultipleAttributes("A"),
@RepeatableWithContainerWithMultipleAttributes("B")
})
@RepeatableWithContainerWithMultipleAttributes("C")
static
|
RepeatableWithContainerWithMultipleAttributes
|
java
|
google__guice
|
core/test/com/google/inject/ParentInjectorTest.java
|
{
"start": 11372,
"end": 11459
}
|
class ____ {
public A interceptedMethod() {
return new A();
}
}
static
|
C
|
java
|
apache__logging-log4j2
|
log4j-api/src/main/java/org/apache/logging/log4j/message/ReusableObjectMessage.java
|
{
"start": 1077,
"end": 4289
}
|
class ____ implements ReusableMessage, ParameterVisitable, Clearable {
private static final long serialVersionUID = 6922476812535519960L;
private transient Object obj;
public void set(final Object object) {
this.obj = object;
}
/**
* Returns the formatted object message.
*
* @return the formatted object message.
*/
@Override
public String getFormattedMessage() {
return String.valueOf(obj);
}
@Override
public void formatTo(final StringBuilder buffer) {
StringBuilders.appendValue(buffer, obj);
}
/**
* Returns the object formatted using its toString method.
*
* @return the String representation of the object.
*/
@Override
public String getFormat() {
return obj instanceof String ? (String) obj : null;
}
/**
* Returns the object parameter.
*
* @return The object.
* @since 2.7
*/
public Object getParameter() {
return obj;
}
/**
* Returns the object as if it were a parameter.
*
* @return The object.
*/
@Override
public Object[] getParameters() {
return new Object[] {obj};
}
@Override
public String toString() {
return getFormattedMessage();
}
/**
* Gets the message if it is a throwable.
*
* @return the message if it is a throwable.
*/
@Override
public Throwable getThrowable() {
return obj instanceof Throwable ? (Throwable) obj : null;
}
/**
* This message has exactly one parameter (the object), so returns it as the first parameter in the array.
* @param emptyReplacement the parameter array to return
* @return the specified array
*/
@Override
public Object[] swapParameters(final Object[] emptyReplacement) {
// it's unlikely that emptyReplacement is of length 0, but if it is,
// go ahead and allocate the memory now;
// this saves an allocation in the future when this buffer is re-used
if (emptyReplacement.length == 0) {
final Object[] params = new Object[10]; // Default reusable parameter buffer size
params[0] = obj;
return params;
}
emptyReplacement[0] = obj;
return emptyReplacement;
}
/**
* This message has exactly one parameter (the object), so always returns one.
* @return 1
*/
@Override
public short getParameterCount() {
return 1;
}
@Override
public <S> void forEachParameter(final ParameterConsumer<S> action, final S state) {
action.accept(obj, 0, state);
}
@Override
public Message memento() {
Message message = new ObjectMessage(obj);
// Since `toString()` methods are not always pure functions and might depend on the thread and other context
// values, we format the message and cache the result.
message.getFormattedMessage();
return message;
}
/**
* @since 2.11.1
*/
@Override
public void clear() {
obj = null;
}
private Object writeReplace() {
return memento();
}
}
|
ReusableObjectMessage
|
java
|
apache__flink
|
flink-clients/src/main/java/org/apache/flink/client/cli/ProgramOptionsUtils.java
|
{
"start": 4801,
"end": 6657
}
|
class ____.",
e);
return Thread.currentThread().getContextClassLoader();
}
}
public static void configurePythonExecution(
Configuration configuration, PackagedProgram packagedProgram) throws Exception {
final Options commandOptions = CliFrontendParser.getRunCommandOptions();
final CommandLine commandLine =
CliFrontendParser.parse(commandOptions, packagedProgram.getArguments(), true);
final ProgramOptions programOptions = createPythonProgramOptions(commandLine);
// Extract real program args by eliminating the PyFlink dependency options
String[] programArgs = programOptions.extractProgramArgs(commandLine);
// Set the real program args to the packaged program
Field argsField = packagedProgram.getClass().getDeclaredField("args");
argsField.setAccessible(true);
argsField.set(packagedProgram, programArgs);
// PyFlink dependency configurations are set in the pythonConfiguration when constructing
// the program option,
// we need to get the python configuration and merge with the execution configuration.
Field pythonConfiguration =
programOptions.getClass().getDeclaredField("pythonConfiguration");
pythonConfiguration.setAccessible(true);
ClassLoader classLoader = getPythonClassLoader();
Class<?> pythonDependencyUtilsClazz =
Class.forName(
"org.apache.flink.python.util.PythonDependencyUtils", false, classLoader);
Method mergeMethod =
pythonDependencyUtilsClazz.getDeclaredMethod(
"merge", Configuration.class, Configuration.class);
mergeMethod.invoke(null, configuration, pythonConfiguration.get(programOptions));
}
}
|
loader
|
java
|
apache__camel
|
components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookPathTest.java
|
{
"start": 1289,
"end": 3151
}
|
class ____ extends WebhookTestBase {
@Test
public void testComponentPath() {
String result = template.requestBody("netty-http:http://localhost:" + port + "/comp", "", String.class);
assertEquals("msg: webhook", result);
}
@Test
public void testUriPath() {
String result = template.requestBody("netty-http:http://localhost:" + port + "/uri", "", String.class);
assertEquals("uri: webhook", result);
}
@Test
public void testRootPathError() {
assertThrows(CamelExecutionException.class,
() -> template.requestBody("netty-http:http://localhost:" + port, "", String.class));
}
@Override
public CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
WebhookComponent comp = (WebhookComponent) context.getComponent("webhook");
comp.getConfiguration().setWebhookPath("/comp");
return context;
}
@Override
protected void bindToRegistry(Registry registry) {
registry.bind("wb-delegate-component", new TestComponent(endpoint -> {
endpoint.setWebhookHandler(proc -> ex -> {
ex.getMessage().setBody("webhook");
proc.process(ex);
});
}));
}
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
restConfiguration()
.host("0.0.0.0")
.port(port);
from("webhook:wb-delegate://xx")
.transform(body().prepend("msg: "));
from("webhook:wb-delegate://xx?webhookPath=/uri")
.transform(body().prepend("uri: "));
}
};
}
}
|
WebhookPathTest
|
java
|
apache__camel
|
components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/ReplyKeyboardMarkup.java
|
{
"start": 1146,
"end": 3392
}
|
class ____ implements Serializable, ReplyMarkup {
private static final long serialVersionUID = 1L;
@JsonProperty("one_time_keyboard")
private Boolean oneTimeKeyboard;
@JsonProperty("remove_keyboard")
private Boolean removeKeyboard;
@JsonProperty("resize_keyboard")
private Boolean resizeKeyboard;
private Boolean selective;
private List<List<InlineKeyboardButton>> keyboard;
public ReplyKeyboardMarkup() {
}
public ReplyKeyboardMarkup(Boolean oneTimeKeyboard, Boolean removeKeyboard, Boolean resizeKeyboard,
Boolean selective, List<List<InlineKeyboardButton>> keyboard) {
this.oneTimeKeyboard = oneTimeKeyboard;
this.removeKeyboard = removeKeyboard;
this.resizeKeyboard = resizeKeyboard;
this.selective = selective;
this.keyboard = keyboard;
}
public Boolean getOneTimeKeyboard() {
return oneTimeKeyboard;
}
public void setOneTimeKeyboard(Boolean oneTimeKeyboard) {
this.oneTimeKeyboard = oneTimeKeyboard;
}
public Boolean getRemoveKeyboard() {
return removeKeyboard;
}
public void setRemoveKeyboard(Boolean removeKeyboard) {
this.removeKeyboard = removeKeyboard;
}
public List<List<InlineKeyboardButton>> getKeyboard() {
return keyboard;
}
public void setKeyboard(List<List<InlineKeyboardButton>> keyboard) {
this.keyboard = keyboard;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ReplyKeyboardMarkup{");
sb.append("oneTimeKeyboard='").append(oneTimeKeyboard).append('\'');
sb.append(", keyboard='").append(keyboard);
sb.append('}');
return sb.toString();
}
public static Builder builder() {
return new Builder();
}
public Boolean getResizeKeyboard() {
return resizeKeyboard;
}
public void setResizeKeyboard(Boolean resizeKeyboard) {
this.resizeKeyboard = resizeKeyboard;
}
public Boolean getSelective() {
return selective;
}
public void setSelective(Boolean selective) {
this.selective = selective;
}
public static
|
ReplyKeyboardMarkup
|
java
|
junit-team__junit5
|
junit-platform-launcher/src/main/java/org/junit/platform/launcher/core/HierarchicalOutputDirectoryCreator.java
|
{
"start": 949,
"end": 2369
}
|
class ____ implements OutputDirectoryCreator {
private static final Pattern FORBIDDEN_CHARS = Pattern.compile("[^a-z0-9.,_\\-() ]", Pattern.CASE_INSENSITIVE);
private static final String REPLACEMENT = "_";
private final Supplier<Path> rootDirSupplier;
private volatile @Nullable Path rootDir;
HierarchicalOutputDirectoryCreator(Supplier<Path> rootDirSupplier) {
this.rootDirSupplier = rootDirSupplier;
}
@Override
public Path createOutputDirectory(TestDescriptor testDescriptor) throws IOException {
Preconditions.notNull(testDescriptor, "testDescriptor must not be null");
List<Segment> segments = testDescriptor.getUniqueId().getSegments();
Path relativePath = segments.stream() //
.skip(1) //
.map(HierarchicalOutputDirectoryCreator::toSanitizedPath) //
.reduce(toSanitizedPath(segments.get(0)), Path::resolve);
return Files.createDirectories(getRootDirectory().resolve(relativePath));
}
@Override
public synchronized Path getRootDirectory() {
var currentRootDir = rootDir;
if (currentRootDir == null) {
currentRootDir = rootDirSupplier.get();
rootDir = currentRootDir;
}
return currentRootDir;
}
private static Path toSanitizedPath(Segment segment) {
return Path.of(sanitizeName(segment.getValue()));
}
private static String sanitizeName(String value) {
return FORBIDDEN_CHARS.matcher(value).replaceAll(REPLACEMENT);
}
}
|
HierarchicalOutputDirectoryCreator
|
java
|
spring-projects__spring-framework
|
spring-jdbc/src/main/java/org/springframework/jdbc/core/ResultSetSupportingSqlParameter.java
|
{
"start": 922,
"end": 4556
}
|
class ____ extends SqlParameter {
private @Nullable ResultSetExtractor<?> resultSetExtractor;
private @Nullable RowCallbackHandler rowCallbackHandler;
private @Nullable RowMapper<?> rowMapper;
/**
* Create a new ResultSetSupportingSqlParameter.
* @param name the name of the parameter, as used in input and output maps
* @param sqlType the parameter SQL type according to {@code java.sql.Types}
*/
public ResultSetSupportingSqlParameter(String name, int sqlType) {
super(name, sqlType);
}
/**
* Create a new ResultSetSupportingSqlParameter.
* @param name the name of the parameter, as used in input and output maps
* @param sqlType the parameter SQL type according to {@code java.sql.Types}
* @param scale the number of digits after the decimal point
* (for DECIMAL and NUMERIC types)
*/
public ResultSetSupportingSqlParameter(String name, int sqlType, int scale) {
super(name, sqlType, scale);
}
/**
* Create a new ResultSetSupportingSqlParameter.
* @param name the name of the parameter, as used in input and output maps
* @param sqlType the parameter SQL type according to {@code java.sql.Types}
* @param typeName the type name of the parameter (optional)
*/
public ResultSetSupportingSqlParameter(String name, int sqlType, @Nullable String typeName) {
super(name, sqlType, typeName);
}
/**
* Create a new ResultSetSupportingSqlParameter.
* @param name the name of the parameter, as used in input and output maps
* @param sqlType the parameter SQL type according to {@code java.sql.Types}
* @param rse the {@link ResultSetExtractor} to use for parsing the {@link ResultSet}
*/
public ResultSetSupportingSqlParameter(String name, int sqlType, ResultSetExtractor<?> rse) {
super(name, sqlType);
this.resultSetExtractor = rse;
}
/**
* Create a new ResultSetSupportingSqlParameter.
* @param name the name of the parameter, as used in input and output maps
* @param sqlType the parameter SQL type according to {@code java.sql.Types}
* @param rch the {@link RowCallbackHandler} to use for parsing the {@link ResultSet}
*/
public ResultSetSupportingSqlParameter(String name, int sqlType, RowCallbackHandler rch) {
super(name, sqlType);
this.rowCallbackHandler = rch;
}
/**
* Create a new ResultSetSupportingSqlParameter.
* @param name the name of the parameter, as used in input and output maps
* @param sqlType the parameter SQL type according to {@code java.sql.Types}
* @param rm the {@link RowMapper} to use for parsing the {@link ResultSet}
*/
public ResultSetSupportingSqlParameter(String name, int sqlType, RowMapper<?> rm) {
super(name, sqlType);
this.rowMapper = rm;
}
/**
* Does this parameter support a ResultSet, i.e. does it hold a
* ResultSetExtractor, RowCallbackHandler or RowMapper?
*/
public boolean isResultSetSupported() {
return (this.resultSetExtractor != null || this.rowCallbackHandler != null || this.rowMapper != null);
}
/**
* Return the ResultSetExtractor held by this parameter, if any.
*/
public @Nullable ResultSetExtractor<?> getResultSetExtractor() {
return this.resultSetExtractor;
}
/**
* Return the RowCallbackHandler held by this parameter, if any.
*/
public @Nullable RowCallbackHandler getRowCallbackHandler() {
return this.rowCallbackHandler;
}
/**
* Return the RowMapper held by this parameter, if any.
*/
public @Nullable RowMapper<?> getRowMapper() {
return this.rowMapper;
}
/**
* This implementation always returns {@code false}.
*/
@Override
public boolean isInputValueProvided() {
return false;
}
}
|
ResultSetSupportingSqlParameter
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/VertexSlotSharingTest.java
|
{
"start": 1923,
"end": 5597
}
|
class ____ {
@RegisterExtension
static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_RESOURCE =
TestingUtils.defaultExecutorExtension();
/**
* Test setup: - v1 is isolated, no slot sharing. - v2 and v3 (not connected) share slots. - v4
* and v5 (connected) share slots.
*/
@Test
void testAssignSlotSharingGroup() {
try {
JobVertex v1 = new JobVertex("v1");
JobVertex v2 = new JobVertex("v2");
JobVertex v3 = new JobVertex("v3");
JobVertex v4 = new JobVertex("v4");
JobVertex v5 = new JobVertex("v5");
v1.setParallelism(4);
v2.setParallelism(5);
v3.setParallelism(7);
v4.setParallelism(1);
v5.setParallelism(11);
v1.setInvokableClass(AbstractInvokable.class);
v2.setInvokableClass(AbstractInvokable.class);
v3.setInvokableClass(AbstractInvokable.class);
v4.setInvokableClass(AbstractInvokable.class);
v5.setInvokableClass(AbstractInvokable.class);
connectNewDataSetAsInput(
v2, v1, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
connectNewDataSetAsInput(
v5, v4, DistributionPattern.POINTWISE, ResultPartitionType.PIPELINED);
SlotSharingGroup jg1 = new SlotSharingGroup();
v2.setSlotSharingGroup(jg1);
v3.setSlotSharingGroup(jg1);
SlotSharingGroup jg2 = new SlotSharingGroup();
v4.setSlotSharingGroup(jg2);
v5.setSlotSharingGroup(jg2);
List<JobVertex> vertices = new ArrayList<>(Arrays.asList(v1, v2, v3, v4, v5));
ExecutionGraph eg =
TestingDefaultExecutionGraphBuilder.newBuilder()
.setVertexParallelismStore(
SchedulerBase.computeVertexParallelismStore(vertices))
.build(EXECUTOR_RESOURCE.getExecutor());
eg.attachJobGraph(
vertices,
UnregisteredMetricGroups.createUnregisteredJobManagerJobMetricGroup());
// verify that the vertices are all in the same slot sharing group
SlotSharingGroup group1;
SlotSharingGroup group2;
// verify that v1 tasks are not in the same slot sharing group as v2
assertThat(eg.getJobVertex(v1.getID()).getSlotSharingGroup())
.isNotEqualTo(eg.getJobVertex(v2.getID()).getSlotSharingGroup());
// v2 and v3 are shared
group1 = eg.getJobVertex(v2.getID()).getSlotSharingGroup();
assertThat(group1).isNotNull();
assertThat(eg.getJobVertex(v3.getID()).getSlotSharingGroup()).isEqualTo(group1);
assertThat(group1.getJobVertexIds()).hasSize(2);
assertThat(group1.getJobVertexIds().contains(v2.getID())).isTrue();
assertThat(group1.getJobVertexIds().contains(v3.getID())).isTrue();
// v4 and v5 are shared
group2 = eg.getJobVertex(v4.getID()).getSlotSharingGroup();
assertThat(group2).isNotNull();
assertThat(eg.getJobVertex(v5.getID()).getSlotSharingGroup()).isEqualTo(group2);
assertThat(group1.getJobVertexIds()).hasSize(2);
assertThat(group2.getJobVertexIds().contains(v4.getID())).isTrue();
assertThat(group2.getJobVertexIds().contains(v5.getID())).isTrue();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
|
VertexSlotSharingTest
|
java
|
apache__commons-lang
|
src/main/java/org/apache/commons/lang3/math/Fraction.java
|
{
"start": 1395,
"end": 16876
}
|
class ____ extends Number implements Comparable<Fraction> {
/**
* Required for serialization support. Lang version 2.0.
*
* @see Serializable
*/
private static final long serialVersionUID = 65382027393090L;
/**
* {@link Fraction} representation of 0.
*/
public static final Fraction ZERO = new Fraction(0, 1);
/**
* {@link Fraction} representation of 1.
*/
public static final Fraction ONE = new Fraction(1, 1);
/**
* {@link Fraction} representation of 1/2.
*/
public static final Fraction ONE_HALF = new Fraction(1, 2);
/**
* {@link Fraction} representation of 1/3.
*/
public static final Fraction ONE_THIRD = new Fraction(1, 3);
/**
* {@link Fraction} representation of 2/3.
*/
public static final Fraction TWO_THIRDS = new Fraction(2, 3);
/**
* {@link Fraction} representation of 1/4.
*/
public static final Fraction ONE_QUARTER = new Fraction(1, 4);
/**
* {@link Fraction} representation of 2/4.
*/
public static final Fraction TWO_QUARTERS = new Fraction(2, 4);
/**
* {@link Fraction} representation of 3/4.
*/
public static final Fraction THREE_QUARTERS = new Fraction(3, 4);
/**
* {@link Fraction} representation of 1/5.
*/
public static final Fraction ONE_FIFTH = new Fraction(1, 5);
/**
* {@link Fraction} representation of 2/5.
*/
public static final Fraction TWO_FIFTHS = new Fraction(2, 5);
/**
* {@link Fraction} representation of 3/5.
*/
public static final Fraction THREE_FIFTHS = new Fraction(3, 5);
/**
* {@link Fraction} representation of 4/5.
*/
public static final Fraction FOUR_FIFTHS = new Fraction(4, 5);
/**
* Adds two integers, checking for overflow.
*
* @param x an addend
* @param y an addend
* @return the sum {@code x+y}
* @throws ArithmeticException if the result cannot be represented as
* an int
*/
private static int addAndCheck(final int x, final int y) {
final long s = (long) x + (long) y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: add");
}
return (int) s;
}
/**
* Creates a {@link Fraction} instance from a {@code double} value.
* <p>
* This method uses the <a href="https://web.archive.org/web/20210516065058/http%3A//archives.math.utk.edu/articles/atuyl/confrac/"> continued fraction
* algorithm</a>, computing a maximum of 25 convergents and bounding the denominator by 10,000.
* </p>
*
* @param value the double value to convert
* @return a new fraction instance that is close to the value
* @throws ArithmeticException if {@code |value| > Integer.MAX_VALUE} or {@code value = NaN}
* @throws ArithmeticException if the calculated denominator is {@code zero}
* @throws ArithmeticException if the algorithm does not converge
*/
public static Fraction getFraction(double value) {
final int sign = value < 0 ? -1 : 1;
value = Math.abs(value);
if (value > Integer.MAX_VALUE || Double.isNaN(value)) {
throw new ArithmeticException("The value must not be greater than Integer.MAX_VALUE or NaN");
}
final int wholeNumber = (int) value;
value -= wholeNumber;
int numer0 = 0; // the pre-previous
int denom0 = 1; // the pre-previous
int numer1 = 1; // the previous
int denom1 = 0; // the previous
int numer2; // the current, setup in calculation
int denom2; // the current, setup in calculation
int a1 = (int) value;
int a2;
double x1 = 1;
double x2;
double y1 = value - a1;
double y2;
double delta1;
double delta2 = Double.MAX_VALUE;
double fraction;
int i = 1;
do {
delta1 = delta2;
a2 = (int) (x1 / y1);
x2 = y1;
y2 = x1 - a2 * y1;
numer2 = a1 * numer1 + numer0;
denom2 = a1 * denom1 + denom0;
fraction = (double) numer2 / (double) denom2;
delta2 = Math.abs(value - fraction);
a1 = a2;
x1 = x2;
y1 = y2;
numer0 = numer1;
denom0 = denom1;
numer1 = numer2;
denom1 = denom2;
i++;
} while (delta1 > delta2 && denom2 <= 10000 && denom2 > 0 && i < 25);
if (i == 25) {
throw new ArithmeticException("Unable to convert double to fraction");
}
return getReducedFraction((numer0 + wholeNumber * denom0) * sign, denom0);
}
/**
* Creates a {@link Fraction} instance with the 2 parts of a fraction Y/Z.
* <p>
* Any negative signs are resolved to be on the numerator.
* </p>
*
* @param numerator the numerator, for example the three in 'three sevenths'
* @param denominator the denominator, for example the seven in 'three sevenths'
* @return a new fraction instance
* @throws ArithmeticException if the denominator is {@code zero} or the denominator is {@code negative} and the numerator is {@code Integer#MIN_VALUE}
*/
public static Fraction getFraction(int numerator, int denominator) {
if (denominator == 0) {
throw new ArithmeticException("The denominator must not be zero");
}
if (denominator < 0) {
if (numerator == Integer.MIN_VALUE || denominator == Integer.MIN_VALUE) {
throw new ArithmeticException("overflow: can't negate");
}
numerator = -numerator;
denominator = -denominator;
}
return new Fraction(numerator, denominator);
}
/**
* Creates a {@link Fraction} instance with the 3 parts of a fraction X Y/Z.
* <p>
* The negative sign must be passed in on the whole number part.
* </p>
*
* @param whole the whole number, for example the one in 'one and three sevenths'
* @param numerator the numerator, for example the three in 'one and three sevenths'
* @param denominator the denominator, for example the seven in 'one and three sevenths'
* @return a new fraction instance
* @throws ArithmeticException if the denominator is {@code zero}
* @throws ArithmeticException if the denominator is negative
* @throws ArithmeticException if the numerator is negative
* @throws ArithmeticException if the resulting numerator exceeds {@code Integer.MAX_VALUE}
*/
public static Fraction getFraction(final int whole, final int numerator, final int denominator) {
if (denominator == 0) {
throw new ArithmeticException("The denominator must not be zero");
}
if (denominator < 0) {
throw new ArithmeticException("The denominator must not be negative");
}
if (numerator < 0) {
throw new ArithmeticException("The numerator must not be negative");
}
final long numeratorValue;
if (whole < 0) {
numeratorValue = whole * (long) denominator - numerator;
} else {
numeratorValue = whole * (long) denominator + numerator;
}
if (numeratorValue < Integer.MIN_VALUE || numeratorValue > Integer.MAX_VALUE) {
throw new ArithmeticException("Numerator too large to represent as an Integer.");
}
return new Fraction((int) numeratorValue, denominator);
}
/**
* Creates a Fraction from a {@link String}.
* <p>
* The formats accepted are:
* </p>
* <ol>
* <li>{@code double} String containing a dot</li>
* <li>'X Y/Z'</li>
* <li>'Y/Z'</li>
* <li>'X' (a simple whole number)</li>
* </ol>
* <p>
* and a .
* </p>
*
* @param str the string to parse, must not be {@code null}
* @return the new {@link Fraction} instance
* @throws NullPointerException if the string is {@code null}
* @throws NumberFormatException if the number format is invalid
*/
public static Fraction getFraction(String str) {
Objects.requireNonNull(str, "str");
// parse double format
int pos = str.indexOf('.');
if (pos >= 0) {
return getFraction(Double.parseDouble(str));
}
// parse X Y/Z format
pos = str.indexOf(' ');
if (pos > 0) {
final int whole = Integer.parseInt(str.substring(0, pos));
str = str.substring(pos + 1);
pos = str.indexOf('/');
if (pos < 0) {
throw new NumberFormatException("The fraction could not be parsed as the format X Y/Z");
}
final int numer = Integer.parseInt(str.substring(0, pos));
final int denom = Integer.parseInt(str.substring(pos + 1));
return getFraction(whole, numer, denom);
}
// parse Y/Z format
pos = str.indexOf('/');
if (pos < 0) {
// simple whole number
return getFraction(Integer.parseInt(str), 1);
}
final int numer = Integer.parseInt(str.substring(0, pos));
final int denom = Integer.parseInt(str.substring(pos + 1));
return getFraction(numer, denom);
}
/**
* Creates a reduced {@link Fraction} instance with the 2 parts of a fraction Y/Z.
* <p>
* For example, if the input parameters represent 2/4, then the created fraction will be 1/2.
* </p>
*
* <p>
* Any negative signs are resolved to be on the numerator.
* </p>
*
* @param numerator the numerator, for example the three in 'three sevenths'
* @param denominator the denominator, for example the seven in 'three sevenths'
* @return a new fraction instance, with the numerator and denominator reduced
* @throws ArithmeticException if the denominator is {@code zero}
*/
public static Fraction getReducedFraction(int numerator, int denominator) {
if (denominator == 0) {
throw new ArithmeticException("The denominator must not be zero");
}
if (numerator == 0) {
return ZERO; // normalize zero.
}
// allow 2^k/-2^31 as a valid fraction (where k>0)
if (denominator == Integer.MIN_VALUE && (numerator & 1) == 0) {
numerator /= 2;
denominator /= 2;
}
if (denominator < 0) {
if (numerator == Integer.MIN_VALUE || denominator == Integer.MIN_VALUE) {
throw new ArithmeticException("overflow: can't negate");
}
numerator = -numerator;
denominator = -denominator;
}
// simplify fraction.
final int gcd = greatestCommonDivisor(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
return new Fraction(numerator, denominator);
}
/**
* Gets the greatest common divisor of the absolute value of
* two numbers, using the "binary gcd" method which avoids
* division and modulo operations. See Knuth 4.5.2 algorithm B.
* This algorithm is due to Josef Stein (1961).
*
* @param u a non-zero number
* @param v a non-zero number
* @return the greatest common divisor, never zero
*/
private static int greatestCommonDivisor(int u, int v) {
// From Commons Math:
if (u == 0 || v == 0) {
if (u == Integer.MIN_VALUE || v == Integer.MIN_VALUE) {
throw new ArithmeticException("overflow: gcd is 2^31");
}
return Math.abs(u) + Math.abs(v);
}
// if either operand is abs 1, return 1:
if (Math.abs(u) == 1 || Math.abs(v) == 1) {
return 1;
}
// keep u and v negative, as negative integers range down to
// -2^31, while positive numbers can only be as large as 2^31-1
// (i.e. we can't necessarily negate a negative number without
// overflow)
if (u > 0) {
u = -u;
} // make u negative
if (v > 0) {
v = -v;
} // make v negative
// B1. [Find power of 2]
int k = 0;
while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { // while u and v are both even...
u /= 2;
v /= 2;
k++; // cast out twos.
}
if (k == 31) {
throw new ArithmeticException("overflow: gcd is 2^31");
}
// B2. Initialize: u and v have been divided by 2^k and at least
// one is odd.
int t = (u & 1) == 1 ? v : -(u / 2)/* B3 */;
// t negative: u was odd, v may be even (t replaces v)
// t positive: u was even, v is odd (t replaces u)
do {
/* assert u<0 && v<0; */
// B4/B3: cast out twos from t.
while ((t & 1) == 0) { // while t is even.
t /= 2; // cast out twos
}
// B5 [reset max(u,v)]
if (t > 0) {
u = -t;
} else {
v = t;
}
// B6/B3. at this point both u and v should be odd.
t = (v - u) / 2;
// |u| larger: t positive (replace u)
// |v| larger: t negative (replace v)
} while (t != 0);
return -u * (1 << k); // gcd is u*2^k
}
/**
* Multiplies two integers, checking for overflow.
*
* @param x a factor
* @param y a factor
* @return the product {@code x*y}
* @throws ArithmeticException if the result cannot be represented as
* an int
*/
private static int mulAndCheck(final int x, final int y) {
final long m = (long) x * (long) y;
if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: mul");
}
return (int) m;
}
/**
* Multiplies two non-negative integers, checking for overflow.
*
* @param x a non-negative factor
* @param y a non-negative factor
* @return the product {@code x*y}
* @throws ArithmeticException if the result cannot be represented as
* an int
*/
private static int mulPosAndCheck(final int x, final int y) {
/* assert x>=0 && y>=0; */
final long m = (long) x * (long) y;
if (m > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: mulPos");
}
return (int) m;
}
/**
* Subtracts two integers, checking for overflow.
*
* @param x the minuend
* @param y the subtrahend
* @return the difference {@code x-y}
* @throws ArithmeticException if the result cannot be represented as
* an int
*/
private static int subAndCheck(final int x, final int y) {
final long s = (long) x - (long) y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: add");
}
return (int) s;
}
/**
* The numerator number part of the fraction (the three in three sevenths).
*/
private final int numerator;
/**
* The denominator number part of the fraction (the seven in three sevenths).
*/
private final int denominator;
/**
* Cached output hashCode (
|
Fraction
|
java
|
spring-projects__spring-boot
|
module/spring-boot-security-oauth2-client/src/test/java/org/springframework/boot/security/oauth2/client/autoconfigure/reactive/ReactiveOAuth2ClientWebSecurityAutoConfigurationTests.java
|
{
"start": 3075,
"end": 6049
}
|
class ____ {
private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientWebSecurityAutoConfiguration.class,
ReactiveWebSecurityAutoConfiguration.class));
@Test
void autoConfigurationShouldBackOffForServletEnvironments() {
new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientWebSecurityAutoConfiguration.class))
.run((context) -> assertThat(context)
.doesNotHaveBean(ReactiveOAuth2ClientWebSecurityAutoConfiguration.class));
}
@Test
void autoConfigurationIsConditionalOnAuthorizedClientService() {
this.contextRunner.run((context) -> assertThat(context)
.doesNotHaveBean(ReactiveOAuth2ClientWebSecurityAutoConfiguration.class));
}
@Test
void configurationRegistersAuthorizedClientRepositoryBean() {
this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class)
.run((context) -> assertThat(context)
.hasSingleBean(AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.class));
}
@Test
void authorizedClientRepositoryBeanIsConditionalOnMissingBean() {
this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class)
.run((context) -> {
assertThat(context).hasSingleBean(ServerOAuth2AuthorizedClientRepository.class);
assertThat(context).hasBean("testAuthorizedClientRepository");
});
}
@Test
void configurationRegistersSecurityWebFilterChainBean() { // gh-17949
this.contextRunner
.withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class,
ServerHttpSecurityConfiguration.class)
.run((context) -> {
assertThat(hasFilter(context, OAuth2LoginAuthenticationWebFilter.class)).isTrue();
assertThat(hasFilter(context, OAuth2AuthorizationCodeGrantWebFilter.class)).isTrue();
});
}
@Test
void securityWebFilterChainBeanConditionalOnWebApplication() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientWebSecurityAutoConfiguration.class,
ReactiveWebSecurityAutoConfiguration.class))
.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class)
.run((context) -> assertThat(context).doesNotHaveBean(SecurityWebFilterChain.class));
}
@SuppressWarnings("unchecked")
private boolean hasFilter(AssertableReactiveWebApplicationContext context, Class<? extends WebFilter> filter) {
SecurityWebFilterChain filterChain = (SecurityWebFilterChain) context
.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN);
List<WebFilter> filters = (List<WebFilter>) ReflectionTestUtils.getField(filterChain, "filters");
assertThat(filters).isNotNull();
return filters.stream().anyMatch(filter::isInstance);
}
@Configuration(proxyBeanMethods = false)
@Import(ReactiveClientRepositoryConfiguration.class)
static
|
ReactiveOAuth2ClientWebSecurityAutoConfigurationTests
|
java
|
elastic__elasticsearch
|
x-pack/plugin/mapper-counted-keyword/src/test/java/org/elasticsearch/xpack/countedkeyword/CountedKeywordFieldTypeTests.java
|
{
"start": 2544,
"end": 4066
}
|
class ____ extends SortedSetDocValues {
private final List<BytesRef> docValues;
private final DocIdSetIterator disi;
private long currentOrd = -1;
private CollectionBasedSortedSetDocValues(List<BytesRef> docValues) {
this.docValues = docValues;
this.disi = DocIdSetIterator.all(docValues.size());
}
@Override
public long nextOrd() {
return ++currentOrd;
}
@Override
public int docValueCount() {
return docValues.size();
}
@Override
public BytesRef lookupOrd(long ord) throws IOException {
return docValues.get((int) ord);
}
@Override
public long getValueCount() {
return docValues.size();
}
@Override
public boolean advanceExact(int target) throws IOException {
currentOrd = -1;
return disi.advance(target) == target;
}
@Override
public int docID() {
return disi.docID();
}
@Override
public int nextDoc() throws IOException {
currentOrd = -1;
return disi.nextDoc();
}
@Override
public int advance(int target) throws IOException {
currentOrd = -1;
return disi.advance(target);
}
@Override
public long cost() {
return disi.cost();
}
}
private static
|
CollectionBasedSortedSetDocValues
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/MySQLColumnValidationTest.java
|
{
"start": 2479,
"end": 6828
}
|
class ____ {
private DriverManagerConnectionProvider connectionProvider;
@BeforeAll
public void init() {
connectionProvider = new DriverManagerConnectionProvider();
connectionProvider.configure( PropertiesHelper.map( Environment.getProperties() ) );
try( Connection connection = connectionProvider.getConnection();
Statement statement = connection.createStatement() ) {
try {
statement.execute( "DROP TABLE TEST_DATA1" );
statement.execute( "DROP TABLE TEST_DATA2" );
statement.execute( "DROP TABLE TEST_DATA3" );
}
catch (SQLException e) {
}
statement.execute( "CREATE TABLE `TEST_DATA1` ( " +
" `ID` int unsigned NOT NULL, " +
" `INTEGRAL1` tinyint unsigned DEFAULT '0', " +
" `INTEGRAL2` tinyint unsigned DEFAULT '0', " +
" PRIMARY KEY (`ID`)" +
") ENGINE=InnoDB" );
statement.execute( "CREATE TABLE `TEST_DATA2` ( " +
" `ID` int unsigned NOT NULL, " +
" `INTEGRAL1` tinyint unsigned DEFAULT '0', " +
" PRIMARY KEY (`ID`)" +
") ENGINE=InnoDB" );
statement.execute( "CREATE TABLE `TEST_DATA3` ( " +
" `ID` int unsigned NOT NULL, " +
" `INTEGRAL1` tinyint unsigned DEFAULT '0', " +
" PRIMARY KEY (`ID`)" +
") ENGINE=InnoDB" );
}
catch (SQLException e) {
fail(e.getMessage());
}
}
@AfterAll
public void releaseResources() {
try( Connection connection = connectionProvider.getConnection();
Statement statement = connection.createStatement() ) {
try {
statement.execute( "DROP TABLE TEST_DATA1" );
statement.execute( "DROP TABLE TEST_DATA2" );
statement.execute( "DROP TABLE TEST_DATA3" );
}
catch (SQLException e) {
}
}
catch (SQLException e) {
fail(e.getMessage());
}
connectionProvider.stop();
}
@Test
public void testValidateColumn(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
TestEntity1 te1 = new TestEntity1( 1, 1, 2 );
session.persist( te1 );
}
);
ConfigurationService configurationService = scope.getSessionFactory().getServiceRegistry()
.requireService( ConfigurationService.class );
ExecutionOptions executionOptions = new ExecutionOptions() {
@Override
public boolean shouldManageNamespaces() {
return true;
}
@Override
public Map<String,Object> getConfigurationValues() {
return configurationService.getSettings();
}
@Override
public ExceptionHandler getExceptionHandler() {
return ExceptionHandlerLoggedImpl.INSTANCE;
}
};
HibernateSchemaManagementTool hsmt = (HibernateSchemaManagementTool) scope.getSessionFactory()
.getServiceRegistry()
.getService( SchemaManagementTool.class );
SchemaValidator schemaValidator = new IndividuallySchemaValidatorImpl( hsmt, DefaultSchemaFilter.INSTANCE );
try {
schemaValidator.doValidation( scope.getMetadataImplementor(), executionOptions,
contributed -> {
return "test_data1".equalsIgnoreCase( contributed.getExportIdentifier() );
} );
}
catch (SchemaManagementException e) {
fail( e.getMessage() );
}
try {
schemaValidator.doValidation( scope.getMetadataImplementor(), executionOptions,
contributed -> {
return "test_data2".equalsIgnoreCase( contributed.getExportIdentifier() );
} );
fail( "SchemaManagementException expected" );
}
catch (SchemaManagementException e) {
assertEquals(
"Schema validation: wrong column type encountered in column [integral1] in table [TEST_DATA2]; found [tinyint unsigned (Types#TINYINT)], but expecting [tinyint (Types#INTEGER)]",
e.getMessage() );
}
try {
schemaValidator.doValidation( scope.getMetadataImplementor(), executionOptions,
contributed -> {
return "test_data3".equalsIgnoreCase( contributed.getExportIdentifier() );
} );
fail( "SchemaManagementException expected" );
}
catch (SchemaManagementException e) {
assertEquals(
"Schema validation: wrong column type encountered in column [integral1] in table [TEST_DATA3]; found [tinyint unsigned (Types#TINYINT)], but expecting [tinyint unsigned default '0' (Types#INTEGER)]",
e.getMessage() );
}
}
@Entity(name = "test_entity1")
@Table(name = "TEST_DATA1")
public static
|
MySQLColumnValidationTest
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/application/ApplicationContainerInitEvent.java
|
{
"start": 1643,
"end": 2024
}
|
class ____ extends ApplicationEvent {
final Container container;
public ApplicationContainerInitEvent(Container container) {
super(container.getContainerId().getApplicationAttemptId()
.getApplicationId(), ApplicationEventType.INIT_CONTAINER);
this.container = container;
}
Container getContainer() {
return container;
}
}
|
ApplicationContainerInitEvent
|
java
|
spring-projects__spring-framework
|
framework-docs/src/main/java/org/springframework/docs/core/aot/hints/testing/SpellCheckServiceTests.java
|
{
"start": 959,
"end": 1398
}
|
class ____ {
// tag::hintspredicates[]
@Test
void shouldRegisterResourceHints() {
RuntimeHints hints = new RuntimeHints();
new SpellCheckServiceRuntimeHints().registerHints(hints, getClass().getClassLoader());
assertThat(RuntimeHintsPredicates.resource().forResource("dicts/en.txt"))
.accepts(hints);
}
// end::hintspredicates[]
// Copied here because it is package private in SpellCheckService
static
|
SpellCheckServiceTests
|
java
|
apache__kafka
|
connect/mirror/src/test/java/org/apache/kafka/connect/mirror/OffsetSyncTest.java
|
{
"start": 1051,
"end": 1898
}
|
class ____ {
@Test
public void testSerde() {
OffsetSync offsetSync = new OffsetSync(new TopicPartition("topic-1", 2), 3, 4);
byte[] key = offsetSync.recordKey();
byte[] value = offsetSync.recordValue();
ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>("any-topic", 6, 7, key, value);
OffsetSync deserialized = OffsetSync.deserializeRecord(record);
assertEquals(offsetSync.topicPartition(), deserialized.topicPartition(),
"Failure on offset sync topic partition serde");
assertEquals(offsetSync.upstreamOffset(), deserialized.upstreamOffset(),
"Failure on upstream offset serde");
assertEquals(offsetSync.downstreamOffset(), deserialized.downstreamOffset(),
"Failure on downstream offset serde");
}
}
|
OffsetSyncTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/dialect/aggregate/HANAAggregateSupport.java
|
{
"start": 29583,
"end": 33480
}
|
class ____ implements XmlWriteExpression {
private final SelectableMapping selectableMapping;
private final String customWriteExpressionStart;
private final String customWriteExpressionEnd;
BasicXmlWriteExpression(SelectableMapping selectableMapping, String customWriteExpression) {
this.selectableMapping = selectableMapping;
if ( customWriteExpression.equals( "?" ) ) {
this.customWriteExpressionStart = "";
this.customWriteExpressionEnd = "";
}
else {
final String[] parts = StringHelper.split( "?", customWriteExpression );
assert parts.length == 2;
this.customWriteExpressionStart = parts[0];
this.customWriteExpressionEnd = parts[1];
}
}
@Override
public boolean isAggregate() {
return selectableMapping.getJdbcMapping().getJdbcType().isXml();
}
@Override
public void append(
SqlAppender sb,
String path,
SqlAstTranslator<?> translator,
AggregateColumnWriteExpression expression) {
final boolean isArray = selectableMapping.getJdbcMapping().getJdbcType().getDefaultSqlTypeCode() == XML_ARRAY;
if ( isAggregate() ) {
sb.append( "coalesce(" );
}
if ( isArray ) {
sb.append( "'<" );
sb.append( selectableMapping.getSelectableName() );
sb.append( ">'||case when " );
sb.append( customWriteExpressionStart );
// We use NO_UNTYPED here so that expressions which require type inference are casted explicitly,
// since we don't know how the custom write expression looks like where this is embedded,
// so we have to be pessimistic and avoid ambiguities
translator.render( expression.getValueExpression( selectableMapping ), SqlAstNodeRenderingMode.NO_UNTYPED );
sb.append( customWriteExpressionEnd );
sb.append( " is null then null else xmlextract(" );
}
sb.append( customWriteExpressionStart );
// We use NO_UNTYPED here so that expressions which require type inference are casted explicitly,
// since we don't know how the custom write expression looks like where this is embedded,
// so we have to be pessimistic and avoid ambiguities
translator.render( expression.getValueExpression( selectableMapping ), SqlAstNodeRenderingMode.NO_UNTYPED );
sb.append( customWriteExpressionEnd );
if ( isArray ) {
sb.append( ",'/*/node()') end||'</" );
sb.append( selectableMapping.getSelectableName() );
sb.append( ">'" );
}
// Since xmlextractvalue throws an error if a xpath expression doesn't resolve to a node,
// insert special null nodes
if ( isAggregate() ) {
sb.append( ",'<" );
sb.append( selectableMapping.getSelectableName() );
if ( selectableMapping.getJdbcMapping().getJdbcType() instanceof AggregateJdbcType ) {
sb.append( ">" );
appendNullTags( sb, selectableMapping );
sb.append( "</" );
sb.append( selectableMapping.getSelectableName() );
sb.append( ">')" );
}
else {
sb.append( "/>')" );
}
}
}
private void appendNullTags(SqlAppender sb, SelectableMapping parentMapping) {
final AggregateJdbcType jdbcType = (AggregateJdbcType) parentMapping.getJdbcMapping().getJdbcType();
final EmbeddableMappingType embeddableMappingType = jdbcType.getEmbeddableMappingType();
final int jdbcValueCount = embeddableMappingType.getJdbcValueCount();
for ( int i = 0; i < jdbcValueCount; i++ ) {
final SelectableMapping selectable = embeddableMappingType.getJdbcValueSelectable( i );
sb.append( "<" );
if ( selectable.getJdbcMapping().getJdbcType() instanceof AggregateJdbcType ) {
sb.append( selectable.getSelectableName() );
sb.append( ">" );
appendNullTags( sb, selectable );
sb.append( "</" );
sb.append( selectable.getSelectableName() );
sb.append( ">" );
}
else {
sb.append( selectable.getSelectableName() );
sb.append( "/>" );
}
}
}
}
private static
|
BasicXmlWriteExpression
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/api/vector/VectorInfo.java
|
{
"start": 757,
"end": 1857
}
|
class ____ implements Serializable {
private long attributesCount;
private long dimensions;
private long size;
private QuantizationType quantizationType;
private long maxConnections;
public long getAttributesCount() {
return attributesCount;
}
public void setAttributesCount(long attributesCount) {
this.attributesCount = attributesCount;
}
public long getDimensions() {
return dimensions;
}
public void setDimensions(long dimensions) {
this.dimensions = dimensions;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public QuantizationType getQuantizationType() {
return quantizationType;
}
public void setQuantizationType(QuantizationType quantizationType) {
this.quantizationType = quantizationType;
}
public long getMaxConnections() {
return maxConnections;
}
public void setMaxConnections(long maxConnections) {
this.maxConnections = maxConnections;
}
}
|
VectorInfo
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/unidir/Child2.java
|
{
"start": 255,
"end": 652
}
|
class ____ {
@Id
@Column(name = "ID")
private Long id;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "CHILD2_ID", nullable = false)
private List<Parent1> parents = new ArrayList<Parent1>();
public Long getId() {
return this.id;
}
public List<Parent1> getParents() {
return this.parents;
}
public void setParents(List<Parent1> parents) {
this.parents = parents;
}
}
|
Child2
|
java
|
apache__flink
|
flink-python/src/main/java/org/apache/flink/streaming/api/operators/python/embedded/AbstractOneInputEmbeddedPythonFunctionOperator.java
|
{
"start": 1868,
"end": 7201
}
|
class ____<IN, OUT>
extends AbstractEmbeddedDataStreamPythonFunctionOperator<OUT>
implements OneInputStreamOperator<IN, OUT>, BoundedOneInput {
private static final long serialVersionUID = 1L;
/** The TypeInformation of the input data. */
private final TypeInformation<IN> inputTypeInfo;
private transient PythonTypeUtils.DataConverter<IN, Object> inputDataConverter;
protected transient long timestamp;
public AbstractOneInputEmbeddedPythonFunctionOperator(
Configuration config,
DataStreamPythonFunctionInfo pythonFunctionInfo,
TypeInformation<IN> inputTypeInfo,
TypeInformation<OUT> outputTypeInfo) {
super(config, pythonFunctionInfo, outputTypeInfo);
this.inputTypeInfo = Preconditions.checkNotNull(inputTypeInfo);
}
@Override
public void open() throws Exception {
super.open();
inputDataConverter =
PythonTypeUtils.TypeInfoToDataConverter.typeInfoDataConverter(inputTypeInfo);
}
@Override
public void openPythonInterpreter() {
// function_protos = ...
// input_coder_info = ...
// output_coder_info = ...
// runtime_context = ...
// function_context = ...
// job_parameters = ...
//
// from pyflink.fn_execution.embedded.operation_utils import
// create_one_input_user_defined_data_stream_function_from_protos
//
// operation = create_one_input_user_defined_data_stream_function_from_protos(
// function_protos, input_coder_info, output_coder_info, runtime_context,
// function_context, job_parameters)
// operation.open()
interpreter.set(
"function_protos",
createUserDefinedFunctionsProto().stream()
.map(AbstractMessageLite::toByteArray)
.collect(Collectors.toList()));
interpreter.set(
"input_coder_info",
ProtoUtils.createRawTypeCoderInfoDescriptorProto(
getInputTypeInfo(),
FlinkFnApi.CoderInfoDescriptor.Mode.SINGLE,
false,
null)
.toByteArray());
interpreter.set(
"output_coder_info",
ProtoUtils.createRawTypeCoderInfoDescriptorProto(
outputTypeInfo,
FlinkFnApi.CoderInfoDescriptor.Mode.SINGLE,
false,
null)
.toByteArray());
interpreter.set("runtime_context", getRuntimeContext());
interpreter.set("function_context", getFunctionContext());
interpreter.set("timer_context", getTimerContext());
interpreter.set("job_parameters", getJobParameters());
interpreter.set("keyed_state_backend", getKeyedStateBackend());
interpreter.set("operator_state_backend", getOperatorStateBackend());
interpreter.set("side_output_context", sideOutputContext);
interpreter.exec(
"from pyflink.fn_execution.embedded.operation_utils import create_one_input_user_defined_data_stream_function_from_protos");
interpreter.exec(
"operation = create_one_input_user_defined_data_stream_function_from_protos("
+ "function_protos,"
+ "input_coder_info,"
+ "output_coder_info,"
+ "runtime_context,"
+ "function_context,"
+ "timer_context,"
+ "side_output_context,"
+ "job_parameters,"
+ "keyed_state_backend,"
+ "operator_state_backend)");
interpreter.invokeMethod("operation", "open");
}
@Override
public void endInput() {
if (interpreter != null) {
interpreter.invokeMethod("operation", "close");
}
}
@Override
public void processElement(StreamRecord<IN> element) throws Exception {
collector.setTimestamp(element);
timestamp = element.getTimestamp();
IN value = element.getValue();
PyIterator results =
(PyIterator)
interpreter.invokeMethod(
"operation",
"process_element",
inputDataConverter.toExternal(value));
while (results.hasNext()) {
OUT result = outputDataConverter.toInternal(results.next());
collector.collect(result);
}
results.close();
}
TypeInformation<IN> getInputTypeInfo() {
return inputTypeInfo;
}
/** Gets the proto representation of the Python user-defined functions to be executed. */
public abstract List<FlinkFnApi.UserDefinedDataStreamFunction>
createUserDefinedFunctionsProto();
/** Gets The function context. */
public abstract Object getFunctionContext();
/** Gets The Timer context. */
public abstract Object getTimerContext();
}
|
AbstractOneInputEmbeddedPythonFunctionOperator
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/SessionCheckMode.java
|
{
"start": 968,
"end": 1488
}
|
enum ____ implements FindMultipleOption {
/**
* The persistence context will be checked. Identifiers for entities already contained
* in the persistence context will not be sent to the database for loading. If the
* entity is marked for removal in the persistence context, whether it is returned
* is controlled by {@linkplain RemovalsMode}.
*
* @see RemovalsMode
*/
ENABLED,
/**
* The default. All identifiers to be loaded will be read from the database and returned.
*/
DISABLED
}
|
SessionCheckMode
|
java
|
apache__logging-log4j2
|
log4j-core-test/src/test/java/org/apache/logging/log4j/LogRolloverTest.java
|
{
"start": 988,
"end": 1581
}
|
class ____ {
private static final String CONFIG = "src/test/resources/rollover-test.xml";
public static void main(final String[] args) throws Exception {
final File file = new File(CONFIG);
try (final LoggerContext ctx =
Configurator.initialize("LogTest", LogRolloverTest.class.getClassLoader(), file.toURI())) {
final Logger logger = LogManager.getLogger("TestLogger");
for (long i = 0; ; i += 1) {
logger.debug("Sequence: " + i);
Thread.sleep(250);
}
}
}
}
|
LogRolloverTest
|
java
|
mybatis__mybatis-3
|
src/main/java/org/apache/ibatis/builder/annotation/MethodResolver.java
|
{
"start": 774,
"end": 1130
}
|
class ____ {
private final MapperAnnotationBuilder annotationBuilder;
private final Method method;
public MethodResolver(MapperAnnotationBuilder annotationBuilder, Method method) {
this.annotationBuilder = annotationBuilder;
this.method = method;
}
public void resolve() {
annotationBuilder.parseStatement(method);
}
}
|
MethodResolver
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvMedianUnsignedLongEvaluator.java
|
{
"start": 857,
"end": 4960
}
|
class ____ extends AbstractMultivalueFunction.AbstractEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(MvMedianUnsignedLongEvaluator.class);
public MvMedianUnsignedLongEvaluator(EvalOperator.ExpressionEvaluator field,
DriverContext driverContext) {
super(driverContext, field);
}
@Override
public String name() {
return "MvMedian";
}
/**
* Evaluate blocks containing at least one multivalued field.
*/
@Override
public Block evalNullable(Block fieldVal) {
if (fieldVal.mvSortedAscending()) {
return evalAscendingNullable(fieldVal);
}
LongBlock v = (LongBlock) fieldVal;
int positionCount = v.getPositionCount();
try (LongBlock.Builder builder = driverContext.blockFactory().newLongBlockBuilder(positionCount)) {
MvMedian.Longs work = new MvMedian.Longs();
for (int p = 0; p < positionCount; p++) {
int valueCount = v.getValueCount(p);
if (valueCount == 0) {
builder.appendNull();
continue;
}
int first = v.getFirstValueIndex(p);
int end = first + valueCount;
for (int i = first; i < end; i++) {
long value = v.getLong(i);
MvMedian.processUnsignedLong(work, value);
}
long result = MvMedian.finishUnsignedLong(work);
builder.appendLong(result);
}
return builder.build();
}
}
/**
* Evaluate blocks containing at least one multivalued field.
*/
@Override
public Block evalNotNullable(Block fieldVal) {
if (fieldVal.mvSortedAscending()) {
return evalAscendingNotNullable(fieldVal);
}
LongBlock v = (LongBlock) fieldVal;
int positionCount = v.getPositionCount();
try (LongVector.FixedBuilder builder = driverContext.blockFactory().newLongVectorFixedBuilder(positionCount)) {
MvMedian.Longs work = new MvMedian.Longs();
for (int p = 0; p < positionCount; p++) {
int valueCount = v.getValueCount(p);
int first = v.getFirstValueIndex(p);
int end = first + valueCount;
for (int i = first; i < end; i++) {
long value = v.getLong(i);
MvMedian.processUnsignedLong(work, value);
}
long result = MvMedian.finishUnsignedLong(work);
builder.appendLong(result);
}
return builder.build().asBlock();
}
}
/**
* Evaluate blocks containing at least one multivalued field and all multivalued fields are in ascending order.
*/
private Block evalAscendingNullable(Block fieldVal) {
LongBlock v = (LongBlock) fieldVal;
int positionCount = v.getPositionCount();
try (LongBlock.Builder builder = driverContext.blockFactory().newLongBlockBuilder(positionCount)) {
MvMedian.Longs work = new MvMedian.Longs();
for (int p = 0; p < positionCount; p++) {
int valueCount = v.getValueCount(p);
if (valueCount == 0) {
builder.appendNull();
continue;
}
int first = v.getFirstValueIndex(p);
long result = MvMedian.ascendingUnsignedLong(v, first, valueCount);
builder.appendLong(result);
}
return builder.build();
}
}
/**
* Evaluate blocks containing at least one multivalued field and all multivalued fields are in ascending order.
*/
private Block evalAscendingNotNullable(Block fieldVal) {
LongBlock v = (LongBlock) fieldVal;
int positionCount = v.getPositionCount();
try (LongVector.FixedBuilder builder = driverContext.blockFactory().newLongVectorFixedBuilder(positionCount)) {
MvMedian.Longs work = new MvMedian.Longs();
for (int p = 0; p < positionCount; p++) {
int valueCount = v.getValueCount(p);
int first = v.getFirstValueIndex(p);
long result = MvMedian.ascendingUnsignedLong(v, first, valueCount);
builder.appendLong(result);
}
return builder.build().asBlock();
}
}
@Override
public long baseRamBytesUsed() {
return BASE_RAM_BYTES_USED + field.baseRamBytesUsed();
}
public static
|
MvMedianUnsignedLongEvaluator
|
java
|
spring-projects__spring-boot
|
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/testing/springbootapplications/autoconfiguredspringdatacassandra/MyDataCassandraTests.java
|
{
"start": 899,
"end": 1009
}
|
class ____ {
@Autowired
@SuppressWarnings("unused")
private SomeRepository repository;
}
|
MyDataCassandraTests
|
java
|
spring-projects__spring-framework
|
spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyExtractorsTests.java
|
{
"start": 16114,
"end": 16634
}
|
class ____ {
@JsonView(SafeToDeserialize.class)
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
}
|
User
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/GeocoderComponentBuilderFactory.java
|
{
"start": 4558,
"end": 5480
}
|
class ____
extends AbstractComponentBuilder<GeoCoderComponent>
implements GeocoderComponentBuilder {
@Override
protected GeoCoderComponent buildConcreteComponent() {
return new GeoCoderComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "lazyStartProducer": ((GeoCoderComponent) component).setLazyStartProducer((boolean) value); return true;
case "autowiredEnabled": ((GeoCoderComponent) component).setAutowiredEnabled((boolean) value); return true;
case "geoApiContext": ((GeoCoderComponent) component).setGeoApiContext((com.google.maps.GeoApiContext) value); return true;
default: return false;
}
}
}
}
|
GeocoderComponentBuilderImpl
|
java
|
spring-projects__spring-framework
|
spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
|
{
"start": 249258,
"end": 249865
}
|
class ____ implements Message<String> {
@Override
public MessageHeaders getHeaders() {
MessageHeaders mh = new MessageHeaders();
mh.put("command", "wibble");
mh.put("command2", "wobble");
return mh;
}
@Override
public int[] getIa() { return new int[] {5,3}; }
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public List getList() {
List l = new ArrayList();
l.add("wibble");
l.add("wobble");
return l;
}
public String getKey() {
return "command2";
}
public int getKey2() {
return 1;
}
}
@SuppressWarnings("serial")
public static
|
MyMessage
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/SortComparatorAnnotation.java
|
{
"start": 472,
"end": 1515
}
|
class ____ implements SortComparator {
private java.lang.Class<? extends java.util.Comparator<?>> value;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public SortComparatorAnnotation(ModelsContext modelContext) {
}
/**
* Used in creating annotation instances from JDK variant
*/
public SortComparatorAnnotation(SortComparator annotation, ModelsContext modelContext) {
this.value = annotation.value();
}
/**
* Used in creating annotation instances from Jandex variant
*/
public SortComparatorAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) {
this.value = (Class<? extends java.util.Comparator<?>>) attributeValues.get( "value" );
}
@Override
public Class<? extends Annotation> annotationType() {
return SortComparator.class;
}
@Override
public java.lang.Class<? extends java.util.Comparator<?>> value() {
return value;
}
public void value(java.lang.Class<? extends java.util.Comparator<?>> value) {
this.value = value;
}
}
|
SortComparatorAnnotation
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/jpa/event/internal/EntityCallback.java
|
{
"start": 703,
"end": 2182
}
|
class ____ implements CallbackDefinition {
private final Method callbackMethod;
private final CallbackType callbackType;
public Definition(Method callbackMethod, CallbackType callbackType) {
this.callbackMethod = callbackMethod;
this.callbackType = callbackType;
}
public Definition(MethodDetails callbackMethod, CallbackType callbackType) {
this.callbackMethod = (Method) callbackMethod.toJavaMember();
this.callbackType = callbackType;
}
@Override
public Callback createCallback(ManagedBeanRegistry beanRegistry) {
return new EntityCallback( callbackMethod, callbackType );
}
}
private final Method callbackMethod;
private EntityCallback(Method callbackMethod, CallbackType callbackType) {
super( callbackType );
this.callbackMethod = callbackMethod;
}
@Override
public void performCallback(Object entity) {
try {
callbackMethod.invoke( entity );
}
catch (InvocationTargetException e) {
//keep runtime exceptions as is
if ( e.getTargetException() instanceof RuntimeException runtimeException ) {
throw runtimeException;
}
else {
throw new RuntimeException( e.getTargetException() );
}
}
catch (Exception e) {
throw new RuntimeException( e );
}
}
@Override
public String toString() {
return String.format(
Locale.ROOT,
"EntityCallback([%s] %s.%s)",
getCallbackType().name(),
callbackMethod.getDeclaringClass().getName(),
callbackMethod.getName()
);
}
}
|
Definition
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/compositefk/ManyToOneEmbeddedIdWithLazyToOneFKTest.java
|
{
"start": 1373,
"end": 7701
}
|
class ____ {
@BeforeEach
public void setUp(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Subsystem subsystem = new Subsystem( 2, "sub1" );
PK userKey = new PK( subsystem, "Fab" );
SystemUser user = new SystemUser( userKey, "Fab" );
System system = new System( 1, "sub1" );
system.setUser( user );
session.persist( subsystem );
session.persist( user );
session.persist( system );
}
);
}
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
public void testGet(SessionFactoryScope scope) {
SQLStatementInspector statementInspector = scope.getCollectingStatementInspector();
statementInspector.clear();
scope.inTransaction(
session -> {
System system = session.get( System.class, 1 );
assertThat( system, is( notNullValue() ) );
assertThat( system.getId(), is( 1 ) );
assertTrue( Hibernate.isInitialized( system.getUser() ) );
PK pk = system.getUser().getPk();
assertFalse( Hibernate.isInitialized( pk.subsystem ) );
SystemUser user = system.getUser();
assertThat( user, is( notNullValue() ) );
statementInspector.assertExecutedCount( 1 );
statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 1 );
statementInspector.clear();
assertThat( pk.username, is( "Fab" ) );
Subsystem subsystem = pk.getSubsystem();
assertThat( subsystem.getId(), is( 2 ) );
assertThat( subsystem.getDescription(), is( "sub1" ) );
statementInspector.assertExecutedCount( 1 );
statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 0 );
}
);
}
@Test
public void testHql(SessionFactoryScope scope) {
SQLStatementInspector statementInspector = scope.getCollectingStatementInspector();
statementInspector.clear();
/*
select
s1_0.id,
s1_0.name,
s1_0.user_subsystem_id,
s1_0.user_username
from
System as s1_0
where
s1_0.id = ?
select
s1_0.subsystem_id,
s1_0.username,
s1_0.name
from
SystemUser as s1_0
where
(
s1_0.subsystem_id, s1_0.username
) in (
(
?, ?
)
)
*/
scope.inTransaction(
session -> {
System system = (System) session.createQuery( "from System e where e.id = :id" )
.setParameter( "id", 1 ).uniqueResult();
assertThat( system, is( notNullValue() ) );
statementInspector.assertExecutedCount( 2 );
statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 0 );
statementInspector.assertNumberOfOccurrenceInQuery( 1, "join", 0 );
assertTrue( Hibernate.isInitialized( system.getUser() ) );
final PK pk = system.getUser().getPk();
assertFalse( Hibernate.isInitialized( pk.subsystem ) );
statementInspector.clear();
assertThat( pk.username, is( "Fab" ) );
Subsystem subsystem = pk.getSubsystem();
assertThat( subsystem.getId(), is( 2 ) );
assertThat( subsystem.getDescription(), is( "sub1" ) );
statementInspector.assertExecutedCount( 1 );
statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 0 );
}
);
}
@Test
public void testHqlJoin(SessionFactoryScope scope) {
SQLStatementInspector statementInspector = scope.getCollectingStatementInspector();
statementInspector.clear();
scope.inTransaction(
session -> {
System system = session.createQuery( "from System e join e.user where e.id = :id", System.class )
.setParameter( "id", 1 ).uniqueResult();
statementInspector.assertExecutedCount( 2 );
statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 1 );
statementInspector.assertNumberOfOccurrenceInQuery( 1, "join", 0 );
assertThat( system, is( notNullValue() ) );
SystemUser user = system.getUser();
assertThat( user, is( notNullValue() ) );
assertTrue( Hibernate.isInitialized( system.getUser() ) );
assertFalse( Hibernate.isInitialized( system.getUser().getPk().subsystem ) );
statementInspector.clear();
PK pk = system.getUser().getPk();
assertThat( pk.username, is( "Fab" ) );
Subsystem subsystem = pk.getSubsystem();
assertThat( subsystem.getId(), is( 2 ) );
assertThat( subsystem.getDescription(), is( "sub1" ) );
statementInspector.assertExecutedCount( 1 );
statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 0 );
}
);
}
@Test
public void testHqlJoinFetch(SessionFactoryScope scope) {
SQLStatementInspector statementInspector = scope.getCollectingStatementInspector();
statementInspector.clear();
scope.inTransaction(
session -> {
System system = session.createQuery(
"from System e join fetch e.user where e.id = :id",
System.class
).setParameter( "id", 1 ).uniqueResult();
statementInspector.assertExecutedCount( 1 );
statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 1 );
assertThat( system, is( notNullValue() ) );
SystemUser user = system.getUser();
assertThat( user, is( notNullValue() ) );
statementInspector.clear();
PK pk = system.getUser().getPk();
assertThat( pk.username, is( "Fab" ) );
Subsystem subsystem = pk.getSubsystem();
assertThat( subsystem.getId(), is( 2 ) );
assertThat( subsystem.getDescription(), is( "sub1" ) );
statementInspector.assertExecutedCount( 1 );
statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 0 );
}
);
}
@Test
public void testHql2(SessionFactoryScope scope) {
SQLStatementInspector statementInspector = scope.getCollectingStatementInspector();
statementInspector.clear();
scope.inTransaction(
session -> {
// intentionally set the Subsystem description to "sub2", only the Subsystem.id value is used for the parameter binding
Subsystem subsystem = new Subsystem( 2, "sub2" );
PK userKey = new PK( subsystem, "Fab" );
SystemUser systemUser = session.createQuery(
"from SystemUser s where s.pk = :id",
SystemUser.class
).setParameter( "id", userKey ).uniqueResult();
assertThat( systemUser.getPk().getSubsystem().getDescription(), is( "sub1" ) );
}
);
}
@Entity(name = "System")
@Table( name = "systems" )
public static
|
ManyToOneEmbeddedIdWithLazyToOneFKTest
|
java
|
apache__camel
|
components/camel-infinispan/camel-infinispan-embedded/src/main/java/org/apache/camel/component/infinispan/embedded/InfinispanEmbeddedUtil.java
|
{
"start": 1285,
"end": 2514
}
|
class ____ extends InfinispanUtil {
protected InfinispanEmbeddedUtil() {
}
@SuppressWarnings("unchecked")
public static <K, V> Cache<K, V> getCacheWithFlags(InfinispanEmbeddedManager manager, String cacheName, Flag... flags) {
final Cache<K, V> cache = manager.getCache(cacheName, Cache.class);
return flags == null || flags.length == 0 ? cache : cache.getAdvancedCache().withFlags(flags);
}
public static Query<?> buildQuery(
InfinispanConfiguration configuration, Cache<Object, Object> cache, Message message) {
InfinispanQueryBuilder builder = message.getHeader(InfinispanConstants.QUERY_BUILDER, InfinispanQueryBuilder.class);
if (builder == null) {
builder = configuration.getQueryBuilder();
}
return buildQuery(builder, cache);
}
public static Query<?> buildQuery(InfinispanConfiguration configuration, Cache<Object, Object> cache) {
return buildQuery(configuration.getQueryBuilder(), cache);
}
public static Query<?> buildQuery(InfinispanQueryBuilder queryBuilder, Cache<Object, Object> cache) {
return queryBuilder != null ? queryBuilder.build(cache) : null;
}
}
|
InfinispanEmbeddedUtil
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/TypeReferenceTest.java
|
{
"start": 206,
"end": 463
}
|
class ____ extends TestCase {
public void test_list() throws Exception {
List<Long> list = JSON.parseObject("[1,2,3]", new TypeReference<List<Long>>() {});
Assert.assertEquals(1L, ((Long) list.get(0)).longValue());
}
}
|
TypeReferenceTest
|
java
|
elastic__elasticsearch
|
test/framework/src/main/java/org/elasticsearch/datageneration/datasource/DataSourceResponse.java
|
{
"start": 3255,
"end": 4161
}
|
interface ____ extends DataSourceResponse {
int generateChildFieldCount();
boolean generateDynamicSubObject();
boolean generateNestedSubObject();
boolean generateRegularSubObject();
String generateFieldName();
}
record FieldTypeGenerator(Supplier<FieldTypeInfo> generator) implements DataSourceResponse {
public record FieldTypeInfo(String fieldType) {}
}
record ObjectArrayGenerator(Supplier<Optional<Integer>> lengthGenerator) implements DataSourceResponse {}
record LeafMappingParametersGenerator(Supplier<Map<String, Object>> mappingGenerator) implements DataSourceResponse {}
record ObjectMappingParametersGenerator(Supplier<Map<String, Object>> mappingGenerator) implements DataSourceResponse {}
record DynamicMappingGenerator(Function<Boolean, Boolean> generator) implements DataSourceResponse {}
}
|
ChildFieldGenerator
|
java
|
quarkusio__quarkus
|
integration-tests/smallrye-config/src/test/java/io/quarkus/it/smallrye/config/ServerResourceTest.java
|
{
"start": 331,
"end": 2543
}
|
class ____ {
@Test
void mapping() {
given()
.get("/server")
.then()
.statusCode(OK.getStatusCode())
.body("name", equalTo("server"))
.body("alias", equalTo("server"))
.body("host", equalTo("localhost"))
.body("port", equalTo(8080))
.body("threads", equalTo(200))
.body("form.form.loginPage", equalTo("login.html"))
.body("form.form.errorPage", equalTo("error.html"))
.body("form.form.landingPage", equalTo("index.html"))
.body("form.form.positions.size()", equalTo(2))
.body("ssl.port", equalTo(8443))
.body("ssl.certificate", equalTo("certificate"))
.body("cors.methods[0]", equalTo("GET"))
.body("cors.methods[1]", equalTo("POST"))
.body("cors.origins[0].host", equalTo("some-server"))
.body("cors.origins[0].port", equalTo(9000))
.body("cors.origins[1].host", equalTo("another-server"))
.body("cors.origins[1].port", equalTo(8000))
.body("log.enabled", equalTo(false))
.body("log.suffix", equalTo(".log"))
.body("log.rotate", equalTo(true))
.body("log.pattern", equalTo("COMMON"))
.body("log.period", equalTo("P1D"));
}
@Test
void properties() {
given()
.get("/server/properties")
.then()
.statusCode(OK.getStatusCode())
.body("host", equalTo("localhost"))
.body("port", equalTo(8080));
}
@Test
void positions() {
given()
.get("/server/positions")
.then()
.statusCode(OK.getStatusCode())
.body(equalTo("[10,20]"));
}
@Test
void info() {
given()
.get("/server/info")
.then()
.statusCode(OK.getStatusCode())
.header("X-VERSION", "1.2.3.4")
.body(containsString("My application info"));
}
}
|
ServerResourceTest
|
java
|
spring-projects__spring-boot
|
build-plugin/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractAotMojo.java
|
{
"start": 1829,
"end": 7096
}
|
class ____ extends AbstractDependencyFilterMojo {
/**
* The current Maven session. This is used for toolchain manager API calls.
*/
@Parameter(defaultValue = "${session}", readonly = true)
@SuppressWarnings("NullAway.Init")
private MavenSession session;
/**
* The toolchain manager to use to locate a custom JDK.
*/
private final ToolchainManager toolchainManager;
/**
* Skip the execution.
*/
@Parameter(property = "spring-boot.aot.skip", defaultValue = "false")
private boolean skip;
/**
* List of JVM system properties to pass to the AOT process.
*/
@Parameter
private @Nullable Map<String, String> systemPropertyVariables;
/**
* JVM arguments that should be associated with the AOT process. On command line, make
* sure to wrap multiple values between quotes.
*/
@Parameter(property = "spring-boot.aot.jvmArguments")
private @Nullable String jvmArguments;
/**
* Arguments that should be provided to the AOT compile process. On command line, make
* sure to wrap multiple values between quotes.
*/
@Parameter(property = "spring-boot.aot.compilerArguments")
private @Nullable String compilerArguments;
protected AbstractAotMojo(ToolchainManager toolchainManager) {
this.toolchainManager = toolchainManager;
}
/**
* Return Maven execution session.
* @return session
* @since 3.0.10
*/
protected final MavenSession getSession() {
return this.session;
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (this.skip) {
getLog().debug("Skipping AOT execution as per configuration");
return;
}
try {
executeAot();
}
catch (Exception ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
}
protected abstract void executeAot() throws Exception;
protected void generateAotAssets(URL[] classPath, String processorClassName, String... arguments) throws Exception {
List<String> command = CommandLineBuilder.forMainClass(processorClassName)
.withSystemProperties(this.systemPropertyVariables)
.withJvmArguments(new RunArguments(this.jvmArguments).asArray())
.withClasspath(classPath)
.withArguments(arguments)
.build();
if (getLog().isDebugEnabled()) {
getLog().debug("Generating AOT assets using command: " + command);
}
JavaProcessExecutor processExecutor = new JavaProcessExecutor(this.session, this.toolchainManager);
processExecutor.run(this.project.getBasedir(), command, Collections.emptyMap());
}
protected final void compileSourceFiles(URL[] classPath, File sourcesDirectory, File outputDirectory)
throws Exception {
List<Path> sourceFiles;
try (Stream<Path> pathStream = Files.walk(sourcesDirectory.toPath())) {
sourceFiles = pathStream.filter(Files::isRegularFile).toList();
}
if (sourceFiles.isEmpty()) {
return;
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
JavaCompilerPluginConfiguration compilerConfiguration = new JavaCompilerPluginConfiguration(this.project);
List<String> args = new ArrayList<>();
args.addAll(ClassPath.of(classPath).args(false));
args.add("-d");
args.add(outputDirectory.toPath().toAbsolutePath().toString());
String releaseVersion = compilerConfiguration.getReleaseVersion();
if (releaseVersion != null) {
args.add("--release");
args.add(releaseVersion);
}
else {
String source = compilerConfiguration.getSourceMajorVersion();
if (source != null) {
args.add("--source");
args.add(source);
}
String target = compilerConfiguration.getTargetMajorVersion();
if (target != null) {
args.add("--target");
args.add(target);
}
}
args.addAll(new RunArguments(this.compilerArguments).getArgs());
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromPaths(sourceFiles);
Errors errors = new Errors();
CompilationTask task = compiler.getTask(null, fileManager, errors, args, null, compilationUnits);
boolean result = task.call();
if (!result || errors.hasReportedErrors()) {
throw new IllegalStateException("Unable to compile generated source" + errors);
}
}
}
protected final URL[] getClassPath(File[] directories, ArtifactsFilter... artifactFilters)
throws MojoExecutionException {
List<URL> urls = new ArrayList<>();
Arrays.stream(directories).map(this::toURL).forEach(urls::add);
urls.addAll(getDependencyURLs(artifactFilters));
return urls.toArray(URL[]::new);
}
protected final void copyAll(Path from, Path to) throws IOException {
if (!Files.exists(from)) {
return;
}
List<Path> files;
try (Stream<Path> pathStream = Files.walk(from)) {
files = pathStream.filter(Files::isRegularFile).toList();
}
for (Path file : files) {
String relativeFileName = file.subpath(from.getNameCount(), file.getNameCount()).toString();
getLog().debug("Copying '" + relativeFileName + "' to " + to);
Path target = to.resolve(relativeFileName);
Files.createDirectories(target.getParent());
Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING);
}
}
/**
* {@link DiagnosticListener} used to collect errors.
*/
protected static
|
AbstractAotMojo
|
java
|
google__guava
|
android/guava-testlib/src/com/google/common/collect/testing/testers/MapCreationTester.java
|
{
"start": 2288,
"end": 5773
}
|
class ____<K, V> extends AbstractMapTester<K, V> {
@MapFeature.Require(ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeySupported() {
initMapWithNullKey();
expectContents(createArrayWithNullKey());
}
@MapFeature.Require(absent = ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeyUnsupported() {
assertThrows(NullPointerException.class, () -> initMapWithNullKey());
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullValueSupported() {
initMapWithNullValue();
expectContents(createArrayWithNullValue());
}
@MapFeature.Require(absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullValueUnsupported() {
assertThrows(NullPointerException.class, () -> initMapWithNullValue());
}
@MapFeature.Require({ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeyAndValueSupported() {
Entry<K, V>[] entries = createSamplesArray();
entries[getNullLocation()] = entry(null, null);
resetMap(entries);
expectContents(entries);
}
@MapFeature.Require(value = ALLOWS_NULL_KEYS, absent = REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nullDuplicatesNotRejected() {
expectFirstRemoved(getEntriesMultipleNullKeys());
}
@MapFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() {
expectFirstRemoved(getEntriesMultipleNonNullKeys());
}
@MapFeature.Require({ALLOWS_NULL_KEYS, REJECTS_DUPLICATES_AT_CREATION})
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nullDuplicatesRejected() {
Entry<K, V>[] entries = getEntriesMultipleNullKeys();
assertThrows(IllegalArgumentException.class, () -> resetMap(entries));
}
@MapFeature.Require(REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nonNullDuplicatesRejected() {
Entry<K, V>[] entries = getEntriesMultipleNonNullKeys();
assertThrows(IllegalArgumentException.class, () -> resetMap(entries));
}
private Entry<K, V>[] getEntriesMultipleNullKeys() {
Entry<K, V>[] entries = createArrayWithNullKey();
entries[0] = entry(null, entries[0].getValue());
return entries;
}
private Entry<K, V>[] getEntriesMultipleNonNullKeys() {
Entry<K, V>[] entries = createSamplesArray();
entries[0] = entry(k1(), v0());
return entries;
}
private void expectFirstRemoved(Entry<K, V>[] entries) {
resetMap(entries);
List<Entry<K, V>> expectedWithDuplicateRemoved = asList(entries).subList(1, getNumElements());
expectContents(expectedWithDuplicateRemoved);
}
/**
* Returns the {@link Method} instance for {@link #testCreateWithNullKeyUnsupported()} so that
* tests can suppress it with {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="https://bugs.openjdk.org/browse/JDK-5045147">JDK-5045147</a> is fixed.
*/
@J2ktIncompatible
@GwtIncompatible // reflection
public static Method getCreateWithNullKeyUnsupportedMethod() {
return getMethod(MapCreationTester.class, "testCreateWithNullKeyUnsupported");
}
}
|
MapCreationTester
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java
|
{
"start": 62043,
"end": 62293
}
|
class ____ {
@Bean
PrefixProperties prefixProperties() {
return new PrefixProperties();
}
}
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(PrefixProperties.class)
static
|
PrefixPropertiesDeclaredAsBeanConfiguration
|
java
|
apache__camel
|
components/camel-schematron/src/main/java/org/apache/camel/component/schematron/constant/Constants.java
|
{
"start": 875,
"end": 966
}
|
class ____ all constants needed for the schematron component.
* <p/>
*/
public final
|
defining
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/ResourceAutoClosingTests.java
|
{
"start": 5227,
"end": 5403
}
|
class ____ implements ExtensionContext.Store.CloseableResource {
private boolean closed = false;
@Override
public void close() {
closed = true;
}
}
}
|
CloseableResource
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
|
{
"start": 41124,
"end": 41179
}
|
class ____<T> {
@Immutable
|
Test
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/StringCharsetTest.java
|
{
"start": 1699,
"end": 2114
}
|
class ____ {
void f(String s) throws Exception {
new String(new byte[0], "utf8");
s.getBytes("latin1");
}
}
""")
.addOutputLines(
"Test.java",
"""
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
|
Test
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java
|
{
"start": 6515,
"end": 14753
}
|
class ____ as a bean definition.
*/
private void registerBeanDefinitionForImportedConfigurationClass(ConfigurationClass configClass) {
AnnotationMetadata metadata = configClass.getMetadata();
AnnotatedGenericBeanDefinition configBeanDef = new AnnotatedGenericBeanDefinition(metadata);
ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(configBeanDef);
configBeanDef.setScope(scopeMetadata.getScopeName());
String configBeanName;
try {
configBeanName = this.importBeanNameGenerator.generateBeanName(configBeanDef, this.registry);
}
catch (IllegalArgumentException ex) {
throw new IllegalStateException("Failed to generate bean name for imported class '" +
configClass.getMetadata().getClassName() + "'", ex);
}
AnnotationConfigUtils.processCommonDefinitionAnnotations(configBeanDef, metadata);
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(configBeanDef, configBeanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
this.registry.registerBeanDefinition(definitionHolder.getBeanName(), definitionHolder.getBeanDefinition());
configClass.setBeanName(configBeanName);
if (logger.isTraceEnabled()) {
logger.trace("Registered bean definition for imported class '" + configBeanName + "'");
}
}
/**
* Read the given {@link BeanMethod}, registering bean definitions
* with the BeanDefinitionRegistry based on its contents.
*/
private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
ConfigurationClass configClass = beanMethod.getConfigurationClass();
MethodMetadata metadata = beanMethod.getMetadata();
String methodName = metadata.getMethodName();
// Do we need to mark the bean as skipped by its condition?
if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
configClass.skippedBeanMethods.add(methodName);
return;
}
if (configClass.skippedBeanMethods.contains(methodName)) {
return;
}
AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
Assert.state(bean != null, "No @Bean annotation attributes");
// Consider name and any aliases.
String[] explicitNames = bean.getStringArray("name");
String beanName = (explicitNames.length > 0 && StringUtils.hasText(explicitNames[0])) ? explicitNames[0] : null;
String localBeanName = defaultBeanName(beanName, methodName);
beanName = (this.importBeanNameGenerator instanceof ConfigurationBeanNameGenerator cbng ?
cbng.deriveBeanName(metadata, beanName) : defaultBeanName(beanName, methodName));
if (explicitNames.length > 0) {
// Register aliases even when overridden below.
for (int i = 1; i < explicitNames.length; i++) {
this.registry.registerAlias(beanName, explicitNames[i]);
}
}
ConfigurationClassBeanDefinition beanDef =
new ConfigurationClassBeanDefinition(configClass, metadata, localBeanName);
beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));
// Has this effectively been overridden before (for example, via XML)?
if (isOverriddenByExistingDefinition(beanMethod, beanName, beanDef)) {
if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) {
throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(),
beanName, "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName() +
"' clashes with bean name for containing configuration class; please make those names unique!");
}
return;
}
if (metadata.isStatic()) {
// static @Bean method
if (configClass.getMetadata() instanceof StandardAnnotationMetadata sam) {
beanDef.setBeanClass(sam.getIntrospectedClass());
}
else {
beanDef.setBeanClassName(configClass.getMetadata().getClassName());
}
beanDef.setUniqueFactoryMethodName(methodName);
}
else {
// instance @Bean method
beanDef.setFactoryBeanName(configClass.getBeanName());
beanDef.setUniqueFactoryMethodName(methodName);
}
if (metadata instanceof StandardMethodMetadata smm &&
configClass.getMetadata() instanceof StandardAnnotationMetadata sam) {
Method method = ClassUtils.getMostSpecificMethod(smm.getIntrospectedMethod(), sam.getIntrospectedClass());
if (method == smm.getIntrospectedMethod()) {
beanDef.setResolvedFactoryMethod(method);
}
}
beanDef.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);
boolean autowireCandidate = bean.getBoolean("autowireCandidate");
if (!autowireCandidate) {
beanDef.setAutowireCandidate(false);
}
boolean defaultCandidate = bean.getBoolean("defaultCandidate");
if (!defaultCandidate) {
beanDef.setDefaultCandidate(false);
}
Bean.Bootstrap instantiation = bean.getEnum("bootstrap");
if (instantiation == Bean.Bootstrap.BACKGROUND) {
beanDef.setBackgroundInit(true);
}
String initMethodName = bean.getString("initMethod");
if (StringUtils.hasText(initMethodName)) {
beanDef.setInitMethodName(initMethodName);
}
String destroyMethodName = bean.getString("destroyMethod");
beanDef.setDestroyMethodName(destroyMethodName);
// Consider scoping
ScopedProxyMode proxyMode = ScopedProxyMode.NO;
AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class);
if (attributes != null) {
beanDef.setScope(attributes.getString("value"));
proxyMode = attributes.getEnum("proxyMode");
if (proxyMode == ScopedProxyMode.DEFAULT) {
proxyMode = ScopedProxyMode.NO;
}
}
// Replace the original bean definition with the target one, if necessary
BeanDefinition beanDefToRegister = beanDef;
if (proxyMode != ScopedProxyMode.NO) {
BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(
new BeanDefinitionHolder(beanDef, beanName), this.registry,
proxyMode == ScopedProxyMode.TARGET_CLASS);
beanDefToRegister = new ConfigurationClassBeanDefinition(
(RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata, localBeanName);
}
if (logger.isTraceEnabled()) {
logger.trace("Registering bean definition for @Bean method %s.%s()"
.formatted(configClass.getMetadata().getClassName(), beanName));
}
this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}
private static String defaultBeanName(@Nullable String beanName, String methodName) {
return (beanName != null ? beanName : methodName);
}
@SuppressWarnings("NullAway") // Reflection
private boolean isOverriddenByExistingDefinition(
BeanMethod beanMethod, String beanName, ConfigurationClassBeanDefinition newBeanDef) {
if (!this.registry.containsBeanDefinition(beanName)) {
return false;
}
BeanDefinition existingBeanDef = this.registry.getBeanDefinition(beanName);
ConfigurationClass configClass = beanMethod.getConfigurationClass();
// If the bean method is an overloaded case on the same configuration class,
// preserve the existing bean definition and mark it as overloaded.
if (existingBeanDef instanceof ConfigurationClassBeanDefinition ccbd) {
if (!ccbd.getMetadata().getClassName().equals(configClass.getMetadata().getClassName())) {
return false;
}
if (ccbd.getFactoryMethodMetadata().getMethodName().equals(beanMethod.getMetadata().getMethodName())) {
ccbd.setNonUniqueFactoryMethodName(ccbd.getFactoryMethodMetadata().getMethodName());
return true;
}
Map<String, @Nullable Object> attributes =
configClass.getMetadata().getAnnotationAttributes(Configuration.class.getName());
if ((attributes != null && (Boolean) attributes.get("enforceUniqueMethods")) ||
!this.registry.isBeanDefinitionOverridable(beanName)) {
throw new BeanDefinitionOverrideException(beanName, newBeanDef, existingBeanDef,
"@Bean method override with same bean name but different method name: " + existingBeanDef);
}
return true;
}
// A bean definition resulting from a component scan can be silently overridden
// by an @Bean method - and as of 6.1, even when general overriding is disabled
// as long as the bean
|
itself
|
java
|
dropwizard__dropwizard
|
dropwizard-health/src/main/java/io/dropwizard/health/StateChangedCallback.java
|
{
"start": 59,
"end": 160
}
|
interface ____ {
void onStateChanged(String healthCheckName, boolean healthy);
}
|
StateChangedCallback
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/StructuredFunctionsITCase.java
|
{
"start": 4292,
"end": 10600
}
|
class ____ but different fields
.testSqlValidationError(
"Type1Constructor(f0, f1) = CAST((14, 'Bob') AS STRUCTURED<'"
+ Type1.class.getName()
+ "', a BOOLEAN, b BOOLEAN>)",
"Cannot apply '=' to arguments")
// Test nesting
.testSqlResult(
String.format(
"NestedConstructor(Type1Constructor(f0, f1), Type2Constructor(15, 'Alice')) = CAST("
+ "(CAST((14, 'Bob') AS %s), CAST((15, 'Alice') AS %s))"
+ " AS %s)",
Type1.TYPE_STRING,
Type2.TYPE_STRING,
NestedType.TYPE_STRING),
true,
DataTypes.BOOLEAN())
.testSqlResult(
String.format(
"CAST((42, ARRAY['1', '2', '3'], MAP['A', TIMESTAMP '2025-06-20 12:00:01', 'B', TIMESTAMP '2025-06-20 12:00:02']) AS %s)",
NonDefaultType.TYPE_STRING),
new NonDefaultType(
42,
List.of("1", "2", "3"),
Map.of(
"A",
Timestamp.valueOf("2025-06-20 12:00:01"),
"B",
Timestamp.valueOf("2025-06-20 12:00:02"))),
DataTypes.of(NonDefaultType.class).notNull()));
}
private static Stream<TestSetSpec> objectOfTestCases() {
final Type1 type1 = Type1.of(42, "Bob");
final Type2 type2 = Type2.of(15, "Alice");
final NestedType nestedType = NestedType.of(type1, type2);
return Stream.of(
TestSetSpec.forFunction(BuiltInFunctionDefinitions.OBJECT_OF)
.onFieldsWithData(42, "Bob")
.andDataTypes(DataTypes.INT(), DataTypes.STRING())
.withFunction(Type1.Type1Constructor.class)
.withFunction(Type2.Type2Constructor.class)
.withFunction(NestedType.NestedConstructor.class)
// Test with OBJECT_OF
.testResult(
objectOf(Type1.class, "a", 42, "b", "Bob"),
"OBJECT_OF('" + Type1.class.getName() + "', 'a', 42, 'b', 'Bob')",
type1,
DataTypes.STRUCTURED(
Type1.class.getName(),
DataTypes.FIELD("a", DataTypes.INT().notNull()),
DataTypes.FIELD("b", DataTypes.CHAR(3).notNull())))
// Test with nested structured types
.testResult(
objectOf(
NestedType.class,
"n1",
objectOf(Type1.class, "a", 42, "b", "Bob"),
"n2",
objectOf(Type2.class, "a", 15, "b", "Alice")),
"OBJECT_OF('"
+ NestedType.class.getName()
+ "', 'n1', OBJECT_OF('"
+ Type1.class.getName()
+ "', 'a', 42, 'b', 'Bob'), "
+ "'n2', OBJECT_OF('"
+ Type2.class.getName()
+ "', 'a', 15, 'b', 'Alice'))",
nestedType,
DataTypes.STRUCTURED(
NestedType.class.getName(),
DataTypes.FIELD(
"n1",
DataTypes.STRUCTURED(
Type1.class.getName(),
DataTypes.FIELD(
"a", DataTypes.INT().notNull()),
DataTypes.FIELD(
"b", DataTypes.CHAR(3).notNull()))),
DataTypes.FIELD(
"n2",
DataTypes.STRUCTURED(
Type2.class.getName(),
DataTypes.FIELD(
"a", DataTypes.INT().notNull()),
DataTypes.FIELD(
"b",
DataTypes.CHAR(5).notNull())))))
// Test equal with constructor
// TODO: Test disabled due to FLINK-38083
// .testSqlResult(
// "Type1Constructor(f0, f1) = OBJECT_OF('"
// + Type1.class.getName()
// + "', 'a', 42, 'b', 'Bob')",
// true,
// DataTypes.BOOLEAN())
// Test OBJECT_OF when
|
name
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/int2darray/Int2DArrayAssert_contains_at_Index_Test.java
|
{
"start": 1093,
"end": 1514
}
|
class ____ extends Int2DArrayAssertBaseTest {
private final Index index = someIndex();
@Override
protected Int2DArrayAssert invoke_api_method() {
return assertions.contains(new int[] { 8, 9 }, index);
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertContains(getInfo(assertions), getActual(assertions), new int[] { 8, 9 }, index);
}
}
|
Int2DArrayAssert_contains_at_Index_Test
|
java
|
apache__camel
|
components/camel-google/camel-google-sheets/src/main/java/org/apache/camel/component/google/sheets/GoogleSheetsConsumer.java
|
{
"start": 1345,
"end": 2291
}
|
class ____ extends AbstractApiConsumer<GoogleSheetsApiName, GoogleSheetsConfiguration> {
public GoogleSheetsConsumer(GoogleSheetsEndpoint endpoint, Processor processor) {
super(endpoint, processor);
}
@Override
protected Object doInvokeMethod(Map<String, Object> properties) throws RuntimeCamelException {
AbstractGoogleClientRequest<?> request = (AbstractGoogleClientRequest) super.doInvokeMethod(properties);
try {
BeanIntrospection beanIntrospection
= PluginHelper.getBeanIntrospection(getEndpoint().getCamelContext());
for (Entry<String, Object> p : properties.entrySet()) {
beanIntrospection.setProperty(getEndpoint().getCamelContext(), request, p.getKey(), p.getValue());
}
return request.execute();
} catch (Exception e) {
throw new RuntimeCamelException(e);
}
}
}
|
GoogleSheetsConsumer
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/bug/Bug_for_jiangwei1.java
|
{
"start": 215,
"end": 620
}
|
class ____ extends TestCase {
public void test_double() throws Exception {
JSONObject json = JSON.parseObject("{\"val\":12.3}");
Assert.assertTrue(12.3D == json.getDoubleValue("val"));
}
public void test_JSONArray_double() throws Exception {
JSONArray json = JSON.parseArray("[12.3]");
Assert.assertTrue(12.3D == json.getDoubleValue(0));
}
}
|
Bug_for_jiangwei1
|
java
|
netty__netty
|
testsuite-native-image/src/main/java/io/netty/testsuite/svm/HttpNativeServer.java
|
{
"start": 6777,
"end": 6857
}
|
enum ____ {
POOLED,
UNPOOLED,
ADAPTIVE
}
}
|
AllocatorType
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointFilteringTests.java
|
{
"start": 7099,
"end": 7319
}
|
class ____ {
private String name = "5150";
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
@ConfigurationProperties("only.bar")
public static
|
Foo
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/reflect/TypeParameterTest.java
|
{
"start": 1025,
"end": 1961
}
|
class ____ extends TestCase {
public <T> void testCaptureTypeParameter() throws Exception {
TypeVariable<?> variable = new TypeParameter<T>() {}.typeVariable;
TypeVariable<?> expected =
TypeParameterTest.class.getDeclaredMethod("testCaptureTypeParameter")
.getTypeParameters()[0];
assertEquals(expected, variable);
}
public void testConcreteTypeRejected() {
assertThrows(IllegalArgumentException.class, () -> new TypeParameter<String>() {});
}
public <A, B> void testEquals() throws Exception {
Method method = TypeParameterTest.class.getDeclaredMethod("testEquals");
new EqualsTester()
.addEqualityGroup(new TypeParameter<A>() {}, new TypeParameter<A>() {})
.addEqualityGroup(new TypeParameter<B>() {})
.testEquals();
}
public void testNullPointers() {
new NullPointerTester().testAllPublicStaticMethods(TypeParameter.class);
}
}
|
TypeParameterTest
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/time/JodaConstructorsTest.java
|
{
"start": 6643,
"end": 7410
}
|
class ____ {
// BUG: Diagnostic contains: I1 = org.joda.time.Instant.now();
private static final org.joda.time.Instant I1 = new org.joda.time.Instant();
// BUG: Diagnostic contains: I2 = org.joda.time.Instant.ofEpochMilli(42);
private static final org.joda.time.Instant I2 = new org.joda.time.Instant(42);
}
""")
.doTest();
}
@Test
public void dateTimeConstructors() {
helper
.addSourceLines(
"TestClass.java",
"""
import org.joda.time.Chronology;
import org.joda.time.chrono.GregorianChronology;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public
|
TestClass
|
java
|
alibaba__nacos
|
naming/src/main/java/com/alibaba/nacos/naming/constants/FieldsConstants.java
|
{
"start": 724,
"end": 2087
}
|
class ____ {
public static final String NAME = "name";
public static final String PROTECT_THRESHOLD = "protectThreshold";
public static final String GROUP_NAME = "groupName";
public static final String SELECTOR = "selector";
public static final String METADATA = "metadata";
public static final String SERVICE = "service";
public static final String CLUSTERS = "clusters";
public static final String SERVICE_LIST = "serviceList";
public static final String COUNT = "count";
public static final String NAME_SPACE_ID = "namespaceId";
public static final String NAME_SPACE = "namespace";
public static final String HEALTH_CHECKER = "healthChecker";
public static final String IP = "ip";
public static final String PORT = "port";
public static final String CLUSTER_NAME = "clusterName";
public static final String SERVICE_NAME = "serviceName";
public static final String EPHEMERAL = "ephemeral";
public static final String STATUSES = "statuses";
public static final String CLIENT_IP = "clientIP";
public static final String SERVICE_STATUS = "serverStatus";
public static final String ENCODING = "encoding";
public static final String NOFIX = "nofix";
}
|
FieldsConstants
|
java
|
elastic__elasticsearch
|
libs/entitlement/bridge/src/main/java/org/elasticsearch/entitlement/bridge/EntitlementChecker.java
|
{
"start": 25069,
"end": 56801
}
|
class ____ abstract
* (not instrumentable).
*/
void check$java_nio_channels_spi_AbstractSelectableChannel$register(
Class<?> callerClass,
SelectableChannel that,
Selector sel,
int ops,
Object att
);
void check$java_nio_channels_SelectableChannel$register(Class<?> callerClass, SelectableChannel that, Selector sel, int ops);
// bind
void check$java_nio_channels_AsynchronousServerSocketChannel$bind(
Class<?> callerClass,
AsynchronousServerSocketChannel that,
SocketAddress local
);
void check$sun_nio_ch_AsynchronousServerSocketChannelImpl$bind(
Class<?> callerClass,
AsynchronousServerSocketChannel that,
SocketAddress local,
int backlog
);
void check$sun_nio_ch_AsynchronousSocketChannelImpl$bind(Class<?> callerClass, AsynchronousSocketChannel that, SocketAddress local);
void check$sun_nio_ch_DatagramChannelImpl$bind(Class<?> callerClass, DatagramChannel that, SocketAddress local);
void check$java_nio_channels_ServerSocketChannel$bind(Class<?> callerClass, ServerSocketChannel that, SocketAddress local);
void check$sun_nio_ch_ServerSocketChannelImpl$bind(Class<?> callerClass, ServerSocketChannel that, SocketAddress local, int backlog);
void check$java_nio_channels_SocketChannel$$open(Class<?> callerClass);
void check$java_nio_channels_SocketChannel$$open(Class<?> callerClass, java.net.ProtocolFamily family);
void check$java_nio_channels_SocketChannel$$open(Class<?> callerClass, SocketAddress remote);
void check$sun_nio_ch_SocketChannelImpl$bind(Class<?> callerClass, SocketChannel that, SocketAddress local);
// connect
void check$sun_nio_ch_SocketChannelImpl$connect(Class<?> callerClass, SocketChannel that, SocketAddress remote);
void check$sun_nio_ch_AsynchronousSocketChannelImpl$connect(Class<?> callerClass, AsynchronousSocketChannel that, SocketAddress remote);
void check$sun_nio_ch_AsynchronousSocketChannelImpl$connect(
Class<?> callerClass,
AsynchronousSocketChannel that,
SocketAddress remote,
Object attachment,
CompletionHandler<Void, Object> handler
);
void check$sun_nio_ch_DatagramChannelImpl$connect(Class<?> callerClass, DatagramChannel that, SocketAddress remote);
// accept
void check$sun_nio_ch_ServerSocketChannelImpl$accept(Class<?> callerClass, ServerSocketChannel that);
void check$sun_nio_ch_AsynchronousServerSocketChannelImpl$accept(Class<?> callerClass, AsynchronousServerSocketChannel that);
void check$sun_nio_ch_AsynchronousServerSocketChannelImpl$accept(
Class<?> callerClass,
AsynchronousServerSocketChannel that,
Object attachment,
CompletionHandler<AsynchronousSocketChannel, Object> handler
);
// send/receive
void check$sun_nio_ch_DatagramChannelImpl$send(Class<?> callerClass, DatagramChannel that, ByteBuffer src, SocketAddress target);
void check$sun_nio_ch_DatagramChannelImpl$receive(Class<?> callerClass, DatagramChannel that, ByteBuffer dst);
// providers (SPI)
// protected constructors
void check$java_nio_channels_spi_SelectorProvider$(Class<?> callerClass);
void check$java_nio_channels_spi_AsynchronousChannelProvider$(Class<?> callerClass);
// provider methods (dynamic)
void checkSelectorProviderInheritedChannel(Class<?> callerClass, SelectorProvider that);
void checkSelectorProviderOpenDatagramChannel(Class<?> callerClass, SelectorProvider that);
void checkSelectorProviderOpenDatagramChannel(Class<?> callerClass, SelectorProvider that, java.net.ProtocolFamily family);
void checkSelectorProviderOpenServerSocketChannel(Class<?> callerClass, SelectorProvider that);
void checkSelectorProviderOpenServerSocketChannel(Class<?> callerClass, SelectorProvider that, java.net.ProtocolFamily family);
void checkSelectorProviderOpenSocketChannel(Class<?> callerClass, SelectorProvider that);
void checkSelectorProviderOpenSocketChannel(Class<?> callerClass, SelectorProvider that, java.net.ProtocolFamily family);
/// /////////////////
//
// Load native libraries
//
// Using the list of restricted methods from https://download.java.net/java/early_access/jdk24/docs/api/restricted-list.html
void check$java_lang_Runtime$load(Class<?> callerClass, Runtime that, String filename);
void check$java_lang_Runtime$loadLibrary(Class<?> callerClass, Runtime that, String libname);
void check$java_lang_System$$load(Class<?> callerClass, String filename);
void check$java_lang_System$$loadLibrary(Class<?> callerClass, String libname);
// Sealed implementation of java.lang.foreign.AddressLayout
void check$jdk_internal_foreign_layout_ValueLayouts$OfAddressImpl$withTargetLayout(
Class<?> callerClass,
AddressLayout that,
MemoryLayout memoryLayout
);
// Sealed implementation of java.lang.foreign.Linker
void check$jdk_internal_foreign_abi_AbstractLinker$downcallHandle(
Class<?> callerClass,
Linker that,
FunctionDescriptor function,
Linker.Option... options
);
void check$jdk_internal_foreign_abi_AbstractLinker$downcallHandle(
Class<?> callerClass,
Linker that,
MemorySegment address,
FunctionDescriptor function,
Linker.Option... options
);
void check$jdk_internal_foreign_abi_AbstractLinker$upcallStub(
Class<?> callerClass,
Linker that,
MethodHandle target,
FunctionDescriptor function,
Arena arena,
Linker.Option... options
);
// Sealed implementation for java.lang.foreign.MemorySegment.reinterpret(long)
void check$jdk_internal_foreign_AbstractMemorySegmentImpl$reinterpret(Class<?> callerClass, MemorySegment that, long newSize);
void check$jdk_internal_foreign_AbstractMemorySegmentImpl$reinterpret(
Class<?> callerClass,
MemorySegment that,
long newSize,
Arena arena,
Consumer<MemorySegment> cleanup
);
void check$jdk_internal_foreign_AbstractMemorySegmentImpl$reinterpret(
Class<?> callerClass,
MemorySegment that,
Arena arena,
Consumer<MemorySegment> cleanup
);
void check$java_lang_foreign_SymbolLookup$$libraryLookup(Class<?> callerClass, String name, Arena arena);
void check$java_lang_foreign_SymbolLookup$$libraryLookup(Class<?> callerClass, Path path, Arena arena);
void check$java_lang_ModuleLayer$Controller$enableNativeAccess(Class<?> callerClass, ModuleLayer.Controller that, Module target);
/// /////////////////
//
// File access
//
// old io (ie File)
void check$java_io_File$canExecute(Class<?> callerClass, File file);
void check$java_io_File$canRead(Class<?> callerClass, File file);
void check$java_io_File$canWrite(Class<?> callerClass, File file);
void check$java_io_File$createNewFile(Class<?> callerClass, File file);
void check$java_io_File$$createTempFile(Class<?> callerClass, String prefix, String suffix);
void check$java_io_File$$createTempFile(Class<?> callerClass, String prefix, String suffix, File directory);
void check$java_io_File$delete(Class<?> callerClass, File file);
void check$java_io_File$deleteOnExit(Class<?> callerClass, File file);
void check$java_io_File$exists(Class<?> callerClass, File file);
void check$java_io_File$isDirectory(Class<?> callerClass, File file);
void check$java_io_File$isFile(Class<?> callerClass, File file);
void check$java_io_File$isHidden(Class<?> callerClass, File file);
void check$java_io_File$lastModified(Class<?> callerClass, File file);
void check$java_io_File$length(Class<?> callerClass, File file);
void check$java_io_File$list(Class<?> callerClass, File file);
void check$java_io_File$list(Class<?> callerClass, File file, FilenameFilter filter);
void check$java_io_File$listFiles(Class<?> callerClass, File file);
void check$java_io_File$listFiles(Class<?> callerClass, File file, FileFilter filter);
void check$java_io_File$listFiles(Class<?> callerClass, File file, FilenameFilter filter);
void check$java_io_File$mkdir(Class<?> callerClass, File file);
void check$java_io_File$mkdirs(Class<?> callerClass, File file);
void check$java_io_File$renameTo(Class<?> callerClass, File file, File dest);
void check$java_io_File$setExecutable(Class<?> callerClass, File file, boolean executable);
void check$java_io_File$setExecutable(Class<?> callerClass, File file, boolean executable, boolean ownerOnly);
void check$java_io_File$setLastModified(Class<?> callerClass, File file, long time);
void check$java_io_File$setReadable(Class<?> callerClass, File file, boolean readable);
void check$java_io_File$setReadable(Class<?> callerClass, File file, boolean readable, boolean ownerOnly);
void check$java_io_File$setReadOnly(Class<?> callerClass, File file);
void check$java_io_File$setWritable(Class<?> callerClass, File file, boolean writable);
void check$java_io_File$setWritable(Class<?> callerClass, File file, boolean writable, boolean ownerOnly);
void check$java_io_FileInputStream$(Class<?> callerClass, File file);
void check$java_io_FileInputStream$(Class<?> callerClass, FileDescriptor fd);
void check$java_io_FileInputStream$(Class<?> callerClass, String name);
void check$java_io_FileOutputStream$(Class<?> callerClass, File file);
void check$java_io_FileOutputStream$(Class<?> callerClass, File file, boolean append);
void check$java_io_FileOutputStream$(Class<?> callerClass, FileDescriptor fd);
void check$java_io_FileOutputStream$(Class<?> callerClass, String name);
void check$java_io_FileOutputStream$(Class<?> callerClass, String name, boolean append);
void check$java_io_FileReader$(Class<?> callerClass, File file);
void check$java_io_FileReader$(Class<?> callerClass, File file, Charset charset);
void check$java_io_FileReader$(Class<?> callerClass, FileDescriptor fd);
void check$java_io_FileReader$(Class<?> callerClass, String name);
void check$java_io_FileReader$(Class<?> callerClass, String name, Charset charset);
void check$java_io_FileWriter$(Class<?> callerClass, File file);
void check$java_io_FileWriter$(Class<?> callerClass, File file, boolean append);
void check$java_io_FileWriter$(Class<?> callerClass, File file, Charset charset);
void check$java_io_FileWriter$(Class<?> callerClass, File file, Charset charset, boolean append);
void check$java_io_FileWriter$(Class<?> callerClass, FileDescriptor fd);
void check$java_io_FileWriter$(Class<?> callerClass, String name);
void check$java_io_FileWriter$(Class<?> callerClass, String name, boolean append);
void check$java_io_FileWriter$(Class<?> callerClass, String name, Charset charset);
void check$java_io_FileWriter$(Class<?> callerClass, String name, Charset charset, boolean append);
void check$java_io_RandomAccessFile$(Class<?> callerClass, String name, String mode);
void check$java_io_RandomAccessFile$(Class<?> callerClass, File file, String mode);
void check$java_security_KeyStore$$getInstance(Class<?> callerClass, File file, char[] password);
void check$java_security_KeyStore$$getInstance(Class<?> callerClass, File file, KeyStore.LoadStoreParameter param);
void check$java_security_KeyStore$Builder$$newInstance(Class<?> callerClass, File file, KeyStore.ProtectionParameter protection);
void check$java_security_KeyStore$Builder$$newInstance(
Class<?> callerClass,
String type,
Provider provider,
File file,
KeyStore.ProtectionParameter protection
);
void check$java_util_Scanner$(Class<?> callerClass, File source);
void check$java_util_Scanner$(Class<?> callerClass, File source, String charsetName);
void check$java_util_Scanner$(Class<?> callerClass, File source, Charset charset);
void check$java_util_jar_JarFile$(Class<?> callerClass, String name);
void check$java_util_jar_JarFile$(Class<?> callerClass, String name, boolean verify);
void check$java_util_jar_JarFile$(Class<?> callerClass, File file);
void check$java_util_jar_JarFile$(Class<?> callerClass, File file, boolean verify);
void check$java_util_jar_JarFile$(Class<?> callerClass, File file, boolean verify, int mode);
void check$java_util_jar_JarFile$(Class<?> callerClass, File file, boolean verify, int mode, Runtime.Version version);
void check$java_util_zip_ZipFile$(Class<?> callerClass, String name);
void check$java_util_zip_ZipFile$(Class<?> callerClass, String name, Charset charset);
void check$java_util_zip_ZipFile$(Class<?> callerClass, File file);
void check$java_util_zip_ZipFile$(Class<?> callerClass, File file, int mode);
void check$java_util_zip_ZipFile$(Class<?> callerClass, File file, Charset charset);
void check$java_util_zip_ZipFile$(Class<?> callerClass, File file, int mode, Charset charset);
// nio
// channels
void check$java_nio_channels_FileChannel$(Class<?> callerClass);
void check$java_nio_channels_FileChannel$$open(
Class<?> callerClass,
Path path,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs
);
void check$java_nio_channels_FileChannel$$open(Class<?> callerClass, Path path, OpenOption... options);
void check$java_nio_channels_AsynchronousFileChannel$(Class<?> callerClass);
void check$java_nio_channels_AsynchronousFileChannel$$open(
Class<?> callerClass,
Path path,
Set<? extends OpenOption> options,
ExecutorService executor,
FileAttribute<?>... attrs
);
void check$java_nio_channels_AsynchronousFileChannel$$open(Class<?> callerClass, Path path, OpenOption... options);
void check$jdk_nio_Channels$$readWriteSelectableChannel(
Class<?> callerClass,
FileDescriptor fd,
Channels.SelectableChannelCloser closer
);
// files
void check$java_nio_file_Files$$getOwner(Class<?> callerClass, Path path, LinkOption... options);
void check$java_nio_file_Files$$probeContentType(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$setOwner(Class<?> callerClass, Path path, UserPrincipal principal);
void check$java_nio_file_Files$$newInputStream(Class<?> callerClass, Path path, OpenOption... options);
void check$java_nio_file_Files$$newOutputStream(Class<?> callerClass, Path path, OpenOption... options);
void check$java_nio_file_Files$$newByteChannel(
Class<?> callerClass,
Path path,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs
);
void check$java_nio_file_Files$$newByteChannel(Class<?> callerClass, Path path, OpenOption... options);
void check$java_nio_file_Files$$newDirectoryStream(Class<?> callerClass, Path dir);
void check$java_nio_file_Files$$newDirectoryStream(Class<?> callerClass, Path dir, String glob);
void check$java_nio_file_Files$$newDirectoryStream(Class<?> callerClass, Path dir, DirectoryStream.Filter<? super Path> filter);
void check$java_nio_file_Files$$createFile(Class<?> callerClass, Path path, FileAttribute<?>... attrs);
void check$java_nio_file_Files$$createDirectory(Class<?> callerClass, Path dir, FileAttribute<?>... attrs);
void check$java_nio_file_Files$$createDirectories(Class<?> callerClass, Path dir, FileAttribute<?>... attrs);
void check$java_nio_file_Files$$createTempFile(Class<?> callerClass, Path dir, String prefix, String suffix, FileAttribute<?>... attrs);
void check$java_nio_file_Files$$createTempFile(Class<?> callerClass, String prefix, String suffix, FileAttribute<?>... attrs);
void check$java_nio_file_Files$$createTempDirectory(Class<?> callerClass, Path dir, String prefix, FileAttribute<?>... attrs);
void check$java_nio_file_Files$$createTempDirectory(Class<?> callerClass, String prefix, FileAttribute<?>... attrs);
void check$java_nio_file_Files$$createSymbolicLink(Class<?> callerClass, Path link, Path target, FileAttribute<?>... attrs);
void check$java_nio_file_Files$$createLink(Class<?> callerClass, Path link, Path existing);
void check$java_nio_file_Files$$delete(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$deleteIfExists(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$copy(Class<?> callerClass, Path source, Path target, CopyOption... options);
void check$java_nio_file_Files$$move(Class<?> callerClass, Path source, Path target, CopyOption... options);
void check$java_nio_file_Files$$readSymbolicLink(Class<?> callerClass, Path link);
void check$java_nio_file_Files$$getFileStore(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$isSameFile(Class<?> callerClass, Path path, Path path2);
void check$java_nio_file_Files$$mismatch(Class<?> callerClass, Path path, Path path2);
void check$java_nio_file_Files$$isHidden(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$getFileAttributeView(
Class<?> callerClass,
Path path,
Class<? extends FileAttributeView> type,
LinkOption... options
);
void check$java_nio_file_Files$$readAttributes(
Class<?> callerClass,
Path path,
Class<? extends BasicFileAttributes> type,
LinkOption... options
);
void check$java_nio_file_Files$$setAttribute(Class<?> callerClass, Path path, String attribute, Object value, LinkOption... options);
void check$java_nio_file_Files$$getAttribute(Class<?> callerClass, Path path, String attribute, LinkOption... options);
void check$java_nio_file_Files$$readAttributes(Class<?> callerClass, Path path, String attributes, LinkOption... options);
void check$java_nio_file_Files$$getPosixFilePermissions(Class<?> callerClass, Path path, LinkOption... options);
void check$java_nio_file_Files$$setPosixFilePermissions(Class<?> callerClass, Path path, Set<PosixFilePermission> perms);
void check$java_nio_file_Files$$isSymbolicLink(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$isDirectory(Class<?> callerClass, Path path, LinkOption... options);
void check$java_nio_file_Files$$isRegularFile(Class<?> callerClass, Path path, LinkOption... options);
void check$java_nio_file_Files$$getLastModifiedTime(Class<?> callerClass, Path path, LinkOption... options);
void check$java_nio_file_Files$$setLastModifiedTime(Class<?> callerClass, Path path, FileTime time);
void check$java_nio_file_Files$$size(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$exists(Class<?> callerClass, Path path, LinkOption... options);
void check$java_nio_file_Files$$notExists(Class<?> callerClass, Path path, LinkOption... options);
void check$java_nio_file_Files$$isReadable(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$isWritable(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$isExecutable(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$walkFileTree(
Class<?> callerClass,
Path start,
Set<FileVisitOption> options,
int maxDepth,
FileVisitor<? super Path> visitor
);
void check$java_nio_file_Files$$walkFileTree(Class<?> callerClass, Path start, FileVisitor<? super Path> visitor);
void check$java_nio_file_Files$$newBufferedReader(Class<?> callerClass, Path path, Charset cs);
void check$java_nio_file_Files$$newBufferedReader(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$newBufferedWriter(Class<?> callerClass, Path path, Charset cs, OpenOption... options);
void check$java_nio_file_Files$$newBufferedWriter(Class<?> callerClass, Path path, OpenOption... options);
void check$java_nio_file_Files$$copy(Class<?> callerClass, InputStream in, Path target, CopyOption... options);
void check$java_nio_file_Files$$copy(Class<?> callerClass, Path source, OutputStream out);
void check$java_nio_file_Files$$readAllBytes(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$readString(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$readString(Class<?> callerClass, Path path, Charset cs);
void check$java_nio_file_Files$$readAllLines(Class<?> callerClass, Path path, Charset cs);
void check$java_nio_file_Files$$readAllLines(Class<?> callerClass, Path path);
void check$java_nio_file_Files$$write(Class<?> callerClass, Path path, byte[] bytes, OpenOption... options);
void check$java_nio_file_Files$$write(
Class<?> callerClass,
Path path,
Iterable<? extends CharSequence> lines,
Charset cs,
OpenOption... options
);
void check$java_nio_file_Files$$write(Class<?> callerClass, Path path, Iterable<? extends CharSequence> lines, OpenOption... options);
void check$java_nio_file_Files$$writeString(Class<?> callerClass, Path path, CharSequence csq, OpenOption... options);
void check$java_nio_file_Files$$writeString(Class<?> callerClass, Path path, CharSequence csq, Charset cs, OpenOption... options);
void check$java_nio_file_Files$$list(Class<?> callerClass, Path dir);
void check$java_nio_file_Files$$walk(Class<?> callerClass, Path start, int maxDepth, FileVisitOption... options);
void check$java_nio_file_Files$$walk(Class<?> callerClass, Path start, FileVisitOption... options);
void check$java_nio_file_Files$$find(
Class<?> callerClass,
Path start,
int maxDepth,
BiPredicate<Path, BasicFileAttributes> matcher,
FileVisitOption... options
);
void check$java_nio_file_Files$$lines(Class<?> callerClass, Path path, Charset cs);
void check$java_nio_file_Files$$lines(Class<?> callerClass, Path path);
void check$java_nio_file_spi_FileSystemProvider$(Class<?> callerClass);
void check$java_util_logging_FileHandler$(Class<?> callerClass);
void check$java_util_logging_FileHandler$(Class<?> callerClass, String pattern);
void check$java_util_logging_FileHandler$(Class<?> callerClass, String pattern, boolean append);
void check$java_util_logging_FileHandler$(Class<?> callerClass, String pattern, int limit, int count);
void check$java_util_logging_FileHandler$(Class<?> callerClass, String pattern, int limit, int count, boolean append);
void check$java_util_logging_FileHandler$(Class<?> callerClass, String pattern, long limit, int count, boolean append);
void check$java_util_logging_FileHandler$close(Class<?> callerClass, FileHandler that);
void check$java_net_http_HttpRequest$BodyPublishers$$ofFile(Class<?> callerClass, Path path);
void check$java_net_http_HttpResponse$BodyHandlers$$ofFile(Class<?> callerClass, Path path);
void check$java_net_http_HttpResponse$BodyHandlers$$ofFile(Class<?> callerClass, Path path, OpenOption... options);
void check$java_net_http_HttpResponse$BodyHandlers$$ofFileDownload(Class<?> callerClass, Path directory, OpenOption... openOptions);
void check$java_net_http_HttpResponse$BodySubscribers$$ofFile(Class<?> callerClass, Path directory);
void check$java_net_http_HttpResponse$BodySubscribers$$ofFile(Class<?> callerClass, Path directory, OpenOption... openOptions);
void checkNewFileSystem(Class<?> callerClass, FileSystemProvider that, URI uri, Map<String, ?> env);
void checkNewFileSystem(Class<?> callerClass, FileSystemProvider that, Path path, Map<String, ?> env);
void checkNewInputStream(Class<?> callerClass, FileSystemProvider that, Path path, OpenOption... options);
void checkNewOutputStream(Class<?> callerClass, FileSystemProvider that, Path path, OpenOption... options);
void checkNewFileChannel(
Class<?> callerClass,
FileSystemProvider that,
Path path,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs
);
void checkNewAsynchronousFileChannel(
Class<?> callerClass,
FileSystemProvider that,
Path path,
Set<? extends OpenOption> options,
ExecutorService executor,
FileAttribute<?>... attrs
);
void checkNewByteChannel(
Class<?> callerClass,
FileSystemProvider that,
Path path,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs
);
void checkNewDirectoryStream(Class<?> callerClass, FileSystemProvider that, Path dir, DirectoryStream.Filter<? super Path> filter);
void checkCreateDirectory(Class<?> callerClass, FileSystemProvider that, Path dir, FileAttribute<?>... attrs);
void checkCreateSymbolicLink(Class<?> callerClass, FileSystemProvider that, Path link, Path target, FileAttribute<?>... attrs);
void checkCreateLink(Class<?> callerClass, FileSystemProvider that, Path link, Path existing);
void checkDelete(Class<?> callerClass, FileSystemProvider that, Path path);
void checkDeleteIfExists(Class<?> callerClass, FileSystemProvider that, Path path);
void checkReadSymbolicLink(Class<?> callerClass, FileSystemProvider that, Path link);
void checkCopy(Class<?> callerClass, FileSystemProvider that, Path source, Path target, CopyOption... options);
void checkMove(Class<?> callerClass, FileSystemProvider that, Path source, Path target, CopyOption... options);
void checkIsSameFile(Class<?> callerClass, FileSystemProvider that, Path path, Path path2);
void checkIsHidden(Class<?> callerClass, FileSystemProvider that, Path path);
void checkGetFileStore(Class<?> callerClass, FileSystemProvider that, Path path);
void checkCheckAccess(Class<?> callerClass, FileSystemProvider that, Path path, AccessMode... modes);
void checkGetFileAttributeView(Class<?> callerClass, FileSystemProvider that, Path path, Class<?> type, LinkOption... options);
void checkReadAttributes(Class<?> callerClass, FileSystemProvider that, Path path, Class<?> type, LinkOption... options);
void checkReadAttributes(Class<?> callerClass, FileSystemProvider that, Path path, String attributes, LinkOption... options);
void checkReadAttributesIfExists(Class<?> callerClass, FileSystemProvider that, Path path, Class<?> type, LinkOption... options);
void checkSetAttribute(Class<?> callerClass, FileSystemProvider that, Path path, String attribute, Object value, LinkOption... options);
void checkExists(Class<?> callerClass, FileSystemProvider that, Path path, LinkOption... options);
// file store
void checkGetFileStoreAttributeView(Class<?> callerClass, FileStore that, Class<?> type);
void checkGetAttribute(Class<?> callerClass, FileStore that, String attribute);
void checkGetBlockSize(Class<?> callerClass, FileStore that);
void checkGetTotalSpace(Class<?> callerClass, FileStore that);
void checkGetUnallocatedSpace(Class<?> callerClass, FileStore that);
void checkGetUsableSpace(Class<?> callerClass, FileStore that);
void checkIsReadOnly(Class<?> callerClass, FileStore that);
void checkName(Class<?> callerClass, FileStore that);
void checkType(Class<?> callerClass, FileStore that);
// path
void checkPathToRealPath(Class<?> callerClass, Path that, LinkOption... options) throws NoSuchFileException;
void checkPathRegister(Class<?> callerClass, Path that, WatchService watcher, WatchEvent.Kind<?>... events);
void checkPathRegister(
Class<?> callerClass,
Path that,
WatchService watcher,
WatchEvent.Kind<?>[] events,
WatchEvent.Modifier... modifiers
);
// URLConnection
void check$sun_net_www_protocol_file_FileURLConnection$connect(Class<?> callerClass, java.net.URLConnection that);
void check$sun_net_www_protocol_file_FileURLConnection$getHeaderFields(Class<?> callerClass, java.net.URLConnection that);
void check$sun_net_www_protocol_file_FileURLConnection$getHeaderField(Class<?> callerClass, java.net.URLConnection that, String name);
void check$sun_net_www_protocol_file_FileURLConnection$getHeaderField(Class<?> callerClass, java.net.URLConnection that, int n);
void check$sun_net_www_protocol_file_FileURLConnection$getContentLength(Class<?> callerClass, java.net.URLConnection that);
void check$sun_net_www_protocol_file_FileURLConnection$getContentLengthLong(Class<?> callerClass, java.net.URLConnection that);
void check$sun_net_www_protocol_file_FileURLConnection$getHeaderFieldKey(Class<?> callerClass, java.net.URLConnection that, int n);
void check$sun_net_www_protocol_file_FileURLConnection$getLastModified(Class<?> callerClass, java.net.URLConnection that);
void check$sun_net_www_protocol_file_FileURLConnection$getInputStream(Class<?> callerClass, java.net.URLConnection that);
void check$java_net_JarURLConnection$getManifest(Class<?> callerClass, java.net.JarURLConnection that);
void check$java_net_JarURLConnection$getJarEntry(Class<?> callerClass, java.net.JarURLConnection that);
void check$java_net_JarURLConnection$getAttributes(Class<?> callerClass, java.net.JarURLConnection that);
void check$java_net_JarURLConnection$getMainAttributes(Class<?> callerClass, java.net.JarURLConnection that);
void check$java_net_JarURLConnection$getCertificates(Class<?> callerClass, java.net.JarURLConnection that);
void check$sun_net_www_protocol_jar_JarURLConnection$getJarFile(Class<?> callerClass, java.net.JarURLConnection that);
void check$sun_net_www_protocol_jar_JarURLConnection$getJarEntry(Class<?> callerClass, java.net.JarURLConnection that);
void check$sun_net_www_protocol_jar_JarURLConnection$connect(Class<?> callerClass, java.net.JarURLConnection that);
void check$sun_net_www_protocol_jar_JarURLConnection$getInputStream(Class<?> callerClass, java.net.JarURLConnection that);
void check$sun_net_www_protocol_jar_JarURLConnection$getContentLength(Class<?> callerClass, java.net.JarURLConnection that);
void check$sun_net_www_protocol_jar_JarURLConnection$getContentLengthLong(Class<?> callerClass, java.net.JarURLConnection that);
void check$sun_net_www_protocol_jar_JarURLConnection$getContent(Class<?> callerClass, java.net.JarURLConnection that);
void check$sun_net_www_protocol_jar_JarURLConnection$getContentType(Class<?> callerClass, java.net.JarURLConnection that);
void check$sun_net_www_protocol_jar_JarURLConnection$getHeaderField(Class<?> callerClass, java.net.JarURLConnection that, String name);
////////////////////
//
// Thread management
//
void check$java_lang_Thread$start(Class<?> callerClass, Thread thread);
void check$java_lang_Thread$setDaemon(Class<?> callerClass, Thread thread, boolean on);
void check$java_lang_ThreadGroup$setDaemon(Class<?> callerClass, ThreadGroup threadGroup, boolean daemon);
void check$java_util_concurrent_ForkJoinPool$setParallelism(Class<?> callerClass, ForkJoinPool forkJoinPool, int size);
void check$java_lang_Thread$setName(Class<?> callerClass, Thread thread, String name);
void check$java_lang_Thread$setPriority(Class<?> callerClass, Thread thread, int newPriority);
void check$java_lang_Thread$setUncaughtExceptionHandler(Class<?> callerClass, Thread thread, Thread.UncaughtExceptionHandler ueh);
void check$java_lang_ThreadGroup$setMaxPriority(Class<?> callerClass, ThreadGroup threadGroup, int pri);
}
|
is
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java
|
{
"start": 3773,
"end": 4300
}
|
class ____ {
private final CountDownLatch latch = new CountDownLatch(1);
private volatile @Nullable ClassLoader threadContextClassLoader;
@Bean
ShutdownEndpoint endpoint() {
return new ShutdownEndpoint();
}
@Bean
ApplicationListener<ContextClosedEvent> listener() {
return (event) -> {
EndpointConfig.this.threadContextClassLoader = Thread.currentThread().getContextClassLoader();
EndpointConfig.this.latch.countDown();
};
}
}
@Configuration(proxyBeanMethods = false)
static
|
EndpointConfig
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CountEntityWithCompositeIdTest.java
|
{
"start": 666,
"end": 1516
}
|
class ____ {
@Test
public void shouldCount(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<EntityWithCompositeId> r = cq.from(EntityWithCompositeId.class);
cq.multiselect(cb.count(r));
assertThat(entityManager.createQuery(cq).getSingleResult().intValue(), is(0));
}
);
scope.inTransaction(
entityManager -> {
HibernateCriteriaBuilder cb = (HibernateCriteriaBuilder) entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
cq.from(EntityWithCompositeId.class);
cq.select(cb.count());
assertThat(entityManager.createQuery(cq).getSingleResult().intValue(), is(0));
}
);
}
}
|
CountEntityWithCompositeIdTest
|
java
|
apache__flink
|
flink-table/flink-sql-client/src/test/java/org/apache/flink/table/client/cli/parser/SqlClientHighlighterTest.java
|
{
"start": 18626,
"end": 19653
}
|
class ____ {
private final String sql;
private final Function<SyntaxHighlightStyle.BuiltInStyle, AttributedStringTestSpecBuilder>
function;
private SqlClientHighlighterTestSpec(
String sql,
Function<SyntaxHighlightStyle.BuiltInStyle, AttributedStringTestSpecBuilder>
function) {
this.sql = sql;
this.function = function;
}
public static SqlClientHighlighterTestSpec forSql(
String sql,
Function<SyntaxHighlightStyle.BuiltInStyle, AttributedStringTestSpecBuilder>
expectedBuilder) {
return new SqlClientHighlighterTestSpec(sql, expectedBuilder);
}
String getExpected(SyntaxHighlightStyle.BuiltInStyle style) {
return function.apply(style).asb.toAnsi();
}
@Override
public String toString() {
return sql;
}
}
static
|
SqlClientHighlighterTestSpec
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.