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/components/joins/ComponentJoinTest.java | {
"start": 933,
"end": 3026
} | class ____ {
public static final String THEVALUE = "thevalue";
@BeforeEach
public void before(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
ManyToOneType manyToOneType = new ManyToOneType( THEVALUE );
EmbeddedType embeddedType = new EmbeddedType( manyToOneType );
Entity entity = new Entity( embeddedType );
entityManager.persist( entity );
}
);
}
@AfterEach
public void after(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory().getSchemaManager().truncate();
}
private void doTest(EntityManagerFactoryScope scope, JoinBuilder joinBuilder) {
scope.inTransaction(
entityManager -> {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
Root<Entity> root = criteriaQuery.from( Entity.class );
Join<Entity, EmbeddedType> join = root.join( "embeddedType", JoinType.LEFT );
// left join to the manyToOne on the embeddable with a string property
Path<String> path = joinBuilder.buildJoinToManyToOneType( join ).get( "value" );
// select the path in the tuple
criteriaQuery.select( builder.tuple( path ) );
List<Tuple> results = entityManager.createQuery( criteriaQuery ).getResultList();
Tuple result = results.iterator().next();
assertEquals( THEVALUE, result.get( 0 ) );
}
);
}
@Test
public void getResultWithStringPropertyDerivedPath(EntityManagerFactoryScope scope) {
doTest( scope,
source -> source.join( "manyToOneType", JoinType.LEFT )
);
}
@Test
@SuppressWarnings("unchecked")
public void getResultWithMetamodelDerivedPath(EntityManagerFactoryScope scope) {
doTest( scope,
source -> {
final SingularAttribute<EmbeddedType, ManyToOneType> attr =
(SingularAttribute<EmbeddedType, ManyToOneType>) scope.getEntityManagerFactory().getMetamodel()
.managedType( EmbeddedType.class )
.getDeclaredSingularAttribute( "manyToOneType" );
return source.join( attr, JoinType.LEFT );
}
);
}
| ComponentJoinTest |
java | spring-projects__spring-boot | module/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/FlywayMigrationInitializerDatabaseInitializerDetector.java | {
"start": 1035,
"end": 1349
} | class ____ extends AbstractBeansOfTypeDatabaseInitializerDetector {
@Override
protected Set<Class<?>> getDatabaseInitializerBeanTypes() {
return Collections.singleton(FlywayMigrationInitializer.class);
}
@Override
public int getOrder() {
return 1;
}
}
| FlywayMigrationInitializerDatabaseInitializerDetector |
java | apache__camel | test-infra/camel-test-infra-azure-common/src/main/java/org/apache/camel/test/infra/azure/common/services/AzuriteContainer.java | {
"start": 1056,
"end": 2238
} | class ____ extends GenericContainer<AzuriteContainer> {
public static final String DEFAULT_ACCOUNT_NAME = "devstoreaccount1";
public static final String DEFAULT_ACCOUNT_KEY
= "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==";
public AzuriteContainer(String containerName, boolean fixedPort) {
super(containerName);
if (fixedPort) {
addFixedExposedPort(AzureServices.BLOB_SERVICE, AzureServices.BLOB_SERVICE);
addFixedExposedPort(AzureServices.QUEUE_SERVICE, AzureServices.QUEUE_SERVICE);
} else {
withExposedPorts(AzureServices.BLOB_SERVICE, AzureServices.QUEUE_SERVICE);
}
waitingFor(Wait.forListeningPort());
}
public AzureCredentialsHolder azureCredentials() {
// Default credentials for Azurite
return new AzureCredentialsHolder() {
@Override
public String accountName() {
return DEFAULT_ACCOUNT_NAME;
}
@Override
public String accountKey() {
return DEFAULT_ACCOUNT_KEY;
}
};
}
}
| AzuriteContainer |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/CBORDataFormat.java | {
"start": 8253,
"end": 8779
} | enum ____
* <tt>com.fasterxml.jackson.databind.SerializationFeature</tt>,
* <tt>com.fasterxml.jackson.databind.DeserializationFeature</tt>, or
* <tt>com.fasterxml.jackson.databind.MapperFeature</tt>
* <p/>
* Multiple features can be separated by comma
*/
public void setDisableFeatures(String disableFeatures) {
this.disableFeatures = disableFeatures;
}
/**
* {@code Builder} is a specific builder for {@link CBORDataFormat}.
*/
@XmlTransient
public static | from |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/java8stream/erroneous/ErroneousStreamToPrimitivePropertyMapper.java | {
"start": 247,
"end": 361
} | interface ____ {
Target mapStreamToNonStreamAsProperty(Source source);
}
| ErroneousStreamToPrimitivePropertyMapper |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/querydsl/query/MatchPhraseQueryTests.java | {
"start": 937,
"end": 3531
} | class ____ extends ESTestCase {
static MatchPhraseQuery randomMatchPhraseQuery() {
return new MatchPhraseQuery(SourceTests.randomSource(), randomAlphaOfLength(5), randomAlphaOfLength(5));
}
public void testEqualsAndHashCode() {
checkEqualsAndHashCode(randomMatchPhraseQuery(), MatchPhraseQueryTests::copy, MatchPhraseQueryTests::mutate);
}
private static MatchPhraseQuery copy(MatchPhraseQuery query) {
return new MatchPhraseQuery(query.source(), query.name(), query.text(), query.options());
}
private static MatchPhraseQuery mutate(MatchPhraseQuery query) {
List<Function<MatchPhraseQuery, MatchPhraseQuery>> options = Arrays.asList(
q -> new MatchPhraseQuery(SourceTests.mutate(q.source()), q.name(), q.text(), q.options()),
q -> new MatchPhraseQuery(q.source(), randomValueOtherThan(q.name(), () -> randomAlphaOfLength(5)), q.text(), q.options()),
q -> new MatchPhraseQuery(q.source(), q.name(), randomValueOtherThan(q.text(), () -> randomAlphaOfLength(5)), q.options())
);
return randomFrom(options).apply(query);
}
public void testQueryBuilding() {
MatchPhraseQueryBuilder qb = getBuilder(Map.of("slop", 2, "zero_terms_query", "none"));
assertThat(qb.slop(), equalTo(2));
assertThat(qb.zeroTermsQuery(), equalTo(ZeroTermsQueryOption.NONE));
Exception e = expectThrows(IllegalArgumentException.class, () -> getBuilder(Map.of("pizza", "yummy")));
assertThat(e.getMessage(), equalTo("illegal match_phrase option [pizza]"));
e = expectThrows(NumberFormatException.class, () -> getBuilder(Map.of("slop", "mushrooms")));
assertThat(e.getMessage(), equalTo("For input string: \"mushrooms\""));
e = expectThrows(ElasticsearchException.class, () -> getBuilder(Map.of("zero_terms_query", "pepperoni")));
assertThat(e.getMessage(), equalTo("unknown serialized type [pepperoni]"));
}
private static MatchPhraseQueryBuilder getBuilder(Map<String, Object> options) {
final Source source = new Source(1, 1, StringUtils.EMPTY);
final MatchPhraseQuery mpq = new MatchPhraseQuery(source, "eggplant", "foo bar", options);
return (MatchPhraseQueryBuilder) mpq.asBuilder();
}
public void testToString() {
final Source source = new Source(1, 1, StringUtils.EMPTY);
final MatchPhraseQuery mpq = new MatchPhraseQuery(source, "eggplant", "foo bar");
assertEquals("MatchPhraseQuery@1:2[eggplant:foo bar]", mpq.toString());
}
}
| MatchPhraseQueryTests |
java | spring-projects__spring-boot | module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityInterceptorTests.java | {
"start": 1770,
"end": 6036
} | class ____ {
@Mock
@SuppressWarnings("NullAway.Init")
private TokenValidator tokenValidator;
@Mock
@SuppressWarnings("NullAway.Init")
private SecurityService securityService;
private SecurityInterceptor interceptor;
private MockHttpServletRequest request;
@BeforeEach
void setup() {
this.interceptor = new SecurityInterceptor(this.tokenValidator, this.securityService, "my-app-id");
this.request = new MockHttpServletRequest();
}
@Test
void preHandleWhenRequestIsPreFlightShouldReturnTrue() {
this.request.setMethod("OPTIONS");
this.request.addHeader(HttpHeaders.ORIGIN, "https://example.com");
this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK);
}
@Test
void preHandleWhenTokenIsMissingShouldReturnFalse() {
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus());
}
@Test
void preHandleWhenTokenIsNotBearerShouldReturnFalse() {
this.request.addHeader("Authorization", mockAccessToken());
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus());
}
@Test
void preHandleWhenApplicationIdIsNullShouldReturnFalse() {
this.interceptor = new SecurityInterceptor(this.tokenValidator, this.securityService, null);
this.request.addHeader("Authorization", "bearer " + mockAccessToken());
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
assertThat(response.getStatus()).isEqualTo(Reason.SERVICE_UNAVAILABLE.getStatus());
}
@Test
void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnFalse() {
this.interceptor = new SecurityInterceptor(this.tokenValidator, null, "my-app-id");
this.request.addHeader("Authorization", "bearer " + mockAccessToken());
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
assertThat(response.getStatus()).isEqualTo(Reason.SERVICE_UNAVAILABLE.getStatus());
}
@Test
void preHandleWhenAccessIsNotAllowedShouldReturnFalse() {
String accessToken = mockAccessToken();
this.request.addHeader("Authorization", "bearer " + accessToken);
given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED);
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
assertThat(response.getStatus()).isEqualTo(Reason.ACCESS_DENIED.getStatus());
}
@Test
void preHandleSuccessfulWithFullAccess() {
String accessToken = mockAccessToken();
this.request.addHeader("Authorization", "Bearer " + accessToken);
given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.FULL);
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
then(this.tokenValidator).should().validate(assertArg((token) -> assertThat(token).hasToString(accessToken)));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK);
assertThat(this.request.getAttribute("cloudFoundryAccessLevel")).isEqualTo(AccessLevel.FULL);
}
@Test
void preHandleSuccessfulWithRestrictedAccess() {
String accessToken = mockAccessToken();
this.request.addHeader("Authorization", "Bearer " + accessToken);
given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED);
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("info"));
then(this.tokenValidator).should().validate(assertArg((token) -> assertThat(token).hasToString(accessToken)));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK);
assertThat(this.request.getAttribute("cloudFoundryAccessLevel")).isEqualTo(AccessLevel.RESTRICTED);
}
private String mockAccessToken() {
return "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwu"
+ "Y29tIiwiZXhwIjoxNDI2NDIwODAwLCJhd2Vzb21lIjp0cnVlfQ."
+ Base64.getEncoder().encodeToString("signature".getBytes());
}
}
| SecurityInterceptorTests |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/KafkaFuture.java | {
"start": 2091,
"end": 2255
} | interface ____<A, B> {
B apply(A a);
}
/**
* A consumer of two different types of object.
*/
@FunctionalInterface
public | BaseFunction |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/shortarray/ShortArrayAssert_usingDefaultComparator_Test.java | {
"start": 1271,
"end": 2014
} | class ____ {
@Test
public void should_revert_to_default_comparator() {
// GIVEN
Comparator<short[]> comparator = alwaysEqual();
ShortArrayAssert assertions = new ShortArrayAssert(emptyArray());
ShortArrays defaultShortArrays = EXTRACTION.fieldValue("arrays", ShortArrays.class, assertions);
// WHEN
assertions.usingComparator(comparator)
.usingDefaultComparator();
// THEN
Objects objects = EXTRACTION.fieldValue("objects", Objects.class, assertions);
then(objects).isSameAs(Objects.instance());
ShortArrays shortArrays = EXTRACTION.fieldValue("arrays", ShortArrays.class, assertions);
then(shortArrays).isSameAs(defaultShortArrays);
}
}
| ShortArrayAssert_usingDefaultComparator_Test |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/nativeio/NativeIO.java | {
"start": 34456,
"end": 41398
} | interface ____ create a FileInputStream that
// shares delete permission on the file opened, and set it to the
// given offset.
//
FileDescriptor fd = NativeIO.Windows.createFile(
f.getAbsolutePath(),
NativeIO.Windows.GENERIC_READ,
NativeIO.Windows.FILE_SHARE_READ |
NativeIO.Windows.FILE_SHARE_WRITE |
NativeIO.Windows.FILE_SHARE_DELETE,
NativeIO.Windows.OPEN_EXISTING);
if (seekOffset > 0)
NativeIO.Windows.setFilePointer(fd, seekOffset, NativeIO.Windows.FILE_BEGIN);
return fd;
}
}
/**
* @return Create the specified File for write access, ensuring that it does not exist.
* @param f the file that we want to create
* @param permissions we want to have on the file (if security is enabled)
*
* @throws AlreadyExistsException if the file already exists
* @throws IOException if any other error occurred
*/
public static FileOutputStream getCreateForWriteFileOutputStream(File f, int permissions)
throws IOException {
if (!Shell.WINDOWS) {
// Use the native wrapper around open(2)
try {
FileDescriptor fd = NativeIO.POSIX.open(f.getAbsolutePath(),
NativeIO.POSIX.O_WRONLY | NativeIO.POSIX.O_CREAT
| NativeIO.POSIX.O_EXCL, permissions);
return new FileOutputStream(fd);
} catch (NativeIOException nioe) {
if (nioe.getErrno() == Errno.EEXIST) {
throw new AlreadyExistsException(nioe);
}
throw nioe;
}
} else {
// Use the Windows native APIs to create equivalent FileOutputStream
try {
FileDescriptor fd = NativeIO.Windows.createFile(f.getCanonicalPath(),
NativeIO.Windows.GENERIC_WRITE,
NativeIO.Windows.FILE_SHARE_DELETE
| NativeIO.Windows.FILE_SHARE_READ
| NativeIO.Windows.FILE_SHARE_WRITE,
NativeIO.Windows.CREATE_NEW);
NativeIO.POSIX.chmod(f.getCanonicalPath(), permissions);
return new FileOutputStream(fd);
} catch (NativeIOException nioe) {
if (nioe.getErrorCode() == 80) {
// ERROR_FILE_EXISTS
// 80 (0x50)
// The file exists
throw new AlreadyExistsException(nioe);
}
throw nioe;
}
}
}
private synchronized static void ensureInitialized() {
if (!initialized) {
cacheTimeout =
new Configuration().getLong("hadoop.security.uid.cache.secs",
4*60*60) * 1000;
LOG.info("Initialized cache for UID to User mapping with a cache" +
" timeout of " + cacheTimeout/1000 + " seconds.");
initialized = true;
}
}
/**
* A version of renameTo that throws a descriptive exception when it fails.
*
* @param src The source path
* @param dst The destination path
*
* @throws NativeIOException On failure.
*/
public static void renameTo(File src, File dst)
throws IOException {
if (!nativeLoaded) {
if (!src.renameTo(dst)) {
throw new IOException("renameTo(src=" + src + ", dst=" +
dst + ") failed.");
}
} else {
renameTo0(src.getAbsolutePath(), dst.getAbsolutePath());
}
}
/**
* Creates a hardlink "dst" that points to "src".
*
* This is deprecated since JDK7 NIO can create hardlinks via the
* {@link java.nio.file.Files} API.
*
* @param src source file
* @param dst hardlink location
* @throws IOException raised on errors performing I/O.
*/
@Deprecated
public static void link(File src, File dst) throws IOException {
if (!nativeLoaded) {
HardLink.createHardLink(src, dst);
} else {
link0(src.getAbsolutePath(), dst.getAbsolutePath());
}
}
/**
* A version of renameTo that throws a descriptive exception when it fails.
*
* @param src The source path
* @param dst The destination path
*
* @throws NativeIOException On failure.
*/
private static native void renameTo0(String src, String dst)
throws NativeIOException;
private static native void link0(String src, String dst)
throws NativeIOException;
/**
* Unbuffered file copy from src to dst without tainting OS buffer cache
*
* In POSIX platform:
* It uses FileChannel#transferTo() which internally attempts
* unbuffered IO on OS with native sendfile64() support and falls back to
* buffered IO otherwise.
*
* It minimizes the number of FileChannel#transferTo call by passing the the
* src file size directly instead of a smaller size as the 3rd parameter.
* This saves the number of sendfile64() system call when native sendfile64()
* is supported. In the two fall back cases where sendfile is not supported,
* FileChannle#transferTo already has its own batching of size 8 MB and 8 KB,
* respectively.
*
* In Windows Platform:
* It uses its own native wrapper of CopyFileEx with COPY_FILE_NO_BUFFERING
* flag, which is supported on Windows Server 2008 and above.
*
* Ideally, we should use FileChannel#transferTo() across both POSIX and Windows
* platform. Unfortunately, the wrapper(Java_sun_nio_ch_FileChannelImpl_transferTo0)
* used by FileChannel#transferTo for unbuffered IO is not implemented on Windows.
* Based on OpenJDK 6/7/8 source code, Java_sun_nio_ch_FileChannelImpl_transferTo0
* on Windows simply returns IOS_UNSUPPORTED.
*
* Note: This simple native wrapper does minimal parameter checking before copy and
* consistency check (e.g., size) after copy.
* It is recommended to use wrapper function like
* the Storage#nativeCopyFileUnbuffered() function in hadoop-hdfs with pre/post copy
* checks.
*
* @param src The source path
* @param dst The destination path
* @throws IOException raised on errors performing I/O.
*/
public static void copyFileUnbuffered(File src, File dst) throws IOException {
if (nativeLoaded && Shell.WINDOWS) {
copyFileUnbuffered0(src.getAbsolutePath(), dst.getAbsolutePath());
} else {
FileInputStream fis = new FileInputStream(src);
FileChannel input = null;
try {
input = fis.getChannel();
try (FileOutputStream fos = new FileOutputStream(dst);
FileChannel output = fos.getChannel()) {
long remaining = input.size();
long position = 0;
long transferred = 0;
while (remaining > 0) {
transferred = input.transferTo(position, remaining, output);
remaining -= transferred;
position += transferred;
}
}
} finally {
IOUtils.cleanupWithLogger(LOG, input, fis);
}
}
}
private static native void copyFileUnbuffered0(String src, String dst)
throws NativeIOException;
}
| to |
java | spring-projects__spring-framework | spring-context-indexer/src/test/java/org/springframework/context/index/processor/CandidateComponentsIndexerTests.java | {
"start": 3048,
"end": 8318
} | class ____ {
private TestCompiler compiler;
@BeforeEach
void createCompiler(@TempDir Path tempDir) throws IOException {
this.compiler = new TestCompiler(tempDir);
}
@Test
void noCandidate() {
CandidateComponentsMetadata metadata = compile(SampleNone.class);
assertThat(metadata.getItems()).isEmpty();
}
@Test
void noAnnotation() {
CandidateComponentsMetadata metadata = compile(CandidateComponentsIndexerTests.class);
assertThat(metadata.getItems()).isEmpty();
}
@Test
void stereotypeComponent() {
testComponent(SampleComponent.class);
}
@Test
void stereotypeService() {
testComponent(SampleService.class);
}
@Test
void stereotypeController() {
testComponent(SampleController.class);
}
@Test
void stereotypeControllerMetaAnnotation() {
testComponent(SampleMetaController.class);
}
@Test
void stereotypeRepository() {
testSingleComponent(SampleRepository.class, Component.class);
}
@Test
void stereotypeControllerMetaIndex() {
testSingleComponent(SampleMetaIndexedController.class, Component.class, MetaControllerIndexed.class);
}
@Test
void stereotypeOnAbstractClass() {
testComponent(AbstractController.class);
}
@Test
void cdiNamed() {
testSingleComponent(SampleNamed.class, Named.class);
}
@Test
void cdiTransactional() {
testSingleComponent(SampleTransactional.class, Transactional.class);
}
@Test
void persistenceEntity() {
testSingleComponent(SampleEntity.class, Entity.class);
}
@Test
void persistenceMappedSuperClass() {
testSingleComponent(SampleMappedSuperClass.class, MappedSuperclass.class);
}
@Test
void persistenceEmbeddable() {
testSingleComponent(SampleEmbeddable.class, Embeddable.class);
}
@Test
void persistenceConverter() {
testSingleComponent(SampleConverter.class, Converter.class);
}
@Test
void packageInfo() {
CandidateComponentsMetadata metadata = compile("org/springframework/context/index/sample/jpa/package-info");
assertThat(metadata).has(Metadata.of("org.springframework.context.index.sample.jpa", "package-info"));
}
@Test
void typeStereotypeFromMetaInterface() {
testSingleComponent(SampleSpecializedRepo.class, Repo.class);
}
@Test
void typeStereotypeFromInterfaceFromSuperClass() {
testSingleComponent(SampleRepo.class, Repo.class);
}
@Test
void typeStereotypeFromSeveralInterfaces() {
testSingleComponent(SampleSmartRepo.class, Repo.class, SmartRepo.class);
}
@Test
void typeStereotypeOnInterface() {
testSingleComponent(SpecializedRepo.class, Repo.class);
}
@Test
void typeStereotypeOnInterfaceFromSeveralInterfaces() {
testSingleComponent(SmartRepo.class, Repo.class, SmartRepo.class);
}
@Test
void typeStereotypeOnIndexedInterface() {
testSingleComponent(Repo.class, Repo.class);
}
@Test
void embeddedCandidatesAreDetected()
throws ClassNotFoundException {
// Validate nested type structure
String nestedType = "org.springframework.context.index.sample.SampleEmbedded.Another$AnotherPublicCandidate";
Class<?> type = ClassUtils.forName(nestedType, getClass().getClassLoader());
assertThat(type).isSameAs(SampleEmbedded.Another.AnotherPublicCandidate.class);
CandidateComponentsMetadata metadata = compile(SampleEmbedded.class);
assertThat(metadata).has(Metadata.of(SampleEmbedded.PublicCandidate.class, Component.class));
assertThat(metadata).has(Metadata.of(nestedType, Component.class.getName()));
assertThat(metadata.getItems()).hasSize(2);
}
@Test
void embeddedNonStaticCandidateAreIgnored() {
CandidateComponentsMetadata metadata = compile(SampleNonStaticEmbedded.class);
assertThat(metadata.getItems()).isEmpty();
}
private void testComponent(Class<?>... classes) {
CandidateComponentsMetadata metadata = compile(classes);
for (Class<?> c : classes) {
assertThat(metadata).has(Metadata.of(c, Component.class));
}
assertThat(metadata.getItems()).hasSameSizeAs(classes);
}
private void testSingleComponent(Class<?> target, Class<?>... stereotypes) {
CandidateComponentsMetadata metadata = compile(target);
assertThat(metadata).has(Metadata.of(target, stereotypes));
assertThat(metadata.getItems()).hasSize(1);
}
@SuppressWarnings("removal")
private CandidateComponentsMetadata compile(Class<?>... types) {
CandidateComponentsIndexer processor = new CandidateComponentsIndexer();
this.compiler.getTask(types).call(processor);
return readGeneratedMetadata(this.compiler.getOutputLocation());
}
@SuppressWarnings("removal")
private CandidateComponentsMetadata compile(String... types) {
CandidateComponentsIndexer processor = new CandidateComponentsIndexer();
this.compiler.getTask(types).call(processor);
return readGeneratedMetadata(this.compiler.getOutputLocation());
}
private CandidateComponentsMetadata readGeneratedMetadata(File outputLocation) {
File metadataFile = new File(outputLocation, MetadataStore.METADATA_PATH);
if (metadataFile.isFile()) {
try (FileInputStream fileInputStream = new FileInputStream(metadataFile)) {
return PropertiesMarshaller.read(fileInputStream);
}
catch (IOException ex) {
throw new IllegalStateException("Failed to read metadata from disk", ex);
}
}
else {
return new CandidateComponentsMetadata();
}
}
}
| CandidateComponentsIndexerTests |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/collection_in_constructor/Container1.java | {
"start": 772,
"end": 1608
} | class ____ {
private Integer num;
private String type;
private List<Store9> stores;
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public List<Store9> getStores() {
return stores;
}
public void setStores(List<Store9> stores) {
this.stores = stores;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
// simulate a misbehaving object with a bad equals override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Container1 that = (Container1) o;
return Objects.equals(num, that.num);
}
@Override
public int hashCode() {
return Objects.hash(num);
}
}
| Container1 |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/convert/StringToDurationConverter.java | {
"start": 1314,
"end": 2435
} | class ____ implements GenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(String.class, Duration.class));
}
@Override
public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (ObjectUtils.isEmpty(source)) {
return null;
}
return convert(source.toString(), getStyle(targetType), getDurationUnit(targetType));
}
private @Nullable DurationStyle getStyle(TypeDescriptor targetType) {
DurationFormat annotation = targetType.getAnnotation(DurationFormat.class);
return (annotation != null) ? annotation.value() : null;
}
private @Nullable ChronoUnit getDurationUnit(TypeDescriptor targetType) {
DurationUnit annotation = targetType.getAnnotation(DurationUnit.class);
return (annotation != null) ? annotation.value() : null;
}
private Duration convert(String source, @Nullable DurationStyle style, @Nullable ChronoUnit unit) {
style = (style != null) ? style : DurationStyle.detect(source);
return style.parse(source, unit);
}
}
| StringToDurationConverter |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeSwitchIfEmptySingle.java | {
"start": 1653,
"end": 3103
} | class ____<T>
extends AtomicReference<Disposable>
implements MaybeObserver<T>, Disposable {
private static final long serialVersionUID = 4603919676453758899L;
final SingleObserver<? super T> downstream;
final SingleSource<? extends T> other;
SwitchIfEmptyMaybeObserver(SingleObserver<? super T> actual, SingleSource<? extends T> other) {
this.downstream = actual;
this.other = other;
}
@Override
public void dispose() {
DisposableHelper.dispose(this);
}
@Override
public boolean isDisposed() {
return DisposableHelper.isDisposed(get());
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.setOnce(this, d)) {
downstream.onSubscribe(this);
}
}
@Override
public void onSuccess(T value) {
downstream.onSuccess(value);
}
@Override
public void onError(Throwable e) {
downstream.onError(e);
}
@Override
public void onComplete() {
Disposable d = get();
if (d != DisposableHelper.DISPOSED) {
if (compareAndSet(d, null)) {
other.subscribe(new OtherSingleObserver<T>(downstream, this));
}
}
}
static final | SwitchIfEmptyMaybeObserver |
java | google__guava | android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java | {
"start": 45733,
"end": 46901
} | class ____ extends Thread {
private final AbstractFuture<?> future;
private final long timeout;
private final TimeUnit unit;
private Exception exception;
private volatile long startTime;
private long timeSpentBlocked;
TimedWaiterThread(AbstractFuture<?> future, long timeout, TimeUnit unit) {
this.future = future;
this.timeout = timeout;
this.unit = unit;
}
@Override
public void run() {
startTime = System.nanoTime();
try {
future.get(timeout, unit);
} catch (Exception e) {
// nothing
exception = e;
} finally {
timeSpentBlocked = System.nanoTime() - startTime;
}
}
@SuppressWarnings("ThreadPriorityCheck") // TODO: b/175898629 - Consider onSpinWait.
void awaitWaiting() {
while (!isBlocked()) {
if (getState() == State.TERMINATED) {
throw new RuntimeException("Thread exited");
}
Thread.yield();
}
}
private boolean isBlocked() {
return getState() == Thread.State.TIMED_WAITING && LockSupport.getBlocker(this) == future;
}
}
private static final | TimedWaiterThread |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/pool/ValidConnectionCheckerAdapter.java | {
"start": 976,
"end": 2816
} | class ____ implements ValidConnectionChecker {
@Override
public boolean isValidConnection(Connection conn, String query, int validationQueryTimeout) throws Exception {
if (StringUtils.isEmpty(query)) {
return true;
}
return execValidQuery(conn, query, validationQueryTimeout);
}
public static boolean execValidQuery(Connection conn, String query, int validationQueryTimeout) throws Exception {
// using raw connection for createStatement to speed up validation by skipping all filters.
Connection rawConn;
if (conn instanceof DruidPooledConnection) {
conn = ((DruidPooledConnection) conn).getConnection();
}
if (conn instanceof ConnectionProxyImpl) {
rawConn = ((ConnectionProxyImpl) conn).getConnectionRaw();
} else {
rawConn = conn;
}
Statement stmt = null;
boolean isDruidStatementConnection;
if (rawConn instanceof DruidStatementConnection) {
stmt = ((DruidStatementConnection) rawConn).getStatement();
isDruidStatementConnection = true;
} else {
isDruidStatementConnection = false;
}
ResultSet rs = null;
try {
if (!isDruidStatementConnection) {
stmt = rawConn.createStatement();
}
if (validationQueryTimeout > 0) {
stmt.setQueryTimeout(validationQueryTimeout);
}
rs = stmt.executeQuery(query);
return rs.next();
} finally {
JdbcUtils.close(rs);
if (!isDruidStatementConnection) {
JdbcUtils.close(stmt);
}
}
}
@Override
public void configFromProperties(Properties properties) {
}
}
| ValidConnectionCheckerAdapter |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java | {
"start": 2382,
"end": 3651
} | class ____ {
* String name;
* int age;
* boolean smoker;
* ...
*
* public int hashCode() {
* // you pick a hard-coded, randomly chosen, non-zero, odd number
* // ideally different for each class
* return new HashCodeBuilder(17, 37).
* append(name).
* append(age).
* append(smoker).
* toHashCode();
* }
* }
* </pre>
*
* <p>
* If required, the superclass {@code hashCode()} can be added using {@link #appendSuper}.
* </p>
*
* <p>
* Alternatively, there is a method that uses reflection to determine the fields to test. Because these fields are
* usually private, the method, {@code reflectionHashCode}, uses {@code AccessibleObject.setAccessible}
* to change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions
* are set up correctly. It is also slower than testing explicitly.
* </p>
*
* <p>
* A typical invocation for this method would look like:
* </p>
*
* <pre>
* public int hashCode() {
* return HashCodeBuilder.reflectionHashCode(this);
* }
* </pre>
*
* <p>The {@link HashCodeExclude} annotation can be used to exclude fields from being
* used by the {@code reflectionHashCode} methods.</p>
*
* @since 1.0
*/
public | Person |
java | quarkusio__quarkus | extensions/mongodb-client/deployment/src/test/java/io/quarkus/mongodb/MongoClientBuildItemConsumerTest.java | {
"start": 574,
"end": 1808
} | class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar.addClasses(MongoTestBase.class))
.withConfigurationResource("default-mongoclient.properties")
.addBuildChainCustomizer(buildCustomizer());
@Test
public void testContainerHasBeans() {
assertThat(Arc.container().instance(MongoClient.class).get()).isNotNull();
assertThat(Arc.container().instance(ReactiveMongoClient.class).get()).isNotNull();
}
protected static Consumer<BuildChainBuilder> buildCustomizer() {
return new Consumer<BuildChainBuilder>() {
// This represents the extension.
@Override
public void accept(BuildChainBuilder builder) {
builder.addBuildStep(context -> {
List<MongoClientBuildItem> mongoClientBuildItems = context.consumeMulti(MongoClientBuildItem.class);
context.produce(new FeatureBuildItem("dummy"));
}).consumes(MongoClientBuildItem.class)
.produces(FeatureBuildItem.class)
.build();
}
};
}
}
| MongoClientBuildItemConsumerTest |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/RedissonReactiveClient.java | {
"start": 17764,
"end": 51394
} | interface ____ mass operations with Bucket objects
* using provided codec for object.
*
* @param codec codec for bucket objects
* @return Buckets
*/
RBucketsReactive getBuckets(Codec codec);
/**
* Returns API for mass operations over Bucket objects with specified <code>options</code>.
*
* @param options instance options
* @return Buckets object
*/
RBucketsReactive getBuckets(OptionalOptions options);
/**
* Use {@link #getBuckets()} instead.
*
* @param <V> type of value
* @param pattern pattern for name of buckets
* @return list of buckets
*/
@Deprecated
<V> List<RBucketReactive<V>> findBuckets(String pattern);
/**
* Returns JSON data holder instance by name using provided codec.
*
* @param <V> type of value
* @param name name of object
* @param codec codec for values
* @return JsonBucket object
*/
<V> RJsonBucketReactive<V> getJsonBucket(String name, JsonCodec codec);
/**
* Returns JSON data holder instance with specified <code>options</code>.
*
* @param <V> type of value
* @param options instance options
* @return JsonBucket object
*/
<V> RJsonBucketReactive<V> getJsonBucket(JsonBucketOptions<V> options);
/**
* Returns API for mass operations over JsonBucket objects
* using provided codec for JSON object with default path.
*
* @param codec using provided codec for JSON object with default path.
* @return JsonBuckets
*/
RJsonBucketsReactive getJsonBuckets(JsonCodec codec);
/**
* Returns HyperLogLog instance by name.
*
* @param <V> type of values
* @param name name of object
* @return HyperLogLog object
*/
<V> RHyperLogLogReactive<V> getHyperLogLog(String name);
/**
* Returns HyperLogLog instance by name
* using provided codec for hll objects.
*
* @param <V> type of values
* @param name name of object
* @param codec codec of values
* @return HyperLogLog object
*/
<V> RHyperLogLogReactive<V> getHyperLogLog(String name, Codec codec);
/**
* Returns HyperLogLog instance with specified <code>options</code>.
*
* @param <V> type of value
* @param options instance options
* @return HyperLogLog object
*/
<V> RHyperLogLogReactive<V> getHyperLogLog(PlainOptions options);
/**
* Returns id generator by name.
*
* @param name name of object
* @return IdGenerator object
*/
RIdGeneratorReactive getIdGenerator(String name);
/**
* Returns id generator instance with specified <code>options</code>.
*
* @param options instance options
* @return IdGenerator object
*/
RIdGeneratorReactive getIdGenerator(CommonOptions options);
/**
* Returns list instance by name.
*
* @param <V> type of values
* @param name name of object
* @return List object
*/
<V> RListReactive<V> getList(String name);
/**
* Returns list instance by name
* using provided codec for list objects.
*
* @param <V> type of values
* @param name name of object
* @param codec codec for values
* @return List object
*/
<V> RListReactive<V> getList(String name, Codec codec);
/**
* Returns list instance with specified <code>options</code>.
*
* @param <V> type of value
* @param options instance options
* @return List object
*/
<V> RListReactive<V> getList(PlainOptions options);
/**
* Returns List based Multimap instance by name.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @return ListMultimap object
*/
<K, V> RListMultimapReactive<K, V> getListMultimap(String name);
/**
* Returns List based Multimap instance by name
* using provided codec for both map keys and values.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @param codec codec for keys and values
* @return RListMultimapReactive object
*/
<K, V> RListMultimapReactive<K, V> getListMultimap(String name, Codec codec);
/**
* Returns List based Multimap instance with specified <code>options</code>.
*
* @param <K> type of key
* @param <V> type of value
* @param options instance options
* @return ListMultimap object
*/
<K, V> RListMultimapReactive<K, V> getListMultimap(PlainOptions options);
/**
* Returns List based Multimap cache instance by name.
* Supports key eviction by specifying a time to live.
* If eviction is not required then it's better to use regular list multimap {@link #getListMultimap(String)}.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @return RListMultimapCacheReactive object
*/
<K, V> RListMultimapCacheReactive<K, V> getListMultimapCache(String name);
/**
* Returns List based Multimap cache instance by name using provided codec for both map keys and values.
* Supports key eviction by specifying a time to live.
* If eviction is not required then it's better to use regular list multimap {@link #getListMultimap(String, Codec)}.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @param codec codec for keys and values
* @return RListMultimapCacheReactive object
*/
<K, V> RListMultimapCacheReactive<K, V> getListMultimapCache(String name, Codec codec);
/**
* Returns List based Multimap instance by name.
* Supports key-entry eviction with a given TTL value.
*
* <p>If eviction is not required then it's better to use regular map {@link #getSetMultimap(String)}.</p>
*
* @param <K> type of key
* @param <V> type of value
* @param options instance options
* @return ListMultimapCache object
*/
<K, V> RListMultimapCacheReactive<K, V> getListMultimapCache(PlainOptions options);
/**
* Returns List based Multimap instance by name.
* Supports key-entry eviction with a given TTL value.
* Stores insertion order and allows duplicates for values mapped to key.
* <p>
* Uses Redis native commands for entry expiration and not a scheduled eviction task.
* <p>
* Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b>
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @return ListMultimapCache object
*/
<K, V> RListMultimapCacheNativeReactive<K, V> getListMultimapCacheNative(String name);
/**
* Returns List based Multimap instance by name
* using provided codec for both map keys and values.
* Supports key-entry eviction with a given TTL value.
* Stores insertion order and allows duplicates for values mapped to key.
* <p>
* Uses Redis native commands for entry expiration and not a scheduled eviction task.
* <p>
* Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b>
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @param codec codec for keys and values
* @return ListMultimapCache object
*/
<K, V> RListMultimapCacheNativeReactive<K, V> getListMultimapCacheNative(String name, Codec codec);
/**
* Returns List based Multimap instance by name.
* Supports key-entry eviction with a given TTL value.
* Stores insertion order and allows duplicates for values mapped to key.
* <p>
* Uses Redis native commands for entry expiration and not a scheduled eviction task.
* <p>
* Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b>
*
* @param <K> type of key
* @param <V> type of value
* @param options instance options
* @return ListMultimapCache object
*/
<K, V> RListMultimapCacheNativeReactive<K, V> getListMultimapCacheNative(PlainOptions options);
/**
* Returns Set based Multimap instance by name.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @return SetMultimap object
*/
<K, V> RSetMultimapReactive<K, V> getSetMultimap(String name);
/**
* Returns Set based Multimap instance by name
* using provided codec for both map keys and values.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @param codec codec for keys and values
* @return SetMultimap object
*/
<K, V> RSetMultimapReactive<K, V> getSetMultimap(String name, Codec codec);
/**
* Returns Set based Multimap instance with specified <code>options</code>.
*
* @param <K> type of key
* @param <V> type of value
* @param options instance options
* @return SetMultimap object
*/
<K, V> RSetMultimapReactive<K, V> getSetMultimap(PlainOptions options);
/**
* Returns Set based Multimap cache instance by name.
* Supports key eviction by specifying a time to live.
* If eviction is not required then it's better to use regular set multimap {@link #getSetMultimap(String)}.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @return RSetMultimapCacheReactive object
*/
<K, V> RSetMultimapCacheReactive<K, V> getSetMultimapCache(String name);
/**
* Returns Set based Multimap cache instance by name using provided codec for both map keys and values.
* Supports key eviction by specifying a time to live.
* If eviction is not required then it's better to use regular set multimap {@link #getSetMultimap(String, Codec)}.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @param codec codec for keys and values
* @return RSetMultimapCacheReactive object
*/
<K, V> RSetMultimapCacheReactive<K, V> getSetMultimapCache(String name, Codec codec);
/**
* Returns Set based Multimap instance with specified <code>options</code>.
* Supports key-entry eviction with a given TTL value.
*
* <p>If eviction is not required then it's better to use regular map {@link #getSetMultimap(PlainOptions)}.</p>
*
* @param <K> type of key
* @param <V> type of value
* @param options instance options
* @return SetMultimapCache object
*/
<K, V> RSetMultimapCacheReactive<K, V> getSetMultimapCache(PlainOptions options);
/**
* Returns Set based Multimap instance by name.
* Supports key-entry eviction with a given TTL value.
* Doesn't allow duplications for values mapped to key.
* <p>
* Uses Redis native commands for entry expiration and not a scheduled eviction task.
* <p>
* Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b>
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @return SetMultimapCache object
*/
<K, V> RSetMultimapCacheNativeReactive<K, V> getSetMultimapCacheNative(String name);
/**
* Returns Set based Multimap instance by name
* using provided codec for both map keys and values.
* Supports key-entry eviction with a given TTL value.
* Doesn't allow duplications for values mapped to key.
* <p>
* Uses Redis native commands for entry expiration and not a scheduled eviction task.
* <p>
* Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b>
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @param codec codec for keys and values
* @return SetMultimapCache object
*/
<K, V> RSetMultimapCacheNativeReactive<K, V> getSetMultimapCacheNative(String name, Codec codec);
/**
* Returns Set based Multimap instance with specified <code>options</code>.
* Supports key-entry eviction with a given TTL value.
* Doesn't allow duplications for values mapped to key.
* <p>
* Uses Redis native commands for entry expiration and not a scheduled eviction task.
* <p>
* Requires <b>Redis 7.4.0 and higher.</b> or <b>Valkey 9.0.0 and higher.</b>
*
* @param <K> type of key
* @param <V> type of value
* @param options instance options
* @return SetMultimapCache object
*/
<K, V> RSetMultimapCacheNativeReactive<K, V> getSetMultimapCacheNative(PlainOptions options);
/**
* Returns map instance by name.
*
* @param <K> type of keys
* @param <V> type of values
* @param name name of object
* @return Map object
*/
<K, V> RMapReactive<K, V> getMap(String name);
/**
* Returns map instance by name.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @param options map options
* @return Map object
*/
@Deprecated
<K, V> RMapReactive<K, V> getMap(String name, MapOptions<K, V> options);
/**
* Returns map instance by name
* using provided codec for both map keys and values.
*
* @param <K> type of keys
* @param <V> type of values
* @param name name of object
* @param codec codec for keys and values
* @return Map object
*/
<K, V> RMapReactive<K, V> getMap(String name, Codec codec);
/**
* Returns map instance by name
* using provided codec for both map keys and values.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @param codec codec for keys and values
* @param options map options
* @return Map object
*/
@Deprecated
<K, V> RMapReactive<K, V> getMap(String name, Codec codec, MapOptions<K, V> options);
/**
* Returns map instance by name.
*
* @param <K> type of key
* @param <V> type of value
* @param options instance options
* @return Map object
*/
<K, V> RMapReactive<K, V> getMap(org.redisson.api.options.MapOptions<K, V> options);
/**
* Returns local cached map instance by name.
* Configured by parameters of options-object.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @param options local map options
* @return LocalCachedMap object
*/
@Deprecated
<K, V> RLocalCachedMapReactive<K, V> getLocalCachedMap(String name, LocalCachedMapOptions<K, V> options);
/**
* Returns local cached map instance by name
* using provided codec. Configured by parameters of options-object.
*
* @param <K> type of key
* @param <V> type of value
* @param name name of object
* @param codec codec for keys and values
* @param options local map options
* @return LocalCachedMap object
*/
@Deprecated
<K, V> RLocalCachedMapReactive<K, V> getLocalCachedMap(String name, Codec codec, LocalCachedMapOptions<K, V> options);
/**
* Returns local cached map instance with specified <code>options</code>.
*
* @param <K> type of key
* @param <V> type of value
* @param options instance options
* @return LocalCachedMap object
*/
<K, V> RLocalCachedMapReactive<K, V> getLocalCachedMap(org.redisson.api.options.LocalCachedMapOptions<K, V> options);
/**
* Returns local cached map cache instance by name.
* Configured by parameters of options-object.
*
* @param <K> type of key
* @param <V> type of value
* @param name - name of object
* @param options - local map options
* @return LocalCachedMapCache object
*/
<K, V> RLocalCachedMapCacheReactive<K, V> getLocalCachedMapCache(String name, LocalCachedMapCacheOptions<K, V> options);
/**
* Returns local cached map cache instance by name using provided codec.
* Configured by parameters of options-object.
*
* @param <K> type of key
* @param <V> type of value
* @param name - name of object
* @param codec - codec for keys and values
* @param options - local map options
* @return LocalCachedMap object
*/
<K, V> RLocalCachedMapCacheReactive<K, V> getLocalCachedMapCache(String name, Codec codec, LocalCachedMapCacheOptions<K, V> options);
/**
* Returns set instance by name.
*
* @param <V> type of values
* @param name name of object
* @return Set object
*/
<V> RSetReactive<V> getSet(String name);
/**
* Returns set instance by name
* using provided codec for set objects.
*
* @param <V> type of values
* @param name name of set
* @param codec codec for values
* @return Set object
*/
<V> RSetReactive<V> getSet(String name, Codec codec);
/**
* Returns set instance with specified <code>options</code>.
*
* @param <V> type of value
* @param options instance options
* @return Set object
*/
<V> RSetReactive<V> getSet(PlainOptions options);
/**
* Returns Redis Sorted Set instance by name.
* This sorted set sorts objects by object score.
*
* @param <V> type of values
* @param name of scored sorted set
* @return ScoredSortedSet object
*/
<V> RScoredSortedSetReactive<V> getScoredSortedSet(String name);
/**
* Returns Redis Sorted Set instance by name
* using provided codec for sorted set objects.
* This sorted set sorts objects by object score.
*
* @param <V> type of values
* @param name name of scored sorted set
* @param codec codec for values
* @return ScoredSortedSet object
*/
<V> RScoredSortedSetReactive<V> getScoredSortedSet(String name, Codec codec);
/**
* Returns Redis Sorted Set instance with specified <code>options</code>.
* This sorted set sorts objects by object score.
*
* @param <V> type of value
* @param options instance options
* @return ScoredSortedSet object
*/
<V> RScoredSortedSetReactive<V> getScoredSortedSet(PlainOptions options);
/**
* Returns String based Redis Sorted Set instance by name
* All elements are inserted with the same score during addition,
* in order to force lexicographical ordering
*
* @param name name of object
* @return LexSortedSet object
*/
RLexSortedSetReactive getLexSortedSet(String name);
/**
* Returns String based Redis Sorted Set instance with specified <code>options</code>.
* All elements are inserted with the same score during addition,
* in order to force lexicographical ordering
*
* @param options instance options
* @return LexSortedSet object
*/
RLexSortedSetReactive getLexSortedSet(CommonOptions options);
/**
* Returns Sharded Topic instance by name.
* <p>
* Messages are delivered to message listeners connected to the same Topic.
* <p>
*
* @param name name of object
* @return Topic object
*/
RShardedTopicReactive getShardedTopic(String name);
/**
* Returns Sharded Topic instance by name using provided codec for messages.
* <p>
* Messages are delivered to message listeners connected to the same Topic.
* <p>
*
* @param name name of object
* @param codec codec for message
* @return Topic object
*/
RShardedTopicReactive getShardedTopic(String name, Codec codec);
/**
* Returns Sharded Topic instance with specified <code>options</code>.
* <p>
* Messages are delivered to message listeners connected to the same Topic.
* <p>
*
* @param options instance options
* @return Topic object
*/
RShardedTopicReactive getShardedTopic(PlainOptions options);
/**
* Returns topic instance by name.
*
* @param name name of object
* @return Topic object
*/
RTopicReactive getTopic(String name);
/**
* Returns topic instance by name
* using provided codec for messages.
*
* @param name name of object
* @param codec codec for message
* @return Topic object
*/
RTopicReactive getTopic(String name, Codec codec);
/**
* Returns topic instance with specified <code>options</code>.
* <p>
* Messages are delivered to message listeners connected to the same Topic.
* <p>
*
* @param options instance options
* @return Topic object
*/
RTopicReactive getTopic(PlainOptions options);
/**
* Returns reliable topic instance by name.
* <p>
* Dedicated Redis connection is allocated per instance (subscriber) of this object.
* Messages are delivered to all listeners attached to the same Redis setup.
* <p>
* Requires <b>Redis 5.0.0 and higher.</b>
*
* @param name name of object
* @return ReliableTopic object
*/
RReliableTopicReactive getReliableTopic(String name);
/**
* Returns reliable topic instance by name
* using provided codec for messages.
* <p>
* Dedicated Redis connection is allocated per instance (subscriber) of this object.
* Messages are delivered to all listeners attached to the same Redis setup.
* <p>
* Requires <b>Redis 5.0.0 and higher.</b>
*
* @param name name of object
* @param codec codec for message
* @return ReliableTopic object
*/
RReliableTopicReactive getReliableTopic(String name, Codec codec);
/**
* Returns reliable topic instance with specified <code>options</code>.
* <p>
* Dedicated Redis connection is allocated per instance (subscriber) of this object.
* Messages are delivered to all listeners attached to the same Redis setup.
* <p>
* Requires <b>Redis 5.0.0 and higher.</b>
*
* @param options instance options
* @return ReliableTopic object
*/
RReliableTopicReactive getReliableTopic(PlainOptions options);
/**
* Returns topic instance satisfies by pattern name.
*
* Supported glob-style patterns:
* h?llo subscribes to hello, hallo and hxllo
* h*llo subscribes to hllo and heeeello
* h[ae]llo subscribes to hello and hallo, but not hillo
*
* @param pattern of the topic
* @return PatternTopic object
*/
RPatternTopicReactive getPatternTopic(String pattern);
/**
* Returns topic instance satisfies by pattern name
* using provided codec for messages.
*
* Supported glob-style patterns:
* h?llo subscribes to hello, hallo and hxllo
* h*llo subscribes to hllo and heeeello
* h[ae]llo subscribes to hello and hallo, but not hillo
*
* @param pattern of the topic
* @param codec codec for message
* @return PatternTopic object
*/
RPatternTopicReactive getPatternTopic(String pattern, Codec codec);
/**
* Returns topic instance satisfies pattern name and specified <code>options</code>..
*
* Supported glob-style patterns:
* h?llo subscribes to hello, hallo and hxllo
* h*llo subscribes to hllo and heeeello
* h[ae]llo subscribes to hello and hallo, but not hillo
*
* @param options instance options
* @return PatterTopic object
*/
RPatternTopicReactive getPatternTopic(PatternTopicOptions options);
/**
* Returns queue instance by name.
*
* @param <V> type of values
* @param name name of object
* @return Queue object
*/
<V> RQueueReactive<V> getQueue(String name);
/**
* Returns queue instance by name
* using provided codec for queue objects.
*
* @param <V> type of values
* @param name name of object
* @param codec codec for values
* @return Queue object
*/
<V> RQueueReactive<V> getQueue(String name, Codec codec);
/**
* Returns unbounded queue instance with specified <code>options</code>.
*
* @param <V> type of value
* @param options instance options
* @return queue object
*/
<V> RQueueReactive<V> getQueue(PlainOptions options);
/**
* Returns a reliable queue instance by name.
* <p>
* The reliable queue provides guaranteed message delivery through acknowledgment mechanisms
* and synchronous replication.
*
* @param name the name of the queue
* @param <V> the type of elements in this queue
* @return Reliable queue instance
*/
<V> RReliableQueueReactive<V> getReliableQueue(String name);
/**
* Returns a reliable queue instance by name and provided codec.
* <p>
* The reliable queue provides guaranteed message delivery through acknowledgment mechanisms
* and synchronous replication.
*
* @param name the name of the queue
* @param codec the codec used for message serialization and deserialization
* @param <V> the type of elements in this queue
* @return Reliable queue instance
*/
<V> RReliableQueueReactive<V> getReliableQueue(String name, Codec codec);
/**
* Returns a reliable queue instance with the specified configuration options.
* <p>
* The reliable queue provides guaranteed message delivery through acknowledgment mechanisms
* and synchronous replication.
*
* @param options configuration options for the reliable queue
* @param <V> the type of elements in this queue
* @return Reliable queue instance
*/
<V> RReliableQueueReactive<V> getReliableQueue(PlainOptions options);
/**
* Returns RingBuffer based queue.
*
* @param <V> value type
* @param name name of object
* @return RingBuffer object
*/
<V> RRingBufferReactive<V> getRingBuffer(String name);
/**
* Returns RingBuffer based queue.
*
* @param <V> value type
* @param name name of object
* @param codec codec for values
* @return RingBuffer object
*/
<V> RRingBufferReactive<V> getRingBuffer(String name, Codec codec);
/**
* Returns RingBuffer based queue instance with specified <code>options</code>.
*
* @param <V> value type
* @param options instance options
* @return RingBuffer object
*/
<V> RRingBufferReactive<V> getRingBuffer(PlainOptions options);
/**
* Returns blocking queue instance by name.
*
* @param <V> type of values
* @param name name of object
* @return BlockingQueue object
*/
<V> RBlockingQueueReactive<V> getBlockingQueue(String name);
/**
* Returns blocking queue instance by name
* using provided codec for queue objects.
*
* @param <V> type of values
* @param name name of object
* @param codec code for values
* @return BlockingQueue object
*/
<V> RBlockingQueueReactive<V> getBlockingQueue(String name, Codec codec);
/**
* Returns unbounded blocking queue instance with specified <code>options</code>.
*
* @param <V> type of value
* @param options instance options
* @return BlockingQueue object
*/
<V> RBlockingQueueReactive<V> getBlockingQueue(PlainOptions options);
/**
* Returns unbounded blocking deque instance by name.
*
* @param <V> type of value
* @param name name of object
* @return BlockingDeque object
*/
<V> RBlockingDequeReactive<V> getBlockingDeque(String name);
/**
* Returns unbounded blocking deque instance by name
* using provided codec for deque objects.
*
* @param <V> type of value
* @param name name of object
* @param codec deque objects codec
* @return BlockingDeque object
*/
<V> RBlockingDequeReactive<V> getBlockingDeque(String name, Codec codec);
/**
* Returns unbounded blocking deque instance with specified <code>options</code>.
*
* @param <V> type of value
* @param options instance options
* @return BlockingDeque object
*/
<V> RBlockingDequeReactive<V> getBlockingDeque(PlainOptions options);
/**
* Returns transfer queue instance by name.
*
* @param <V> type of values
* @param name name of object
* @return TransferQueue object
*/
<V> RTransferQueueReactive<V> getTransferQueue(String name);
/**
* Returns transfer queue instance by name
* using provided codec for queue objects.
*
* @param <V> type of values
* @param name name of object
* @param codec code for values
* @return TransferQueue object
*/
<V> RTransferQueueReactive<V> getTransferQueue(String name, Codec codec);
/**
* Returns transfer queue instance with specified <code>options</code>.
*
* @param <V> type of values
* @param options instance options
* @return TransferQueue object
*/
<V> RTransferQueueReactive<V> getTransferQueue(PlainOptions options);
/**
* Returns deque instance by name.
*
* @param <V> type of values
* @param name name of object
* @return Deque object
*/
<V> RDequeReactive<V> getDeque(String name);
/**
* Returns deque instance by name
* using provided codec for deque objects.
*
* @param <V> type of values
* @param name name of object
* @param codec coded for values
* @return Deque object
*/
<V> RDequeReactive<V> getDeque(String name, Codec codec);
/**
* Returns unbounded deque instance with specified <code>options</code>.
*
* @param <V> type of value
* @param options instance options
* @return Deque object
*/
<V> RDequeReactive<V> getDeque(PlainOptions options);
/**
* Returns "atomic long" instance by name.
*
* @param name of the "atomic long"
* @return AtomicLong object
*/
RAtomicLongReactive getAtomicLong(String name);
/**
* Returns atomicLong instance with specified <code>options</code>.
*
* @param options instance options
* @return AtomicLong object
*/
RAtomicLongReactive getAtomicLong(CommonOptions options);
/**
* Returns "atomic double" instance by name.
*
* @param name of the "atomic double"
* @return AtomicLong object
*/
RAtomicDoubleReactive getAtomicDouble(String name);
/**
* Returns atomicDouble instance with specified <code>options</code>.
*
* @param options instance options
* @return AtomicDouble object
*/
RAtomicDoubleReactive getAtomicDouble(CommonOptions options);
/**
* Returns object for remote operations prefixed with the default name (redisson_remote_service)
*
* @return RemoteService object
*/
@Deprecated
RRemoteService getRemoteService();
/**
* Returns object for remote operations prefixed with the default name (redisson_remote_service)
* and uses provided codec for method arguments and result.
*
* @param codec codec for response and request
* @return RemoteService object
*/
@Deprecated
RRemoteService getRemoteService(Codec codec);
/**
* Returns object for remote operations prefixed with the specified name
*
* @param name the name used as the Redis key prefix for the services
* @return RemoteService object
*/
RRemoteService getRemoteService(String name);
/**
* Returns object for remote operations prefixed with the specified name
* and uses provided codec for method arguments and result.
*
* @param name the name used as the Redis key prefix for the services
* @param codec codec for response and request
* @return RemoteService object
*/
RRemoteService getRemoteService(String name, Codec codec);
/**
* Returns object for remote operations prefixed with specified <code>options</code>.
*
* @param options instance options
* @return RemoteService object
*/
RRemoteService getRemoteService(PlainOptions options);
/**
* Returns bitSet instance by name.
*
* @param name name of object
* @return BitSet object
*/
RBitSetReactive getBitSet(String name);
/**
* Returns bitSet instance with specified <code>options</code>.
*
* @param options instance options
* @return BitSet object
*/
RBitSetReactive getBitSet(CommonOptions options);
/**
* Returns bloom filter instance by name.
*
* @param <V> type of value
* @param name name of object
* @return BloomFilter object
*/
<V> RBloomFilterReactive<V> getBloomFilter(String name);
/**
* Returns bloom filter instance by name
* using provided codec for objects.
*
* @param <V> type of value
* @param name name of object
* @param codec codec for values
* @return BloomFilter object
*/
<V> RBloomFilterReactive<V> getBloomFilter(String name, Codec codec);
/**
* Returns bloom filter instance with specified <code>options</code>.
*
* @param <V> type of value
* @param options instance options
* @return BloomFilter object
*/
<V> RBloomFilterReactive<V> getBloomFilter(PlainOptions options);
/**
* Returns | for |
java | spring-projects__spring-boot | module/spring-boot-couchbase/src/main/java/org/springframework/boot/couchbase/autoconfigure/health/CouchbaseReactiveHealthContributorAutoConfiguration.java | {
"start": 2217,
"end": 2754
} | class ____
extends CompositeReactiveHealthContributorConfiguration<CouchbaseReactiveHealthIndicator, Cluster> {
CouchbaseReactiveHealthContributorAutoConfiguration() {
super(CouchbaseReactiveHealthIndicator::new);
}
@Bean
@ConditionalOnMissingBean(name = { "couchbaseHealthIndicator", "couchbaseHealthContributor" })
ReactiveHealthContributor couchbaseHealthContributor(ConfigurableListableBeanFactory beanFactory) {
return createContributor(beanFactory, Cluster.class);
}
}
| CouchbaseReactiveHealthContributorAutoConfiguration |
java | apache__spark | common/utils-java/src/test/java/org/apache/spark/util/StructuredSparkLoggerSuite.java | {
"start": 1172,
"end": 5419
} | class ____ extends SparkLoggerSuiteBase {
// Enable Structured Logging before running the tests
@BeforeAll
public static void setup() {
SparkLoggerFactory.enableStructuredLogging();
}
// Disable Structured Logging after running the tests
@AfterAll
public static void teardown() {
SparkLoggerFactory.disableStructuredLogging();
}
private static final SparkLogger LOGGER =
SparkLoggerFactory.getLogger(StructuredSparkLoggerSuite.class);
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
private String compactAndToRegexPattern(Level level, String json) {
try {
return JSON_MAPPER.readTree(json).toString()
.replace("<level>", level.toString())
.replace("<className>", className())
.replace("<timestamp>", "[^\"]+")
.replace("\"<stacktrace>\"", ".*")
.replace("{", "\\{") + "\n";
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Override
SparkLogger logger() {
return LOGGER;
}
@Override
String className() {
return StructuredSparkLoggerSuite.class.getSimpleName();
}
@Override
String logFilePath() {
return "target/structured.log";
}
@Override
String expectedPatternForBasicMsg(Level level) {
return compactAndToRegexPattern(level, """
{
"ts": "<timestamp>",
"level": "<level>",
"msg": "This is a log message",
"logger": "<className>"
}""");
}
@Override
String expectedPatternForBasicMsgWithEscapeChar(Level level) {
return compactAndToRegexPattern(level, """
{
"ts": "<timestamp>",
"level": "<level>",
"msg": "This is a log message\\\\nThis is a new line \\\\t other msg",
"logger": "<className>"
}""");
}
@Override
String expectedPatternForBasicMsgWithException(Level level) {
return compactAndToRegexPattern(level, """
{
"ts": "<timestamp>",
"level": "<level>",
"msg": "This is a log message",
"exception": {
"class": "java.lang.RuntimeException",
"msg": "OOM",
"stacktrace": "<stacktrace>"
},
"logger": "<className>"
}""");
}
@Override
String expectedPatternForMsgWithMDC(Level level) {
return compactAndToRegexPattern(level, """
{
"ts": "<timestamp>",
"level": "<level>",
"msg": "Lost executor 1.",
"context": {
"executor_id": "1"
},
"logger": "<className>"
}""");
}
@Override
String expectedPatternForMsgWithMDCs(Level level) {
return compactAndToRegexPattern(level, """
{
"ts": "<timestamp>",
"level": "<level>",
"msg": "Lost executor 1, reason: the shuffle data is too large",
"context": {
"executor_id": "1",
"reason": "the shuffle data is too large"
},
"logger": "<className>"
}""");
}
@Override
String expectedPatternForMsgWithMDCsAndException(Level level) {
return compactAndToRegexPattern(level, """
{
"ts": "<timestamp>",
"level": "<level>",
"msg": "Lost executor 1, reason: the shuffle data is too large",
"context": {
"executor_id": "1",
"reason": "the shuffle data is too large"
},
"exception": {
"class": "java.lang.RuntimeException",
"msg": "OOM",
"stacktrace": "<stacktrace>"
},
"logger": "<className>"
}""");
}
@Override
String expectedPatternForMsgWithMDCValueIsNull(Level level) {
return compactAndToRegexPattern(level, """
{
"ts": "<timestamp>",
"level": "<level>",
"msg": "Lost executor null.",
"context": {
"executor_id": null
},
"logger": "<className>"
}""");
}
@Override
String expectedPatternForCustomLogKey(Level level) {
return compactAndToRegexPattern(level, """
{
"ts": "<timestamp>",
"level": "<level>",
"msg": "Custom log message.",
"context": {
"custom_log_key": "Custom log message."
},
"logger": "<className>"
}""");
}
}
| StructuredSparkLoggerSuite |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/jmx/AbstractJmxTests.java | {
"start": 1054,
"end": 1532
} | class ____ extends AbstractMBeanServerTests {
private ConfigurableApplicationContext ctx;
@Override
protected final void onSetUp() {
ctx = loadContext(getApplicationContextPath());
}
@Override
protected final void onTearDown() {
if (ctx != null) {
ctx.close();
}
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/applicationContext.xml";
}
protected ApplicationContext getContext() {
return this.ctx;
}
}
| AbstractJmxTests |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/builditem/nativeimage/ReflectiveHierarchyIgnoreWarningBuildItem.java | {
"start": 334,
"end": 853
} | class ____ extends MultiBuildItem {
private final Predicate<DotName> predicate;
// used by external extensions
public ReflectiveHierarchyIgnoreWarningBuildItem(DotName dotName) {
this.predicate = new DotNameExclusion(dotName);
}
public ReflectiveHierarchyIgnoreWarningBuildItem(Predicate<DotName> predicate) {
this.predicate = predicate;
}
public Predicate<DotName> getPredicate() {
return predicate;
}
public static | ReflectiveHierarchyIgnoreWarningBuildItem |
java | quarkusio__quarkus | extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/QuarkusErrorHandler.java | {
"start": 18083,
"end": 18181
} | class ____ {
private static final String BASE_ID = UUID.randomUUID() + "-";
}
}
| LazyHolder |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/schedulers/SingleScheduler.java | {
"start": 1112,
"end": 5592
} | class ____ extends Scheduler {
final ThreadFactory threadFactory;
final AtomicReference<ScheduledExecutorService> executor = new AtomicReference<>();
/** The name of the system property for setting the thread priority for this Scheduler. */
private static final String KEY_SINGLE_PRIORITY = "rx3.single-priority";
private static final String THREAD_NAME_PREFIX = "RxSingleScheduler";
static final RxThreadFactory SINGLE_THREAD_FACTORY;
static final ScheduledExecutorService SHUTDOWN;
static {
SHUTDOWN = Executors.newScheduledThreadPool(0);
SHUTDOWN.shutdown();
int priority = Math.max(Thread.MIN_PRIORITY, Math.min(Thread.MAX_PRIORITY,
Integer.getInteger(KEY_SINGLE_PRIORITY, Thread.NORM_PRIORITY)));
SINGLE_THREAD_FACTORY = new RxThreadFactory(THREAD_NAME_PREFIX, priority, true);
}
public SingleScheduler() {
this(SINGLE_THREAD_FACTORY);
}
/**
* Constructs a SingleScheduler with the given ThreadFactory and prepares the
* single scheduler thread.
* @param threadFactory thread factory to use for creating worker threads. Note that this takes precedence over any
* system properties for configuring new thread creation. Cannot be null.
*/
public SingleScheduler(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
executor.lazySet(createExecutor(threadFactory));
}
static ScheduledExecutorService createExecutor(ThreadFactory threadFactory) {
return SchedulerPoolFactory.create(threadFactory);
}
@Override
public void start() {
ScheduledExecutorService next = null;
for (;;) {
ScheduledExecutorService current = executor.get();
if (current != SHUTDOWN) {
if (next != null) {
next.shutdown();
}
return;
}
if (next == null) {
next = createExecutor(threadFactory);
}
if (executor.compareAndSet(current, next)) {
return;
}
}
}
@Override
public void shutdown() {
ScheduledExecutorService current = executor.getAndSet(SHUTDOWN);
if (current != SHUTDOWN) {
current.shutdownNow();
}
}
@NonNull
@Override
public Worker createWorker() {
return new ScheduledWorker(executor.get());
}
@NonNull
@Override
public Disposable scheduleDirect(@NonNull Runnable run, long delay, TimeUnit unit) {
ScheduledDirectTask task = new ScheduledDirectTask(RxJavaPlugins.onSchedule(run), true);
try {
Future<?> f;
if (delay <= 0L) {
f = executor.get().submit(task);
} else {
f = executor.get().schedule(task, delay, unit);
}
task.setFuture(f);
return task;
} catch (RejectedExecutionException ex) {
RxJavaPlugins.onError(ex);
return EmptyDisposable.INSTANCE;
}
}
@NonNull
@Override
public Disposable schedulePeriodicallyDirect(@NonNull Runnable run, long initialDelay, long period, TimeUnit unit) {
final Runnable decoratedRun = RxJavaPlugins.onSchedule(run);
if (period <= 0L) {
ScheduledExecutorService exec = executor.get();
InstantPeriodicTask periodicWrapper = new InstantPeriodicTask(decoratedRun, exec);
Future<?> f;
try {
if (initialDelay <= 0L) {
f = exec.submit(periodicWrapper);
} else {
f = exec.schedule(periodicWrapper, initialDelay, unit);
}
periodicWrapper.setFirst(f);
} catch (RejectedExecutionException ex) {
RxJavaPlugins.onError(ex);
return EmptyDisposable.INSTANCE;
}
return periodicWrapper;
}
ScheduledDirectPeriodicTask task = new ScheduledDirectPeriodicTask(decoratedRun, true);
try {
Future<?> f = executor.get().scheduleAtFixedRate(task, initialDelay, period, unit);
task.setFuture(f);
return task;
} catch (RejectedExecutionException ex) {
RxJavaPlugins.onError(ex);
return EmptyDisposable.INSTANCE;
}
}
static final | SingleScheduler |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/accesscontrol/FieldSubsetReader.java | {
"start": 14871,
"end": 16221
} | class ____ extends StoredFieldsReader {
final StoredFieldsReader reader;
final IgnoredSourceFieldMapper.IgnoredSourceFormat ignoredSourceFormat;
FieldSubsetStoredFieldsReader(StoredFieldsReader reader, IgnoredSourceFieldMapper.IgnoredSourceFormat ignoredSourceFormat) {
this.reader = reader;
this.ignoredSourceFormat = ignoredSourceFormat;
}
@Override
public void document(int docID, StoredFieldVisitor visitor) throws IOException {
reader.document(docID, new FieldSubsetStoredFieldVisitor(visitor, ignoredSourceFormat));
}
@Override
public StoredFieldsReader clone() {
return new FieldSubsetStoredFieldsReader(reader.clone(), ignoredSourceFormat);
}
@Override
public StoredFieldsReader getMergeInstance() {
return new FieldSubsetStoredFieldsReader(reader.getMergeInstance(), ignoredSourceFormat);
}
@Override
public void checkIntegrity() throws IOException {
reader.checkIntegrity();
}
@Override
public void close() throws IOException {
reader.close();
}
}
/**
* A field visitor that filters out stored fields and source fields that should not be visible.
*/
| FieldSubsetStoredFieldsReader |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/file/FileBeginFailureOneTimeTest.java | {
"start": 1256,
"end": 2449
} | class ____ extends ContextTestSupport {
private static final String TEST_FILE_NAME = "hello" + UUID.randomUUID() + ".txt";
private final MyStrategy myStrategy = new MyStrategy();
@Override
protected Registry createCamelRegistry() throws Exception {
Registry jndi = super.createCamelRegistry();
jndi.bind("myStrategy", myStrategy);
return jndi;
}
@Test
public void testBeginFailureOneTime() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
template.sendBodyAndHeader(fileUri(), "Hello World", Exchange.FILE_NAME, TEST_FILE_NAME);
assertMockEndpointsSatisfied();
assertEquals(2, myStrategy.getInvoked(), "Begin should have been invoked 2 times");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from(fileUri("?initialDelay=0&delay=10&processStrategy=#myStrategy")).convertBodyTo(String.class)
.to("mock:result");
}
};
}
private static | FileBeginFailureOneTimeTest |
java | quarkusio__quarkus | integration-tests/security-webauthn/src/main/java/io/quarkus/it/security/webauthn/LoginResource.java | {
"start": 679,
"end": 4261
} | class ____ {
@Inject
WebAuthnSecurity webAuthnSecurity;
@Path("/login")
@POST
@WithTransaction
public Uni<Response> login(@RestForm String username,
@BeanParam WebAuthnLoginResponse webAuthnResponse,
RoutingContext ctx) {
// Input validation
if (username == null || username.isEmpty()
|| !webAuthnResponse.isSet()
|| !webAuthnResponse.isValid()) {
return Uni.createFrom().item(Response.status(Status.BAD_REQUEST).build());
}
Uni<User> userUni = User.findByUsername(username);
return userUni.flatMap(user -> {
if (user == null) {
// Invalid user
return Uni.createFrom().item(Response.status(Status.BAD_REQUEST).build());
}
Uni<WebAuthnCredentialRecord> authenticator = this.webAuthnSecurity.login(webAuthnResponse, ctx);
return authenticator
// bump the auth counter
.invoke(auth -> user.webAuthnCredential.counter = auth.getCounter())
.map(auth -> {
// make a login cookie
this.webAuthnSecurity.rememberUser(auth.getUsername(), ctx);
return Response.ok().build();
})
// handle login failure
.onFailure().recoverWithItem(x -> {
x.printStackTrace();
// make a proper error response
return Response.status(Status.BAD_REQUEST).build();
});
});
}
@Path("/register")
@POST
@WithTransaction
public Uni<Response> register(@RestForm String username,
@BeanParam WebAuthnRegisterResponse webAuthnResponse,
RoutingContext ctx) {
// Input validation
if (username == null || username.isEmpty()
|| !webAuthnResponse.isSet()
|| !webAuthnResponse.isValid()) {
return Uni.createFrom().item(Response.status(Status.BAD_REQUEST).build());
}
Uni<User> userUni = User.findByUsername(username);
return userUni.flatMap(user -> {
if (user != null) {
// Duplicate user
return Uni.createFrom().item(Response.status(Status.BAD_REQUEST).build());
}
Uni<WebAuthnCredentialRecord> authenticator = this.webAuthnSecurity.register(username, webAuthnResponse, ctx);
return authenticator
// store the user
.flatMap(auth -> {
User newUser = new User();
newUser.username = auth.getUsername();
WebAuthnCredential credential = new WebAuthnCredential(auth, newUser);
return credential.persist()
.flatMap(c -> newUser.<User> persist());
})
.map(newUser -> {
// make a login cookie
this.webAuthnSecurity.rememberUser(newUser.username, ctx);
return Response.ok().build();
})
// handle login failure
.onFailure().recoverWithItem(x -> {
// make a proper error response
x.printStackTrace();
return Response.status(Status.BAD_REQUEST).build();
});
});
}
}
| LoginResource |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RequestMapping.java | {
"start": 2145,
"end": 13578
} | class ____ implements Condition<RequestMapping, HttpRequest> {
private final String name;
private final String sig;
private final PathCondition pathCondition;
private final MethodsCondition methodsCondition;
private final ParamsCondition paramsCondition;
private final HeadersCondition headersCondition;
private final ConsumesCondition consumesCondition;
private final ProducesCondition producesCondition;
private final ConditionWrapper customCondition;
private final CorsMeta cors;
private final ResponseMeta response;
private int hashCode;
private RequestMapping(
String name,
String sig,
PathCondition pathCondition,
MethodsCondition methodsCondition,
ParamsCondition paramsCondition,
HeadersCondition headersCondition,
ConsumesCondition consumesCondition,
ProducesCondition producesCondition,
ConditionWrapper customCondition,
CorsMeta cors,
ResponseMeta response) {
this.name = name;
this.sig = sig;
this.pathCondition = pathCondition;
this.methodsCondition = methodsCondition;
this.paramsCondition = paramsCondition;
this.headersCondition = headersCondition;
this.consumesCondition = consumesCondition;
this.producesCondition = producesCondition;
this.customCondition = customCondition;
this.cors = cors;
this.response = response;
}
public static Builder builder() {
return new Builder();
}
@Override
public RequestMapping combine(RequestMapping other) {
return new RequestMapping(
combineName(name, other.name, other.sig),
other.sig,
combine(pathCondition, other.pathCondition),
combine(methodsCondition, other.methodsCondition),
combine(paramsCondition, other.paramsCondition),
combine(headersCondition, other.headersCondition),
combine(consumesCondition, other.consumesCondition),
combine(producesCondition, other.producesCondition),
combine(customCondition, other.customCondition),
CorsMeta.combine(cors, other.cors),
ResponseMeta.combine(response, other.response));
}
private String combineName(String name, String otherName, String otherSig) {
if (name == null) {
name = otherName;
} else if (otherName != null) {
name += '#' + otherName;
}
return otherSig == null ? name : name + '~' + otherSig;
}
private <T extends Condition<T, HttpRequest>> T combine(T source, T other) {
return source == null ? other : other == null ? source : source.combine(other);
}
public RequestMapping match(HttpRequest request, PathExpression path) {
return doMatch(request, new PathCondition(path));
}
public boolean matchMethod(String method) {
return methodsCondition == null || methodsCondition.getMethods().contains(method);
}
public boolean matchParams(HttpRequest request) {
return paramsCondition == null || paramsCondition.match(request) != null;
}
public boolean matchConsumes(HttpRequest request) {
return consumesCondition == null || consumesCondition.match(request) != null;
}
public boolean matchProduces(HttpRequest request) {
return producesCondition == null || producesCondition.match(request) != null;
}
@Override
public RequestMapping match(HttpRequest request) {
return doMatch(request, null);
}
private RequestMapping doMatch(HttpRequest request, PathCondition pathCondition) {
MethodsCondition methods = null;
if (methodsCondition != null) {
methods = methodsCondition.match(request);
if (methods == null) {
return null;
}
}
PathCondition paths = pathCondition;
if (paths == null && this.pathCondition != null) {
paths = this.pathCondition.match(request);
if (paths == null) {
return null;
}
}
ParamsCondition params = null;
if (paramsCondition != null) {
params = paramsCondition.match(request);
if (params == null) {
return null;
}
}
HeadersCondition headers = null;
if (headersCondition != null) {
headers = headersCondition.match(request);
if (headers == null) {
return null;
}
}
ConsumesCondition consumes = null;
if (consumesCondition != null) {
consumes = consumesCondition.match(request);
if (consumes == null) {
return null;
}
}
ProducesCondition produces = null;
if (producesCondition != null) {
produces = producesCondition.match(request);
if (produces == null) {
return null;
}
}
ConditionWrapper custom = null;
if (customCondition != null) {
custom = customCondition.match(request);
if (custom == null) {
return null;
}
}
if (StringUtils.isNotEmpty(sig)) {
String rSig = request.attribute(RestConstants.SIG_ATTRIBUTE);
if (rSig != null && !rSig.equals(sig)) {
return null;
}
}
return new RequestMapping(
name, sig, paths, methods, params, headers, consumes, produces, custom, cors, response);
}
public String getName() {
return name;
}
public String getSig() {
return sig;
}
public PathCondition getPathCondition() {
return pathCondition;
}
public MethodsCondition getMethodsCondition() {
return methodsCondition;
}
public ParamsCondition getParamsCondition() {
return paramsCondition;
}
public HeadersCondition getHeadersCondition() {
return headersCondition;
}
public ConsumesCondition getConsumesCondition() {
return consumesCondition;
}
public ProducesCondition getProducesCondition() {
return producesCondition;
}
public ConditionWrapper getCustomCondition() {
return customCondition;
}
public CorsMeta getCors() {
return cors;
}
public ResponseMeta getResponse() {
return response;
}
@Override
public int compareTo(RequestMapping other, HttpRequest request) {
int result;
if (methodsCondition != null && HttpMethods.HEAD.name().equals(request.method())) {
result = methodsCondition.compareTo(other.methodsCondition, request);
if (result != 0) {
return result;
}
}
if (pathCondition != null) {
result = pathCondition.compareTo(other.pathCondition, request);
if (result != 0) {
return result;
}
}
if (paramsCondition != null) {
result = paramsCondition.compareTo(other.paramsCondition, request);
if (result != 0) {
return result;
}
}
if (headersCondition != null) {
result = headersCondition.compareTo(other.headersCondition, request);
if (result != 0) {
return result;
}
}
if (consumesCondition != null) {
result = consumesCondition.compareTo(other.consumesCondition, request);
if (result != 0) {
return result;
}
}
if (producesCondition != null) {
result = producesCondition.compareTo(other.producesCondition, request);
if (result != 0) {
return result;
}
}
if (methodsCondition != null) {
result = methodsCondition.compareTo(other.methodsCondition, request);
if (result != 0) {
return result;
}
}
if (customCondition != null) {
result = customCondition.compareTo(other.customCondition, request);
if (result != 0) {
return result;
}
}
if (sig != null && other.sig != null) {
int size = request.queryParameters().size();
int size1 = sig.length();
int size2 = other.sig.length();
if (size1 == size) {
if (size2 != size) {
return -1;
}
} else if (size2 == size) {
return 1;
}
}
return 0;
}
@Override
public int hashCode() {
int hashCode = this.hashCode;
if (hashCode == 0) {
hashCode = Objects.hash(
pathCondition,
methodsCondition,
paramsCondition,
headersCondition,
consumesCondition,
producesCondition,
customCondition,
sig);
this.hashCode = hashCode;
}
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != RequestMapping.class) {
return false;
}
RequestMapping other = (RequestMapping) obj;
return Objects.equals(pathCondition, other.pathCondition)
&& Objects.equals(methodsCondition, other.methodsCondition)
&& Objects.equals(paramsCondition, other.paramsCondition)
&& Objects.equals(headersCondition, other.headersCondition)
&& Objects.equals(consumesCondition, other.consumesCondition)
&& Objects.equals(producesCondition, other.producesCondition)
&& Objects.equals(customCondition, other.customCondition)
&& Objects.equals(sig, other.sig);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("RequestMapping{name='");
sb.append(name).append('\'');
if (pathCondition != null) {
sb.append(", path=").append(pathCondition);
}
if (methodsCondition != null) {
sb.append(", methods=").append(methodsCondition);
}
if (paramsCondition != null) {
sb.append(", params=").append(paramsCondition);
}
if (headersCondition != null) {
sb.append(", headers=").append(headersCondition);
}
if (consumesCondition != null) {
sb.append(", consumes=").append(consumesCondition);
}
if (producesCondition != null) {
sb.append(", produces=").append(producesCondition);
}
if (customCondition != null) {
sb.append(", custom=").append(customCondition);
}
if (response != null) {
sb.append(", response=").append(response);
}
if (cors != null) {
sb.append(", cors=").append(cors);
}
sb.append('}');
return sb.toString();
}
public static final | RequestMapping |
java | apache__camel | components/camel-vertx/camel-vertx-common/src/main/java/org/apache/camel/component/vertx/common/KeyManagerFactoryOptions.java | {
"start": 1045,
"end": 1929
} | class ____ implements KeyCertOptions {
private final KeyManagerFactory keyManagerFactory;
public KeyManagerFactoryOptions(KeyManagerFactory keyManagerFactory) {
this.keyManagerFactory = keyManagerFactory;
}
private KeyManagerFactoryOptions(KeyManagerFactoryOptions other) {
this.keyManagerFactory = other.keyManagerFactory;
}
@Override
public KeyCertOptions copy() {
return new KeyManagerFactoryOptions(this);
}
@Override
public KeyManagerFactory getKeyManagerFactory(Vertx vertx) {
return keyManagerFactory;
}
@Override
public Function<String, X509KeyManager> keyManagerMapper(Vertx vertx) {
return keyManagerFactory.getKeyManagers()[0] instanceof X509KeyManager
? serverName -> (X509KeyManager) keyManagerFactory.getKeyManagers()[0] : null;
}
}
| KeyManagerFactoryOptions |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/util/GenericFieldInfoTest2.java | {
"start": 622,
"end": 683
} | class ____ <T> extends A2<List<T>> {
}
public static | A3 |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/AggregationReduceContext.java | {
"start": 5132,
"end": 6682
} | class ____ extends AggregationReduceContext {
private final IntConsumer multiBucketConsumer;
public ForPartial(
BigArrays bigArrays,
ScriptService scriptService,
Supplier<Boolean> isCanceled,
AggregatorFactories.Builder builders,
IntConsumer multiBucketConsumer
) {
super(bigArrays, scriptService, isCanceled, builders);
this.multiBucketConsumer = multiBucketConsumer;
}
public ForPartial(
BigArrays bigArrays,
ScriptService scriptService,
Supplier<Boolean> isCanceled,
AggregationBuilder builder,
IntConsumer multiBucketConsumer
) {
super(bigArrays, scriptService, isCanceled, builder);
this.multiBucketConsumer = multiBucketConsumer;
}
@Override
public boolean isFinalReduce() {
return false;
}
@Override
protected void consumeBucketCountAndMaybeBreak(int size) {
multiBucketConsumer.accept(size);
}
@Override
public PipelineTree pipelineTreeRoot() {
return null;
}
@Override
protected AggregationReduceContext forSubAgg(AggregationBuilder sub) {
return new ForPartial(bigArrays(), scriptService(), isCanceled(), sub, multiBucketConsumer);
}
}
/**
* A {@linkplain AggregationReduceContext} to perform the final reduction.
*/
public static final | ForPartial |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/external/response/streaming/NewlineDelimitedByteProcessorTests.java | {
"start": 1007,
"end": 4113
} | class ____ extends ESTestCase {
private Flow.Subscription upstream;
private Flow.Subscriber<Deque<String>> downstream;
private NewlineDelimitedByteProcessor processor;
@Before
public void setUp() throws Exception {
super.setUp();
upstream = mock();
downstream = mock();
processor = new NewlineDelimitedByteProcessor();
processor.onSubscribe(upstream);
processor.subscribe(downstream);
}
public void testEmptyBody() {
processor.next(result(null));
processor.onComplete();
verify(upstream, times(1)).request(1);
verify(downstream, times(0)).onNext(any());
}
private HttpResult result(String response) {
return new HttpResult(mock(), response == null ? new byte[0] : response.getBytes(StandardCharsets.UTF_8));
}
public void testEmptyParseResponse() {
processor.next(result(""));
verify(upstream, times(1)).request(1);
verify(downstream, times(0)).onNext(any());
}
public void testValidResponse() {
processor.next(result("{\"hello\":\"there\"}\n"));
verify(downstream, times(1)).onNext(assertArg(deque -> {
assertThat(deque, notNullValue());
assertThat(deque.size(), is(1));
assertThat(deque.getFirst(), is("{\"hello\":\"there\"}"));
}));
}
public void testMultipleValidResponse() {
processor.next(result("""
{"value": 1}
{"value": 2}
{"value": 3}
"""));
verify(upstream, times(0)).request(1);
verify(downstream, times(1)).onNext(assertArg(deque -> {
assertThat(deque, notNullValue());
assertThat(deque.size(), is(3));
var items = deque.iterator();
IntStream.range(1, 4).forEach(i -> {
assertThat(items.hasNext(), is(true));
assertThat(items.next(), containsString(String.valueOf(i)));
});
}));
}
public void testOnCompleteFlushesResponse() {
processor.next(result("""
{"value": 1}"""));
// onNext should not be called with only one value
verify(downstream, times(0)).onNext(any());
verify(downstream, times(0)).onComplete();
// onComplete should flush the value pending, and onNext should be called
processor.onComplete();
verify(downstream, times(1)).onNext(assertArg(deque -> {
assertThat(deque, notNullValue());
assertThat(deque.size(), is(1));
var item = deque.getFirst();
assertThat(item, containsString(String.valueOf(1)));
}));
verify(downstream, times(0)).onComplete();
// next time the downstream requests data, onComplete is called
var downstreamSubscription = ArgumentCaptor.forClass(Flow.Subscription.class);
verify(downstream).onSubscribe(downstreamSubscription.capture());
downstreamSubscription.getValue().request(1);
verify(downstream, times(1)).onComplete();
}
}
| NewlineDelimitedByteProcessorTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/property/access/spi/SetterMethodImpl.java | {
"start": 3289,
"end": 3653
} | class ____ extends AbstractSetterMethodSerialForm implements Serializable {
private SerialForm(Class<?> containerClass, String propertyName, Method method) {
super( containerClass, propertyName, method );
}
@Serial
private Object readResolve() {
return new SetterMethodImpl( getContainerClass(), getPropertyName(), resolveMethod() );
}
}
}
| SerialForm |
java | junit-team__junit5 | junit-platform-engine/src/main/java/org/junit/platform/engine/DiscoveryIssue.java | {
"start": 2599,
"end": 3209
} | enum ____ {
/**
* Indicates that the engine encountered something that could be
* potentially problematic, but could also happen due to a valid setup
* or configuration.
*/
INFO,
/**
* Indicates that the engine encountered something that is problematic
* and might lead to unexpected behavior or will be removed or changed
* in a future release.
*/
WARNING,
/**
* Indicates that the engine encountered something that is definitely
* problematic and will lead to unexpected behavior.
*/
ERROR
}
/**
* Builder for creating a {@code DiscoveryIssue}.
*/
| Severity |
java | greenrobot__EventBus | EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java | {
"start": 1297,
"end": 1397
} | class ____ kept, it is accessed via reflection.
* E.g. add a rule like
* <pre>
* -keepclassmembers | is |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/headers/UserAgentTest.java | {
"start": 2295,
"end": 2526
} | interface ____ {
@Path("/")
@GET
String callWithImplicitValue();
@Path("/")
@GET
String callWithExplicitValue(@HeaderParam("User-Agent") String userAgent);
}
}
| ClientWithAnnotation |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/output/ScoredValueScanOutput.java | {
"start": 398,
"end": 1161
} | class ____<K, V> extends ScanOutput<K, V, ScoredValueScanCursor<V>> {
private V value;
private boolean hasValue;
public ScoredValueScanOutput(RedisCodec<K, V> codec) {
super(codec, new ScoredValueScanCursor<V>());
}
@Override
protected void setOutput(ByteBuffer bytes) {
if (!hasValue) {
value = codec.decodeValue(bytes);
hasValue = true;
return;
}
double score = LettuceStrings.toDouble(decodeString(bytes));
set(score);
}
@Override
public void set(double number) {
if (hasValue) {
output.getValues().add(ScoredValue.just(number, value));
}
value = null;
hasValue = false;
}
}
| ScoredValueScanOutput |
java | quarkusio__quarkus | extensions/hibernate-search-standalone-elasticsearch/runtime/src/main/java/io/quarkus/hibernate/search/standalone/elasticsearch/runtime/management/HibernateSearchStandaloneManagementPostRequestProcessor.java | {
"start": 707,
"end": 4537
} | class ____ {
private static final String QUERY_PARAM_WAIT_FOR = "wait_for";
public void process(RoutingContext ctx) {
JsonObject config = ctx.body().asJsonObject();
if (config == null) {
config = new JsonObject();
}
try (InstanceHandle<SearchMapping> searchMappingInstanceHandle = Arc.container().instance(SearchMapping.class)) {
SearchMapping searchMapping = searchMappingInstanceHandle.get();
JsonObject filter = config.getJsonObject("filter");
List<String> types = getTypesToFilter(filter);
Set<String> tenants = getTenants(filter);
MassIndexer massIndexer;
if (types == null || types.isEmpty()) {
massIndexer = createMassIndexer(searchMapping.scope(Object.class), tenants);
} else {
massIndexer = createMassIndexer(searchMapping.scope(Object.class, types), tenants);
}
HibernateSearchMassIndexerConfiguration.configure(massIndexer, config.getJsonObject("massIndexer"));
CompletionStage<?> massIndexerFuture = massIndexer.start();
if (WaitFor.STARTED.equals(getWaitForParameter(ctx.request()))) {
ctx.response().end(message(202, "Reindexing started"));
} else {
ctx.response()
.setChunked(true)
.write(message(202, "Reindexing started"),
ignored -> massIndexerFuture.whenComplete((ignored2, throwable) -> {
if (throwable == null) {
ctx.response().end(message(200, "Reindexing succeeded"));
} else {
ctx.response().end(message(
500,
"Reindexing failed:\n" + Arrays.stream(throwable.getStackTrace())
.map(Object::toString)
.collect(Collectors.joining("\n"))));
}
}));
}
}
}
private MassIndexer createMassIndexer(SearchScope<Object> scope, Set<String> tenants) {
if (tenants == null || tenants.isEmpty()) {
return scope.massIndexer();
} else {
return scope.massIndexer(tenants);
}
}
private List<String> getTypesToFilter(JsonObject filter) {
if (filter == null) {
return null;
}
JsonArray array = filter.getJsonArray("types");
if (array == null) {
return null;
}
List<String> types = array
.stream()
.map(Object::toString)
.collect(Collectors.toList());
return types.isEmpty() ? null : types;
}
private Set<String> getTenants(JsonObject filter) {
if (filter == null) {
return null;
}
JsonArray array = filter.getJsonArray("tenants");
if (array == null) {
return null;
}
Set<String> types = array
.stream()
.map(Object::toString)
.collect(Collectors.toSet());
return types.isEmpty() ? null : types;
}
private WaitFor getWaitForParameter(HttpServerRequest request) {
return WaitFor.valueOf(request.getParam(QUERY_PARAM_WAIT_FOR, WaitFor.STARTED.name()).toUpperCase(Locale.ROOT));
}
private static String message(int code, String message) {
return JsonObject.of("code", code, "message", message) + "\n";
}
private | HibernateSearchStandaloneManagementPostRequestProcessor |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/metrics/util/MetricUtilsTest.java | {
"start": 18574,
"end": 19641
} | class ____ implements GarbageCollectorMXBean {
final String name;
final long collectionCount;
final long collectionTime;
public TestGcBean(String name, long collectionCount, long collectionTime) {
this.name = name;
this.collectionCount = collectionCount;
this.collectionTime = collectionTime;
}
@Override
public long getCollectionCount() {
return collectionCount;
}
@Override
public long getCollectionTime() {
return collectionTime;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isValid() {
throw new UnsupportedOperationException();
}
@Override
public String[] getMemoryPoolNames() {
throw new UnsupportedOperationException();
}
@Override
public ObjectName getObjectName() {
throw new UnsupportedOperationException();
}
}
}
| TestGcBean |
java | alibaba__nacos | core/src/main/java/com/alibaba/nacos/core/paramcheck/AbstractHttpParamExtractor.java | {
"start": 927,
"end": 1292
} | class ____ implements ParamExtractor<HttpServletRequest, ParamInfo> {
/**
* Extract param.
*
* @param request the request
* @return the list
* @throws NacosException the exception
*/
@Override
public abstract List<ParamInfo> extractParam(HttpServletRequest request) throws NacosException;
}
| AbstractHttpParamExtractor |
java | apache__camel | core/camel-core-processor/src/main/java/org/apache/camel/processor/DefaultClaimCheckRepository.java | {
"start": 1131,
"end": 2213
} | class ____ implements ClaimCheckRepository {
private final Map<String, Exchange> map = new HashMap<>();
private final Deque<Exchange> stack = new ArrayDeque<>();
@Override
public boolean add(String key, Exchange exchange) {
return map.put(key, exchange) == null;
}
@Override
public boolean contains(String key) {
return map.containsKey(key);
}
@Override
public Exchange get(String key) {
return map.get(key);
}
@Override
public Exchange getAndRemove(String key) {
return map.remove(key);
}
@Override
public void push(Exchange exchange) {
stack.push(exchange);
}
@Override
public Exchange pop() {
if (!stack.isEmpty()) {
return stack.pop();
} else {
return null;
}
}
@Override
public void clear() {
map.clear();
stack.clear();
}
@Override
public void start() {
// noop
}
@Override
public void stop() {
// noop
}
}
| DefaultClaimCheckRepository |
java | elastic__elasticsearch | x-pack/plugin/sql/sql-action/src/main/java/org/elasticsearch/xpack/sql/action/AbstractSqlRequest.java | {
"start": 1012,
"end": 3445
} | class ____ extends LegacyActionRequest {
private RequestInfo requestInfo;
protected AbstractSqlRequest() {
this.requestInfo = new RequestInfo(Mode.PLAIN);
}
protected AbstractSqlRequest(RequestInfo requestInfo) {
this.requestInfo = requestInfo;
}
protected AbstractSqlRequest(StreamInput in) throws IOException {
super(in);
Mode mode = in.readEnum(Mode.class);
String clientId = in.readOptionalString();
String clientVersion = in.readOptionalString();
requestInfo = new RequestInfo(mode, clientId, clientVersion);
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (requestInfo == null || requestInfo.mode() == null) {
validationException = addValidationError("[mode] is required", validationException);
}
return validationException;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeEnum(requestInfo.mode());
out.writeOptionalString(requestInfo.clientId());
out.writeOptionalString(requestInfo.version() == null ? null : requestInfo.version().toString());
}
public RequestInfo requestInfo() {
return requestInfo;
}
public void requestInfo(RequestInfo requestInfo) {
this.requestInfo = requestInfo;
}
public Mode mode() {
return requestInfo.mode();
}
public void mode(Mode mode) {
this.requestInfo.mode(mode);
}
public void mode(String mode) {
this.requestInfo.mode(Mode.fromString(mode));
}
public String clientId() {
return requestInfo.clientId();
}
public void clientId(String clientId) {
this.requestInfo.clientId(clientId);
}
public void version(String clientVersion) {
requestInfo.version(clientVersion);
}
public SqlVersion version() {
return requestInfo.version();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractSqlRequest that = (AbstractSqlRequest) o;
return Objects.equals(requestInfo, that.requestInfo);
}
@Override
public int hashCode() {
return requestInfo.hashCode();
}
}
| AbstractSqlRequest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/metadata/IndexAbstraction.java | {
"start": 7463,
"end": 12974
} | class ____ implements IndexAbstraction {
private final String aliasName;
private final List<Index> referenceIndices;
private final Index writeIndex;
private final boolean isHidden;
private final boolean isSystem;
private final boolean dataStreamAlias;
private final List<String> dataStreams;
public Alias(AliasMetadata aliasMetadata, List<IndexMetadata> indexMetadatas) {
// note: don't capture a reference to any of these indexMetadata here
this.aliasName = aliasMetadata.getAlias();
this.referenceIndices = new ArrayList<>(indexMetadatas.size());
boolean isSystem = true;
Index widx = null;
for (IndexMetadata imd : indexMetadatas) {
this.referenceIndices.add(imd.getIndex());
if (Boolean.TRUE.equals(imd.getAliases().get(aliasName).writeIndex())) {
if (widx != null) {
throw new IllegalStateException("write indices size can only be 0 or 1, but is at least 2");
}
widx = imd.getIndex();
}
isSystem = isSystem && imd.isSystem();
}
this.referenceIndices.sort(Index.COMPARE_BY_NAME);
if (widx == null && indexMetadatas.size() == 1 && indexMetadatas.get(0).getAliases().get(aliasName).writeIndex() == null) {
widx = indexMetadatas.get(0).getIndex();
}
this.writeIndex = widx;
this.isHidden = aliasMetadata.isHidden() == null ? false : aliasMetadata.isHidden();
this.isSystem = isSystem;
dataStreamAlias = false;
dataStreams = List.of();
}
public Alias(
DataStreamAlias dataStreamAlias,
List<Index> indicesOfAllDataStreams,
Index writeIndexOfWriteDataStream,
List<String> dataStreams
) {
this.aliasName = dataStreamAlias.getName();
this.referenceIndices = indicesOfAllDataStreams;
this.writeIndex = writeIndexOfWriteDataStream;
this.isHidden = false;
this.isSystem = false;
this.dataStreamAlias = true;
this.dataStreams = dataStreams;
}
@Override
public Type getType() {
return Type.ALIAS;
}
public String getName() {
return aliasName;
}
@Override
public List<Index> getIndices() {
return referenceIndices;
}
@Override
public List<Index> getFailureIndices(ProjectMetadata metadata) {
if (isDataStreamRelated() == false) {
return List.of();
}
assert metadata != null : "metadata must not be null to be able to retrieve the failure indices";
List<Index> failureIndices = new ArrayList<>();
for (String dataStreamName : dataStreams) {
DataStream dataStream = metadata.dataStreams().get(dataStreamName);
if (dataStream != null && dataStream.getFailureIndices().isEmpty() == false) {
failureIndices.addAll(dataStream.getFailureIndices());
}
}
return failureIndices;
}
@Nullable
public Index getWriteIndex() {
return writeIndex;
}
@Nullable
@Override
public Index getWriteFailureIndex(ProjectMetadata metadata) {
if (isDataStreamRelated() == false || writeIndex == null) {
return null;
}
assert metadata != null : "metadata must not be null to be able to retrieve the failure indices";
DataStream dataStream = metadata.getIndicesLookup().get(writeIndex.getName()).getParentDataStream();
return dataStream == null ? null : dataStream.getWriteFailureIndex();
}
@Override
public Index getWriteIndex(IndexRequest request, ProjectMetadata project) {
if (dataStreamAlias == false) {
return getWriteIndex();
}
return project.getIndicesLookup().get(getWriteIndex().getName()).getParentDataStream().getWriteIndex(request, project);
}
@Override
public DataStream getParentDataStream() {
// aliases may not be part of a data stream
return null;
}
@Override
public boolean isHidden() {
return isHidden;
}
@Override
public boolean isSystem() {
return isSystem;
}
@Override
public boolean isDataStreamRelated() {
return dataStreamAlias;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Alias alias = (Alias) o;
return isHidden == alias.isHidden
&& isSystem == alias.isSystem
&& dataStreamAlias == alias.dataStreamAlias
&& aliasName.equals(alias.aliasName)
&& referenceIndices.equals(alias.referenceIndices)
&& Objects.equals(writeIndex, alias.writeIndex);
}
@Override
public int hashCode() {
return Objects.hash(aliasName, referenceIndices, writeIndex, isHidden, isSystem, dataStreamAlias);
}
}
}
| Alias |
java | quarkusio__quarkus | extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/RequestURLAttribute.java | {
"start": 1277,
"end": 1951
} | class ____ implements ExchangeAttributeBuilder {
@Override
public String name() {
return "Request URL";
}
@Override
public ExchangeAttribute build(final String token) {
if (token.equals(REQUEST_URL) || token.equals(REQUEST_URL_SHORT)) {
return RequestURLAttribute.INSTANCE;
} else if (token.equals(ORIGINAL_REQUEST_URL) || token.equals(ORIGINAL_REQUEST_URL_SHORT)) {
return RequestURLAttribute.INSTANCE_ORIGINAL_REQUEST;
}
return null;
}
@Override
public int priority() {
return 0;
}
}
}
| Builder |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/file/FileSystemOptions.java | {
"start": 4060,
"end": 5164
} | class ____ resolving.
*
* @param fileCachingEnabled the value
* @return a reference to this, so the API can be used fluently
*/
public FileSystemOptions setFileCachingEnabled(boolean fileCachingEnabled) {
this.fileCachingEnabled = fileCachingEnabled;
return this;
}
/**
* @return the configured file cache dir
*/
public String getFileCacheDir() {
return this.fileCacheDir;
}
/**
* When vert.x reads a file that is packaged with the application it gets
* extracted to this directory first and subsequent reads will use the extracted
* file to get better IO performance.
*
* @param fileCacheDir the value
* @return a reference to this, so the API can be used fluently
*/
public FileSystemOptions setFileCacheDir(String fileCacheDir) {
this.fileCacheDir = fileCacheDir;
return this;
}
@Override
public String toString() {
return "FileSystemOptions{" +
"classPathResolvingEnabled=" + classPathResolvingEnabled +
", fileCachingEnabled=" + fileCachingEnabled +
", fileCacheDir=" + fileCacheDir +
'}';
}
}
| path |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/CodeTemplates.java | {
"start": 21532,
"end": 21695
} | interface ____ {
}
// mapping to get private field from superclass by calling the enhanced reader, for use when field is not visible
static | BidirectionalAttribute |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Issue1017.java | {
"start": 875,
"end": 1193
} | class ____ implements Serializable {
private List<String> pictureList;
public List<String> getPictureList() {
return pictureList;
}
public User setPictureList(List<String> pictureList) {
this.pictureList = pictureList;
return this;
}
}
}
| User |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/deser/JSONFieldSetterTest.java | {
"start": 214,
"end": 444
} | class ____ extends TestCase {
public void test_for_setter() throws Exception {
Model model = JSON.parseObject("{\"id\":123}", Model.class);
assertEquals(123, model._id);
}
public static | JSONFieldSetterTest |
java | spring-projects__spring-boot | smoke-test/spring-boot-smoke-test-kafka/src/test/java/smoketest/kafka/SampleKafkaApplicationTests.java | {
"start": 1456,
"end": 1777
} | class ____ {
@Autowired
private Consumer consumer;
@Test
void testVanillaExchange() {
Awaitility.waitAtMost(Duration.ofSeconds(30)).until(this.consumer::getMessages, not(empty()));
assertThat(this.consumer.getMessages()).extracting("message").containsOnly("A simple test message");
}
}
| SampleKafkaApplicationTests |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/cluster/metadata/IndexWriteLoadTests.java | {
"start": 921,
"end": 5962
} | class ____ extends ESTestCase {
public void testGetWriteLoadForShardAndGetUptimeInMillisForShard() {
final int numberOfPopulatedShards = 10;
final int numberOfShards = randomIntBetween(numberOfPopulatedShards, 20);
final IndexWriteLoad.Builder indexWriteLoadBuilder = IndexWriteLoad.builder(numberOfShards);
final double[] populatedShardWriteLoads = new double[numberOfPopulatedShards];
final double[] populatedShardRecentWriteLoads = new double[numberOfPopulatedShards];
final double[] populatedShardPeakWriteLoads = new double[numberOfPopulatedShards];
final long[] populatedShardUptimes = new long[numberOfPopulatedShards];
for (int shardId = 0; shardId < numberOfPopulatedShards; shardId++) {
double writeLoad = randomDoubleBetween(1, 128, true);
double recentWriteLoad = randomDoubleBetween(1, 128, true);
double peakWriteLoad = randomDoubleBetween(1, 128, true);
long uptimeInMillis = randomNonNegativeLong();
populatedShardWriteLoads[shardId] = writeLoad;
populatedShardRecentWriteLoads[shardId] = recentWriteLoad;
populatedShardPeakWriteLoads[shardId] = peakWriteLoad;
populatedShardUptimes[shardId] = uptimeInMillis;
indexWriteLoadBuilder.withShardWriteLoad(shardId, writeLoad, recentWriteLoad, peakWriteLoad, uptimeInMillis);
}
final IndexWriteLoad indexWriteLoad = indexWriteLoadBuilder.build();
for (int shardId = 0; shardId < numberOfShards; shardId++) {
if (shardId < numberOfPopulatedShards) {
assertThat(indexWriteLoad.getWriteLoadForShard(shardId), equalTo(OptionalDouble.of(populatedShardWriteLoads[shardId])));
assertThat(
indexWriteLoad.getRecentWriteLoadForShard(shardId),
equalTo(OptionalDouble.of(populatedShardRecentWriteLoads[shardId]))
);
assertThat(
indexWriteLoad.getPeakWriteLoadForShard(shardId),
equalTo(OptionalDouble.of(populatedShardPeakWriteLoads[shardId]))
);
assertThat(indexWriteLoad.getUptimeInMillisForShard(shardId), equalTo(OptionalLong.of(populatedShardUptimes[shardId])));
} else {
assertThat(indexWriteLoad.getWriteLoadForShard(shardId), equalTo(OptionalDouble.empty()));
assertThat(indexWriteLoad.getRecentWriteLoadForShard(shardId), equalTo(OptionalDouble.empty()));
assertThat(indexWriteLoad.getUptimeInMillisForShard(shardId), equalTo(OptionalLong.empty()));
}
}
}
public void testXContent_roundTrips() throws IOException {
IndexWriteLoad original = randomIndexWriteLoad();
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().value(original).endObject();
IndexWriteLoad roundTripped = IndexWriteLoad.fromXContent(createParser(xContentBuilder));
assertThat(roundTripped, equalTo(original));
}
public void testXContent_missingRecentWriteAndPeakLoad() throws IOException {
// Simulate a JSON serialization from before we added recent write load:
IndexWriteLoad original = randomIndexWriteLoad();
XContentBuilder builder = XContentBuilder.builder(
XContentType.JSON,
emptySet(),
Set.of(
IndexWriteLoad.SHARDS_RECENT_WRITE_LOAD_FIELD.getPreferredName(),
IndexWriteLoad.SHARDS_PEAK_WRITE_LOAD_FIELD.getPreferredName()
)
).startObject().value(original).endObject();
// Deserialize, and assert that it matches the original except the recent write loads are all missing:
IndexWriteLoad roundTripped = IndexWriteLoad.fromXContent(createParser(builder));
for (int i = 0; i < original.numberOfShards(); i++) {
assertThat(roundTripped.getUptimeInMillisForShard(i), equalTo(original.getUptimeInMillisForShard(i)));
assertThat(roundTripped.getWriteLoadForShard(i), equalTo(original.getWriteLoadForShard(i)));
assertThat(roundTripped.getRecentWriteLoadForShard(i), equalTo(OptionalDouble.empty()));
assertThat(roundTripped.getPeakWriteLoadForShard(i), equalTo(OptionalDouble.empty()));
}
}
private static IndexWriteLoad randomIndexWriteLoad() {
int numberOfPopulatedShards = 10;
int numberOfShards = randomIntBetween(numberOfPopulatedShards, 20);
IndexWriteLoad.Builder builder = IndexWriteLoad.builder(numberOfShards);
for (int shardId = 0; shardId < numberOfPopulatedShards; shardId++) {
builder.withShardWriteLoad(
shardId,
randomDoubleBetween(1, 128, true),
randomDoubleBetween(1, 128, true),
randomDoubleBetween(1, 128, true),
randomNonNegativeLong()
);
}
return builder.build();
}
}
| IndexWriteLoadTests |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/producer/ProducerWithParameterizedInterceptedMethodsTest.java | {
"start": 2384,
"end": 3114
} | class ____ {
private final String value;
MyNonbean() {
this(null);
}
MyNonbean(String value) {
this.value = value;
}
@MyBinding2
String hello1(int i) {
return "hello1_" + i + "_" + value;
}
String hello2(int i, int j) {
return "hello2_" + i + "_" + j + "_" + value;
}
@NoClassInterceptors
@MyBinding2
String hello3(int i, int j, int k) {
return "hello3_" + i + "_" + j + "_" + k + "_" + value;
}
@NoClassInterceptors
String hello4(int i) {
return "hello4_" + i + "_" + value;
}
}
@Dependent
static | MyNonbean |
java | apache__hadoop | hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/WorkReport.java | {
"start": 915,
"end": 1060
} | class ____ and its
* corresponding retry counter that indicates how many times this item
* was previously attempted to be processed.
*/
public | T |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java | {
"start": 1531,
"end": 8385
} | class ____ {
private static final String MESSAGE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSSSS";
private static final DateTimeFormatter MESSAGE_DATE_FORMATTER = DateTimeFormatter.ofPattern(MESSAGE_DATE_FORMAT);
private static final String VERSION = "version";
private static final String GROUP = "group";
private static final String SERVICE = "service";
private static final String METHOD_NAME = "method-name";
private static final String INVOCATION_TIME = "invocation-time";
private static final String OUT_TIME = "out-time";
private static final String TYPES = "types";
private static final String ARGUMENTS = "arguments";
private static final String REMOTE_HOST = "remote-host";
private static final String REMOTE_PORT = "remote-port";
private static final String LOCAL_HOST = "localhost";
private static final String LOCAL_PORT = "local-port";
/**
* This is used to store log data in key val format.
*/
private final Map<String, Object> data;
/**
* Default constructor.
*/
private AccessLogData() {
RpcContext context = RpcContext.getServiceContext();
data = new HashMap<>();
setLocalHost(context.getLocalHost());
setLocalPort(context.getLocalPort());
setRemoteHost(context.getRemoteHost());
setRemotePort(context.getRemotePort());
}
/**
* Get new instance of log data.
*
* @return instance of AccessLogData
*/
public static AccessLogData newLogData() {
return new AccessLogData();
}
/**
* Add version information.
*
* @param version
*/
public void setVersion(String version) {
set(VERSION, version);
}
/**
* Add service name.
*
* @param serviceName
*/
public void setServiceName(String serviceName) {
set(SERVICE, serviceName);
}
/**
* Add group name
*
* @param group
*/
public void setGroup(String group) {
set(GROUP, group);
}
/**
* Set the invocation date. As an argument it accept date string.
*
* @param invocationTime
*/
public void setInvocationTime(Date invocationTime) {
set(INVOCATION_TIME, invocationTime);
}
/**
* Set the out date. As an argument it accept date string.
*
* @param outTime
*/
public void setOutTime(Date outTime) {
set(OUT_TIME, outTime);
}
/**
* Set caller remote host
*
* @param remoteHost
*/
private void setRemoteHost(String remoteHost) {
set(REMOTE_HOST, remoteHost);
}
/**
* Set caller remote port.
*
* @param remotePort
*/
private void setRemotePort(Integer remotePort) {
set(REMOTE_PORT, remotePort);
}
/**
* Set local host
*
* @param localHost
*/
private void setLocalHost(String localHost) {
set(LOCAL_HOST, localHost);
}
/**
* Set local port of exported service
*
* @param localPort
*/
private void setLocalPort(Integer localPort) {
set(LOCAL_PORT, localPort);
}
/**
* Set target method name.
*
* @param methodName
*/
public void setMethodName(String methodName) {
set(METHOD_NAME, methodName);
}
/**
* Set invocation's method's input parameter's types
*
* @param types
*/
public void setTypes(Class[] types) {
set(TYPES, types != null ? Arrays.copyOf(types, types.length) : null);
}
/**
* Sets invocation arguments
*
* @param arguments
*/
public void setArguments(Object[] arguments) {
set(ARGUMENTS, arguments != null ? Arrays.copyOf(arguments, arguments.length) : null);
}
/**
* Return gthe service of access log entry
*
* @return
*/
public String getServiceName() {
return get(SERVICE).toString();
}
public String getLogMessage() {
StringBuilder sn = new StringBuilder();
sn.append("[")
.append(LocalDateTime.ofInstant(getInvocationTime().toInstant(), ZoneId.systemDefault())
.format(MESSAGE_DATE_FORMATTER))
.append("] ")
.append("-> ")
.append("[")
.append(LocalDateTime.ofInstant(getOutTime().toInstant(), ZoneId.systemDefault())
.format(MESSAGE_DATE_FORMATTER))
.append("] ")
.append(get(REMOTE_HOST))
.append(':')
.append(get(REMOTE_PORT))
.append(" -> ")
.append(get(LOCAL_HOST))
.append(':')
.append(get(LOCAL_PORT))
.append(" - ");
String group = get(GROUP) != null ? get(GROUP).toString() : "";
if (StringUtils.isNotEmpty(group)) {
sn.append(group).append('/');
}
sn.append(get(SERVICE));
String version = get(VERSION) != null ? get(VERSION).toString() : "";
if (StringUtils.isNotEmpty(version)) {
sn.append(':').append(version);
}
sn.append(' ');
sn.append(get(METHOD_NAME));
sn.append('(');
Class<?>[] types = get(TYPES) != null ? (Class<?>[]) get(TYPES) : new Class[0];
boolean first = true;
for (Class<?> type : types) {
if (first) {
first = false;
} else {
sn.append(',');
}
sn.append(type.getName());
}
sn.append(") ");
Object[] args = get(ARGUMENTS) != null ? (Object[]) get(ARGUMENTS) : null;
if (args != null && args.length > 0) {
sn.append(ToStringUtils.printToString(args));
}
return sn.toString();
}
private Date getInvocationTime() {
return (Date) get(INVOCATION_TIME);
}
private Date getOutTime() {
return (Date) get(OUT_TIME);
}
/**
* Return value of key
*
* @param key
* @return
*/
private Object get(String key) {
return data.get(key);
}
/**
* Add log key along with his value.
*
* @param key Any not null or non empty string
* @param value Any object including null.
*/
private void set(String key, Object value) {
data.put(key, value);
}
public void buildAccessLogData(Invoker<?> invoker, Invocation inv) {
setServiceName(invoker.getInterface().getName());
setMethodName(RpcUtils.getMethodName(inv));
setVersion(invoker.getUrl().getVersion());
setGroup(invoker.getUrl().getGroup());
setInvocationTime(new Date());
setTypes(inv.getParameterTypes());
setArguments(inv.getArguments());
}
}
| AccessLogData |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java | {
"start": 6946,
"end": 7047
} | class ____ a value class.
*
* @see Client
*/
@Public
@InterfaceStability.Evolving
public abstract | and |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/extendshbm/Person.java | {
"start": 177,
"end": 801
} | class ____ {
private long id;
private String name;
private char sex;
/**
* @return Returns the sex.
*/
public char getSex() {
return sex;
}
/**
* @param sex The sex to set.
*/
public void setSex(char sex) {
this.sex = sex;
}
/**
* @return Returns the id.
*/
public long getId() {
return id;
}
/**
* @param id The id to set.
*/
public void setId(long id) {
this.id = id;
}
/**
* @return Returns the identity.
*/
public String getName() {
return name;
}
/**
* @param identity The identity to set.
*/
public void setName(String identity) {
this.name = identity;
}
}
| Person |
java | alibaba__nacos | config/src/main/java/com/alibaba/nacos/config/server/model/ConfigMetadata.java | {
"start": 873,
"end": 3187
} | class ____ {
private String group;
private String dataId;
private String desc;
private String type;
private String appName;
private String configTags;
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getConfigTags() {
return configTags;
}
public void setConfigTags(String configTags) {
this.configTags = configTags;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConfigExportItem that = (ConfigExportItem) o;
return Objects.equals(group, that.group) && Objects.equals(dataId, that.dataId) && Objects
.equals(desc, that.desc) && Objects.equals(type, that.type) && Objects
.equals(appName, that.appName) && Objects.equals(configTags, that.configTags);
}
@Override
public int hashCode() {
return Objects.hash(group, dataId, desc, type, appName, configTags);
}
}
public List<ConfigExportItem> getMetadata() {
return metadata;
}
public void setMetadata(List<ConfigExportItem> metadata) {
this.metadata = metadata;
}
}
| ConfigExportItem |
java | alibaba__nacos | console/src/main/java/com/alibaba/nacos/console/controller/v2/HealthControllerV2.java | {
"start": 1567,
"end": 2773
} | class ____ {
/**
* Whether the Nacos is in broken states or not, and cannot recover except by being restarted.
*
* @return HTTP code equal to 200 indicates that Nacos is in right states. HTTP code equal to 500 indicates that
* Nacos is in broken states.
*/
@GetMapping("/liveness")
@Compatibility(apiType = ApiType.CONSOLE_API, alternatives = "GET ${contextPath:nacos}/v3/console/health/liveness")
public Result<String> liveness() {
return Result.success("ok");
}
/**
* Ready to receive the request or not.
*
* @return HTTP code equal to 200 indicates that Nacos is ready. HTTP code equal to 500 indicates that Nacos is not
* ready.
*/
@GetMapping("/readiness")
@Compatibility(apiType = ApiType.CONSOLE_API, alternatives = "GET ${contextPath:nacos}/v3/console/health/readiness")
public Result<String> readiness(HttpServletRequest request) {
ReadinessResult result = ModuleHealthCheckerHolder.getInstance().checkReadiness();
if (result.isSuccess()) {
return Result.success("ok");
}
return Result.failure(result.getResultMessage());
}
}
| HealthControllerV2 |
java | elastic__elasticsearch | libs/entitlement/qa/entitlement-test-plugin/src/main/java/org/elasticsearch/entitlement/qa/test/DummyImplementations.java | {
"start": 5620,
"end": 5943
} | class ____ extends DateFormatSymbolsProvider {
@Override
public DateFormatSymbols getInstance(Locale locale) {
throw unexpected();
}
@Override
public Locale[] getAvailableLocales() {
throw unexpected();
}
}
static | DummyDateFormatSymbolsProvider |
java | apache__avro | lang/java/thrift/src/test/java/org/apache/avro/thrift/test/Test.java | {
"start": 53726,
"end": 53921
} | class ____ implements org.apache.thrift.scheme.SchemeFactory {
public TestStandardScheme getScheme() {
return new TestStandardScheme();
}
}
private static | TestStandardSchemeFactory |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/factory/xml/ProtectedLifecycleBean.java | {
"start": 1207,
"end": 4492
} | class ____ implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
protected boolean initMethodDeclared = false;
protected String beanName;
protected BeanFactory owningFactory;
protected boolean postProcessedBeforeInit;
protected boolean inited;
protected boolean initedViaDeclaredInitMethod;
protected boolean postProcessedAfterInit;
protected boolean destroyed;
public void setInitMethodDeclared(boolean initMethodDeclared) {
this.initMethodDeclared = initMethodDeclared;
}
public boolean isInitMethodDeclared() {
return initMethodDeclared;
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
public String getBeanName() {
return beanName;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.owningFactory = beanFactory;
}
public void postProcessBeforeInit() {
if (this.inited || this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called postProcessBeforeInit after afterPropertiesSet");
}
if (this.postProcessedBeforeInit) {
throw new RuntimeException("Factory called postProcessBeforeInit twice");
}
this.postProcessedBeforeInit = true;
}
@Override
public void afterPropertiesSet() {
if (this.owningFactory == null) {
throw new RuntimeException("Factory didn't call setBeanFactory before afterPropertiesSet on lifecycle bean");
}
if (!this.postProcessedBeforeInit) {
throw new RuntimeException("Factory didn't call postProcessBeforeInit before afterPropertiesSet on lifecycle bean");
}
if (this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory initialized via declared init method before initializing via afterPropertiesSet");
}
if (this.inited) {
throw new RuntimeException("Factory called afterPropertiesSet twice");
}
this.inited = true;
}
public void declaredInitMethod() {
if (!this.inited) {
throw new RuntimeException("Factory didn't call afterPropertiesSet before declared init method");
}
if (this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called declared init method twice");
}
this.initedViaDeclaredInitMethod = true;
}
public void postProcessAfterInit() {
if (!this.inited) {
throw new RuntimeException("Factory called postProcessAfterInit before afterPropertiesSet");
}
if (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called postProcessAfterInit before calling declared init method");
}
if (this.postProcessedAfterInit) {
throw new RuntimeException("Factory called postProcessAfterInit twice");
}
this.postProcessedAfterInit = true;
}
/**
* Dummy business method that will fail unless the factory
* managed the bean's lifecycle correctly
*/
public void businessMethod() {
if (!this.inited || (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) ||
!this.postProcessedAfterInit) {
throw new RuntimeException("Factory didn't initialize lifecycle object correctly");
}
}
@Override
public void destroy() {
if (this.destroyed) {
throw new IllegalStateException("Already destroyed");
}
this.destroyed = true;
}
public boolean isDestroyed() {
return destroyed;
}
public static | ProtectedLifecycleBean |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest104.java | {
"start": 1039,
"end": 4463
} | class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = //
"SELECT\n" +
" /* DS_SVC */\n" +
" /*+ cursor_sharing_exact dynamic_sampling(0) no_sql_tune no_monitoring optimizer_features_enable(default) */\n" +
" SUM(C1)\n" +
"FROM\n" +
" (SELECT\n" +
" /*+ qb_name(\"innerQuery\") */\n" +
" 1 AS C1\n" +
" FROM SYS.\"X$KZSPR\" \"X$KZSPR\"\n" +
" WHERE (\"X$KZSPR\".\"INST_ID\" =USERENV('INSTANCE'))\n" +
" AND ((-\"X$KZSPR\".\"KZSPRPRV\")=(-45)\n" +
" OR ( -\"X$KZSPR\".\"KZSPRPRV\")=(-47)\n" +
" OR ( -\"X$KZSPR\".\"KZSPRPRV\")=(-48)\n" +
" OR ( -\"X$KZSPR\".\"KZSPRPRV\")=(-49)\n" +
" OR ( -\"X$KZSPR\".\"KZSPRPRV\")=(-50))\n" +
" ) innerQuery";
System.out.println(sql);
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0);
System.out.println(stmt.toString());
assertEquals(1, statementList.size());
// SQLMethodInvokeExpr expr = (SQLMethodInvokeExpr) stmt.getSelect().getQueryBlock().getSelectList().get(0).getExpr();
// SQLMethodInvokeExpr param0 = (SQLMethodInvokeExpr) expr.getParameters().get(0);
// assertTrue(param0.getParameters().get(0)
// instanceof SQLAggregateExpr);
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.accept(visitor);
{
String text = SQLUtils.toOracleString(stmt);
assertEquals("SELECT /* DS_SVC */\n" +
"/*+ cursor_sharing_exact dynamic_sampling(0) no_sql_tune no_monitoring optimizer_features_enable(default) */ SUM(C1)\n" +
"FROM (\n" +
"\tSELECT /*+ qb_name(\"innerQuery\") */ 1 AS C1\n" +
"\tFROM SYS.\"X$KZSPR\" \"X$KZSPR\"\n" +
"\tWHERE (\"X$KZSPR\".\"INST_ID\" = USERENV('INSTANCE'))\n" +
"\t\tAND ((-\"X$KZSPR\".\"KZSPRPRV\") = -45\n" +
"\t\t\tOR (-\"X$KZSPR\".\"KZSPRPRV\") = -47\n" +
"\t\t\tOR (-\"X$KZSPR\".\"KZSPRPRV\") = -48\n" +
"\t\t\tOR (-\"X$KZSPR\".\"KZSPRPRV\") = -49\n" +
"\t\t\tOR (-\"X$KZSPR\".\"KZSPRPRV\") = -50)\n" +
") innerQuery", text);
}
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(2, visitor.getColumns().size());
assertEquals(1, visitor.getConditions().size());
assertEquals(0, visitor.getRelationships().size());
assertEquals(0, visitor.getOrderByColumns().size());
}
}
| OracleSelectTest104 |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/support/OpenTest4JAndJUnit4AwareThrowableCollectorTests.java | {
"start": 3824,
"end": 4551
} | class ____ extends URLClassLoader {
private static final URL[] CLASSPATH_URLS = new URL[] {
OpenTest4JAndJUnit4AwareThrowableCollector.class.getProtectionDomain().getCodeSource().getLocation() };
private final boolean simulateJUnit4Missing;
private final boolean simulateHamcrestMissing;
TestClassLoader(boolean simulateJUnit4Missing, boolean simulateHamcrestMissing) {
super(CLASSPATH_URLS, getSystemClassLoader());
this.simulateJUnit4Missing = simulateJUnit4Missing;
this.simulateHamcrestMissing = simulateHamcrestMissing;
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
// Load a new instance of the OpenTest4JAndJUnit4AwareThrowableCollector | TestClassLoader |
java | apache__flink | flink-core/src/main/java/org/apache/flink/core/memory/DataInputViewStreamWrapper.java | {
"start": 1028,
"end": 1124
} | class ____ turns an {@link InputStream} into a {@link DataInputView}. */
@PublicEvolving
public | that |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/android/IsLoggableTagLengthTest.java | {
"start": 1250,
"end": 1725
} | class ____ {
public static boolean isLoggable(String tag, int level) {
return false;
}
public static final int INFO = 0;
}\
""")
.setArgs(ImmutableList.of("-XDandroidCompatible=true"));
@Test
public void negativeCaseLiteral() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import android.util.Log;
| Log |
java | google__dagger | javatests/dagger/internal/codegen/MissingBindingValidationTest.java | {
"start": 85145,
"end": 85334
} | interface ____ {}");
Source bar =
CompilerTests.javaSource( // force one-string-per-line format
"test.Bar",
"package test;",
"",
" | Foo |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/utils/ExecNodePlanDumper.java | {
"start": 7593,
"end": 8698
} | class ____ {
// build reuse id
private final ReuseIdBuilder reuseIdBuilder;
// mapping node object to visited times
protected final Map<ExecNode<?>, Integer> mapNodeToVisitedTimes;
protected ReuseInfo(List<ExecNode<?>> nodes, List<ExecNode<?>> borders) {
this.reuseIdBuilder = new ReuseIdBuilder(borders);
nodes.forEach(reuseIdBuilder::visit);
this.mapNodeToVisitedTimes = new IdentityHashMap<>();
}
/** Returns reuse id if the given node is a reuse node, else -1. */
Integer getReuseId(ExecNode<?> node) {
return reuseIdBuilder.getReuseId(node);
}
/** Returns true if the given node is first visited, else false. */
abstract boolean isFirstVisited(ExecNode<?> node);
/** Updates visited times for given node, return the new times. */
int addVisitedTimes(ExecNode<?> node) {
return mapNodeToVisitedTimes.compute(node, (k, v) -> v == null ? 1 : v + 1);
}
}
/** {@link ReuseInfo} for node tree. */
private static | ReuseInfo |
java | apache__camel | components/camel-log/src/generated/java/org/apache/camel/component/log/LogEndpointConfigurer.java | {
"start": 730,
"end": 11859
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
LogEndpoint target = (LogEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "exchangeformatter":
case "exchangeFormatter": target.setExchangeFormatter(property(camelContext, org.apache.camel.spi.ExchangeFormatter.class, value)); return true;
case "groupactiveonly":
case "groupActiveOnly": target.setGroupActiveOnly(property(camelContext, boolean.class, value)); return true;
case "groupdelay":
case "groupDelay": target.setGroupDelay(property(camelContext, java.lang.Long.class, value)); return true;
case "groupinterval":
case "groupInterval": target.setGroupInterval(property(camelContext, java.lang.Long.class, value)); return true;
case "groupsize":
case "groupSize": target.setGroupSize(property(camelContext, java.lang.Integer.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "level": target.setLevel(property(camelContext, java.lang.String.class, value)); return true;
case "logmask":
case "logMask": target.setLogMask(property(camelContext, java.lang.Boolean.class, value)); return true;
case "marker": target.setMarker(property(camelContext, java.lang.String.class, value)); return true;
case "maxchars":
case "maxChars": target.setMaxChars(property(camelContext, int.class, value)); return true;
case "multiline": target.setMultiline(property(camelContext, boolean.class, value)); return true;
case "plain": target.setPlain(property(camelContext, boolean.class, value)); return true;
case "showall":
case "showAll": target.setShowAll(property(camelContext, boolean.class, value)); return true;
case "showallproperties":
case "showAllProperties": target.setShowAllProperties(property(camelContext, boolean.class, value)); return true;
case "showbody":
case "showBody": target.setShowBody(property(camelContext, boolean.class, value)); return true;
case "showbodytype":
case "showBodyType": target.setShowBodyType(property(camelContext, boolean.class, value)); return true;
case "showcachedstreams":
case "showCachedStreams": target.setShowCachedStreams(property(camelContext, boolean.class, value)); return true;
case "showcaughtexception":
case "showCaughtException": target.setShowCaughtException(property(camelContext, boolean.class, value)); return true;
case "showexception":
case "showException": target.setShowException(property(camelContext, boolean.class, value)); return true;
case "showexchangeid":
case "showExchangeId": target.setShowExchangeId(property(camelContext, boolean.class, value)); return true;
case "showexchangepattern":
case "showExchangePattern": target.setShowExchangePattern(property(camelContext, boolean.class, value)); return true;
case "showfiles":
case "showFiles": target.setShowFiles(property(camelContext, boolean.class, value)); return true;
case "showfuture":
case "showFuture": target.setShowFuture(property(camelContext, boolean.class, value)); return true;
case "showheaders":
case "showHeaders": target.setShowHeaders(property(camelContext, boolean.class, value)); return true;
case "showproperties":
case "showProperties": target.setShowProperties(property(camelContext, boolean.class, value)); return true;
case "showroutegroup":
case "showRouteGroup": target.setShowRouteGroup(property(camelContext, boolean.class, value)); return true;
case "showrouteid":
case "showRouteId": target.setShowRouteId(property(camelContext, boolean.class, value)); return true;
case "showstacktrace":
case "showStackTrace": target.setShowStackTrace(property(camelContext, boolean.class, value)); return true;
case "showstreams":
case "showStreams": target.setShowStreams(property(camelContext, boolean.class, value)); return true;
case "showvariables":
case "showVariables": target.setShowVariables(property(camelContext, boolean.class, value)); return true;
case "skipbodylineseparator":
case "skipBodyLineSeparator": target.setSkipBodyLineSeparator(property(camelContext, boolean.class, value)); return true;
case "sourcelocationloggername":
case "sourceLocationLoggerName": target.setSourceLocationLoggerName(property(camelContext, boolean.class, value)); return true;
case "style": target.setStyle(property(camelContext, org.apache.camel.support.processor.DefaultExchangeFormatter.OutputStyle.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "exchangeformatter":
case "exchangeFormatter": return org.apache.camel.spi.ExchangeFormatter.class;
case "groupactiveonly":
case "groupActiveOnly": return boolean.class;
case "groupdelay":
case "groupDelay": return java.lang.Long.class;
case "groupinterval":
case "groupInterval": return java.lang.Long.class;
case "groupsize":
case "groupSize": return java.lang.Integer.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "level": return java.lang.String.class;
case "logmask":
case "logMask": return java.lang.Boolean.class;
case "marker": return java.lang.String.class;
case "maxchars":
case "maxChars": return int.class;
case "multiline": return boolean.class;
case "plain": return boolean.class;
case "showall":
case "showAll": return boolean.class;
case "showallproperties":
case "showAllProperties": return boolean.class;
case "showbody":
case "showBody": return boolean.class;
case "showbodytype":
case "showBodyType": return boolean.class;
case "showcachedstreams":
case "showCachedStreams": return boolean.class;
case "showcaughtexception":
case "showCaughtException": return boolean.class;
case "showexception":
case "showException": return boolean.class;
case "showexchangeid":
case "showExchangeId": return boolean.class;
case "showexchangepattern":
case "showExchangePattern": return boolean.class;
case "showfiles":
case "showFiles": return boolean.class;
case "showfuture":
case "showFuture": return boolean.class;
case "showheaders":
case "showHeaders": return boolean.class;
case "showproperties":
case "showProperties": return boolean.class;
case "showroutegroup":
case "showRouteGroup": return boolean.class;
case "showrouteid":
case "showRouteId": return boolean.class;
case "showstacktrace":
case "showStackTrace": return boolean.class;
case "showstreams":
case "showStreams": return boolean.class;
case "showvariables":
case "showVariables": return boolean.class;
case "skipbodylineseparator":
case "skipBodyLineSeparator": return boolean.class;
case "sourcelocationloggername":
case "sourceLocationLoggerName": return boolean.class;
case "style": return org.apache.camel.support.processor.DefaultExchangeFormatter.OutputStyle.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
LogEndpoint target = (LogEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "exchangeformatter":
case "exchangeFormatter": return target.getExchangeFormatter();
case "groupactiveonly":
case "groupActiveOnly": return target.isGroupActiveOnly();
case "groupdelay":
case "groupDelay": return target.getGroupDelay();
case "groupinterval":
case "groupInterval": return target.getGroupInterval();
case "groupsize":
case "groupSize": return target.getGroupSize();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "level": return target.getLevel();
case "logmask":
case "logMask": return target.getLogMask();
case "marker": return target.getMarker();
case "maxchars":
case "maxChars": return target.getMaxChars();
case "multiline": return target.isMultiline();
case "plain": return target.isPlain();
case "showall":
case "showAll": return target.isShowAll();
case "showallproperties":
case "showAllProperties": return target.isShowAllProperties();
case "showbody":
case "showBody": return target.isShowBody();
case "showbodytype":
case "showBodyType": return target.isShowBodyType();
case "showcachedstreams":
case "showCachedStreams": return target.isShowCachedStreams();
case "showcaughtexception":
case "showCaughtException": return target.isShowCaughtException();
case "showexception":
case "showException": return target.isShowException();
case "showexchangeid":
case "showExchangeId": return target.isShowExchangeId();
case "showexchangepattern":
case "showExchangePattern": return target.isShowExchangePattern();
case "showfiles":
case "showFiles": return target.isShowFiles();
case "showfuture":
case "showFuture": return target.isShowFuture();
case "showheaders":
case "showHeaders": return target.isShowHeaders();
case "showproperties":
case "showProperties": return target.isShowProperties();
case "showroutegroup":
case "showRouteGroup": return target.isShowRouteGroup();
case "showrouteid":
case "showRouteId": return target.isShowRouteId();
case "showstacktrace":
case "showStackTrace": return target.isShowStackTrace();
case "showstreams":
case "showStreams": return target.isShowStreams();
case "showvariables":
case "showVariables": return target.isShowVariables();
case "skipbodylineseparator":
case "skipBodyLineSeparator": return target.isSkipBodyLineSeparator();
case "sourcelocationloggername":
case "sourceLocationLoggerName": return target.isSourceLocationLoggerName();
case "style": return target.getStyle();
default: return null;
}
}
}
| LogEndpointConfigurer |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/DefaultStringifier.java | {
"start": 4850,
"end": 5855
} | class ____ the item
* @param conf the configuration to use
* @param items the objects to be stored
* @param keyName the name of the key to use
* @throws IndexOutOfBoundsException if the items array is empty
* @throws IOException : forwards Exceptions from the underlying
* {@link Serialization} classes.
*/
public static <K> void storeArray(Configuration conf, K[] items,
String keyName) throws IOException {
if (items.length == 0) {
throw new IndexOutOfBoundsException();
}
DefaultStringifier<K> stringifier = new DefaultStringifier<K>(conf,
GenericsUtil.getClass(items[0]));
try {
StringBuilder builder = new StringBuilder();
for (K item : items) {
builder.append(stringifier.toString(item)).append(SEPARATOR);
}
conf.set(keyName, builder.toString());
}
finally {
stringifier.close();
}
}
/**
* Restores the array of objects from the configuration.
*
* @param <K> the | of |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/log/LogDelegateFactory.java | {
"start": 2723,
"end": 3365
} | class ____}
*/
public static Log getHiddenLog(Class<?> clazz) {
return getHiddenLog(clazz.getName());
}
/**
* Create a "hidden" logger with a category name prefixed with "_", thus
* precluding it from being enabled together with other log categories from
* the same package. This is useful for specialized output that is either
* too verbose or otherwise optional or unnecessary to see all the time.
* @param category the log category to use
* @return a Log with the category {@code "_" + category}
* @since 5.3.5
*/
public static Log getHiddenLog(String category) {
return LogFactory.getLog("_" + category);
}
}
| name |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/CacheManager.java | {
"start": 5932,
"end": 6249
} | class ____ instantiated by the FSNamesystem.
* It maintains the mapping of cached blocks to datanodes via processing
* datanode cache reports. Based on these reports and addition and removal of
* caching directives, we will schedule caching and uncaching work.
*/
@InterfaceAudience.LimitedPrivate({"HDFS"})
public | is |
java | netty__netty | common/src/main/java/io/netty/util/internal/svm/PlatformDependentSubstitution.java | {
"start": 1008,
"end": 1534
} | class ____ caches the byte array base offset by reading the
* field from PlatformDependent0. The automatic recomputation of Substrate VM
* correctly recomputes the field in PlatformDependent0, but since the caching
* in PlatformDependent happens during image building, the non-recomputed value
* is cached.
*/
@Alias
@RecomputeFieldValue(
kind = RecomputeFieldValue.Kind.ArrayBaseOffset,
declClass = byte[].class)
private static long BYTE_ARRAY_BASE_OFFSET;
}
| PlatformDependent |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/sql/internal/SqlAstQueryPartProcessingStateImpl.java | {
"start": 1156,
"end": 7092
} | class ____
extends AbstractSqlAstQueryNodeProcessingStateImpl
implements SqlAstQueryPartProcessingState {
private final QueryPart queryPart;
private final boolean deduplicateSelectionItems;
private FetchParent nestingFetchParent;
public SqlAstQueryPartProcessingStateImpl(
QueryPart queryPart,
SqlAstProcessingState parent,
SqlAstCreationState creationState,
Supplier<Clause> currentClauseAccess,
boolean deduplicateSelectionItems) {
super( parent, creationState, currentClauseAccess );
this.queryPart = queryPart;
this.deduplicateSelectionItems = deduplicateSelectionItems;
}
public SqlAstQueryPartProcessingStateImpl(
QueryPart queryPart,
SqlAstProcessingState parent,
SqlAstCreationState creationState,
Function<SqlExpressionResolver, SqlExpressionResolver> expressionResolverDecorator,
Supplier<Clause> currentClauseAccess,
boolean deduplicateSelectionItems) {
super( parent, creationState, expressionResolverDecorator, currentClauseAccess );
this.queryPart = queryPart;
this.deduplicateSelectionItems = deduplicateSelectionItems;
}
public FetchParent getNestingFetchParent() {
return nestingFetchParent;
}
public void setNestingFetchParent(FetchParent nestedParent) {
this.nestingFetchParent = nestedParent;
}
@Override
public QueryPart getInflightQueryPart() {
return queryPart;
}
@Override
public FromClause getFromClause() {
return queryPart.getLastQuerySpec().getFromClause();
}
@Override
public void applyPredicate(Predicate predicate) {
queryPart.getLastQuerySpec().applyPredicate( predicate );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SqlExpressionResolver
private Map<?, ?> sqlSelectionMap;
private int nextJdbcPosition = 1;
@Override
public SqlSelection resolveSqlSelection(
Expression expression,
JavaType<?> javaType,
FetchParent fetchParent,
TypeConfiguration typeConfiguration) {
if ( nestingFetchParent != null ) {
final String selectableName;
if ( expression instanceof ColumnReference ) {
selectableName = ( (ColumnReference) expression ).getSelectableName();
}
else {
throw new IllegalArgumentException( "Illegal expression passed for nested fetching: " + expression );
}
final int selectableIndex = nestingFetchParent.getReferencedMappingType().getSelectableIndex( selectableName );
if ( selectableIndex != -1 ) {
return expression.createSqlSelection(
-1,
selectableIndex,
javaType,
true,
typeConfiguration
);
}
}
final Map<Expression, Object> selectionMap;
if ( deduplicateSelectionItems ) {
if ( sqlSelectionMap == null ) {
sqlSelectionMap = new HashMap<>();
}
//noinspection unchecked
selectionMap = (Map<Expression, Object>) sqlSelectionMap;
}
else if ( fetchParent != null ) {
// De-duplicate selection items within the root of a fetch parent
final Map<FetchParent, Map<Expression, Object>> fetchParentSqlSelectionMap;
final FetchParent root = fetchParent.getRoot();
if ( sqlSelectionMap == null ) {
sqlSelectionMap = fetchParentSqlSelectionMap = new HashMap<>();
fetchParentSqlSelectionMap.put( root, selectionMap = new HashMap<>() );
}
else {
//noinspection unchecked
fetchParentSqlSelectionMap = (Map<FetchParent, Map<Expression, Object>>) sqlSelectionMap;
final Map<Expression, Object> map = fetchParentSqlSelectionMap.get( root );
if ( map == null ) {
fetchParentSqlSelectionMap.put( root, selectionMap = new HashMap<>() );
}
else {
selectionMap = map;
}
}
}
else {
selectionMap = null;
}
final int jdbcPosition;
final Object existingSelection;
if ( selectionMap != null ) {
existingSelection = selectionMap.get( expression );
if ( existingSelection != null ) {
if ( existingSelection instanceof SqlSelection sqlSelection ) {
if ( sqlSelection.getExpressionType() == expression.getExpressionType() ) {
return sqlSelection;
}
jdbcPosition = sqlSelection.getJdbcResultSetIndex();
}
else {
final SqlSelection[] selections = (SqlSelection[]) existingSelection;
for ( SqlSelection sqlSelection : selections ) {
if ( sqlSelection.getExpressionType() == expression.getExpressionType() ) {
return sqlSelection;
}
}
jdbcPosition = selections[0].getJdbcResultSetIndex();
}
}
else {
jdbcPosition = nextJdbcPosition++;
}
}
else {
jdbcPosition = nextJdbcPosition++;
existingSelection = null;
}
final boolean virtual = existingSelection != null;
final SelectClause selectClause = ( (QuerySpec) queryPart ).getSelectClause();
final int valuesArrayPosition = selectClause.getSqlSelections().size();
final SqlSelection sqlSelection;
if ( isTopLevel() ) {
sqlSelection = expression.createDomainResultSqlSelection(
jdbcPosition,
valuesArrayPosition,
javaType,
virtual,
typeConfiguration
);
}
else {
sqlSelection = expression.createSqlSelection(
jdbcPosition,
valuesArrayPosition,
javaType,
virtual,
typeConfiguration
);
}
selectClause.addSqlSelection( sqlSelection );
if ( selectionMap != null ) {
if ( virtual ) {
final SqlSelection[] selections;
if ( existingSelection instanceof SqlSelection ) {
selections = new SqlSelection[2];
selections[0] = (SqlSelection) existingSelection;
}
else {
final SqlSelection[] existingSelections = (SqlSelection[]) existingSelection;
selections = new SqlSelection[existingSelections.length + 1];
System.arraycopy( existingSelections, 0, selections, 0, existingSelections.length );
}
selections[selections.length - 1] = sqlSelection;
selectionMap.put( expression, selections );
}
else {
selectionMap.put( expression, sqlSelection );
}
}
return sqlSelection;
}
}
| SqlAstQueryPartProcessingStateImpl |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/pool/SpringMybatisFilterTest.java | {
"start": 3529,
"end": 3811
} | interface ____ {
@Insert(value = "insert into t_User (id, name) values (#{user.id}, #{user.name})")
void addUser(@Param("user") User user);
@Select(value = "delete from t_User where id = #{id}")
void errorSelect(@Param("id") long id);
}
}
| UserMapper |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/descriptors/DescriptorProperties.java | {
"start": 53854,
"end": 54817
} | enum ____. */
public void validateEnum(
String key, boolean isOptional, Map<String, Consumer<String>> enumValidation) {
validateOptional(
key,
isOptional,
(value) -> {
if (!enumValidation.containsKey(value)) {
throw new ValidationException(
"Unknown value for property '"
+ key
+ "'.\n"
+ "Supported values are "
+ enumValidation.keySet()
+ " but was: "
+ value);
} else {
// run validation logic
enumValidation.get(value).accept(key);
}
});
}
/** Validates an | value |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoBeanForFactoryBeanIntegrationTests.java | {
"start": 1553,
"end": 2184
} | class ____ {
@MockitoBean
private TestBean testBean;
@Autowired
private ApplicationContext applicationContext;
@Order(1)
@Test
void beanReturnedByFactoryIsMocked() {
TestBean bean = this.applicationContext.getBean(TestBean.class);
assertThat(bean).isSameAs(this.testBean);
when(this.testBean.hello()).thenReturn("amock");
assertThat(bean.hello()).isEqualTo("amock");
assertThat(TestFactoryBean.USED).isFalse();
}
@Order(2)
@Test
void beanReturnedByFactoryIsReset() {
assertThat(this.testBean.hello()).isNull();
}
@Configuration(proxyBeanMethods = false)
static | MockitoBeanForFactoryBeanIntegrationTests |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/config/MvcNamespaceHandler.java | {
"start": 1073,
"end": 2524
} | class ____ extends NamespaceHandlerSupport {
private static final Log logger = LogFactory.getLog(MvcNamespaceHandler.class);
@Override
public void init() {
logger.warn("The XML configuration namespace for Spring MVC is deprecated, please use Java configuration instead.");
registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser());
registerBeanDefinitionParser("default-servlet-handler", new DefaultServletHandlerBeanDefinitionParser());
registerBeanDefinitionParser("interceptors", new InterceptorsBeanDefinitionParser());
registerBeanDefinitionParser("resources", new ResourcesBeanDefinitionParser());
registerBeanDefinitionParser("view-controller", new ViewControllerBeanDefinitionParser());
registerBeanDefinitionParser("redirect-view-controller", new ViewControllerBeanDefinitionParser());
registerBeanDefinitionParser("status-controller", new ViewControllerBeanDefinitionParser());
registerBeanDefinitionParser("view-resolvers", new ViewResolversBeanDefinitionParser());
registerBeanDefinitionParser("freemarker-configurer", new FreeMarkerConfigurerBeanDefinitionParser());
registerBeanDefinitionParser("groovy-configurer", new GroovyMarkupConfigurerBeanDefinitionParser());
registerBeanDefinitionParser("script-template-configurer", new ScriptTemplateConfigurerBeanDefinitionParser());
registerBeanDefinitionParser("cors", new CorsBeanDefinitionParser());
}
}
| MvcNamespaceHandler |
java | elastic__elasticsearch | modules/lang-painless/src/main/java/org/elasticsearch/painless/antlr/PainlessParser.java | {
"start": 105248,
"end": 106052
} | class ____ extends UnarynotaddsubContext {
public UnaryContext unary() {
return getRuleContext(UnaryContext.class, 0);
}
public TerminalNode BOOLNOT() {
return getToken(PainlessParser.BOOLNOT, 0);
}
public TerminalNode BWNOT() {
return getToken(PainlessParser.BWNOT, 0);
}
public NotContext(UnarynotaddsubContext ctx) {
copyFrom(ctx);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if (visitor instanceof PainlessParserVisitor) return ((PainlessParserVisitor<? extends T>) visitor).visitNot(this);
else return visitor.visitChildren(this);
}
}
@SuppressWarnings("CheckReturnValue")
public static | NotContext |
java | apache__camel | components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpTcpServerConsumerBindTimeoutTest.java | {
"start": 1555,
"end": 3953
} | class ____ extends CamelTestSupport {
@RegisterExtension
public MllpClientResource mllpClient = new MllpClientResource();
@EndpointInject("mock://result")
MockEndpoint result;
@Override
public boolean isUseAdviceWith() {
return true;
}
@Override
protected CamelContext createCamelContext() throws Exception {
DefaultCamelContext context = (DefaultCamelContext) super.createCamelContext();
context.setUseMDCLogging(true);
context.getCamelContextExtension().setName(this.getClass().getSimpleName());
return context;
}
@Override
protected RouteBuilder createRouteBuilder() {
mllpClient.setMllpHost("localhost");
mllpClient.setMllpPort(AvailablePortFinder.getNextAvailable());
return new RouteBuilder() {
int connectTimeout = 500;
int responseTimeout = 5000;
@Override
public void configure() {
String routeId = "mllp-test-receiver-route";
onCompletion()
.toF("log:%s?level=INFO&showAll=true", routeId)
.log(LoggingLevel.INFO, routeId, "Test route complete");
fromF("mllp://%s:%d?autoAck=true&connectTimeout=%d&receiveTimeout=%d",
mllpClient.getMllpHost(), mllpClient.getMllpPort(), connectTimeout, responseTimeout)
.routeId(routeId)
.log(LoggingLevel.INFO, routeId, "Test route received message")
.to(result);
}
};
}
@Test
public void testReceiveSingleMessage() throws Exception {
result.expectedMessageCount(1);
Thread tmpThread = new Thread(() -> {
try {
ServerSocket tmpSocket = new ServerSocket(mllpClient.getMllpPort());
Thread.sleep(15000);
tmpSocket.close();
} catch (Exception ex) {
throw new RuntimeCamelException("Exception caught in dummy listener", ex);
}
});
tmpThread.start();
context.start();
mllpClient.connect();
mllpClient.sendMessageAndWaitForAcknowledgement(Hl7TestMessageGenerator.generateMessage(), 10000);
MockEndpoint.assertIsSatisfied(context, 10, TimeUnit.SECONDS);
}
}
| MllpTcpServerConsumerBindTimeoutTest |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/throwables/Throwables_assertHasNoSuppressedExceptions_Test.java | {
"start": 932,
"end": 1564
} | class ____ extends ThrowablesBaseTest {
@Test
void should_pass_if_throwable_has_no_suppressed_exceptions() {
throwables.assertHasNoSuppressedExceptions(INFO, new Throwable());
}
@Test
void should_fail_if_throwable_has_suppressed_exceptions() {
// GIVEN
Throwable actual = new Throwable();
actual.addSuppressed(new IllegalArgumentException("Suppressed Message"));
// WHEN
expectAssertionError(() -> throwables.assertHasNoSuppressedExceptions(INFO, actual));
// THEN
verify(failures).failure(INFO, shouldHaveNoSuppressedExceptions(actual));
}
}
| Throwables_assertHasNoSuppressedExceptions_Test |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java | {
"start": 42020,
"end": 42047
} | interface ____ {
| NameToClass |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/bidirectional/BidirectionalOneToOneLazyFKTest.java | {
"start": 3186,
"end": 4082
} | class ____ {
@Id
@GeneratedValue
private Long id;
@Column(name = "business_id", unique = true, updatable = false)
private Long businessId;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "bar_business_id", referencedColumnName = "business_id", nullable = false, updatable = false)
private BarEntity bar;
private String name;
public BarEntity getBar() {
return bar;
}
public void setBar(BarEntity bar) {
this.bar = bar;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getBusinessId() {
return businessId;
}
public void setBusinessId(Long businessId) {
this.businessId = businessId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity(name = "BarEntity")
@Table(name = "bar_table")
public static | FooEntity |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java | {
"start": 19874,
"end": 20703
} | class ____ {
@JsonView(MyJacksonView1.class)
private String with1;
@JsonView(MyJacksonView2.class)
private String with2;
private String without;
private MySampleBean() {
}
private MySampleBean(String with1, String with2, String without) {
this.with1 = with1;
this.with2 = with2;
this.without = without;
}
public String getWith1() {
return with1;
}
public void setWith1(String with1) {
this.with1 = with1;
}
public String getWith2() {
return with2;
}
public void setWith2(String with2) {
this.with2 = with2;
}
public String getWithout() {
return without;
}
public void setWithout(String without) {
this.without = without;
}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
public static | MySampleBean |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/spi/ObjectThreadContextMap.java | {
"start": 899,
"end": 1051
} | interface ____ allow putting Object values in the
* {@link org.apache.logging.log4j.ThreadContext}.
*
* @see ThreadContextMap
* @since 2.8
*/
public | to |
java | elastic__elasticsearch | x-pack/plugin/transform/src/test/java/org/elasticsearch/xpack/transform/notifications/MockTransformAuditor.java | {
"start": 1774,
"end": 4400
} | class ____ extends TransformAuditor {
private static final String MOCK_NODE_NAME = "mock_node_name";
private static final Logger logger = LogManager.getLogger(MockTransformAuditor.class);
@SuppressWarnings("unchecked")
public static MockTransformAuditor createMockAuditor() {
Map<String, IndexTemplateMetadata> templates = Map.of(AUDIT_INDEX, mock(IndexTemplateMetadata.class));
Metadata metadata = mock(Metadata.class);
ProjectMetadata project = mock(ProjectMetadata.class);
when(metadata.getProject()).thenReturn(project);
when(project.templates()).thenReturn(templates);
ClusterState state = mock(ClusterState.class);
when(state.getMetadata()).thenReturn(metadata);
ClusterService clusterService = mock(ClusterService.class);
when(clusterService.state()).thenReturn(state);
ThreadPool threadPool = mock();
when(threadPool.generic()).thenReturn(EsExecutors.DIRECT_EXECUTOR_SERVICE);
when(clusterService.threadPool()).thenReturn(threadPool);
return new MockTransformAuditor(clusterService, mock(IndexNameExpressionResolver.class));
}
private final List<AuditExpectation> expectations;
private MockTransformAuditor(ClusterService clusterService, IndexNameExpressionResolver indexNameResolver) {
super(mock(Client.class), MOCK_NODE_NAME, clusterService, indexNameResolver, true);
expectations = new CopyOnWriteArrayList<>();
}
/**
* Adds an audit expectation.
* Must be called *before* the code that uses auditor's {@code info}, {@code warning} or {@code error} methods.
*/
public void addExpectation(AuditExpectation expectation) {
expectations.add(expectation);
}
// we can dynamically change the auditor, like attaching and removing the log appender
public void reset() {
expectations.clear();
}
public void audit(Level level, String resourceId, String message) {
doAudit(level, resourceId, message);
}
@Override
public void info(String resourceId, String message) {
doAudit(Level.INFO, resourceId, message);
}
@Override
public void warning(String resourceId, String message) {
doAudit(Level.WARNING, resourceId, message);
}
@Override
public void error(String resourceId, String message) {
doAudit(Level.ERROR, resourceId, message);
}
public void assertAllExpectationsMatched() {
for (AuditExpectation expectation : expectations) {
expectation.assertMatched();
}
}
public | MockTransformAuditor |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/AbstractJackson2View.java | {
"start": 1558,
"end": 1968
} | class ____ Jackson 2.x based and content type independent
* {@link AbstractView} implementations.
*
* @author Jeremy Grelle
* @author Arjen Poutsma
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @author Sebastien Deleuze
* @since 4.1
* @deprecated since 7.0 in favor of {@link AbstractJacksonView}
*/
@Deprecated(since = "7.0", forRemoval = true)
@SuppressWarnings("removal")
public abstract | for |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/JavaLookup.java | {
"start": 1182,
"end": 4325
} | class ____ extends AbstractLookup {
private final SystemPropertiesLookup spLookup = new SystemPropertiesLookup();
/**
* Accessible through the Lookup key {@code hw}.
* @return hardware processor information.
*/
public String getHardware() {
return "processors: " + Runtime.getRuntime().availableProcessors() + ", architecture: "
+ getSystemProperty("os.arch") + this.getSystemProperty("-", "sun.arch.data.model")
+ this.getSystemProperty(", instruction sets: ", "sun.cpu.isalist");
}
/**
* Accessible through the Lookup key {@code locale}.
* @return system locale and file encoding information.
*/
public String getLocale() {
return "default locale: " + Locale.getDefault() + ", platform encoding: " + getSystemProperty("file.encoding");
}
/**
* Accessible through the Lookup key {@code os}.
* @return operating system information.
*/
public String getOperatingSystem() {
return getSystemProperty("os.name") + " " + getSystemProperty("os.version")
+ getSystemProperty(" ", "sun.os.patch.level") + ", architecture: " + getSystemProperty("os.arch")
+ getSystemProperty("-", "sun.arch.data.model");
}
/**
* Accessible through the Lookup key {@code runtime}.
* @return Java Runtime Environment information.
*/
public String getRuntime() {
return getSystemProperty("java.runtime.name") + " (build " + getSystemProperty("java.runtime.version")
+ ") from " + getSystemProperty("java.vendor");
}
private String getSystemProperty(final String name) {
return spLookup.lookup(name);
}
private String getSystemProperty(final String prefix, final String name) {
final String value = getSystemProperty(name);
if (Strings.isEmpty(value)) {
return Strings.EMPTY;
}
return prefix + value;
}
/**
* Accessible through the Lookup key {@code vm}.
* @return Java Virtual Machine information.
*/
public String getVirtualMachine() {
return getSystemProperty("java.vm.name") + " (build " + getSystemProperty("java.vm.version") + ", "
+ getSystemProperty("java.vm.info") + ")";
}
/**
* Looks up the value of the environment variable.
*
* @param key
* the key to be looked up, may be null
* @return The value of the environment variable.
*/
@Override
public String lookup(final LogEvent ignored, final String key) {
switch (key) {
case "version":
return "Java version " + getSystemProperty("java.version");
case "runtime":
return getRuntime();
case "vm":
return getVirtualMachine();
case "os":
return getOperatingSystem();
case "hw":
return getHardware();
case "locale":
return getLocale();
default:
throw new IllegalArgumentException(key);
}
}
}
| JavaLookup |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/http/lib/StaticUserWebFilter.java | {
"start": 1796,
"end": 2013
} | class ____ extends FilterInitializer {
static final String DEPRECATED_UGI_KEY = "dfs.web.ugi";
private static final Logger LOG =
LoggerFactory.getLogger(StaticUserWebFilter.class);
static | StaticUserWebFilter |
java | apache__flink | flink-state-backends/flink-statebackend-forst/src/main/java/org/apache/flink/state/forst/ForStAggregatingState.java | {
"start": 2085,
"end": 7402
} | class ____<K, N, IN, ACC, OUT>
extends AbstractAggregatingState<K, N, IN, ACC, OUT> implements ForStInnerTable<K, N, ACC> {
/** The column family which this internal value state belongs to. */
private final ColumnFamilyHandle columnFamilyHandle;
/** The serialized key builder which should be thread-safe. */
private final ThreadLocal<SerializedCompositeKeyBuilder<K>> serializedKeyBuilder;
/** The data outputStream used for value serializer, which should be thread-safe. */
private final ThreadLocal<DataOutputSerializer> valueSerializerView;
/** The data inputStream used for value deserializer, which should be thread-safe. */
private final ThreadLocal<DataInputDeserializer> valueDeserializerView;
/** The serializer for namespace. * */
private final ThreadLocal<TypeSerializer<N>> namespaceSerializer;
/** The default namespace if not set. * */
private final N defaultNamespace;
/** Whether to enable the reuse of serialized key(and namespace). */
private final boolean enableKeyReuse;
/* Creates a new InternalKeyedState with the given asyncExecutionController and stateDescriptor.
*
* @param stateRequestHandler The async request handler for handling all requests.
* @param stateDescriptor The properties of the state.
*/
public ForStAggregatingState(
AggregateFunction<IN, ACC, OUT> aggregateFunction,
TypeSerializer<ACC> valueSerializer,
StateRequestHandler stateRequestHandler,
ColumnFamilyHandle columnFamily,
Supplier<SerializedCompositeKeyBuilder<K>> serializedKeyBuilderInitializer,
N defaultNamespace,
Supplier<TypeSerializer<N>> namespaceSerializerInitializer,
Supplier<DataOutputSerializer> valueSerializerViewInitializer,
Supplier<DataInputDeserializer> valueDeserializerViewInitializer) {
super(stateRequestHandler, aggregateFunction, valueSerializer);
this.columnFamilyHandle = columnFamily;
this.serializedKeyBuilder = ThreadLocal.withInitial(serializedKeyBuilderInitializer);
this.namespaceSerializer = ThreadLocal.withInitial(namespaceSerializerInitializer);
this.defaultNamespace = defaultNamespace;
this.valueDeserializerView = ThreadLocal.withInitial(valueDeserializerViewInitializer);
this.valueSerializerView = ThreadLocal.withInitial(valueSerializerViewInitializer);
// We only enable key reuse for the most common namespace across all states.
this.enableKeyReuse =
(defaultNamespace instanceof VoidNamespace)
&& (namespaceSerializerInitializer.get()
instanceof VoidNamespaceSerializer);
}
@Override
public ColumnFamilyHandle getColumnFamilyHandle() {
return columnFamilyHandle;
}
@Override
public byte[] serializeKey(ContextKey<K, N> contextKey) throws IOException {
return ForStSerializerUtils.serializeKeyAndNamespace(
contextKey,
serializedKeyBuilder.get(),
defaultNamespace,
namespaceSerializer.get(),
enableKeyReuse);
}
@Override
public byte[] serializeValue(ACC value) throws IOException {
DataOutputSerializer outputView = valueSerializerView.get();
outputView.clear();
getValueSerializer().serialize(value, outputView);
return outputView.getCopyOfBuffer();
}
@Override
public ACC deserializeValue(byte[] value) throws IOException {
DataInputDeserializer inputView = valueDeserializerView.get();
inputView.setBuffer(value);
return getValueSerializer().deserialize(inputView);
}
@SuppressWarnings("unchecked")
@Override
public ForStDBGetRequest<K, N, ACC, ?> buildDBGetRequest(
StateRequest<?, ?, ?, ?> stateRequest) {
Preconditions.checkArgument(
stateRequest.getRequestType() == StateRequestType.AGGREGATING_GET);
ContextKey<K, N> contextKey =
new ContextKey<>(
(RecordContext<K>) stateRequest.getRecordContext(),
(N) stateRequest.getNamespace());
return new ForStDBSingleGetRequest<>(
contextKey, this, (InternalAsyncFuture<ACC>) stateRequest.getFuture());
}
@SuppressWarnings("unchecked")
@Override
public ForStDBPutRequest<?, ?, ?> buildDBPutRequest(StateRequest<?, ?, ?, ?> stateRequest) {
Preconditions.checkArgument(
stateRequest.getRequestType() == StateRequestType.AGGREGATING_ADD
|| stateRequest.getRequestType() == StateRequestType.CLEAR);
ContextKey<K, N> contextKey =
new ContextKey<>(
(RecordContext<K>) stateRequest.getRecordContext(),
(N) stateRequest.getNamespace());
ACC aggregate =
stateRequest.getRequestType() == StateRequestType.CLEAR
? null
: (ACC) stateRequest.getPayload();
return ForStDBPutRequest.of(
contextKey, aggregate, this, (InternalAsyncFuture<Void>) stateRequest.getFuture());
}
}
| ForStAggregatingState |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/savedrequest/RequestCache.java | {
"start": 1023,
"end": 2218
} | interface ____ {
/**
* Caches the current request for later retrieval, once authentication has taken
* place. Used by <tt>ExceptionTranslationFilter</tt>.
* @param request the request to be stored
*/
void saveRequest(HttpServletRequest request, HttpServletResponse response);
/**
* Returns the saved request, leaving it cached.
* @param request the current request
* @return the saved request which was previously cached, or null if there is none.
*/
@Nullable SavedRequest getRequest(HttpServletRequest request, HttpServletResponse response);
/**
* Returns a wrapper around the saved request, if it matches the current request. The
* saved request should be removed from the cache.
* @param request
* @param response
* @return the wrapped save request, if it matches the original, or null if there is
* no cached request or it doesn't match.
*/
@Nullable HttpServletRequest getMatchingRequest(HttpServletRequest request, HttpServletResponse response);
/**
* Removes the cached request.
* @param request the current request, allowing access to the cache.
*/
void removeRequest(HttpServletRequest request, HttpServletResponse response);
}
| RequestCache |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/CoordinationRequest.java | {
"start": 907,
"end": 1048
} | interface ____ all requests from the client to a {@link OperatorCoordinator} which requests
* for a {@link CoordinationResponse}.
*/
public | for |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/query/Operator.java | {
"start": 839,
"end": 1661
} | enum ____ implements Writeable {
OR,
AND;
public BooleanClause.Occur toBooleanClauseOccur() {
return switch (this) {
case OR -> BooleanClause.Occur.SHOULD;
case AND -> BooleanClause.Occur.MUST;
};
}
public QueryParser.Operator toQueryParserOperator() {
return switch (this) {
case OR -> QueryParser.Operator.OR;
case AND -> QueryParser.Operator.AND;
};
}
public static Operator readFromStream(StreamInput in) throws IOException {
return in.readEnum(Operator.class);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeEnum(this);
}
public static Operator fromString(String op) {
return valueOf(op.toUpperCase(Locale.ROOT));
}
}
| Operator |
java | elastic__elasticsearch | x-pack/plugin/esql/qa/server/multi-node/src/yamlRestTest/java/org/elasticsearch/xpack/esql/qa/multi_node/EsqlClientYamlIT.java | {
"start": 720,
"end": 1380
} | class ____ extends ESClientYamlSuiteTestCase {
@ClassRule
public static ElasticsearchCluster cluster = Clusters.testCluster(spec -> {});
@Override
protected String getTestRestCluster() {
return cluster.getHttpAddresses();
}
public EsqlClientYamlIT(final ClientYamlTestCandidate testCandidate) {
super(testCandidate);
}
@ParametersFactory
public static Iterable<Object[]> parameters() throws Exception {
return createParameters();
}
@Before
@After
public void assertRequestBreakerEmpty() throws Exception {
EsqlSpecTestCase.assertRequestBreakerEmpty();
}
}
| EsqlClientYamlIT |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/UpdateEntityWithIdClassAndJsonFieldTest.java | {
"start": 4961,
"end": 5183
} | class ____ {
@Column(name = "TEXT_COLUMN")
private String text;
public Description() {
}
public Description(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
}
| Description |
java | alibaba__nacos | console/src/main/java/com/alibaba/nacos/console/handler/core/NamespaceHandler.java | {
"start": 966,
"end": 3082
} | interface ____ {
/**
* Get a list of namespaces.
*
* @return list of namespaces
* @throws NacosException if there is an issue fetching the namespaces
*/
List<Namespace> getNamespaceList() throws NacosException;
/**
* Get details of a specific namespace.
*
* @param namespaceId the ID of the namespace
* @return namespace details
* @throws NacosException if there is an issue fetching the namespace
*/
Namespace getNamespaceDetail(String namespaceId) throws NacosException;
/**
* Create a new namespace.
*
* @param namespaceId the ID of the namespace
* @param namespaceName the name of the namespace
* @param namespaceDesc the description of the namespace
* @return true if the namespace was successfully created, otherwise false
* @throws NacosException if there is an issue creating the namespace
*/
Boolean createNamespace(String namespaceId, String namespaceName, String namespaceDesc) throws NacosException;
/**
* Update an existing namespace.
*
* @param namespaceForm the form containing the updated namespace details
* @return true if the namespace was successfully updated, otherwise false
* @throws NacosException if there is an issue updating the namespace
*/
Boolean updateNamespace(NamespaceForm namespaceForm) throws NacosException;
/**
* Delete a namespace by its ID.
*
* @param namespaceId the ID of the namespace
* @return true if the namespace was successfully deleted, otherwise false
* @throws NacosException if there is an issue deleting the namespace
*/
Boolean deleteNamespace(String namespaceId) throws NacosException;
/**
* Check if a namespace ID exists.
*
* @param namespaceId the ID of the namespace to check
* @return true if the namespace exists, otherwise false
* @throws NacosException if there is an issue checking the namespace
*/
Boolean checkNamespaceIdExist(String namespaceId) throws NacosException;
}
| NamespaceHandler |
java | spring-projects__spring-framework | spring-jms/src/main/java/org/springframework/jms/listener/SubscriptionNameProvider.java | {
"start": 1213,
"end": 1365
} | interface ____ {
/**
* Determine the subscription name for this message listener object.
*/
String getSubscriptionName();
}
| SubscriptionNameProvider |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-proxyexchange-webflux/src/test/java/org/springframework/cloud/gateway/webflux/ProductionConfigurationTests.java | {
"start": 17929,
"end": 18212
} | class ____ {
private String name;
Foo() {
}
Foo(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
static | Foo |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/CascadeManagedAndTransientTest.java | {
"start": 8119,
"end": 10067
} | class ____ {
@Id
@GeneratedValue
private Long transportID;
@Version
private long version;
@Basic(optional = false)
private String name;
@ManyToOne(
optional = false,
cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH},
fetch = FetchType.EAGER)
@JoinColumn(name = "pickupNodeID", nullable = false)
private Node pickupNode = null;
@ManyToOne(
optional = false,
cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH},
fetch = FetchType.EAGER)
@JoinColumn(name = "deliveryNodeID", nullable = false)
private Node deliveryNode = null;
@ManyToOne(
optional = false,
cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH},
fetch = FetchType.EAGER
)
private Vehicle vehicle;
@Transient
private String transientField = "transport original value";
public Node getDeliveryNode() {
return deliveryNode;
}
public void setDeliveryNode(Node deliveryNode) {
this.deliveryNode = deliveryNode;
}
public Node getPickupNode() {
return pickupNode;
}
protected void setTransportID(Long transportID) {
this.transportID = transportID;
}
public void setPickupNode(Node pickupNode) {
this.pickupNode = pickupNode;
}
public Vehicle getVehicle() {
return vehicle;
}
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
public Long getTransportID() {
return transportID;
}
public long getVersion() {
return version;
}
protected void setVersion(long version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTransientField() {
return transientField;
}
public void setTransientField(String transientField) {
this.transientField = transientField;
}
}
@Entity(name = "Vehicle")
@Table(name = "HB_Vehicle")
public static | Transport |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/internal/Classes.java | {
"start": 14711,
"end": 17357
} | class ____ compare actual with should not be null");
}
private static SortedSet<String> getMethodsWithModifier(Set<Method> methods, int modifier) {
SortedSet<String> methodsWithModifier = newTreeSet();
for (Method method : methods) {
if ((method.getModifiers() & modifier) != 0) {
methodsWithModifier.add(method.getName());
}
}
return methodsWithModifier;
}
private static boolean noNonMatchingModifier(Set<String> expectedMethodNames, Map<String, Integer> methodsModifier,
Map<String, String> nonMatchingModifiers, int modifier) {
for (String method : methodsModifier.keySet()) {
if (expectedMethodNames.contains(method) && (methodsModifier.get(method) & modifier) == 0) {
nonMatchingModifiers.put(method, Modifier.toString(methodsModifier.get(method)));
}
}
return nonMatchingModifiers.isEmpty();
}
private static boolean hasPublicMethods(Method[] methods) {
for (Method method : methods) {
if (Modifier.isPublic(method.getModifiers())) {
return true;
}
}
return false;
}
private static SortedSet<String> methodsToName(Set<Method> methods) {
SortedSet<String> methodsName = newTreeSet();
for (Method method : methods) {
methodsName.add(method.getName());
}
return methodsName;
}
private static Map<String, Integer> methodsToNameAndModifier(Method[] methods) {
Map<String, Integer> methodMap = new LinkedHashMap<>(methods.length);
for (Method method : methods) {
methodMap.put(method.getName(), method.getModifiers());
}
return methodMap;
}
private static Method[] getAllMethods(Class<?> actual) {
Set<Method> allMethods = newLinkedHashSet();
Method[] declaredMethods = actual.getDeclaredMethods();
allMethods.addAll(newLinkedHashSet(declaredMethods));
Class<?> superclass = actual.getSuperclass();
if (superclass != null) {
allMethods.addAll(newLinkedHashSet(getAllMethods(superclass)));
}
for (Class<?> superinterface : actual.getInterfaces()) {
allMethods.addAll(newLinkedHashSet(getAllMethods(superinterface)));
}
return allMethods.toArray(new Method[0]);
}
private static <M extends Member> Set<M> filterSyntheticMembers(M[] members) {
Set<M> filteredMembers = newLinkedHashSet();
for (M member : members) {
if (!member.isSynthetic()) {
filteredMembers.add(member);
}
}
return filteredMembers;
}
private static void assertNotNull(AssertionInfo info, Class<?> actual) {
Objects.instance().assertNotNull(info, actual);
}
}
| to |
java | apache__flink | flink-clients/src/test/java/org/apache/flink/client/program/ClientTest.java | {
"start": 20196,
"end": 20577
} | class ____ {
public static void main(String[] args) throws Exception {
final StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment();
env.fromData(1, 2).sinkTo(new DiscardingSink<>());
env.execute().getAllAccumulatorResults();
}
}
private static final | TestGetAllAccumulator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.