language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java | {
"start": 5931,
"end": 6400
} | class ____
*/
public static ClassLoader getClassLoader(Class<?> clazz) {
ClassLoader cl = null;
if (!clazz.getName().startsWith("org.apache.dubbo")) {
cl = clazz.getClassLoader();
}
if (cl == null) {
try {
cl = Thread.currentThread().getContextClassLoader();
} catch (Exception ignored) {
// Cannot access thread context ClassLoader - falling back to system | loader |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/RandomDatum.java | {
"start": 979,
"end": 2508
} | class ____ implements WritableComparable<RandomDatum> {
private int length;
private byte[] data;
public RandomDatum() {}
public RandomDatum(Random random) {
length = 10 + (int) Math.pow(10.0, random.nextFloat() * 3.0);
data = new byte[length];
random.nextBytes(data);
}
public int getLength() {
return length;
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(length);
out.write(data);
}
@Override
public void readFields(DataInput in) throws IOException {
length = in.readInt();
if (data == null || length > data.length)
data = new byte[length];
in.readFully(data, 0, length);
}
@Override
public int compareTo(RandomDatum o) {
return WritableComparator.compareBytes(this.data, 0, this.length,
o.data, 0, o.length);
}
@Override
public boolean equals(Object o) {
return compareTo((RandomDatum)o) == 0;
}
@Override
public int hashCode() {
return Arrays.hashCode(this.data);
}
private static final char[] HEX_DIGITS =
{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
/** Returns a string representation of this object. */
@Override
public String toString() {
StringBuilder buf = new StringBuilder(length*2);
for (int i = 0; i < length; i++) {
int b = data[i];
buf.append(HEX_DIGITS[(b >> 4) & 0xf]);
buf.append(HEX_DIGITS[b & 0xf]);
}
return buf.toString();
}
public static | RandomDatum |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringValidateRegExpTest.java | {
"start": 1039,
"end": 1285
} | class ____ extends ValidateRegExpTest {
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/spring/processor/validate.xml");
}
}
| SpringValidateRegExpTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java | {
"start": 13156,
"end": 13438
} | class ____ {
public void doTest() {
Client client = new Client();
client.setDeadline(42);
}
}
""")
.addOutputLines(
"out/Caller.java",
"""
public final | Caller |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java | {
"start": 6985,
"end": 7123
} | class ____ introspect
* @param annotationName the fully-qualified name of the searchable annotation type
* @return {@code false} if the | to |
java | hibernate__hibernate-orm | hibernate-vector/src/test/java/org/hibernate/vector/ByteVectorTest.java | {
"start": 9632,
"end": 10178
} | class ____ {
@Id
private Long id;
@Column( name = "the_vector" )
@JdbcTypeCode(SqlTypes.VECTOR_INT8)
@Array(length = 3)
private byte[] theVector;
public VectorEntity() {
}
public VectorEntity(Long id, byte[] theVector) {
this.id = id;
this.theVector = theVector;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public byte[] getTheVector() {
return theVector;
}
public void setTheVector(byte[] theVector) {
this.theVector = theVector;
}
}
}
| VectorEntity |
java | spring-projects__spring-framework | spring-jms/src/main/java/org/springframework/jms/connection/DelegatingConnectionFactory.java | {
"start": 1548,
"end": 1837
} | class ____ JMS 2.0 {@code JMSContext}
* calls and therefore requires the JMS 2.0 API to be present at runtime.
* It may nevertheless run against a JMS 1.1 driver (bound to the JMS 2.0 API)
* as long as no actual JMS 2.0 calls are triggered by the application's setup.
*
* <p>This | supports |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java | {
"start": 14473,
"end": 14643
} | class ____ implements AutoCloseable {
public ActiveResource getResource() {
return this;
}
@Override
public void close() {
}
}
public static | ActiveResource |
java | quarkusio__quarkus | extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/JKSKeyStoreWithoutPasswordTest.java | {
"start": 953,
"end": 1917
} | class ____ {
private static final String configuration = """
quarkus.tls.key-store.jks.path=target/certs/test-credentials-provider-keystore.jks
quarkus.tls.key-store.credentials-provider.name=tls
""";
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addClass(MyCredentialProvider.class)
.add(new StringAsset(configuration), "application.properties"))
.assertException(t -> {
assertThat(t).hasStackTraceContaining(
"the key store password is not set and cannot be retrieved from the credential provider");
});
@Test
void test() throws KeyStoreException, CertificateParsingException {
fail("Should not be called");
}
@ApplicationScoped
public static | JKSKeyStoreWithoutPasswordTest |
java | quarkusio__quarkus | extensions/oidc-client/deployment/src/test/java/io/quarkus/oidc/client/OidcClientCredentialsJwtPrivateP12KeyStoreTest.java | {
"start": 391,
"end": 1364
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(OidcClientResource.class, ProtectedResource.class)
.addAsResource("application-oidc-client-credentials-jwt-private-p12-key-store.properties",
"application.properties")
.addAsResource("exportedCertificate.pem")
.addAsResource("exportedPrivateKey.pem")
.addAsResource("keystore.pkcs12"));
@Test
public void testClientCredentialsToken() {
String token = RestAssured.when().get("/client/token").body().asString();
RestAssured.given().auth().oauth2(token)
.when().get("/protected")
.then()
.statusCode(200)
.body(equalTo("service-account-quarkus-app"));
}
}
| OidcClientCredentialsJwtPrivateP12KeyStoreTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/notfound/OptionalEagerRefNonPKNotFoundTest.java | {
"start": 15101,
"end": 15756
} | class ____ extends Person {
@Id
private Long id;
@OneToOne(cascade = CascadeType.PERSIST)
@PrimaryKeyJoinColumn
@NotFound(action = NotFoundAction.IGNORE)
@Fetch(FetchMode.SELECT)
@JoinColumn(
name = "cityName",
referencedColumnName = "name",
foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)
)
private City city;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public City getCity() {
return city;
}
@Override
public void setCity(City city) {
this.city = city;
}
}
@Entity
@Table(name = "PersonMapsIdJoinException")
public static | PersonPkjcSelectIgnore |
java | alibaba__nacos | config/src/test/java/com/alibaba/nacos/config/server/utils/ContentUtilsTest.java | {
"start": 937,
"end": 3507
} | class ____ {
@Test
void testVerifyIncrementPubContent() {
String content = "";
try {
ContentUtils.verifyIncrementPubContent(content);
fail();
} catch (IllegalArgumentException e) {
assertNotNull(e.toString());
}
content = "\r";
try {
ContentUtils.verifyIncrementPubContent(content);
fail();
} catch (IllegalArgumentException e) {
assertNotNull(e.toString());
}
content = "\n";
try {
ContentUtils.verifyIncrementPubContent(content);
fail();
} catch (IllegalArgumentException e) {
assertNotNull(e.toString());
}
content = Constants.WORD_SEPARATOR + "test";
try {
ContentUtils.verifyIncrementPubContent(content);
fail();
} catch (IllegalArgumentException e) {
assertNotNull(e.toString());
}
}
@Test
void testGetContentIdentity() {
String content = "abc" + Constants.WORD_SEPARATOR + "edf";
String result = ContentUtils.getContentIdentity(content);
assertEquals("abc", result);
content = "test";
try {
ContentUtils.getContentIdentity(content);
fail();
} catch (IllegalArgumentException e) {
assertNotNull(e.toString());
}
}
@Test
void testGetContent() {
String content = "abc" + Constants.WORD_SEPARATOR + "edf";
String result = ContentUtils.getContent(content);
assertEquals("edf", result);
content = "test";
try {
ContentUtils.getContent(content);
fail();
} catch (IllegalArgumentException e) {
assertNotNull(e.toString());
}
}
@Test
void testTruncateContent() {
String content = "test";
String result = ContentUtils.truncateContent(content);
assertEquals(content, result);
String content2 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
String result2 = ContentUtils.truncateContent(content2);
String expected = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv...";
assertEquals(expected, result2);
assertEquals("", ContentUtils.truncateContent(null));
}
}
| ContentUtilsTest |
java | grpc__grpc-java | xds/src/generated/thirdparty/grpc/com/github/xds/service/orca/v3/OpenRcaServiceGrpc.java | {
"start": 16180,
"end": 16350
} | class ____
extends OpenRcaServiceBaseDescriptorSupplier {
OpenRcaServiceFileDescriptorSupplier() {}
}
private static final | OpenRcaServiceFileDescriptorSupplier |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/LanyProxylessManyToOneTests.java | {
"start": 2067,
"end": 8619
} | class ____ {
@Test
public void testLazyManyToOne(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
final Order order = session.byId(Order.class).getReference(1);
assertThat( Hibernate.isPropertyInitialized( order, "customer"), is(false) );
assertThat( order.customer, nullValue() );
Customer customer = order.getCustomer();
assertThat( Hibernate.isPropertyInitialized( order, "customer"), is(true) );
assertThat( order.customer, notNullValue() );
assertThat( customer, notNullValue() );
assertThat( Hibernate.isInitialized(customer), is(false) );
assertThat( customer.getId(), is(1) );
assertThat( Hibernate.isInitialized(customer), is(false) );
assertThat( customer.getName(), is("Acme Brick") );
assertThat( Hibernate.isInitialized(customer), is(true) );
}
);
scope.inTransaction(
(session) -> {
final Order order = session.byId(Order.class).getReference(1);
assertThat( Hibernate.isPropertyInitialized( order, "customer"), is(false) );
assertThat( order.customer, nullValue() );
Customer customer = order.getCustomer();
assertThat( Hibernate.isPropertyInitialized( order, "customer"), is(true) );
assertThat( order.customer, notNullValue() );
assertThat( customer, notNullValue() );
assertThat( Hibernate.isInitialized(customer), is(false) );
Hibernate.initialize( customer );
assertThat( Hibernate.isInitialized(customer), is(true) );
assertThat( customer.id, is(1) );
assertThat( customer.name, is("Acme Brick") );
}
);
}
@Test
public void testOwnerIsProxy(SessionFactoryScope scope) {
SQLStatementInspector statementInspector = (SQLStatementInspector) scope.getSessionFactory()
.getSessionFactoryOptions()
.getStatementInspector();
final EntityPersister orderDescriptor = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor( Order.class );
final BytecodeEnhancementMetadata orderEnhancementMetadata = orderDescriptor.getBytecodeEnhancementMetadata();
assertThat( orderEnhancementMetadata.isEnhancedForLazyLoading(), is( true ) );
final EntityPersister customerDescriptor = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor( Customer.class );
final BytecodeEnhancementMetadata customerEnhancementMetadata = customerDescriptor.getBytecodeEnhancementMetadata();
assertThat( customerEnhancementMetadata.isEnhancedForLazyLoading(), is( true ) );
scope.inTransaction(
(session) -> {
final Order order = session.byId( Order.class ).getReference( 1 );
// we should have just the uninitialized proxy of the owner - and
// therefore no SQL statements should have been executed
assertThat( statementInspector.getSqlQueries().size(), is( 0 ) );
final BytecodeLazyAttributeInterceptor initialInterceptor = orderEnhancementMetadata.extractLazyInterceptor( order );
assertThat( initialInterceptor, instanceOf( EnhancementAsProxyLazinessInterceptor.class ) );
// access the id - should do nothing with db
order.getId();
assertThat( statementInspector.getSqlQueries().size(), is( 0 ) );
assertThat( initialInterceptor, sameInstance( orderEnhancementMetadata.extractLazyInterceptor( order ) ) );
// this should trigger loading the entity's base state
order.getAmount();
assertThat( statementInspector.getSqlQueries().size(), is( 1 ) );
final BytecodeLazyAttributeInterceptor interceptor = orderEnhancementMetadata.extractLazyInterceptor( order );
assertThat( initialInterceptor, not( sameInstance( interceptor ) ) );
assertThat( interceptor, instanceOf( LazyAttributeLoadingInterceptor.class ) );
final LazyAttributeLoadingInterceptor attrInterceptor = (LazyAttributeLoadingInterceptor) interceptor;
assertThat( attrInterceptor.hasAnyUninitializedAttributes(), is( false ) );
// should not trigger a load and the `customer` reference should be an uninitialized enhanced proxy
final Customer customer = order.getCustomer();
assertThat( statementInspector.getSqlQueries().size(), is( 1 ) );
final BytecodeLazyAttributeInterceptor initialCustomerInterceptor = customerEnhancementMetadata.extractLazyInterceptor( customer );
assertThat( initialCustomerInterceptor, instanceOf( EnhancementAsProxyLazinessInterceptor.class ) );
// just as above, accessing id should trigger no loads
customer.getId();
assertThat( statementInspector.getSqlQueries().size(), is( 1 ) );
assertThat( initialCustomerInterceptor, sameInstance( customerEnhancementMetadata.extractLazyInterceptor( customer ) ) );
customer.getName();
assertThat( statementInspector.getSqlQueries().size(), is( 2 ) );
assertThat( customerEnhancementMetadata.extractLazyInterceptor( customer ), instanceOf( LazyAttributeLoadingInterceptor.class ) );
}
);
}
@Test
@JiraKey("HHH-14659")
public void testQueryJoinFetch(SessionFactoryScope scope) {
SQLStatementInspector statementInspector = (SQLStatementInspector) scope.getSessionFactory()
.getSessionFactoryOptions()
.getStatementInspector();
Order order = scope.fromTransaction( (session) -> {
final Order result = session.createQuery(
"select o from Order o join fetch o.customer",
Order.class )
.uniqueResult();
assertThat( statementInspector.getSqlQueries().size(), is( 1 ) );
return result;
} );
// The "join fetch" should have already initialized the property,
// so that the getter can safely be called outside of a session.
assertTrue( Hibernate.isPropertyInitialized( order, "customer" ) );
// The "join fetch" should have already initialized the associated entity.
Customer customer = order.getCustomer();
assertTrue( Hibernate.isInitialized( customer ) );
assertThat( statementInspector.getSqlQueries().size(), is( 1 ) );
}
@BeforeEach
public void createTestData(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
final Customer customer = new Customer( 1, "Acme Brick" );
session.persist( customer );
final Order order = new Order( 1, customer, BigDecimal.ONE );
session.persist( order );
}
);
( (SQLStatementInspector) scope.getSessionFactory().getSessionFactoryOptions()
.getStatementInspector() ).clear();
}
@AfterEach
public void dropTestData(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Entity( name = "Customer" )
@Table( name = "customer" )
public static | LanyProxylessManyToOneTests |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/test/issue5379/GoogleUserDetailsMapper.java | {
"start": 721,
"end": 936
} | class ____ {
List<SomeConfiguration> controllers;
public SomeConfigurationList(List<SomeConfiguration> controllers) {
this.controllers = controllers;
}
}
@EachProperty("test")
| SomeConfigurationList |
java | quarkusio__quarkus | extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/multiplepersistenceunits/MultiplePersistenceUnitsInterceptorTest.java | {
"start": 990,
"end": 3823
} | class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClass(DefaultEntity.class)
.addClass(User.class)
.addClass(Plane.class)
.addClass(MyDefaultPUInterceptor.class)
.addClass(MyInventoryPUInterceptor.class))
.withConfigurationResource("application-multiple-persistence-units.properties");
@Inject
Session defaultSession;
@Inject
@PersistenceUnit("users")
Session usersSession;
@Inject
@PersistenceUnit("inventory")
Session inventorySession;
@Inject
UserTransaction transaction;
private long defaultEntityId;
private long userId;
private long planeId;
@BeforeEach
public void initData() throws Exception {
transaction.begin();
DefaultEntity entity = new DefaultEntity("default");
defaultSession.persist(entity);
transaction.commit();
transaction.begin();
User user = new User("user");
usersSession.persist(user);
transaction.commit();
transaction.begin();
Plane plane = new Plane("plane");
inventorySession.persist(plane);
transaction.commit();
defaultEntityId = entity.getId();
userId = user.getId();
planeId = plane.getId();
}
@Test
public void test() throws Exception {
assertThat(MyDefaultPUInterceptor.instances).hasSize(1);
assertThat(MyInventoryPUInterceptor.instances).hasSize(1);
assertThat(MyDefaultPUInterceptor.loadedIds).isEmpty();
assertThat(MyInventoryPUInterceptor.loadedIds).isEmpty();
transaction.begin();
defaultSession.find(DefaultEntity.class, defaultEntityId);
transaction.commit();
assertThat(MyDefaultPUInterceptor.loadedIds).containsExactly(defaultEntityId);
assertThat(MyInventoryPUInterceptor.loadedIds).isEmpty();
transaction.begin();
usersSession.find(User.class, userId);
transaction.commit();
assertThat(MyDefaultPUInterceptor.loadedIds).containsExactly(defaultEntityId);
assertThat(MyInventoryPUInterceptor.loadedIds).isEmpty();
transaction.begin();
inventorySession.find(Plane.class, planeId);
transaction.commit();
assertThat(MyDefaultPUInterceptor.loadedIds).containsExactly(defaultEntityId);
assertThat(MyInventoryPUInterceptor.loadedIds).containsExactly(planeId);
// No new instance: it's application-scoped
assertThat(MyDefaultPUInterceptor.instances).hasSize(1);
assertThat(MyInventoryPUInterceptor.instances).hasSize(1);
}
@PersistenceUnitExtension
public static | MultiplePersistenceUnitsInterceptorTest |
java | apache__rocketmq | remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/namesrv/RegisterBrokerRequestHeader.java | {
"start": 1612,
"end": 3832
} | class ____ implements CommandCustomHeader {
@CFNotNull
private String brokerName;
@CFNotNull
private String brokerAddr;
@CFNotNull
@RocketMQResource(ResourceType.CLUSTER)
private String clusterName;
@CFNotNull
private String haServerAddr;
@CFNotNull
private Long brokerId;
@CFNullable
private Long heartbeatTimeoutMillis;
@CFNullable
private Boolean enableActingMaster;
private boolean compressed;
private Integer bodyCrc32 = 0;
@Override
public void checkFields() throws RemotingCommandException {
}
public String getBrokerName() {
return brokerName;
}
public void setBrokerName(String brokerName) {
this.brokerName = brokerName;
}
public String getBrokerAddr() {
return brokerAddr;
}
public void setBrokerAddr(String brokerAddr) {
this.brokerAddr = brokerAddr;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public String getHaServerAddr() {
return haServerAddr;
}
public void setHaServerAddr(String haServerAddr) {
this.haServerAddr = haServerAddr;
}
public Long getBrokerId() {
return brokerId;
}
public void setBrokerId(Long brokerId) {
this.brokerId = brokerId;
}
public Long getHeartbeatTimeoutMillis() {
return heartbeatTimeoutMillis;
}
public void setHeartbeatTimeoutMillis(Long heartbeatTimeoutMillis) {
this.heartbeatTimeoutMillis = heartbeatTimeoutMillis;
}
public boolean isCompressed() {
return compressed;
}
public void setCompressed(boolean compressed) {
this.compressed = compressed;
}
public Integer getBodyCrc32() {
return bodyCrc32;
}
public void setBodyCrc32(Integer bodyCrc32) {
this.bodyCrc32 = bodyCrc32;
}
public Boolean getEnableActingMaster() {
return enableActingMaster;
}
public void setEnableActingMaster(Boolean enableActingMaster) {
this.enableActingMaster = enableActingMaster;
}
}
| RegisterBrokerRequestHeader |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/PooledObjectFactory.java | {
"start": 966,
"end": 1108
} | interface ____<T> extends Service, CamelContextAware {
/**
* Utilization statistics of the this factory.
*/
| PooledObjectFactory |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/streaming/api/datastream/DataStreamSourceTest.java | {
"start": 1260,
"end": 1910
} | class ____ {
/** Test constructor for new Sources (FLIP-27). */
@Test
void testConstructor() {
int expectParallelism = 100;
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
MockSource mockSource = new MockSource(Boundedness.BOUNDED, 10);
DataStreamSource<Integer> stream =
env.fromSource(mockSource, WatermarkStrategy.noWatermarks(), "TestingSource");
stream.setParallelism(expectParallelism);
assertThat(stream.isParallel()).isTrue();
assertThat(stream.getParallelism()).isEqualTo(expectParallelism);
}
}
| DataStreamSourceTest |
java | elastic__elasticsearch | build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/match/AddMatch.java | {
"start": 1258,
"end": 2845
} | class ____ implements RestTestTransformByParentArray {
private static JsonNodeFactory jsonNodeFactory = JsonNodeFactory.withExactBigDecimals(false);
private final String matchKey;
private final String testName;
private final SerializableJsonNode<JsonNode> matchValue;
public AddMatch(String matchKey, SerializableJsonNode<JsonNode> matchValue, String testName) {
this.matchKey = matchKey;
this.matchValue = matchValue;
this.testName = Objects.requireNonNull(testName, "adding matches is only supported for named tests");
}
@Override
public boolean shouldApply(RestTestContext testContext) {
return testContext.testName().equals(testName);
}
@Override
public void transformTest(ArrayNode matchParent) {
ObjectNode matchObject = new ObjectNode(jsonNodeFactory);
ObjectNode matchContent = new ObjectNode(jsonNodeFactory);
matchContent.set(matchKey, matchValue.toJsonNode());
matchObject.set("match", matchContent);
matchParent.add(matchObject);
}
@Override
@Internal
public String getKeyOfArrayToFind() {
// match objects are always in the array that is the direct child of the test name, i.e.
// "my test name" : [ {"do" : ... }, { "match" : .... }]
return testName;
}
@Input
public String getMatchKey() {
return matchKey;
}
@Input
public String getTestName() {
return testName;
}
@Input
public JsonNode getMatchValue() {
return matchValue.toJsonNode();
}
}
| AddMatch |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/index/IndexRequestTests.java | {
"start": 2557,
"end": 24190
} | class ____ extends ESTestCase {
public void testIndexRequestOpTypeFromString() throws Exception {
String create = "create";
String index = "index";
String createUpper = "CREATE";
String indexUpper = "INDEX";
IndexRequest indexRequest = new IndexRequest("");
indexRequest.opType(create);
assertThat(indexRequest.opType(), equalTo(DocWriteRequest.OpType.CREATE));
indexRequest.opType(createUpper);
assertThat(indexRequest.opType(), equalTo(DocWriteRequest.OpType.CREATE));
indexRequest.opType(index);
assertThat(indexRequest.opType(), equalTo(DocWriteRequest.OpType.INDEX));
indexRequest.opType(indexUpper);
assertThat(indexRequest.opType(), equalTo(DocWriteRequest.OpType.INDEX));
}
public void testReadIncorrectOpType() {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new IndexRequest("").opType("foobar"));
assertThat(e.getMessage(), equalTo("opType must be 'create' or 'index', found: [foobar]"));
}
public void testCreateOperationRejectsVersions() {
Set<VersionType> allButInternalSet = new HashSet<>(Arrays.asList(VersionType.values()));
allButInternalSet.remove(VersionType.INTERNAL);
VersionType[] allButInternal = allButInternalSet.toArray(new VersionType[] {});
IndexRequest request = new IndexRequest("index").id("1");
request.opType(IndexRequest.OpType.CREATE);
request.versionType(randomFrom(allButInternal));
assertThat(request.validate().validationErrors(), not(empty()));
request.versionType(VersionType.INTERNAL);
request.version(randomIntBetween(0, Integer.MAX_VALUE));
assertThat(request.validate().validationErrors(), not(empty()));
}
public void testIndexingRejectsLongIds() {
String id = randomAlphaOfLength(511);
IndexRequest request = new IndexRequest("index").id(id);
request.source("{}", XContentType.JSON);
ActionRequestValidationException validate = request.validate();
assertNull(validate);
id = randomAlphaOfLength(512);
request = new IndexRequest("index").id(id);
request.source("{}", XContentType.JSON);
validate = request.validate();
assertNull(validate);
id = randomAlphaOfLength(513);
request = new IndexRequest("index").id(id);
request.source("{}", XContentType.JSON);
validate = request.validate();
assertThat(validate, notNullValue());
assertThat(validate.getMessage(), containsString("id [" + id + "] is too long, must be no longer than 512 bytes but was: 513"));
}
public void testWaitForActiveShards() {
IndexRequest request = new IndexRequest("index");
final int count = randomIntBetween(0, 10);
request.waitForActiveShards(ActiveShardCount.from(count));
assertEquals(request.waitForActiveShards(), ActiveShardCount.from(count));
// test negative shard count value not allowed
expectThrows(IllegalArgumentException.class, () -> request.waitForActiveShards(ActiveShardCount.from(randomIntBetween(-10, -1))));
}
public void testAutoGenerateId() {
IndexRequest request = new IndexRequest("index");
request.autoGenerateId();
assertTrue("expected > 0 but got: " + request.getAutoGeneratedTimestamp(), request.getAutoGeneratedTimestamp() > 0);
}
public void testAutoGenerateTimeBasedId() {
IndexRequest request = new IndexRequest("index");
request.autoGenerateTimeBasedId();
assertTrue("expected > 0 but got: " + request.getAutoGeneratedTimestamp(), request.getAutoGeneratedTimestamp() > 0);
}
public void testIndexResponse() {
ShardId shardId = new ShardId(randomAlphaOfLengthBetween(3, 10), randomAlphaOfLengthBetween(3, 10), randomIntBetween(0, 1000));
String id = randomAlphaOfLengthBetween(3, 10);
long version = randomLong();
boolean created = randomBoolean();
var failureStatus = randomFrom(Set.of(IndexDocFailureStoreStatus.USED, IndexDocFailureStoreStatus.NOT_APPLICABLE_OR_UNKNOWN));
IndexResponse indexResponse = new IndexResponse(
shardId,
id,
SequenceNumbers.UNASSIGNED_SEQ_NO,
0,
version,
created,
null,
failureStatus
);
int total = randomIntBetween(1, 10);
int successful = randomIntBetween(1, 10);
ReplicationResponse.ShardInfo shardInfo = ReplicationResponse.ShardInfo.of(total, successful);
indexResponse.setShardInfo(shardInfo);
boolean forcedRefresh = false;
if (randomBoolean()) {
forcedRefresh = randomBoolean();
indexResponse.setForcedRefresh(forcedRefresh);
}
assertEquals(id, indexResponse.getId());
assertEquals(version, indexResponse.getVersion());
assertEquals(shardId, indexResponse.getShardId());
assertEquals(created ? RestStatus.CREATED : RestStatus.OK, indexResponse.status());
assertEquals(total, indexResponse.getShardInfo().getTotal());
assertEquals(successful, indexResponse.getShardInfo().getSuccessful());
assertEquals(forcedRefresh, indexResponse.forcedRefresh());
assertEquals(failureStatus, indexResponse.getFailureStoreStatus());
Object[] args = new Object[] {
shardId.getIndexName(),
id,
version,
created ? "created" : "updated",
SequenceNumbers.UNASSIGNED_SEQ_NO,
0,
total,
successful,
failureStatus.getLabel() };
assertEquals(Strings.format("""
IndexResponse[index=%s,id=%s,version=%s,result=%s,seqNo=%s,primaryTerm=%s,shards=\
{"total":%s,"successful":%s,"failed":0},failure_store=%s]\
""", args), indexResponse.toString());
}
public void testIndexRequestXContentSerialization() throws IOException {
IndexRequest indexRequest = new IndexRequest("foo").id("1");
boolean isRequireAlias = randomBoolean();
Map<String, String> dynamicTemplates = IntStream.range(0, randomIntBetween(0, 10))
.boxed()
.collect(Collectors.toMap(n -> "field-" + n, n -> "name-" + n));
indexRequest.source("{}", XContentType.JSON);
indexRequest.setDynamicTemplates(dynamicTemplates);
Map<String, Map<String, String>> dynamicTemplateParams = createRandomDynamicTemplateParams(0, 10);
indexRequest.setDynamicTemplateParams(dynamicTemplateParams);
indexRequest.setRequireAlias(isRequireAlias);
assertEquals(XContentType.JSON, indexRequest.getContentType());
BytesStreamOutput out = new BytesStreamOutput();
indexRequest.writeTo(out);
StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes);
IndexRequest serialized = new IndexRequest(in);
assertEquals(XContentType.JSON, serialized.getContentType());
assertThat(serialized.source(), equalBytes(new BytesArray("{}")));
assertEquals(isRequireAlias, serialized.isRequireAlias());
assertThat(serialized.getDynamicTemplates(), equalTo(dynamicTemplates));
}
private static Map<String, Map<String, String>> createRandomDynamicTemplateParams(int min, int max) {
return IntStream.range(0, randomIntBetween(min, max))
.boxed()
.collect(Collectors.toMap(n -> "field-" + n, n -> Map.of("key-" + n, "value-" + n)));
}
// reindex makes use of index requests without a source so this needs to be handled
public void testSerializationOfEmptyRequestWorks() throws IOException {
IndexRequest request = new IndexRequest("index");
assertNull(request.getContentType());
assertEquals("index", request.index());
try (BytesStreamOutput out = new BytesStreamOutput()) {
request.writeTo(out);
try (StreamInput in = out.bytes().streamInput()) {
IndexRequest serialized = new IndexRequest(in);
assertNull(serialized.getContentType());
assertEquals("index", serialized.index());
}
}
}
public void testSerializeDynamicTemplates() throws Exception {
IndexRequest indexRequest = new IndexRequest("foo").id("1");
indexRequest.source("{}", XContentType.JSON);
// Empty dynamic templates
{
if (randomBoolean()) {
indexRequest.setDynamicTemplates(Map.of());
}
TransportVersion ver = TransportVersionUtils.randomCompatibleVersion(random());
BytesStreamOutput out = new BytesStreamOutput();
out.setTransportVersion(ver);
indexRequest.writeTo(out);
StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes);
in.setTransportVersion(ver);
IndexRequest serialized = new IndexRequest(in);
assertThat(serialized.getDynamicTemplates(), anEmptyMap());
}
// new version
{
Map<String, String> dynamicTemplates = IntStream.range(0, randomIntBetween(0, 10))
.boxed()
.collect(Collectors.toMap(n -> "field-" + n, n -> "name-" + n));
indexRequest.setDynamicTemplates(dynamicTemplates);
TransportVersion ver = TransportVersionUtils.randomCompatibleVersion(random());
BytesStreamOutput out = new BytesStreamOutput();
out.setTransportVersion(ver);
indexRequest.writeTo(out);
StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes);
in.setTransportVersion(ver);
IndexRequest serialized = new IndexRequest(in);
assertThat(serialized.getDynamicTemplates(), equalTo(dynamicTemplates));
}
}
public void testSerializeDynamicTemplateParams() throws Exception {
IndexRequest indexRequest = new IndexRequest("foo").id("1");
indexRequest.source("{}", XContentType.JSON);
// Empty dynamic templates
{
if (randomBoolean()) {
indexRequest.setDynamicTemplateParams(Map.of());
}
TransportVersion ver = TransportVersionUtils.randomCompatibleVersion(random());
BytesStreamOutput out = new BytesStreamOutput();
out.setTransportVersion(ver);
indexRequest.writeTo(out);
StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes);
in.setTransportVersion(ver);
IndexRequest serialized = new IndexRequest(in);
assertThat(serialized.getDynamicTemplateParams(), anEmptyMap());
}
// old version
{
indexRequest.setDynamicTemplateParams(createRandomDynamicTemplateParams(1, 10));
TransportVersion ver = TransportVersionUtils.randomVersionBetween(
random(),
TransportVersion.minimumCompatible(),
TransportVersionUtils.getPreviousVersion(IndexRequest.INGEST_REQUEST_DYNAMIC_TEMPLATE_PARAMS)
);
BytesStreamOutput out = new BytesStreamOutput();
out.setTransportVersion(ver);
indexRequest.writeTo(out);
StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes);
in.setTransportVersion(ver);
IndexRequest serialized = new IndexRequest(in);
assertThat(serialized.getDynamicTemplateParams(), anEmptyMap());
}
// new version
{
Map<String, Map<String, String>> dynamicTemplateParams = createRandomDynamicTemplateParams(0, 10);
indexRequest.setDynamicTemplateParams(dynamicTemplateParams);
TransportVersion ver = TransportVersionUtils.randomVersionBetween(
random(),
IndexRequest.INGEST_REQUEST_DYNAMIC_TEMPLATE_PARAMS,
TransportVersion.current()
);
BytesStreamOutput out = new BytesStreamOutput();
out.setTransportVersion(ver);
indexRequest.writeTo(out);
StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes);
in.setTransportVersion(ver);
IndexRequest serialized = new IndexRequest(in);
assertThat(serialized.getDynamicTemplateParams(), equalTo(dynamicTemplateParams));
}
}
public void testToStringSizeLimit() {
IndexRequest request = new IndexRequest("index");
String source = "{\"name\":\"value\"}";
request.source(source, XContentType.JSON);
assertEquals("index {[index][null], source[" + source + "]}", request.toString());
source = Strings.format("""
{"name":"%s"}
""", randomUnicodeOfLength(IndexRequest.MAX_SOURCE_LENGTH_IN_TOSTRING));
request.source(source, XContentType.JSON);
int actualBytes = source.getBytes(StandardCharsets.UTF_8).length;
assertEquals(
"index {[index][null], source[n/a, actual length: ["
+ ByteSizeValue.ofBytes(actualBytes).toString()
+ "], max length: "
+ ByteSizeValue.ofBytes(IndexRequest.MAX_SOURCE_LENGTH_IN_TOSTRING).toString()
+ "]}",
request.toString()
);
}
public void testRejectsEmptyStringPipeline() {
IndexRequest request = new IndexRequest("index");
request.source("{}", XContentType.JSON);
request.setPipeline("");
ActionRequestValidationException validate = request.validate();
assertThat(validate, notNullValue());
assertThat(validate.getMessage(), containsString("pipeline cannot be an empty string"));
}
public void testGetConcreteWriteIndex() {
Instant currentTime = ZonedDateTime.of(2022, 12, 12, 6, 0, 0, 0, ZoneOffset.UTC).toInstant();
Instant start1 = currentTime.minus(6, ChronoUnit.HOURS);
Instant end1 = currentTime.minus(2, ChronoUnit.HOURS);
Instant start2 = currentTime.minus(2, ChronoUnit.HOURS);
Instant end2 = currentTime.plus(2, ChronoUnit.HOURS);
String tsdbDataStream = "logs_my-app_prod";
var clusterState = DataStreamTestHelper.getClusterStateWithDataStream(
tsdbDataStream,
List.of(Tuple.tuple(start1, end1), Tuple.tuple(start2, end2))
);
var metadata = clusterState.getMetadata();
var project = metadata.getProject();
String source = """
{
"@timestamp": $time
}""";
{
// Not a create request => resolve to the latest backing index
IndexRequest request = new IndexRequest(tsdbDataStream);
request.source(renderSource(source, start1), XContentType.JSON);
var result = request.getConcreteWriteIndex(project.getIndicesLookup().get(tsdbDataStream), project);
assertThat(result, equalTo(project.dataStreams().get(tsdbDataStream).getIndices().get(1)));
}
{
// Target is a regular index => resolve to this index only
String indexName = project.indices().keySet().iterator().next();
IndexRequest request = new IndexRequest(indexName);
request.source(renderSource(source, randomFrom(start1, end1, start2, end2)), XContentType.JSON);
var result = request.getConcreteWriteIndex(project.getIndicesLookup().get(indexName), project);
assertThat(result.getName(), equalTo(indexName));
}
{
String regularDataStream = "logs_another-app_prod";
var backingIndex1 = DataStreamTestHelper.createBackingIndex(regularDataStream, 1).build();
var backingIndex2 = DataStreamTestHelper.createBackingIndex(regularDataStream, 2).build();
var metadata2 = Metadata.builder(metadata)
.put(backingIndex1, true)
.put(backingIndex2, true)
.put(
DataStreamTestHelper.newInstance(
regularDataStream,
List.of(backingIndex1.getIndex(), backingIndex2.getIndex()),
2,
null
)
)
.build();
var project2 = metadata2.getProject();
// Target is a regular data stream => always resolve to the latest backing index
IndexRequest request = new IndexRequest(regularDataStream);
request.source(renderSource(source, randomFrom(start1, end1, start2, end2)), XContentType.JSON);
var result = request.getConcreteWriteIndex(project2.getIndicesLookup().get(regularDataStream), project2);
assertThat(result.getName(), equalTo(backingIndex2.getIndex().getName()));
}
{
// provided timestamp resolves to the first backing index
IndexRequest request = new IndexRequest(tsdbDataStream);
request.opType(DocWriteRequest.OpType.CREATE);
request.source(renderSource(source, start1), XContentType.JSON);
var result = request.getConcreteWriteIndex(project.getIndicesLookup().get(tsdbDataStream), project);
assertThat(result, equalTo(project.dataStreams().get(tsdbDataStream).getIndices().get(0)));
}
{
// provided timestamp as millis since epoch resolves to the first backing index
IndexRequest request = new IndexRequest(tsdbDataStream);
request.opType(DocWriteRequest.OpType.CREATE);
request.source(source.replace("$time", "" + start1.toEpochMilli()), XContentType.JSON);
var result = request.getConcreteWriteIndex(project.getIndicesLookup().get(tsdbDataStream), project);
assertThat(result, equalTo(project.dataStreams().get(tsdbDataStream).getIndices().get(0)));
}
{
IndexRequest request = new IndexRequest(tsdbDataStream);
request.opType(DocWriteRequest.OpType.CREATE);
request.source(
source.replace("$time", "\"" + DateFormatter.forPattern(FormatNames.STRICT_DATE.getName()).format(start1) + "\""),
XContentType.JSON
);
var result = request.getConcreteWriteIndex(project.getIndicesLookup().get(tsdbDataStream), project);
assertThat(result, equalTo(project.dataStreams().get(tsdbDataStream).getIndices().get(0)));
}
{
// provided timestamp resolves to the latest backing index
IndexRequest request = new IndexRequest(tsdbDataStream);
request.opType(DocWriteRequest.OpType.CREATE);
request.source(renderSource(source, start2), XContentType.JSON);
var result = request.getConcreteWriteIndex(project.getIndicesLookup().get(tsdbDataStream), project);
assertThat(result, equalTo(project.dataStreams().get(tsdbDataStream).getIndices().get(1)));
}
{
// provided timestamp resolves to no index => fail with an exception
IndexRequest request = new IndexRequest(tsdbDataStream);
request.opType(DocWriteRequest.OpType.CREATE);
request.source(renderSource(source, end2), XContentType.JSON);
var e = expectThrows(
IllegalArgumentException.class,
() -> request.getConcreteWriteIndex(project.getIndicesLookup().get(tsdbDataStream), project)
);
assertThat(
e.getMessage(),
equalTo(
"the document timestamp [$time] is outside of ranges of currently writable indices [[$start1,$end1][$start2,$end2]]"
.replace("$time", formatInstant(end2))
.replace("$start1", formatInstant(start1))
.replace("$end1", formatInstant(end1))
.replace("$start2", formatInstant(start2))
.replace("$end2", formatInstant(end2))
)
);
}
{
// no @timestamp field
IndexRequest request = new IndexRequest(tsdbDataStream);
request.opType(DocWriteRequest.OpType.CREATE);
request.source(Map.of("foo", randomAlphaOfLength(5)), XContentType.JSON);
var e = expectThrows(
IllegalArgumentException.class,
() -> request.getConcreteWriteIndex(project.getIndicesLookup().get(tsdbDataStream), project)
);
assertThat(
e.getMessage(),
equalTo(
"Error extracting data stream timestamp field: "
+ "Failed to parse object: expecting token of type [START_OBJECT] but found [null]"
)
);
}
{
// set error format timestamp
IndexRequest request = new IndexRequest(tsdbDataStream);
request.opType(DocWriteRequest.OpType.CREATE);
request.source(Map.of("foo", randomAlphaOfLength(5)), XContentType.JSON);
request.setRawTimestamp(10.0d);
var e = expectThrows(
IllegalArgumentException.class,
() -> request.getConcreteWriteIndex(project.getIndicesLookup().get(tsdbDataStream), project)
);
assertThat(
e.getMessage(),
equalTo("Error get data stream timestamp field: timestamp [10.0] type [ | IndexRequestTests |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesDeploymentsEndpointBuilderFactory.java | {
"start": 1643,
"end": 16282
} | interface ____
extends
EndpointConsumerBuilder {
default AdvancedKubernetesDeploymentsEndpointConsumerBuilder advanced() {
return (AdvancedKubernetesDeploymentsEndpointConsumerBuilder) this;
}
/**
* The Kubernetes API Version to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param apiVersion the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder apiVersion(String apiVersion) {
doSetProperty("apiVersion", apiVersion);
return this;
}
/**
* The dns domain, used for ServiceCall EIP.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param dnsDomain the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder dnsDomain(String dnsDomain) {
doSetProperty("dnsDomain", dnsDomain);
return this;
}
/**
* Default KubernetesClient to use if provided.
*
* The option is a:
* <code>io.fabric8.kubernetes.client.KubernetesClient</code> type.
*
* Group: common
*
* @param kubernetesClient the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder kubernetesClient(io.fabric8.kubernetes.client.KubernetesClient kubernetesClient) {
doSetProperty("kubernetesClient", kubernetesClient);
return this;
}
/**
* Default KubernetesClient to use if provided.
*
* The option will be converted to a
* <code>io.fabric8.kubernetes.client.KubernetesClient</code> type.
*
* Group: common
*
* @param kubernetesClient the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder kubernetesClient(String kubernetesClient) {
doSetProperty("kubernetesClient", kubernetesClient);
return this;
}
/**
* The namespace.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param namespace the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder namespace(String namespace) {
doSetProperty("namespace", namespace);
return this;
}
/**
* The port name, used for ServiceCall EIP.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param portName the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder portName(String portName) {
doSetProperty("portName", portName);
return this;
}
/**
* The port protocol, used for ServiceCall EIP.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: tcp
* Group: common
*
* @param portProtocol the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder portProtocol(String portProtocol) {
doSetProperty("portProtocol", portProtocol);
return this;
}
/**
* The Consumer CRD Resource Group we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param crdGroup the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder crdGroup(String crdGroup) {
doSetProperty("crdGroup", crdGroup);
return this;
}
/**
* The Consumer CRD Resource name we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param crdName the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder crdName(String crdName) {
doSetProperty("crdName", crdName);
return this;
}
/**
* The Consumer CRD Resource Plural we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param crdPlural the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder crdPlural(String crdPlural) {
doSetProperty("crdPlural", crdPlural);
return this;
}
/**
* The Consumer CRD Resource Scope we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param crdScope the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder crdScope(String crdScope) {
doSetProperty("crdScope", crdScope);
return this;
}
/**
* The Consumer CRD Resource Version we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param crdVersion the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder crdVersion(String crdVersion) {
doSetProperty("crdVersion", crdVersion);
return this;
}
/**
* The Consumer Label key when watching at some resources.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param labelKey the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder labelKey(String labelKey) {
doSetProperty("labelKey", labelKey);
return this;
}
/**
* The Consumer Label value when watching at some resources.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param labelValue the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder labelValue(String labelValue) {
doSetProperty("labelValue", labelValue);
return this;
}
/**
* The Consumer pool size.
*
* The option is a: <code>int</code> type.
*
* Default: 1
* Group: consumer
*
* @param poolSize the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder poolSize(int poolSize) {
doSetProperty("poolSize", poolSize);
return this;
}
/**
* The Consumer pool size.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 1
* Group: consumer
*
* @param poolSize the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder poolSize(String poolSize) {
doSetProperty("poolSize", poolSize);
return this;
}
/**
* The Consumer Resource Name we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param resourceName the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder resourceName(String resourceName) {
doSetProperty("resourceName", resourceName);
return this;
}
/**
* The CA Cert Data.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param caCertData the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder caCertData(String caCertData) {
doSetProperty("caCertData", caCertData);
return this;
}
/**
* The CA Cert File.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param caCertFile the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder caCertFile(String caCertFile) {
doSetProperty("caCertFile", caCertFile);
return this;
}
/**
* The Client Cert Data.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientCertData the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder clientCertData(String clientCertData) {
doSetProperty("clientCertData", clientCertData);
return this;
}
/**
* The Client Cert File.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientCertFile the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder clientCertFile(String clientCertFile) {
doSetProperty("clientCertFile", clientCertFile);
return this;
}
/**
* The Key Algorithm used by the client.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientKeyAlgo the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder clientKeyAlgo(String clientKeyAlgo) {
doSetProperty("clientKeyAlgo", clientKeyAlgo);
return this;
}
/**
* The Client Key data.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientKeyData the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder clientKeyData(String clientKeyData) {
doSetProperty("clientKeyData", clientKeyData);
return this;
}
/**
* The Client Key file.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientKeyFile the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder clientKeyFile(String clientKeyFile) {
doSetProperty("clientKeyFile", clientKeyFile);
return this;
}
/**
* The Client Key Passphrase.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientKeyPassphrase the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder clientKeyPassphrase(String clientKeyPassphrase) {
doSetProperty("clientKeyPassphrase", clientKeyPassphrase);
return this;
}
/**
* The Auth Token.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param oauthToken the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder oauthToken(String oauthToken) {
doSetProperty("oauthToken", oauthToken);
return this;
}
/**
* Password to connect to Kubernetes.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param password the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder password(String password) {
doSetProperty("password", password);
return this;
}
/**
* Define if the certs we used are trusted anyway or not.
*
* The option is a: <code>java.lang.Boolean</code> type.
*
* Default: false
* Group: security
*
* @param trustCerts the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder trustCerts(Boolean trustCerts) {
doSetProperty("trustCerts", trustCerts);
return this;
}
/**
* Define if the certs we used are trusted anyway or not.
*
* The option will be converted to a <code>java.lang.Boolean</code>
* type.
*
* Default: false
* Group: security
*
* @param trustCerts the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder trustCerts(String trustCerts) {
doSetProperty("trustCerts", trustCerts);
return this;
}
/**
* Username to connect to Kubernetes.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param username the value to set
* @return the dsl builder
*/
default KubernetesDeploymentsEndpointConsumerBuilder username(String username) {
doSetProperty("username", username);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the Kubernetes Deployments component.
*/
public | KubernetesDeploymentsEndpointConsumerBuilder |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/support/CancellableFanOut.java | {
"start": 9547,
"end": 10140
} | class ____ implementing this method, and that will prevent the
* early release of any accumulated results. Beware of lambdas, and test carefully.
*/
protected abstract void onItemFailure(Item item, Exception e);
/**
* Called when responses for all items have been processed, on the thread that processed the last per-item response or possibly the
* thread which called {@link #run} if all items were processed before {@link #run} returns. Not called if the task is cancelled.
* <p>
* Note that it's easy to accidentally capture another reference to this | when |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/AlwaysThrows.java | {
"start": 2607,
"end": 4558
} | class ____ extends BugChecker implements MethodInvocationTreeMatcher {
@SuppressWarnings("UnnecessarilyFullyQualified")
private static final ImmutableMap<String, Consumer<CharSequence>> VALIDATORS =
ImmutableMap.<String, Consumer<CharSequence>>builder()
.put("java.time.Duration", java.time.Duration::parse)
.put("java.time.Instant", java.time.Instant::parse)
.put("java.time.LocalDate", java.time.LocalDate::parse)
.put("java.time.LocalDateTime", java.time.LocalDateTime::parse)
.put("java.time.LocalTime", java.time.LocalTime::parse)
.put("java.time.MonthDay", java.time.MonthDay::parse)
.put("java.time.OffsetDateTime", java.time.OffsetDateTime::parse)
.put("java.time.OffsetTime", java.time.OffsetTime::parse)
.put("java.time.Period", java.time.Period::parse)
.put("java.time.Year", java.time.Year::parse)
.put("java.time.YearMonth", java.time.YearMonth::parse)
.put("java.time.ZonedDateTime", java.time.ZonedDateTime::parse)
.buildOrThrow();
private static final Matcher<ExpressionTree> IMMUTABLE_MAP_OF =
staticMethod().onDescendantOf("com.google.common.collect.ImmutableMap").named("of");
private static final Matcher<ExpressionTree> IMMUTABLE_BI_MAP_OF =
staticMethod().onDescendantOf("com.google.common.collect.ImmutableBiMap").named("of");
private static final Matcher<ExpressionTree> IMMUTABLE_MAP_PUT =
instanceMethod()
.onDescendantOf("com.google.common.collect.ImmutableMap.Builder")
.namedAnyOf("put")
.withParameters("java.lang.Object", "java.lang.Object");
private static final Matcher<ExpressionTree> IMMUTABLE_BI_MAP_PUT =
instanceMethod()
.onDescendantOf("com.google.common.collect.ImmutableBiMap.Builder")
.namedAnyOf("put")
.withParameters("java.lang.Object", "java.lang.Object");
| AlwaysThrows |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/Http1SseServerChannelObserver.java | {
"start": 1405,
"end": 3066
} | class ____ extends Http1ServerChannelObserver {
private HttpMessageEncoder originalResponseEncoder;
public Http1SseServerChannelObserver(HttpChannel httpChannel) {
super(httpChannel);
}
@Override
public void setResponseEncoder(HttpMessageEncoder responseEncoder) {
super.setResponseEncoder(new ServerSentEventEncoder(responseEncoder));
this.originalResponseEncoder = responseEncoder;
}
@Override
protected void doOnCompleted(Throwable throwable) {
if (!isHeaderSent()) {
sendMetadata(encodeHttpMetadata(true));
}
super.doOnCompleted(throwable);
}
@Override
protected HttpMetadata encodeHttpMetadata(boolean endStream) {
return super.encodeHttpMetadata(endStream)
.header(HttpHeaderNames.TRANSFER_ENCODING.getKey(), HttpConstants.CHUNKED)
.header(HttpHeaderNames.CACHE_CONTROL.getKey(), HttpConstants.NO_CACHE);
}
@Override
protected HttpOutputMessage buildMessage(int statusCode, Object data) throws Throwable {
if (data instanceof HttpResult) {
data = ((HttpResult<?>) data).getBody();
if (data == null && statusCode != 200) {
return null;
}
HttpOutputMessage message = encodeHttpOutputMessage(data);
try {
originalResponseEncoder.encode(message.getBody(), data);
} catch (Throwable t) {
message.close();
throw t;
}
return message;
}
return super.buildMessage(statusCode, data);
}
}
| Http1SseServerChannelObserver |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cache/SharedRegionTest.java | {
"start": 1096,
"end": 1686
} | class ____ {
@Test
public void test(SessionFactoryScope scope) {
// create a StateCodes
scope.inTransaction( s -> {
s.persist( new StateCodes( 1 ) );
} );
// now try to load a ZipCodes using the same id : should just return null rather than blow up :)
scope.inTransaction( s -> {
ZipCodes zc = s.find( ZipCodes.class, 1 );
assertNull( zc );
} );
scope.inTransaction( s -> {
s.find( ZipCodes.class, 1 );
} );
}
@Entity(name = "StateCodes")
@Cache(region = "com.acme.referenceData", usage = CacheConcurrencyStrategy.READ_WRITE)
public static | SharedRegionTest |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/internal/invocation/ArgumentsProcessor.java | {
"start": 430,
"end": 2624
} | class ____ {
// drops hidden synthetic parameters (last continuation parameter from Kotlin suspending
// functions)
// and expands varargs
public static Object[] expandArgs(MockitoMethod method, Object[] args) {
int nParams = method.getParameterTypes().length;
if (args != null && args.length > nParams) {
args = Arrays.copyOf(args, nParams);
} // drop extra args (currently -- Kotlin continuation synthetic
// arg)
return expandVarArgs(method.isVarArgs(), args);
}
// expands array varArgs that are given by runtime (1, [a, b]) into true
// varArgs (1, a, b);
private static Object[] expandVarArgs(final boolean isVarArgs, final Object[] args) {
if (!isVarArgs
|| isNullOrEmpty(args)
|| (args[args.length - 1] != null && !args[args.length - 1].getClass().isArray())) {
return args == null ? new Object[0] : args;
}
final int nonVarArgsCount = args.length - 1;
Object[] varArgs;
if (args[nonVarArgsCount] == null) {
// in case someone deliberately passed null varArg array
varArgs = new Object[] {null};
} else {
varArgs = ArrayEquals.createObjectArray(args[nonVarArgsCount]);
}
final int varArgsCount = varArgs.length;
Object[] newArgs = new Object[nonVarArgsCount + varArgsCount];
System.arraycopy(args, 0, newArgs, 0, nonVarArgsCount);
System.arraycopy(varArgs, 0, newArgs, nonVarArgsCount, varArgsCount);
return newArgs;
}
private static <T> boolean isNullOrEmpty(T[] array) {
return array == null || array.length == 0;
}
public static List<ArgumentMatcher> argumentsToMatchers(Object[] arguments) {
List<ArgumentMatcher> matchers = new ArrayList<>(arguments.length);
for (Object arg : arguments) {
if (arg != null && arg.getClass().isArray()) {
matchers.add(new ArrayEquals(arg));
} else {
matchers.add(new Equals(arg));
}
}
return matchers;
}
private ArgumentsProcessor() {}
}
| ArgumentsProcessor |
java | apache__camel | components/camel-caffeine/src/test/java/org/apache/camel/component/caffeine/loadcache/CaffeineLoadCacheTestSupport.java | {
"start": 1117,
"end": 1604
} | class ____ extends CamelTestSupport {
private Cache cache;
@BindToRegistry("cache")
public Cache createCache() {
CacheLoader cl = new CacheLoader<String, Integer>() {
@Override
public Integer load(String key) {
return Integer.parseInt(key) + 1;
}
};
return cache = Caffeine.newBuilder().build(cl);
}
protected Cache getTestCache() {
return cache;
}
}
| CaffeineLoadCacheTestSupport |
java | apache__camel | test-infra/camel-test-infra-aws-common/src/main/java/org/apache/camel/test/infra/aws/common/AWSProperties.java | {
"start": 866,
"end": 993
} | class ____ {
public static final String AWS_CONTAINER = "aws.container";
private AWSProperties() {
}
}
| AWSProperties |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/Endpoint.java | {
"start": 1000,
"end": 3220
} | class ____ {
private final String listener;
private final SecurityProtocol securityProtocol;
private final String host;
private final int port;
public Endpoint(String listener, SecurityProtocol securityProtocol, String host, int port) {
this.listener = listener;
this.securityProtocol = securityProtocol;
this.host = host;
this.port = port;
}
/**
* Returns the listener name of this endpoint.
*/
public String listener() {
return listener;
}
/**
* Returns the listener name of this endpoint. This is non-empty for endpoints provided
* to broker plugins, but may be empty when used in clients.
* @deprecated Since 4.1. Use {@link #listener()} instead. This function will be removed in 5.0.
*/
@Deprecated(since = "4.1", forRemoval = true)
public Optional<String> listenerName() {
return Optional.ofNullable(listener);
}
/**
* Returns the security protocol of this endpoint.
*/
public SecurityProtocol securityProtocol() {
return securityProtocol;
}
/**
* Returns advertised host name of this endpoint.
*/
public String host() {
return host;
}
/**
* Returns the port to which the listener is bound.
*/
public int port() {
return port;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Endpoint)) {
return false;
}
Endpoint that = (Endpoint) o;
return Objects.equals(this.listener, that.listener) &&
Objects.equals(this.securityProtocol, that.securityProtocol) &&
Objects.equals(this.host, that.host) &&
this.port == that.port;
}
@Override
public int hashCode() {
return Objects.hash(listener, securityProtocol, host, port);
}
@Override
public String toString() {
return "Endpoint(" +
"listenerName='" + listener + '\'' +
", securityProtocol=" + securityProtocol +
", host='" + host + '\'' +
", port=" + port +
')';
}
}
| Endpoint |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/reflect/ConstructorUtils.java | {
"start": 9075,
"end": 9192
} | enum ____.
* </ul>
* @throws InstantiationException Thrown if the | type |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/filter/MapInclusion2573Test.java | {
"start": 525,
"end": 3185
} | class ____
{
public String model;
public Map<String, Integer> properties;
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final Map<String, Integer> CAR_PROPERTIES = new LinkedHashMap<>();
{
CAR_PROPERTIES.put("Speed", 100);
CAR_PROPERTIES.put("Weight", null);
}
private final Car CAR = new Car();
{
CAR.model = "F60";
CAR.properties = CAR_PROPERTIES;
}
private final JsonInclude.Value BOTH_NON_NULL = JsonInclude.Value.construct(
JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL);
// final private ObjectMapper MAPPER = newJsonMapper();
// [databind#2572]
@Test
public void test2572MapDefault() throws Exception
{
ObjectMapper mapper = JsonMapper.builder()
.changeDefaultPropertyInclusion(incl -> BOTH_NON_NULL)
.build();
assertEquals(a2q("{'Speed':100}"),
mapper.writeValueAsString(CAR_PROPERTIES));
assertEquals(a2q("{'model':'F60','properties':{'Speed':100}}"),
mapper.writeValueAsString(CAR));
}
// [databind#2572]
@Test
public void test2572MapOverrideUseDefaults() throws Exception
{
ObjectMapper mapper = JsonMapper.builder()
.changeDefaultPropertyInclusion(incl -> BOTH_NON_NULL)
.withConfigOverride(Map.class,
o -> o.setInclude(JsonInclude.Value.construct(JsonInclude.Include.USE_DEFAULTS,
JsonInclude.Include.USE_DEFAULTS)))
.build();
assertEquals(a2q("{'Speed':100}"),
mapper.writeValueAsString(CAR_PROPERTIES));
assertEquals(a2q("{'model':'F60','properties':{'Speed':100}}"),
mapper.writeValueAsString(CAR));
}
// [databind#2572]
@Test
public void test2572MapOverrideInclAlways() throws Exception
{
ObjectMapper mapper = JsonMapper.builder()
.changeDefaultPropertyInclusion(incl -> BOTH_NON_NULL)
.withConfigOverride(Map.class,
o -> o.setInclude(JsonInclude.Value.construct(JsonInclude.Include.ALWAYS,
JsonInclude.Include.ALWAYS)))
.build();
assertEquals(a2q("{'Speed':100,'Weight':null}"),
mapper.writeValueAsString(CAR_PROPERTIES));
assertEquals(a2q("{'model':'F60','properties':{'Speed':100,'Weight':null}}"),
mapper.writeValueAsString(CAR));
}
}
| Car |
java | spring-projects__spring-framework | spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/InitBinderBindingContextTests.java | {
"start": 10829,
"end": 11515
} | class ____ {
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
@InitBinder(value="foo")
public void initBinderWithAttributeName(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
@InitBinder
public String initBinderReturnValue(WebDataBinder dataBinder) {
return "invalid";
}
@InitBinder
public void initBinderTypeConversion(WebDataBinder dataBinder, @RequestParam int requestParam) {
dataBinder.setDisallowedFields("requestParam-" + requestParam);
}
}
private record DataBean(String name, int age, @BindParam("Some-Int-Array") Integer[] someIntArray) {
}
}
| InitBinderHandler |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/json/JsonComparison.java | {
"start": 850,
"end": 1914
} | class ____ {
private final Result result;
private final @Nullable String message;
private JsonComparison(Result result, @Nullable String message) {
this.result = result;
this.message = message;
}
/**
* Factory method to create a new {@link JsonComparison} when the JSON
* strings match.
* @return a new {@link JsonComparison} instance
*/
public static JsonComparison match() {
return new JsonComparison(Result.MATCH, null);
}
/**
* Factory method to create a new {@link JsonComparison} when the JSON strings
* do not match.
* @param message a message describing the mismatch
* @return a new {@link JsonComparison} instance
*/
public static JsonComparison mismatch(String message) {
return new JsonComparison(Result.MISMATCH, message);
}
/**
* Return the result of the comparison.
*/
public Result getResult() {
return this.result;
}
/**
* Return a message describing the comparison.
*/
public @Nullable String getMessage() {
return this.message;
}
/**
* Comparison results.
*/
public | JsonComparison |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/output/committer/manifest/ManifestCommitterTestSupport.java | {
"start": 12694,
"end": 13443
} | class ____<K, V> implements AutoCloseable {
private final RecordWriter<K, V> writer;
private final TaskAttemptContext context;
public CloseWriter(RecordWriter<K, V> writer,
TaskAttemptContext context) {
this.writer = writer;
this.context = context;
}
@Override
public void close() {
try {
writer.close(context);
} catch (IOException | InterruptedException e) {
LOG.error("When closing {} on context {}",
writer, context, e);
}
}
}
public static final String ATTEMPT_STRING =
"attempt_%s_m_%06d_%d";
/**
* Creates a random JobID and then as many tasks
* with the specific number of task attempts.
*/
public static final | CloseWriter |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/stats/SearchContextStatsTests.java | {
"start": 1346,
"end": 8452
} | class ____ extends MapperServiceTestCase {
private final Directory directory = newDirectory();
private SearchStats searchStats;
private List<MapperService> mapperServices;
private List<IndexReader> readers;
private long minMillis, maxMillis, minNanos, maxNanos;
@Before
public void setup() throws IOException {
int indexCount = randomIntBetween(1, 5);
List<SearchExecutionContext> contexts = new ArrayList<>(indexCount);
mapperServices = new ArrayList<>(indexCount);
readers = new ArrayList<>(indexCount);
maxMillis = minMillis = dateTimeToLong("2025-01-01T00:00:01");
maxNanos = minNanos = dateNanosToLong("2025-01-01T00:00:01");
MapperServiceTestCase mapperHelper = new MapperServiceTestCase() {
};
// create one or more index, so that there is one or more SearchExecutionContext in SearchStats
for (int i = 0; i < indexCount; i++) {
// Start with millis/nanos, numeric and keyword types in the index mapping, more data types can be covered later if needed.
// SearchContextStats returns min/max for millis and nanos only currently, null is returned for the other types min and max.
MapperService mapperService;
if (i == 0) {
mapperService = mapperHelper.createMapperService("""
{
"doc": { "properties": {
"byteField": { "type": "byte" },
"shortField": { "type": "short" },
"intField": { "type": "integer" },
"longField": { "type": "long" },
"floatField": { "type": "float" },
"doubleField": { "type": "double" },
"dateField": { "type": "date" },
"dateNanosField": { "type": "date_nanos" },
"keywordField": { "type": "keyword" },
"maybeMixedField": { "type": "long" }
}}
}""");
} else {
mapperService = mapperHelper.createMapperService("""
{
"doc": { "properties": {
"byteField": { "type": "byte" },
"shortField": { "type": "short" },
"intField": { "type": "integer" },
"longField": { "type": "long" },
"floatField": { "type": "float" },
"doubleField": { "type": "double" },
"dateField": { "type": "date" },
"dateNanosField": { "type": "date_nanos" },
"maybeMixedField": { "type": "date" }
}}
}""");
}
mapperServices.add(mapperService);
int perIndexDocumentCount = randomIntBetween(1, 5);
IndexReader reader;
try (RandomIndexWriter writer = new RandomIndexWriter(random(), directory)) {
List<Byte> byteValues = randomList(perIndexDocumentCount, perIndexDocumentCount, ESTestCase::randomByte);
List<Short> shortValues = randomList(perIndexDocumentCount, perIndexDocumentCount, ESTestCase::randomShort);
List<Integer> intValues = randomList(perIndexDocumentCount, perIndexDocumentCount, ESTestCase::randomInt);
List<Long> longValues = randomList(perIndexDocumentCount, perIndexDocumentCount, ESTestCase::randomLong);
List<Float> floatValues = randomList(perIndexDocumentCount, perIndexDocumentCount, ESTestCase::randomFloat);
List<Double> doubleValues = randomList(perIndexDocumentCount, perIndexDocumentCount, ESTestCase::randomDouble);
List<String> keywordValues = randomList(perIndexDocumentCount, perIndexDocumentCount, () -> randomAlphaOfLength(5));
for (int j = 0; j < perIndexDocumentCount; j++) {
long millis = minMillis + (j == 0 ? 0 : randomInt(1000));
long nanos = minNanos + (j == 0 ? 0 : randomInt(1000));
maxMillis = Math.max(millis, maxMillis);
maxNanos = Math.max(nanos, maxNanos);
minMillis = Math.min(millis, minMillis);
minNanos = Math.min(nanos, minNanos);
writer.addDocument(
List.of(
new IntField("byteField", byteValues.get(j), Field.Store.NO),
new IntField("shortField", shortValues.get(j), Field.Store.NO),
new IntField("intField", intValues.get(j), Field.Store.NO),
new LongField("longField", longValues.get(j), Field.Store.NO),
new FloatField("floatField", floatValues.get(j), Field.Store.NO),
new DoubleField("doubleField", doubleValues.get(j), Field.Store.NO),
new LongField("dateField", millis, Field.Store.NO),
new LongField("dateNanosField", nanos, Field.Store.NO),
new StringField("keywordField", keywordValues.get(j), Field.Store.NO),
new LongField("maybeMixedField", millis, Field.Store.NO)
)
);
}
reader = writer.getReader();
readers.add(reader);
}
// create SearchExecutionContext for each index
SearchExecutionContext context = mapperHelper.createSearchExecutionContext(mapperService, newSearcher(reader));
contexts.add(context);
}
// create SearchContextStats
searchStats = SearchContextStats.from(contexts);
}
public void testMinMax() {
List<String> fields = List.of(
"byteField",
"shortField",
"intField",
"longField",
"floatField",
"doubleField",
"dateField",
"dateNanosField",
"keywordField"
);
for (String field : fields) {
Object min = searchStats.min(new FieldAttribute.FieldName(field));
Object max = searchStats.max(new FieldAttribute.FieldName(field));
if (field.startsWith("date") == false) {
assertNull(min);
assertNull(max);
} else if (field.equals("dateField")) {
assertEquals(minMillis, min);
assertEquals(maxMillis, max);
} else if (field.equals("dateNanosField")) {
assertEquals(minNanos, min);
assertEquals(maxNanos, max);
}
}
}
@After
public void cleanup() throws IOException {
IOUtils.close(readers);
IOUtils.close(mapperServices);
IOUtils.close(directory);
}
}
| SearchContextStatsTests |
java | apache__kafka | tools/src/main/java/org/apache/kafka/tools/TransactionsCommand.java | {
"start": 3441,
"end": 9841
} | class ____ extends TransactionsCommand {
AbortTransactionCommand(Time time) {
super(time);
}
@Override
String name() {
return "abort";
}
@Override
void addSubparser(Subparsers subparsers) {
Subparser subparser = subparsers.addParser(name())
.help("abort a hanging transaction (requires administrative privileges)");
subparser.addArgument("--topic")
.help("topic name")
.action(store())
.type(String.class)
.required(true);
subparser.addArgument("--partition")
.help("partition number")
.action(store())
.type(Integer.class)
.required(true);
ArgumentGroup newBrokerArgumentGroup = subparser
.addArgumentGroup("Brokers on versions 3.0 and above")
.description("For newer brokers, only the start offset of the transaction " +
"to be aborted is required");
newBrokerArgumentGroup.addArgument("--start-offset")
.help("start offset of the transaction to abort")
.action(store())
.type(Long.class);
ArgumentGroup olderBrokerArgumentGroup = subparser
.addArgumentGroup("Brokers on versions older than 3.0")
.description("For older brokers, you must provide all of these arguments");
olderBrokerArgumentGroup.addArgument("--producer-id")
.help("producer id")
.action(store())
.type(Long.class);
olderBrokerArgumentGroup.addArgument("--producer-epoch")
.help("producer epoch")
.action(store())
.type(Short.class);
olderBrokerArgumentGroup.addArgument("--coordinator-epoch")
.help("coordinator epoch")
.action(store())
.type(Integer.class);
}
private AbortTransactionSpec buildAbortSpec(
Admin admin,
TopicPartition topicPartition,
long startOffset
) throws Exception {
final DescribeProducersResult.PartitionProducerState result;
try {
result = admin.describeProducers(Set.of(topicPartition))
.partitionResult(topicPartition)
.get();
} catch (ExecutionException e) {
printErrorAndExit("Failed to validate producer state for partition "
+ topicPartition, e.getCause());
return null;
}
Optional<ProducerState> foundProducerState = result.activeProducers().stream()
.filter(producerState -> {
OptionalLong txnStartOffsetOpt = producerState.currentTransactionStartOffset();
return txnStartOffsetOpt.isPresent() && txnStartOffsetOpt.getAsLong() == startOffset;
})
.findFirst();
if (foundProducerState.isEmpty()) {
printErrorAndExit("Could not find any open transactions starting at offset " +
startOffset + " on partition " + topicPartition);
return null;
}
ProducerState producerState = foundProducerState.get();
return new AbortTransactionSpec(
topicPartition,
producerState.producerId(),
(short) producerState.producerEpoch(),
producerState.coordinatorEpoch().orElse(0)
);
}
private void abortTransaction(
Admin admin,
AbortTransactionSpec abortSpec
) throws Exception {
try {
admin.abortTransaction(abortSpec).all().get();
} catch (ExecutionException e) {
TransactionsCommand.printErrorAndExit("Failed to abort transaction " + abortSpec, e.getCause());
}
}
@Override
void execute(Admin admin, Namespace ns, PrintStream out) throws Exception {
String topicName = ns.getString("topic");
Integer partitionId = ns.getInt("partition");
TopicPartition topicPartition = new TopicPartition(topicName, partitionId);
Long startOffset = ns.getLong("start_offset");
Long producerId = ns.getLong("producer_id");
if (startOffset == null && producerId == null) {
printErrorAndExit("The transaction to abort must be identified either with " +
"--start-offset (for brokers on 3.0 or above) or with " +
"--producer-id, --producer-epoch, and --coordinator-epoch (for older brokers)");
return;
}
final AbortTransactionSpec abortSpec;
if (startOffset == null) {
Short producerEpoch = ns.getShort("producer_epoch");
if (producerEpoch == null) {
printErrorAndExit("Missing required argument --producer-epoch");
return;
}
Integer coordinatorEpoch = ns.getInt("coordinator_epoch");
if (coordinatorEpoch == null) {
printErrorAndExit("Missing required argument --coordinator-epoch");
return;
}
// If a transaction was started by a new producerId and became hanging
// before the initial commit/abort, then the coordinator epoch will be -1
// as seen in the `DescribeProducers` output. In this case, we conservatively
// use a coordinator epoch of 0, which is less than or equal to any possible
// leader epoch.
if (coordinatorEpoch < 0) {
coordinatorEpoch = 0;
}
abortSpec = new AbortTransactionSpec(
topicPartition,
producerId,
producerEpoch,
coordinatorEpoch
);
} else {
abortSpec = buildAbortSpec(admin, topicPartition, startOffset);
}
abortTransaction(admin, abortSpec);
}
}
static | AbortTransactionCommand |
java | apache__camel | core/camel-base/src/main/java/org/apache/camel/impl/event/AbstractContextEvent.java | {
"start": 1063,
"end": 1656
} | class ____ extends EventObject implements CamelContextEvent {
private static final @Serial long serialVersionUID = 1L;
private final CamelContext context;
private long timestamp;
public AbstractContextEvent(CamelContext source) {
super(source);
this.context = source;
}
@Override
public CamelContext getContext() {
return context;
}
@Override
public long getTimestamp() {
return timestamp;
}
@Override
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
}
| AbstractContextEvent |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/ITestAzureBlobFileSystemChooseSAS.java | {
"start": 6426,
"end": 6856
} | class ____ be chosen and User Delegation SAS should be used.
* @throws Exception
*/
@Test
public void testBothProviderFixedTokenConfigured() throws Exception {
assumeDfsServiceType();
assumeHnsEnabled();
AbfsConfiguration testAbfsConfig = new AbfsConfiguration(
getRawConfiguration(), this.getAccountName());
removeAnyPresetConfiguration(testAbfsConfig);
// Configuring a SASTokenProvider | should |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/junit/jupiter/SpringExtensionConfig.java | {
"start": 2438,
"end": 2860
} | class ____.
*
* <p>By default, the {@code SpringExtension} uses a test-method scoped
* {@code ExtensionContext}. Thus, there is no need to declare this annotation
* attribute with a value of {@code false}.
*
* @see SpringExtension
* @see SpringExtension#getTestInstantiationExtensionContextScope(org.junit.jupiter.api.extension.ExtensionContext)
*/
boolean useTestClassScopedExtensionContext();
}
| hierarchies |
java | spring-projects__spring-boot | build-plugin/spring-boot-maven-plugin/src/intTest/projects/run-working-directory/src/main/java/org/test/SampleApplication.java | {
"start": 652,
"end": 869
} | class ____ {
public static void main(String[] args) {
String workingDirectory = System.getProperty("user.dir");
System.out.println(String.format("I haz been run from %s", workingDirectory));
}
}
| SampleApplication |
java | apache__camel | core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ComponentVerifierExtension.java | {
"start": 13427,
"end": 13804
} | interface ____ extends Attribute {
/**
* Group name
*/
GroupAttribute GROUP_NAME = new GroupErrorAttribute("GROUP_NAME");
/**
* Options for the group
*/
GroupAttribute GROUP_OPTIONS = new GroupErrorAttribute("GROUP_OPTIONS");
}
}
/**
* Custom | GroupAttribute |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/logging/structured/StructuredLoggingJsonPropertiesBeanFactoryInitializationAotProcessorTests.java | {
"start": 5408,
"end": 5570
} | class ____ implements StructuredLoggingJsonMembersCustomizer<String> {
@Override
public void customize(Members<String> members) {
}
}
static | TestCustomizer |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/scalar/EndsWithFunction.java | {
"start": 1353,
"end": 2559
} | class ____ extends BuiltInScalarFunction {
public EndsWithFunction(SpecializedContext context) {
super(BuiltInFunctionDefinitions.ENDS_WITH, context);
}
public @Nullable Boolean eval(@Nullable StringData expr, @Nullable StringData endExpr) {
if (expr == null || endExpr == null) {
return null;
}
if (BinaryStringDataUtil.isEmpty((BinaryStringData) endExpr)) {
return true;
}
return ((BinaryStringData) expr).endsWith((BinaryStringData) endExpr);
}
public @Nullable Boolean eval(@Nullable byte[] expr, @Nullable byte[] endExpr) {
if (expr == null || endExpr == null) {
return null;
}
if (endExpr.length == 0) {
return true;
}
return matchAtEnd(expr, endExpr);
}
private static boolean matchAtEnd(byte[] source, byte[] target) {
int start = source.length - target.length;
if (start < 0) {
return false;
}
for (int i = start; i < source.length; i++) {
if (source[i] != target[i - start]) {
return false;
}
}
return true;
}
}
| EndsWithFunction |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng7772CoreExtensionsNotFoundTest.java | {
"start": 1157,
"end": 2220
} | class ____ extends AbstractMavenIntegrationTestCase {
@Test
public void testCoreExtensionsNotFound() throws Exception {
File testDir = extractResources("/mng-7772-core-extensions-not-found");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setUserHomeDirectory(Paths.get(testDir.toPath().toString(), "home"));
try {
verifier.addCliArgument("validate");
verifier.execute();
fail("should have failed ");
} catch (VerificationException e) {
try {
verifier.verifyTextInLog("[ERROR] Error executing Maven.");
verifier.verifyTextInLog(
"Extension org.apache.maven.its.it-core-extensions:maven-it-unknown-extensions:0.1 or one of its dependencies could not be resolved");
} catch (VerificationException e2) {
throw new VerificationException(e2.getMessage() + "\nLog:" + verifier.loadLogContent());
}
}
}
}
| MavenITmng7772CoreExtensionsNotFoundTest |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/connector/sink/TransformationSinkProvider.java | {
"start": 2239,
"end": 2522
} | interface ____ extends ProviderContext {
/** Input transformation to transform. */
Transformation<RowData> getInputTransformation();
/** Returns the field index of the rowtime attribute, or {@code -1} otherwise. */
int getRowtimeIndex();
}
}
| Context |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_3300/Issue3334.java | {
"start": 117,
"end": 1409
} | class ____ extends TestCase {
public void test_for_issue() throws Exception {
assertEquals(0,
JSON.parseObject("{\"id\":false}", VO.class).id);
assertEquals(1,
JSON.parseObject("{\"id\":true}", VO.class).id);
assertEquals(0,
JSON.parseObject("{\"id64\":false}", VO.class).id64);
assertEquals(1,
JSON.parseObject("{\"id64\":true}", VO.class).id64);
assertEquals(0,
JSON.parseObject("{\"id16\":false}", VO.class).id16);
assertEquals(1,
JSON.parseObject("{\"id16\":true}", VO.class).id16);
assertEquals(0,
JSON.parseObject("{\"id8\":false}", VO.class).id8);
assertEquals(1,
JSON.parseObject("{\"id8\":true}", VO.class).id8);
assertEquals(0F,
JSON.parseObject("{\"floatValue\":false}", VO.class).floatValue);
assertEquals(1F,
JSON.parseObject("{\"floatValue\":true}", VO.class).floatValue);
assertEquals(0D,
JSON.parseObject("{\"doubleValue\":false}", VO.class).doubleValue);
assertEquals(1D,
JSON.parseObject("{\"doubleValue\":true}", VO.class).doubleValue);
}
public static | Issue3334 |
java | quarkusio__quarkus | extensions/panache/hibernate-reactive-rest-data-panache/deployment/src/test/java/io/quarkus/hibernate/reactive/rest/data/panache/deployment/entity/PanacheEntityResourcePostMethodTest.java | {
"start": 390,
"end": 1217
} | class ____ extends AbstractPostMethodTest {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(Collection.class, CollectionsResource.class, AbstractEntity.class, AbstractItem.class,
Item.class, ItemsResource.class)
.addAsResource("application.properties")
.addAsResource("import.sql"));
@Test
void shouldCopyAdditionalMethodsAsResources() {
given().accept("application/json")
.when().post("/collections/name/mycollection")
.then().statusCode(200)
.and().body("id", is("mycollection"))
.and().body("name", is("mycollection"));
}
}
| PanacheEntityResourcePostMethodTest |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/type/AbstractMethodMetadataTests.java | {
"start": 8472,
"end": 8698
} | class ____ {
@Tag
@MetaAnnotationAttributes1
@MetaAnnotationAttributes2
public abstract String test();
}
@Retention(RetentionPolicy.RUNTIME)
@AnnotationAttributes(name = "m1", size = 1)
@ | WithMetaAnnotationAttributes |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KinesisFirehose2EndpointBuilderFactory.java | {
"start": 20349,
"end": 22560
} | interface ____ {
/**
* AWS Kinesis Firehose (camel-aws2-kinesis)
* Produce data to AWS Kinesis Firehose streams.
*
* Category: cloud,messaging
* Since: 3.2
* Maven coordinates: org.apache.camel:camel-aws2-kinesis
*
* @return the dsl builder for the headers' name.
*/
default KinesisFirehose2HeaderNameBuilder aws2KinesisFirehose() {
return KinesisFirehose2HeaderNameBuilder.INSTANCE;
}
/**
* AWS Kinesis Firehose (camel-aws2-kinesis)
* Produce data to AWS Kinesis Firehose streams.
*
* Category: cloud,messaging
* Since: 3.2
* Maven coordinates: org.apache.camel:camel-aws2-kinesis
*
* Syntax: <code>aws2-kinesis-firehose:streamName</code>
*
* Path parameter: streamName (required)
* Name of the stream
*
* @param path streamName
* @return the dsl builder
*/
default KinesisFirehose2EndpointBuilder aws2KinesisFirehose(String path) {
return KinesisFirehose2EndpointBuilderFactory.endpointBuilder("aws2-kinesis-firehose", path);
}
/**
* AWS Kinesis Firehose (camel-aws2-kinesis)
* Produce data to AWS Kinesis Firehose streams.
*
* Category: cloud,messaging
* Since: 3.2
* Maven coordinates: org.apache.camel:camel-aws2-kinesis
*
* Syntax: <code>aws2-kinesis-firehose:streamName</code>
*
* Path parameter: streamName (required)
* Name of the stream
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path streamName
* @return the dsl builder
*/
default KinesisFirehose2EndpointBuilder aws2KinesisFirehose(String componentName, String path) {
return KinesisFirehose2EndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the AWS Kinesis Firehose component.
*/
public static | KinesisFirehose2Builders |
java | google__dagger | dagger-compiler/main/java/dagger/internal/codegen/xprocessing/XAnnotationSpecs.java | {
"start": 4705,
"end": 7495
} | class ____ {
private final XClassName className;
private final Set<String> nonArrayMembers = new HashSet<>();
private final ListMultimap<String, XCodeBlock> members = LinkedListMultimap.create();
Builder(XClassName className) {
this.className = className;
}
/** Adds the given member to the annotation. */
@CanIgnoreReturnValue
public Builder addMember(String name, String format, Object... args) {
return addMember(name, XCodeBlock.of(format, args));
}
/** Adds the given annotation names to the method. */
@CanIgnoreReturnValue
public Builder addMember(String name, XCodeBlock value) {
checkState(nonArrayMembers.add(name));
checkState(!members.containsKey(name));
members.put(name, value);
return this;
}
/** Adds the given member to the annotation. */
@CanIgnoreReturnValue
public Builder addArrayMember(String name, String format, Object... args) {
return addArrayMember(name, XCodeBlock.of(format, args));
}
/** Adds the given annotation names to the method. */
@CanIgnoreReturnValue
public Builder addArrayMember(String name, XCodeBlock value) {
checkState(!nonArrayMembers.contains(name));
members.put(name, value);
return this;
}
/** Builds the parameter and returns an {@link XParameterSpec}. */
public XAnnotationSpec build() {
XAnnotationSpec.Builder builder = XAnnotationSpec.builder(className);
// JavaPoet supports array-typed annotation values natively so just add all members normally.
for (String name : members.keySet()) {
for (XCodeBlock value : members.get(name)) {
toJavaPoet(builder).addMember(name, toJavaPoet(value));
}
}
// KotlinPoet does not support array-typed annotation values, so roll our own.
for (String name : members.keySet()) {
List<XCodeBlock> values = members.get(name);
if (nonArrayMembers.contains(name)) {
toKotlinPoet(builder).addMember("%L = %L", name, toKotlinPoet(values.get(0)));
} else if (values.size() == 1) {
toKotlinPoet(builder).addMember("%L = [%L]", name, toKotlinPoet(values.get(0)));
} else {
toKotlinPoet(builder)
.addMember("%L = [\n⇥⇥%L⇤⇤\n]", name, toKotlinPoet(formattedList(values)));
}
}
return builder.build();
}
private XCodeBlock formattedList(List<XCodeBlock> values) {
XCodeBlock.Builder builder = XCodeBlock.builder();
for (int i = 0; i < values.size(); i++) {
builder.add(values.get(i));
if (values.size() > 1 && i < values.size() - 1) {
builder.add(",\n");
}
}
return builder.build();
}
}
private XAnnotationSpecs() {}
}
| Builder |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/io/InputStreamSource.java | {
"start": 735,
"end": 828
} | interface ____ objects that are sources for an {@link InputStream}.
*
* <p>This is the base | for |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/admin/UnregisterBrokerResult.java | {
"start": 1061,
"end": 1389
} | class ____ {
private final KafkaFuture<Void> future;
UnregisterBrokerResult(final KafkaFuture<Void> future) {
this.future = future;
}
/**
* Return a future which succeeds if the operation is successful.
*/
public KafkaFuture<Void> all() {
return future;
}
}
| UnregisterBrokerResult |
java | elastic__elasticsearch | x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/execution/search/QueryRequest.java | {
"start": 378,
"end": 554
} | interface ____ {
SearchSourceBuilder searchSource();
default void nextAfter(Ordinal ordinal) {
searchSource().searchAfter(ordinal.toArray());
}
}
| QueryRequest |
java | elastic__elasticsearch | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/ltr/QueryFeatureExtractorTests.java | {
"start": 1708,
"end": 8831
} | class ____ extends AbstractBuilderTestCase {
private IndexReader addDocs(Directory dir, String[] textValues, int[] numberValues) throws IOException {
var config = newIndexWriterConfig();
// override the merge policy to ensure that docs remain in the same ingestion order
config.setMergePolicy(newLogMergePolicy(random()));
try (RandomIndexWriter indexWriter = new RandomIndexWriter(random(), dir, config)) {
for (int i = 0; i < textValues.length; i++) {
Document doc = new Document();
doc.add(newTextField(TEXT_FIELD_NAME, textValues[i], Field.Store.NO));
doc.add(new IntField(INT_FIELD_NAME, numberValues[i], Field.Store.YES));
indexWriter.addDocument(doc);
if (randomBoolean()) {
indexWriter.flush();
}
}
return indexWriter.getReader();
}
}
public void testQueryExtractor() throws IOException {
try (var dir = newDirectory()) {
try (
var reader = addDocs(
dir,
new String[] { "the quick brown fox", "the slow brown fox", "the grey dog", "yet another string" },
new int[] { 5, 10, 12, 11 }
)
) {
var searcher = newSearcher(reader);
searcher.setSimilarity(new ClassicSimilarity());
QueryRewriteContext ctx = createQueryRewriteContext();
List<QueryExtractorBuilder> queryExtractorBuilders = List.of(
new QueryExtractorBuilder(
"text_score",
QueryProvider.fromParsedQuery(QueryBuilders.matchQuery(TEXT_FIELD_NAME, "quick fox"))
).rewrite(ctx),
new QueryExtractorBuilder(
"number_score",
QueryProvider.fromParsedQuery(QueryBuilders.rangeQuery(INT_FIELD_NAME).from(12).to(12))
).rewrite(ctx),
new QueryExtractorBuilder(
"matching_none",
QueryProvider.fromParsedQuery(QueryBuilders.termQuery(TEXT_FIELD_NAME, "never found term"))
).rewrite(ctx),
new QueryExtractorBuilder(
"matching_missing_field",
QueryProvider.fromParsedQuery(QueryBuilders.termQuery("missing_text", "quick fox"))
).rewrite(ctx),
new QueryExtractorBuilder(
"phrase_score",
QueryProvider.fromParsedQuery(QueryBuilders.matchPhraseQuery(TEXT_FIELD_NAME, "slow brown fox"))
).rewrite(ctx)
);
SearchExecutionContext dummySEC = createSearchExecutionContext();
List<Weight> weights = new ArrayList<>();
List<String> featureNames = new ArrayList<>();
for (QueryExtractorBuilder qeb : queryExtractorBuilders) {
Query q = qeb.query().getParsedQuery().toQuery(dummySEC);
Weight weight = searcher.rewrite(q).createWeight(searcher, ScoreMode.COMPLETE, 1f);
weights.add(weight);
featureNames.add(qeb.featureName());
}
QueryFeatureExtractor queryFeatureExtractor = new QueryFeatureExtractor(featureNames, weights);
List<Map<String, Object>> extractedFeatures = new ArrayList<>();
for (LeafReaderContext leafReaderContext : searcher.getLeafContexts()) {
int maxDoc = leafReaderContext.reader().maxDoc();
queryFeatureExtractor.setNextReader(leafReaderContext);
for (int i = 0; i < maxDoc; i++) {
Map<String, Object> featureMap = new HashMap<>();
queryFeatureExtractor.addFeatures(featureMap, i);
extractedFeatures.add(featureMap);
}
}
assertThat(extractedFeatures, hasSize(4));
// Should never add features for queries that don't match a document or on documents where the field is missing
for (Map<String, Object> features : extractedFeatures) {
assertThat(features, not(hasKey("matching_none")));
assertThat(features, not(hasKey("matching_missing_field")));
}
// First two only match the text field
assertThat(extractedFeatures.get(0), hasEntry("text_score", 1.7135582f));
assertThat(extractedFeatures.get(0), not(hasKey("number_score")));
assertThat(extractedFeatures.get(0), not(hasKey("phrase_score")));
assertThat(extractedFeatures.get(1), hasEntry("text_score", 0.7554128f));
assertThat(extractedFeatures.get(1), not(hasKey("number_score")));
assertThat(extractedFeatures.get(1), hasEntry("phrase_score", 2.468971f));
// Only matches the range query
assertThat(extractedFeatures.get(2), hasEntry("number_score", 1f));
assertThat(extractedFeatures.get(2), not(hasKey("text_score")));
assertThat(extractedFeatures.get(2), not(hasKey("phrase_score")));
// No query matches
assertThat(extractedFeatures.get(3), anEmptyMap());
}
}
}
public void testEmptyDisiPriorityQueue() throws IOException {
try (var dir = newDirectory()) {
var config = newIndexWriterConfig();
config.setMergePolicy(NoMergePolicy.INSTANCE);
try (
var reader = addDocs(
dir,
new String[] { "the quick brown fox", "the slow brown fox", "the grey dog", "yet another string" },
new int[] { 5, 10, 12, 11 }
)
) {
var searcher = newSearcher(reader);
searcher.setSimilarity(new ClassicSimilarity());
// Scorers returned by weights are null
List<String> featureNames = randomList(1, 10, ESTestCase::randomIdentifier);
List<Weight> weights = Stream.generate(() -> mock(Weight.class)).limit(featureNames.size()).toList();
QueryFeatureExtractor featureExtractor = new QueryFeatureExtractor(featureNames, weights);
for (LeafReaderContext leafReaderContext : searcher.getLeafContexts()) {
int maxDoc = leafReaderContext.reader().maxDoc();
featureExtractor.setNextReader(leafReaderContext);
for (int i = 0; i < maxDoc; i++) {
Map<String, Object> featureMap = new HashMap<>();
featureExtractor.addFeatures(featureMap, i);
assertThat(featureMap, anEmptyMap());
}
}
}
}
}
}
| QueryFeatureExtractorTests |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/asm/ClassReader.java | {
"start": 159595,
"end": 160165
} | class ____ or adapters.</i>
*
* @param offset the start offset of the bytes to be read in this {@link ClassReader}.
* @param length the number of bytes to read.
* @return the read bytes.
*/
public byte[] readBytes(final int offset, final int length) {
byte[] result = new byte[length];
System.arraycopy(classFileBuffer, offset, result, 0, length);
return result;
}
/**
* Reads an unsigned short value in this {@link ClassReader}. <i>This method is intended for
* {@link Attribute} sub classes, and is normally not needed by | generators |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/json/SlotSharingGroupIDSerializer.java | {
"start": 1285,
"end": 1728
} | class ____ extends StdSerializer<SlotSharingGroupId> {
private static final long serialVersionUID = -4052148694985726120L;
public SlotSharingGroupIDSerializer() {
super(SlotSharingGroupId.class);
}
@Override
public void serialize(SlotSharingGroupId value, JsonGenerator gen, SerializerProvider provider)
throws IOException {
gen.writeString(value.toString());
}
}
| SlotSharingGroupIDSerializer |
java | quarkusio__quarkus | extensions/reactive-routes/deployment/src/test/java/io/quarkus/vertx/web/reactive/RequestContextPropagationTest.java | {
"start": 1862,
"end": 2267
} | class ____ {
static final CompletableFuture<Boolean> DESTROYED = new CompletableFuture<>();
private volatile String prefix;
void init(String prefix) {
this.prefix = prefix;
}
String pong(String pong) {
return prefix + pong;
}
@PreDestroy
void destroy() {
DESTROYED.complete(true);
}
}
}
| Ping |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/SubResourcesAsBeansTest.java | {
"start": 2122,
"end": 2379
} | class ____ {
@Inject
ResourceContext resourceContext;
@Path("{last}")
public RestSubResource hello() {
return resourceContext.getResource(RestSubResource.class);
}
}
public static | MiddleRestResource |
java | apache__camel | components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvContainingMultiQuoteCharEscapeFalseTest.java | {
"start": 6019,
"end": 6917
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
@DataField(pos = 1)
private String firstField;
@DataField(pos = 2)
private String secondField;
@DataField(pos = 3, pattern = "########.##")
private BigDecimal number;
public String getFirstField() {
return firstField;
}
public void setFirstField(String firstField) {
this.firstField = firstField;
}
public String getSecondField() {
return secondField;
}
public void setSecondField(String secondField) {
this.secondField = secondField;
}
public BigDecimal getNumber() {
return number;
}
public void setNumber(BigDecimal number) {
this.number = number;
}
}
}
| BindyCsvRowFormat75192 |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/event/service/internal/EventListenerGroupAppendListenerTest.java | {
"start": 905,
"end": 3167
} | class ____ extends BaseSessionFactoryFunctionalTest {
private static final DuplicationStrategy DUPLICATION_STRATEGY_REPLACE_ORIGINAL = new DuplicationStrategy() {
@Override
public boolean areMatch(
Object added, Object existing) {
return true;
}
@Override
public Action getAction() {
return Action.REPLACE_ORIGINAL;
}
};
@Test
public void testAppendListenerWithNoStrategy() {
SpecificMergeEventListener1 mergeEventListener = new SpecificMergeEventListener1();
runAppendListenerTest( null, mergeEventListener );
}
@Test
public void testAppendListenerWithReplaceOriginalStrategy() {
SpecificMergeEventListener2 mergeEventListener = new SpecificMergeEventListener2();
runAppendListenerTest( DUPLICATION_STRATEGY_REPLACE_ORIGINAL, mergeEventListener );
}
private void runAppendListenerTest(
DuplicationStrategy duplicationStrategy,
DefaultMergeEventListener mergeEventListener) {
inTransaction( session -> {
EventListenerGroup<MergeEventListener> group =
sessionFactory().getEventListenerRegistry()
.getEventListenerGroup( EventType.MERGE );
if ( duplicationStrategy != null ) {
group.addDuplicationStrategy( duplicationStrategy );
}
group.appendListener( mergeEventListener );
Iterable<MergeEventListener> listeners = group.listeners();
assertTrue( listeners.iterator().hasNext(), "Should have at least one listener" );
listeners.forEach( this::assertCallbackRegistry );
} );
}
private void assertCallbackRegistry(
MergeEventListener listener) {
try {
assertNotNull( getCallbackRegistry( listener ), "callbackRegistry should not be null" );
}
catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
fail( "Unable to get callbackRegistry field on listener" );
}
}
private static CallbackRegistry getCallbackRegistry(
MergeEventListener listener)
throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
Class<?> clazz = Class.forName( "org.hibernate.event.internal.AbstractSaveEventListener" );
Field field = clazz.getDeclaredField( "callbackRegistry" );
field.setAccessible( true );
return (CallbackRegistry) field.get( listener );
}
private static | EventListenerGroupAppendListenerTest |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/cglib_lazy_error/PersonMapper.java | {
"start": 712,
"end": 845
} | interface ____ {
Person selectById(int id);
Person selectByStringId(String id);
int insertPerson(Person person);
}
| PersonMapper |
java | spring-projects__spring-boot | module/spring-boot-security/src/main/java/org/springframework/boot/security/autoconfigure/rsocket/RSocketSecurityAutoConfiguration.java | {
"start": 2182,
"end": 2494
} | class ____ {
@Bean
RSocketMessageHandlerCustomizer rSocketAuthenticationPrincipalMessageHandlerCustomizer() {
return (messageHandler) -> messageHandler.getArgumentResolverConfigurer()
.addCustomResolver(new AuthenticationPrincipalArgumentResolver());
}
}
}
| RSocketSecurityMessageHandlerConfiguration |
java | alibaba__nacos | naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2.java | {
"start": 938,
"end": 1324
} | interface ____ {
/**
* Run check task for service.
*
* @param task health check task v2
* @param service service of current process
* @param metadata cluster metadata of current process
*/
void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata);
/**
* Get check task type, refer to | HealthCheckProcessorV2 |
java | spring-projects__spring-security | access/src/test/java/org/springframework/security/access/intercept/AbstractSecurityInterceptorTests.java | {
"start": 1312,
"end": 2540
} | class ____ {
@Test
public void detectsIfInvocationPassedIncompatibleSecureObject() {
MockSecurityInterceptorWhichOnlySupportsStrings si = new MockSecurityInterceptorWhichOnlySupportsStrings();
si.setRunAsManager(mock(RunAsManager.class));
si.setAuthenticationManager(mock(AuthenticationManager.class));
si.setAfterInvocationManager(mock(AfterInvocationManager.class));
si.setAccessDecisionManager(mock(AccessDecisionManager.class));
si.setSecurityMetadataSource(mock(SecurityMetadataSource.class));
assertThatIllegalArgumentException().isThrownBy(() -> si.beforeInvocation(new SimpleMethodInvocation()));
}
@Test
public void detectsViolationOfGetSecureObjectClassMethod() throws Exception {
MockSecurityInterceptorReturnsNull si = new MockSecurityInterceptorReturnsNull();
si.setRunAsManager(mock(RunAsManager.class));
si.setAuthenticationManager(mock(AuthenticationManager.class));
si.setAfterInvocationManager(mock(AfterInvocationManager.class));
si.setAccessDecisionManager(mock(AccessDecisionManager.class));
si.setSecurityMetadataSource(mock(SecurityMetadataSource.class));
assertThatIllegalArgumentException().isThrownBy(si::afterPropertiesSet);
}
private | AbstractSecurityInterceptorTests |
java | apache__camel | components/camel-irc/src/main/java/org/apache/camel/component/irc/IrcComponent.java | {
"start": 1503,
"end": 7312
} | class ____ extends DefaultComponent implements SSLContextParametersAware {
private static final Logger LOG = LoggerFactory.getLogger(IrcComponent.class);
private final transient Map<String, IRCConnection> connectionCache = new HashMap<>();
@Metadata(label = "security", defaultValue = "false")
private boolean useGlobalSslContextParameters;
public IrcComponent() {
}
@Override
public IrcEndpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
// every endpoint gets it's own configuration
IrcConfiguration config = new IrcConfiguration();
config.configure(uri);
IrcEndpoint endpoint = new IrcEndpoint(uri, this, config);
setProperties(endpoint, parameters);
return endpoint;
}
public IRCConnection getIRCConnection(IrcConfiguration configuration) {
lock.lock();
try {
final IRCConnection connection;
if (connectionCache.containsKey(configuration.getCacheKey())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Returning Cached Connection to {}:{}", configuration.getHostname(), configuration.getNickname());
}
connection = connectionCache.get(configuration.getCacheKey());
} else {
connection = createConnection(configuration);
connectionCache.put(configuration.getCacheKey(), connection);
}
return connection;
} finally {
lock.unlock();
}
}
public void closeIRCConnection(IrcConfiguration configuration) {
lock.lock();
try {
IRCConnection connection = connectionCache.get(configuration.getCacheKey());
if (connection != null) {
closeConnection(connection);
connectionCache.remove(configuration.getCacheKey());
}
} finally {
lock.unlock();
}
}
protected IRCConnection createConnection(IrcConfiguration configuration) {
IRCConnection conn = null;
IRCEventListener ircLogger;
if (configuration.getUsingSSL()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Creating SSL Connection to {} destination(s): {} nick: {} user: {}",
configuration.getHostname(), configuration.getSpaceSeparatedChannelNames(),
configuration.getNickname(), configuration.getUsername());
}
SSLContextParameters sslParams = configuration.getSslContextParameters();
if (sslParams == null) {
sslParams = retrieveGlobalSslContextParameters();
}
if (sslParams != null) {
conn = new CamelSSLIRCConnection(
configuration.getHostname(), configuration.getPorts(), configuration.getPassword(),
configuration.getNickname(), configuration.getUsername(), configuration.getRealname(),
sslParams, getCamelContext());
} else {
SSLIRCConnection sconn = new SSLIRCConnection(
configuration.getHostname(), configuration.getPorts(), configuration.getPassword(),
configuration.getNickname(), configuration.getUsername(), configuration.getRealname());
sconn.addTrustManager(configuration.getTrustManager());
conn = sconn;
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Creating Connection to {} destination(s): {} nick: {} user: {}",
configuration.getHostname(), configuration.getSpaceSeparatedChannelNames(),
configuration.getNickname(), configuration.getUsername());
}
conn = new IRCConnection(
configuration.getHostname(), configuration.getPorts(), configuration.getPassword(),
configuration.getNickname(), configuration.getUsername(), configuration.getRealname());
}
conn.setEncoding("UTF-8");
conn.setColors(configuration.isColors());
conn.setPong(true);
if (LOG.isDebugEnabled()) {
LOG.debug("Adding IRC event logging listener");
ircLogger = createIrcLogger(configuration.getHostname());
conn.addIRCEventListener(ircLogger);
}
try {
conn.connect();
} catch (Exception e) {
throw new RuntimeCamelException(e);
}
return conn;
}
public void closeConnection(IRCConnection connection) {
try {
connection.doQuit();
connection.close();
} catch (Exception e) {
LOG.warn("Error during closing connection.", e);
}
}
@Override
protected void doStop() throws Exception {
// lets use a copy so we can clear the connections eagerly in case of exceptions
Map<String, IRCConnection> map = new HashMap<>(connectionCache);
connectionCache.clear();
for (Map.Entry<String, IRCConnection> entry : map.entrySet()) {
closeConnection(entry.getValue());
}
super.doStop();
}
protected IRCEventListener createIrcLogger(String hostname) {
return new IrcLogger(LOG, hostname);
}
@Override
public boolean isUseGlobalSslContextParameters() {
return this.useGlobalSslContextParameters;
}
/**
* Enable usage of global SSL context parameters.
*/
@Override
public void setUseGlobalSslContextParameters(boolean useGlobalSslContextParameters) {
this.useGlobalSslContextParameters = useGlobalSslContextParameters;
}
}
| IrcComponent |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/debug/Logger.java | {
"start": 931,
"end": 1815
} | class ____ {
private static final Log logger = LogFactory.getLog("Spring Security Debugger");
void info(String message) {
info(message, false);
}
void info(String message, boolean dumpStack) {
StringBuilder output = new StringBuilder(256);
output.append("\n\n************************************************************\n\n");
output.append(message).append("\n");
if (dumpStack) {
StringWriter os = new StringWriter();
new Exception().printStackTrace(new PrintWriter(os));
StringBuffer buffer = os.getBuffer();
// Remove the exception in case it scares people.
int start = buffer.indexOf("java.lang.Exception");
buffer.replace(start, start + 19, "");
output.append("\nCall stack: \n").append(os.toString());
}
output.append("\n\n************************************************************\n\n");
logger.info(output.toString());
}
}
| Logger |
java | quarkusio__quarkus | extensions/smallrye-fault-tolerance/deployment/src/test/java/io/quarkus/smallrye/faulttolerance/test/hotreload/HotReloadTest.java | {
"start": 297,
"end": 869
} | class ____ {
@RegisterExtension
final static QuarkusDevModeTest test = new QuarkusDevModeTest()
.withApplicationRoot(jar -> jar.addClasses(HotReloadBean.class, HotReloadRoute.class));
@Test
public void test() {
when().get("/").then().statusCode(200).body(is("fallback1"));
test.modifySourceFile("HotReloadBean.java", src -> {
return src.replace("fallbackMethod = \"fallback1\"", "fallbackMethod = \"fallback2\"");
});
when().get("/").then().statusCode(200).body(is("fallback2"));
}
}
| HotReloadTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/MissingCasesInEnumSwitchTest.java | {
"start": 11969,
"end": 12331
} | enum ____ {
A,
B
}
public static Object test(E e) {
return switch (e) {
case A:
yield new Object();
default:
yield null;
};
}
}
""")
.doTest();
}
}
| E |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/ThreadUtil.java | {
"start": 3149,
"end": 3858
} | class ____ of the current thread is null");
}
return getResourceAsStream(cl, resourceName);
}
/**
* Convenience method that returns a resource as inputstream from the
* classpath using given classloader.
* <p>
*
* @param cl ClassLoader to be used to retrieve resource.
* @param resourceName resource to retrieve.
*
* @throws IOException thrown if resource cannot be loaded
* @return inputstream with the resource.
*/
public static InputStream getResourceAsStream(ClassLoader cl,
String resourceName)
throws IOException {
if (cl == null) {
throw new IOException("Can not read resource file '" + resourceName +
"' because given | loader |
java | apache__rocketmq | common/src/main/java/org/apache/rocketmq/common/constant/GrpcConstants.java | {
"start": 906,
"end": 3244
} | class ____ {
public static final Context.Key<Metadata> METADATA = Context.key("rpc-metadata");
/**
* Remote address key in attributes of call
*/
public static final Metadata.Key<String> REMOTE_ADDRESS
= Metadata.Key.of("rpc-remote-address", Metadata.ASCII_STRING_MARSHALLER);
/**
* Local address key in attributes of call
*/
public static final Metadata.Key<String> LOCAL_ADDRESS
= Metadata.Key.of("rpc-local-address", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> AUTHORIZATION
= Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> NAMESPACE_ID
= Metadata.Key.of("x-mq-namespace", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> DATE_TIME
= Metadata.Key.of("x-mq-date-time", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> REQUEST_ID
= Metadata.Key.of("x-mq-request-id", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> LANGUAGE
= Metadata.Key.of("x-mq-language", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> CLIENT_VERSION
= Metadata.Key.of("x-mq-client-version", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> PROTOCOL_VERSION
= Metadata.Key.of("x-mq-protocol", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> RPC_NAME
= Metadata.Key.of("x-mq-rpc-name", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> SIMPLE_RPC_NAME
= Metadata.Key.of("x-mq-simple-rpc-name", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> SESSION_TOKEN
= Metadata.Key.of("x-mq-session-token", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> CLIENT_ID
= Metadata.Key.of("x-mq-client-id", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> AUTHORIZATION_AK
= Metadata.Key.of("x-mq-authorization-ak", Metadata.ASCII_STRING_MARSHALLER);
public static final Metadata.Key<String> CHANNEL_ID
= Metadata.Key.of("x-mq-channel-id", Metadata.ASCII_STRING_MARSHALLER);
}
| GrpcConstants |
java | apache__dubbo | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderService.java | {
"start": 882,
"end": 964
} | interface ____ used to check if the exported provider works well or not.
*/
public | is |
java | apache__flink | flink-python/src/main/java/org/apache/flink/table/runtime/arrow/writers/VarCharWriter.java | {
"start": 1163,
"end": 2310
} | class ____<T> extends ArrowFieldWriter<T> {
public static VarCharWriter<RowData> forRow(VarCharVector varCharVector) {
return new VarCharWriterForRow(varCharVector);
}
public static VarCharWriter<ArrayData> forArray(VarCharVector varCharVector) {
return new VarCharWriterForArray(varCharVector);
}
// ------------------------------------------------------------------------------------------
private VarCharWriter(VarCharVector varCharVector) {
super(varCharVector);
}
abstract boolean isNullAt(T in, int ordinal);
abstract StringData readString(T in, int ordinal);
@Override
public void doWrite(T in, int ordinal) {
if (isNullAt(in, ordinal)) {
((VarCharVector) getValueVector()).setNull(getCount());
} else {
((VarCharVector) getValueVector())
.setSafe(getCount(), readString(in, ordinal).toBytes());
}
}
// ------------------------------------------------------------------------------------------
/** {@link VarCharWriter} for {@link RowData} input. */
public static final | VarCharWriter |
java | quarkusio__quarkus | core/deployment/src/test/java/io/quarkus/deployment/util/AsmUtilTest.java | {
"start": 377,
"end": 1427
} | class ____ {
@ParameterizedTest
@MethodSource
void testGetParameterTypes(String methodDescriptor, String... expected) {
assertArrayEquals(expected,
Stream.of(AsmUtil.getParameterTypes(methodDescriptor)).map(Type::toString).toArray(String[]::new));
}
private static final Stream<Arguments> testGetParameterTypes() {
List<Arguments> arguments = new ArrayList<>();
final var array1 = new StringBuilder();
final var array2 = new StringBuilder();
for (int i = 0; i < 5; i++) {
for (Character c : AsmUtil.PRIMITIVE_DESCRIPTOR_TO_PRIMITIVE_CLASS_LITERAL.keySet()) {
arguments.add(Arguments.of("(" + array2 + c + ")V",
toArray(AsmUtil.PRIMITIVE_DESCRIPTOR_TO_PRIMITIVE_CLASS_LITERAL.get(c) + array1)));
}
array1.append("[]");
array2.append('[');
}
return arguments.stream();
}
private static String[] toArray(String... values) {
return values;
}
}
| AsmUtilTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/FinalTest.java | {
"start": 486,
"end": 587
} | class ____ {
public final static int id = 1001;
public final int value = 1001;
}
}
| VO |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/model/ParamConverterProviders.java | {
"start": 359,
"end": 1147
} | class ____ {
private final List<ResourceParamConverterProvider> paramConverterProviders = new ArrayList<>();
public void addParamConverterProviders(ResourceParamConverterProvider resourceFeature) {
paramConverterProviders.add(resourceFeature);
}
public List<ResourceParamConverterProvider> getParamConverterProviders() {
return paramConverterProviders;
}
public void sort() {
Collections.sort(paramConverterProviders);
}
public void initializeDefaultFactories(Function<String, BeanFactory<?>> factoryCreator) {
for (ResourceParamConverterProvider i : paramConverterProviders) {
i.setFactory((BeanFactory<ParamConverterProvider>) factoryCreator.apply(i.getClassName()));
}
}
}
| ParamConverterProviders |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/processor/MultipleInputNodeCreationProcessorTest.java | {
"start": 2102,
"end": 7783
} | class ____ extends TableTestBase {
private final BatchTableTestUtil batchUtil = batchTestUtil(TableConfig.getDefault());
private final StreamTableTestUtil streamUtil = streamTestUtil(TableConfig.getDefault());
@Test
void testIsChainableDataStreamSource() {
createChainableStream(batchUtil);
assertChainableSource("chainableStream", batchUtil, true);
createChainableStream(streamUtil);
assertChainableSource("chainableStream", streamUtil, true);
}
@Test
void testNonChainableDataStreamSource() {
createNonChainableStream(batchUtil);
assertChainableSource("nonChainableStream", batchUtil, false);
createNonChainableStream(streamUtil);
assertChainableSource("nonChainableStream", streamUtil, false);
}
@Test
void testIsChainableTableSource() throws IOException {
createTestFileSource(batchUtil.tableEnv(), "fileSource1", "Source");
assertChainableSource("fileSource1", batchUtil, true);
createTestFileSource(streamUtil.tableEnv(), "fileSource1", "Source");
assertChainableSource("fileSource1", streamUtil, true);
createTestFileSource(batchUtil.tableEnv(), "fileSource2", "DataStream");
assertChainableSource("fileSource2", batchUtil, true);
createTestFileSource(streamUtil.tableEnv(), "fileSource2", "DataStream");
assertChainableSource("fileSource2", streamUtil, true);
}
@Test
void testNonChainableTableSource() throws IOException {
createTestValueSource(batchUtil.tableEnv(), "valueSource1", "DataStream");
assertChainableSource("valueSource1", batchUtil, false);
createTestValueSource(streamUtil.tableEnv(), "valueSource1", "DataStream");
assertChainableSource("valueSource1", streamUtil, false);
createTestValueSource(batchUtil.tableEnv(), "valueSource2", "SourceFunction");
assertChainableSource("valueSource2", batchUtil, false);
createTestValueSource(streamUtil.tableEnv(), "valueSource2", "SourceFunction");
assertChainableSource("valueSource2", streamUtil, false);
createTestValueSource(batchUtil.tableEnv(), "valueSource3", "InputFormat");
assertChainableSource("valueSource3", batchUtil, false);
createTestValueSource(streamUtil.tableEnv(), "valueSource3", "InputFormat");
assertChainableSource("valueSource3", streamUtil, false);
}
private void assertChainableSource(String name, TableTestUtil util, boolean expected) {
String sql = "SELECT * FROM " + name;
ExecNodeGraph execGraph = TableTestUtil.toExecNodeGraph(util.tableEnv(), sql);
ExecNode<?> execNode = execGraph.getRootNodes().get(0);
while (!execNode.getInputEdges().isEmpty()) {
execNode = execNode.getInputEdges().get(0).getSource();
}
ProcessorContext context = new ProcessorContext(util.getPlanner());
assertThat(MultipleInputNodeCreationProcessor.isChainableSource(execNode, context))
.isEqualTo(expected);
}
private void createChainableStream(TableTestUtil util) {
DataStreamSource<Integer> dataStream =
util.getStreamEnv()
.fromSource(
new MockSource(Boundedness.BOUNDED, 1),
WatermarkStrategy.noWatermarks(),
"chainableStream");
TableTestUtil.createTemporaryView(
util.tableEnv(),
"chainableStream",
dataStream,
scala.Option.apply(new Expression[] {ApiExpressionUtils.unresolvedRef("a")}),
scala.Option.empty(),
scala.Option.empty());
}
private void createNonChainableStream(TableTestUtil util) {
DataStreamSource<Integer> dataStream = util.getStreamEnv().addSource(new LegacySource());
TableTestUtil.createTemporaryView(
util.tableEnv(),
"nonChainableStream",
dataStream,
scala.Option.apply(new Expression[] {ApiExpressionUtils.unresolvedRef("a")}),
scala.Option.empty(),
scala.Option.empty());
}
private void createTestFileSource(TableEnvironment tEnv, String name, String runtimeSource)
throws IOException {
File file = TempDirUtils.newFile(tempFolder());
file.delete();
file.createNewFile();
FileUtils.writeFileUtf8(file, "1\n2\n3\n");
tEnv.executeSql(
"CREATE TABLE "
+ name
+ "(\n"
+ " a STRING\n"
+ ") WITH (\n"
+ " 'connector' = 'test-file',\n"
+ " 'path' = '"
+ file.toURI()
+ "',\n"
+ " 'runtime-source' = '"
+ runtimeSource
+ "'\n"
+ ")");
}
private void createTestValueSource(TableEnvironment tEnv, String name, String runtimeSource) {
tEnv.executeSql(
"CREATE TABLE "
+ name
+ "(\n"
+ " a STRING\n"
+ ") WITH (\n"
+ " 'connector' = 'values',\n"
+ " 'bounded' = 'true',\n"
+ " 'runtime-source' = '"
+ runtimeSource
+ "'\n"
+ ")");
}
private static | MultipleInputNodeCreationProcessorTest |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/seqno/RetentionLeasesTests.java | {
"start": 1021,
"end": 5799
} | class ____ extends ESTestCase {
public void testPrimaryTermOutOfRange() {
final long primaryTerm = randomLongBetween(Long.MIN_VALUE, 0);
final IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
() -> new RetentionLeases(primaryTerm, randomNonNegativeLong(), Collections.emptyList())
);
assertThat(e, hasToString(containsString("primary term must be positive but was [" + primaryTerm + "]")));
}
public void testVersionOutOfRange() {
final long version = randomLongBetween(Long.MIN_VALUE, -1);
final IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
() -> new RetentionLeases(randomLongBetween(1, Long.MAX_VALUE), version, Collections.emptyList())
);
assertThat(e, hasToString(containsString("version must be non-negative but was [" + version + "]")));
}
public void testSupersedesByPrimaryTerm() {
final long lowerPrimaryTerm = randomLongBetween(1, Long.MAX_VALUE);
final RetentionLeases left = new RetentionLeases(lowerPrimaryTerm, randomLongBetween(1, Long.MAX_VALUE), Collections.emptyList());
final long higherPrimaryTerm = randomLongBetween(lowerPrimaryTerm + 1, Long.MAX_VALUE);
final RetentionLeases right = new RetentionLeases(higherPrimaryTerm, randomLongBetween(1, Long.MAX_VALUE), Collections.emptyList());
assertTrue(right.supersedes(left));
assertTrue(right.supersedes(left.primaryTerm(), left.version()));
assertFalse(left.supersedes(right));
assertFalse(left.supersedes(right.primaryTerm(), right.version()));
}
public void testSupersedesByVersion() {
final long primaryTerm = randomLongBetween(1, Long.MAX_VALUE);
final long lowerVersion = randomLongBetween(1, Long.MAX_VALUE);
final long higherVersion = randomLongBetween(lowerVersion + 1, Long.MAX_VALUE);
final RetentionLeases left = new RetentionLeases(primaryTerm, lowerVersion, Collections.emptyList());
final RetentionLeases right = new RetentionLeases(primaryTerm, higherVersion, Collections.emptyList());
assertTrue(right.supersedes(left));
assertTrue(right.supersedes(left.primaryTerm(), left.version()));
assertFalse(left.supersedes(right));
assertFalse(left.supersedes(right.primaryTerm(), right.version()));
}
public void testRetentionLeasesRejectsDuplicates() {
final RetentionLeases retentionLeases = randomRetentionLeases(false);
final RetentionLease retentionLease = randomFrom(retentionLeases.leases());
final IllegalStateException e = expectThrows(
IllegalStateException.class,
() -> new RetentionLeases(
retentionLeases.primaryTerm(),
retentionLeases.version(),
Stream.concat(retentionLeases.leases().stream(), Stream.of(retentionLease)).toList()
)
);
assertThat(e, hasToString(containsString("duplicate retention lease ID [" + retentionLease.id() + "]")));
}
public void testLeasesPreservesIterationOrder() {
final RetentionLeases retentionLeases = randomRetentionLeases(true);
if (retentionLeases.leases().isEmpty()) {
assertThat(retentionLeases.leases(), empty());
} else {
assertThat(retentionLeases.leases(), contains(retentionLeases.leases().toArray(new RetentionLease[0])));
}
}
public void testRetentionLeasesMetadataStateFormat() throws IOException {
final Path path = createTempDir();
final RetentionLeases retentionLeases = randomRetentionLeases(true);
RetentionLeases.FORMAT.writeAndCleanup(retentionLeases, path);
assertThat(RetentionLeases.FORMAT.loadLatestState(logger, NamedXContentRegistry.EMPTY, path), equalTo(retentionLeases));
}
private RetentionLeases randomRetentionLeases(boolean allowEmpty) {
final long primaryTerm = randomNonNegativeLong();
final long version = randomNonNegativeLong();
final int length = randomIntBetween(allowEmpty ? 0 : 1, 8);
final List<RetentionLease> leases = new ArrayList<>(length);
for (int i = 0; i < length; i++) {
final String id = randomAlphaOfLength(8);
final long retainingSequenceNumber = randomNonNegativeLong();
final long timestamp = randomNonNegativeLong();
final String source = randomAlphaOfLength(8);
final RetentionLease retentionLease = new RetentionLease(id, retainingSequenceNumber, timestamp, source);
leases.add(retentionLease);
}
return new RetentionLeases(primaryTerm, version, leases);
}
}
| RetentionLeasesTests |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/docs/datavalidation/pogo/Email.java | {
"start": 786,
"end": 1211
} | class ____ {
@NotBlank // <1>
String subject;
@NotBlank // <1>
String recipient;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
}
//end::clazz[]
| Email |
java | apache__spark | sql/catalyst/src/main/java/org/apache/spark/sql/connector/write/SupportsDynamicOverwrite.java | {
"start": 1474,
"end": 1740
} | interface ____ extends WriteBuilder {
/**
* Configures a write to dynamically replace partitions with data committed in the write.
*
* @return this write builder for method chaining
*/
WriteBuilder overwriteDynamicPartitions();
}
| SupportsDynamicOverwrite |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java | {
"start": 5352,
"end": 5691
} | class ____
* be loaded or if an error occurs while instantiating any factory
* @since 6.0
*/
public <T> List<T> load(Class<T> factoryType) {
return load(factoryType, null, null);
}
/**
* Load and instantiate the factory implementations of the given type from
* {@value #FACTORIES_RESOURCE_LOCATION}, using the configured | cannot |
java | quarkusio__quarkus | integration-tests/awt/src/test/java/io/quarkus/awt/it/TestUtil.java | {
"start": 491,
"end": 4483
} | class ____ {
/**
* These exceptions in native-image runtime are a hallmark of either
* JNI access or reflection misconfiguration. Test should always fail the
* logs check if these are found.
*/
private static final Pattern BLACKLISTED_EXCEPTIONS = Pattern.compile("(?i:.*(" +
"java.lang.NoSuchFieldError|" +
"java.lang.NoClassDefFoundError|" +
"java.lang.NullPointerException" +
").*)");
/**
* Looks for a pattern in the log or just seeks blacklisted errors.
*
* @param lineMatchRegexp pattern
* @param name identifier
*/
public static void checkLog(final Pattern lineMatchRegexp, final String name) {
final Path accessLogFilePath = Paths.get(".", "target", "quarkus.log").toAbsolutePath();
org.awaitility.Awaitility.given().pollInterval(100, TimeUnit.MILLISECONDS)
.atMost(3, TimeUnit.SECONDS)
.untilAsserted(() -> {
assertTrue(Files.exists(accessLogFilePath), "Quarkus log file " + accessLogFilePath + " is missing");
boolean found = false;
final StringBuilder sbLog = new StringBuilder();
final Set<String> offendingLines = new HashSet<>();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(accessLogFilePath)),
StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
if (BLACKLISTED_EXCEPTIONS.matcher(line).matches()) {
offendingLines.add(line);
}
sbLog.append(line).append("\r\n");
if (lineMatchRegexp != null) {
found = lineMatchRegexp.matcher(line).matches();
if (found) {
break;
}
}
}
}
assertTrue(offendingLines.isEmpty(),
name + ": Log file must not contain blacklisted exceptions. " +
"See the offending lines: \n" +
String.join("\n", offendingLines) +
"\n in the context of the log: " + sbLog);
if (lineMatchRegexp != null) {
assertTrue(found,
name + ": Log file doesn't contain a line matching " + lineMatchRegexp.pattern() +
", log was: " + sbLog);
}
});
}
/**
* Compares two int arrays, pair by pair. If the difference
* between members of the pair is bigger than threshold,
* arrays are not the same.
*
* @param a array
* @param b array
* @param threshold array tolerance for the absolute difference between array elements
* @return true if they are the same (within the threshold)
*/
public static boolean compareArrays(int[] a, int[] b, int[] threshold) {
if (a.length != b.length || a.length != threshold.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (Math.max(a[i], b[i]) - Math.min(a[i], b[i]) > threshold[i]) {
return false;
}
}
return true;
}
public static int[] decodeArray4(final String array) {
final String[] ints = array.split(",");
return new int[] {
Integer.parseInt(ints[0]),
Integer.parseInt(ints[1]),
Integer.parseInt(ints[2]),
Integer.parseInt(ints[3])
};
}
}
| TestUtil |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/coordination/CoordinationDiagnosticsAction.java | {
"start": 1655,
"end": 2036
} | class ____ extends ActionType<CoordinationDiagnosticsAction.Response> {
public static final CoordinationDiagnosticsAction INSTANCE = new CoordinationDiagnosticsAction();
public static final String NAME = "internal:cluster/coordination_diagnostics/info";
private CoordinationDiagnosticsAction() {
super(NAME);
}
public static | CoordinationDiagnosticsAction |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/admin/ListConsumerGroupOffsetsOptions.java | {
"start": 984,
"end": 1421
} | class ____ extends AbstractOptions<ListConsumerGroupOffsetsOptions> {
private boolean requireStable = false;
/**
* Sets an optional requireStable flag.
*/
public ListConsumerGroupOffsetsOptions requireStable(final boolean requireStable) {
this.requireStable = requireStable;
return this;
}
public boolean requireStable() {
return requireStable;
}
}
| ListConsumerGroupOffsetsOptions |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/cluster/coordination/AbstractCoordinatorTestCase.java | {
"start": 88831,
"end": 90218
} | class ____ extends FakeThreadPoolMasterService {
AckCollector nextAckCollector = new AckCollector();
boolean publicationMayFail = false;
AckedFakeThreadPoolMasterService(String nodeName, ThreadPool threadPool, Consumer<Runnable> onTaskAvailableToRun) {
super(nodeName, threadPool, onTaskAvailableToRun);
}
@Override
protected ClusterStatePublisher.AckListener wrapAckListener(ClusterStatePublisher.AckListener ackListener) {
final AckCollector ackCollector = nextAckCollector;
nextAckCollector = new AckCollector();
return new ClusterStatePublisher.AckListener() {
@Override
public void onCommit(TimeValue commitTime) {
ackCollector.onCommit(commitTime);
ackListener.onCommit(commitTime);
}
@Override
public void onNodeAck(DiscoveryNode node, Exception e) {
ackCollector.onNodeAck(node, e);
ackListener.onNodeAck(node, e);
}
};
}
public void allowPublicationFailure() {
publicationMayFail = true;
}
@Override
protected boolean publicationMayFail() {
return publicationMayFail;
}
}
static | AckedFakeThreadPoolMasterService |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/MessageBodyReaderTests.java | {
"start": 10311,
"end": 11979
} | class ____ implements Instance<ObjectMapper> {
@Override
public Instance<ObjectMapper> select(Annotation... qualifiers) {
throw new IllegalStateException("Should never be called");
}
@Override
public <U extends ObjectMapper> Instance<U> select(Class<U> subtype, Annotation... qualifiers) {
throw new IllegalStateException("Should never be called");
}
@Override
public <U extends ObjectMapper> Instance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers) {
throw new IllegalStateException("Should never be called");
}
@Override
public boolean isUnsatisfied() {
throw new IllegalStateException("Should never be called");
}
@Override
public boolean isAmbiguous() {
throw new IllegalStateException("Should never be called");
}
@Override
public void destroy(ObjectMapper instance) {
throw new IllegalStateException("Should never be called");
}
@Override
public Handle<ObjectMapper> getHandle() {
throw new IllegalStateException("Should never be called");
}
@Override
public Iterable<? extends Handle<ObjectMapper>> handles() {
throw new IllegalStateException("Should never be called");
}
@Override
public ObjectMapper get() {
return new ObjectMapper();
}
@Override
public Iterator<ObjectMapper> iterator() {
throw new IllegalStateException("Should never be called");
}
}
}
| NewObjectMapperInstance |
java | apache__camel | components/camel-infinispan/camel-infinispan-embedded/src/test/java/org/apache/camel/component/infinispan/embedded/InfinispanEmbeddedAggregationRepositoryOperationsTest.java | {
"start": 1311,
"end": 7217
} | class ____ extends InfinispanEmbeddedTestSupport {
private InfinispanEmbeddedAggregationRepository aggregationRepository;
@Override
public void setupResources() throws Exception {
super.setupResources();
InfinispanEmbeddedConfiguration configuration = new InfinispanEmbeddedConfiguration();
configuration.setCacheContainer(cacheContainer);
aggregationRepository = new InfinispanEmbeddedAggregationRepository(getCacheName());
aggregationRepository.setConfiguration(configuration);
aggregationRepository.start();
}
@Override
public void cleanupResources() {
if (aggregationRepository != null) {
aggregationRepository.stop();
}
}
private boolean exists(String key) {
return aggregationRepository.getCache().get(key) != null;
}
@Test
public void testAdd() {
// cleanup
aggregationRepository.getCache().clear();
// Given
String key = "Add";
assertFalse(exists(key));
Exchange exchange = new DefaultExchange(context());
// When
aggregationRepository.add(context(), key, exchange);
// Then
assertTrue(exists(key));
}
@Test
public void testGetExists() {
// cleanup
aggregationRepository.getCache().clear();
// Given
String key = "Get_Exists";
Exchange exchange = new DefaultExchange(context());
aggregationRepository.add(context(), key, exchange);
assertTrue(exists(key));
// When
Exchange exchange2 = aggregationRepository.get(context(), key);
// Then
assertNotNull(exchange2);
assertEquals(exchange.getExchangeId(), exchange2.getExchangeId());
}
@Test
public void testGetNotExists() {
// cleanup
aggregationRepository.getCache().clear();
// Given
String key = "Get_NotExists";
assertFalse(exists(key));
// When
Exchange exchange2 = aggregationRepository.get(context(), key);
// Then
assertNull(exchange2);
}
@Test
public void testRemoveExists() {
// cleanup
aggregationRepository.getCache().clear();
// Given
String key = "Remove_Exists";
Exchange exchange = new DefaultExchange(context());
aggregationRepository.add(context(), key, exchange);
assertTrue(exists(key));
// When
aggregationRepository.remove(context(), key, exchange);
// Then
assertFalse(exists(key));
}
@Test
public void testRemoveNotExists() {
// cleanup
aggregationRepository.getCache().clear();
// Given
String key = "RemoveNotExists";
Exchange exchange = new DefaultExchange(context());
assertFalse(exists(key));
// When
aggregationRepository.remove(context(), key, exchange);
// Then
assertFalse(exists(key));
}
@Test
public void testGetKeys() {
// cleanup
aggregationRepository.getCache().clear();
// Given
String[] keys = { "GetKeys1", "GetKeys2" };
addExchanges(keys);
// When
Set<String> keySet = aggregationRepository.getKeys();
// Then
for (String key : keys) {
assertTrue(keySet.contains(key));
}
}
@Test
public void testConfirmExist() {
// cleanup
aggregationRepository.getCache().clear();
// Given
for (int i = 1; i < 4; i++) {
String key = "Confirm_" + i;
Exchange exchange = new DefaultExchange(context());
exchange.setExchangeId("Exchange_" + i);
aggregationRepository.add(context(), key, exchange);
assertTrue(exists(key));
}
// When
aggregationRepository.confirm(context(), "Confirm_2");
// Then
assertTrue(exists("Confirm_1"));
assertFalse(exists("Confirm_2"));
assertTrue(exists("Confirm_3"));
}
@Test
public void testConfirmNotExist() {
// cleanup
aggregationRepository.getCache().clear();
// Given
String[] keys = new String[3];
for (int i = 1; i < 4; i++) {
keys[i - 1] = "Confirm" + i;
}
addExchanges(keys);
for (String key : keys) {
assertTrue(exists(key));
}
// When
aggregationRepository.confirm(context(), "Exchange-Confirm5");
// Then
for (String key : keys) {
assertTrue(exists(key));
}
}
private void addExchanges(String... keys) {
// cleanup
aggregationRepository.getCache().clear();
for (String key : keys) {
Exchange exchange = new DefaultExchange(context());
exchange.setExchangeId("Exchange-" + key);
aggregationRepository.add(context(), key, exchange);
}
}
@Test
public void testScan() {
// cleanup
aggregationRepository.getCache().clear();
// Given
String[] keys = { "Scan1", "Scan2" };
addExchanges(keys);
// When
Set<String> exchangeIdSet = aggregationRepository.scan(context());
// Then
for (String key : keys) {
assertTrue(exchangeIdSet.contains(key));
}
}
@Test
public void testRecover() {
// cleanup
aggregationRepository.getCache().clear();
// Given
String[] keys = { "Recover1", "Recover2" };
addExchanges(keys);
// When
Exchange exchange2 = aggregationRepository.recover(context(), "Recover2");
Exchange exchange3 = aggregationRepository.recover(context(), "Recover3");
// Then
assertNotNull(exchange2);
assertNull(exchange3);
}
}
| InfinispanEmbeddedAggregationRepositoryOperationsTest |
java | quarkusio__quarkus | integration-tests/spring-web/src/test/java/io/quarkus/it/spring/web/SpringSchedulerIT.java | {
"start": 120,
"end": 176
} | class ____ extends SpringSchedulerTest {
}
| SpringSchedulerIT |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/core/security/transport/netty4/SecurityNetty4TransportTests.java | {
"start": 894,
"end": 8573
} | class ____ extends ESTestCase {
public void testBuildRemoteClusterClientBootStrapOptions() {
// 1. The default
final Settings settings1 = Settings.builder().build();
final var options1 = RemoteClusterClientBootstrapOptions.fromSettings(settings1);
assertThat(options1.isEmpty(), is(true));
// 2. Configuration for default profile only, _remote_cluster profile defaults to settings of the default profile
final Settings settings2 = Settings.builder()
.put(TransportSettings.TCP_NO_DELAY.getKey(), randomBoolean())
.put(TransportSettings.TCP_KEEP_ALIVE.getKey(), randomBoolean())
.put(TransportSettings.TCP_KEEP_IDLE.getKey(), randomIntBetween(-1, 300))
.put(TransportSettings.TCP_KEEP_INTERVAL.getKey(), randomIntBetween(-1, 300))
.put(TransportSettings.TCP_KEEP_COUNT.getKey(), randomIntBetween(-1, 300))
.put(TransportSettings.TCP_SEND_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(randomIntBetween(-1, 1000)))
.put(TransportSettings.TCP_RECEIVE_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(randomIntBetween(-1, 1000)))
.put(TransportSettings.TCP_REUSE_ADDRESS.getKey(), randomBoolean())
.build();
final var options2 = RemoteClusterClientBootstrapOptions.fromSettings(settings2);
assertThat(options2.isEmpty(), is(true));
// 3. Configure different settings for _remote_cluster profile
final Settings.Builder builder3 = Settings.builder();
if (randomBoolean()) {
builder3.put(TransportSettings.TCP_NO_DELAY.getKey(), true)
.put(TransportSettings.TCP_KEEP_ALIVE.getKey(), true)
.put(TransportSettings.TCP_KEEP_IDLE.getKey(), randomIntBetween(-1, 300))
.put(TransportSettings.TCP_KEEP_INTERVAL.getKey(), randomIntBetween(-1, 300))
.put(TransportSettings.TCP_KEEP_COUNT.getKey(), randomIntBetween(-1, 300))
.put(TransportSettings.TCP_SEND_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(-1))
.put(TransportSettings.TCP_RECEIVE_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(-1));
}
final Settings settings3 = builder3.put(RemoteClusterPortSettings.TCP_NO_DELAY.getKey(), false)
.put(RemoteClusterPortSettings.TCP_KEEP_ALIVE.getKey(), false)
.put(RemoteClusterPortSettings.TCP_SEND_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(42))
.put(RemoteClusterPortSettings.TCP_RECEIVE_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(99))
.put(RemoteClusterPortSettings.TCP_REUSE_ADDRESS.getKey(), false == TransportSettings.TCP_REUSE_ADDRESS.get(Settings.EMPTY))
.build();
final var options3 = RemoteClusterClientBootstrapOptions.fromSettings(settings3);
assertThat(options3.isEmpty(), is(false));
assertThat(options3.tcpNoDelay(), is(false));
assertThat(options3.tcpKeepAlive(), is(false));
assertThat(options3.tcpKeepIdle(), nullValue());
assertThat(options3.tcpKeepInterval(), nullValue());
assertThat(options3.tcpKeepCount(), nullValue());
assertThat(options3.tcpSendBufferSize(), equalTo(ByteSizeValue.ofBytes(42)));
assertThat(options3.tcpReceiveBufferSize(), equalTo(ByteSizeValue.ofBytes(99)));
assertThat(options3.tcpReuseAddress(), notNullValue());
// 4. Configure different keepIdle, keepInterval or keepCount
final Settings.Builder builder4 = Settings.builder();
if (randomBoolean()) {
builder4.put(TransportSettings.TCP_NO_DELAY.getKey(), true)
.put(TransportSettings.TCP_KEEP_ALIVE.getKey(), true)
.put(TransportSettings.TCP_KEEP_IDLE.getKey(), 299)
.put(TransportSettings.TCP_KEEP_INTERVAL.getKey(), 299)
.put(TransportSettings.TCP_KEEP_COUNT.getKey(), 299)
.put(TransportSettings.TCP_SEND_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(-1))
.put(TransportSettings.TCP_RECEIVE_BUFFER_SIZE.getKey(), ByteSizeValue.ofBytes(-1));
}
if (randomBoolean()) {
builder4.put(RemoteClusterPortSettings.TCP_KEEP_ALIVE.getKey(), true);
}
final boolean differentKeepIdle = randomBoolean();
if (differentKeepIdle) {
builder4.put(RemoteClusterPortSettings.TCP_KEEP_IDLE.getKey(), 42);
}
final boolean differentKeepInterval = randomBoolean();
final boolean differentKeepCount = false == differentKeepInterval;
if (differentKeepInterval) {
builder4.put(RemoteClusterPortSettings.TCP_KEEP_INTERVAL.getKey(), 43);
}
if (differentKeepCount) {
builder4.put(RemoteClusterPortSettings.TCP_KEEP_COUNT.getKey(), 44);
}
final Settings settings4 = builder4.build();
final var options4 = RemoteClusterClientBootstrapOptions.fromSettings(settings4);
assertThat(options4.isEmpty(), is(false));
assertThat(options4.tcpKeepAlive(), is(true));
assertThat(options4.tcpKeepIdle(), differentKeepIdle ? equalTo(42) : nullValue());
assertThat(options4.tcpKeepInterval(), differentKeepInterval ? equalTo(43) : nullValue());
assertThat(options4.tcpKeepCount(), differentKeepCount ? equalTo(44) : nullValue());
// 5. Identical TCP settings between default and remote cluster client connections
final Settings settings5 = Settings.builder()
.put(settings2)
.put(RemoteClusterPortSettings.TCP_NO_DELAY.getKey(), TransportSettings.TCP_NO_DELAY.get(settings2))
.put(RemoteClusterPortSettings.TCP_KEEP_ALIVE.getKey(), TransportSettings.TCP_KEEP_ALIVE.get(settings2))
.put(RemoteClusterPortSettings.TCP_KEEP_IDLE.getKey(), TransportSettings.TCP_KEEP_IDLE.get(settings2))
.put(RemoteClusterPortSettings.TCP_KEEP_INTERVAL.getKey(), TransportSettings.TCP_KEEP_INTERVAL.get(settings2))
.put(RemoteClusterPortSettings.TCP_KEEP_COUNT.getKey(), TransportSettings.TCP_KEEP_COUNT.get(settings2))
.put(RemoteClusterPortSettings.TCP_SEND_BUFFER_SIZE.getKey(), TransportSettings.TCP_SEND_BUFFER_SIZE.get(settings2))
.put(RemoteClusterPortSettings.TCP_RECEIVE_BUFFER_SIZE.getKey(), TransportSettings.TCP_RECEIVE_BUFFER_SIZE.get(settings2))
.put(RemoteClusterPortSettings.TCP_REUSE_ADDRESS.getKey(), TransportSettings.TCP_REUSE_ADDRESS.get(settings2))
.build();
final var options5 = RemoteClusterClientBootstrapOptions.fromSettings(settings5);
assertThat(options5.isEmpty(), is(true));
// 6. When keepAlive is false, other keepXxx settings do not matter
final Settings settings6 = Settings.builder()
.put(TransportSettings.TCP_KEEP_ALIVE.getKey(), false)
.put(TransportSettings.TCP_KEEP_IDLE.getKey(), randomIntBetween(-1, 300))
.put(TransportSettings.TCP_KEEP_INTERVAL.getKey(), randomIntBetween(-1, 300))
.put(TransportSettings.TCP_KEEP_COUNT.getKey(), randomIntBetween(-1, 300))
.put(RemoteClusterPortSettings.TCP_KEEP_ALIVE.getKey(), false)
.put(RemoteClusterPortSettings.TCP_KEEP_IDLE.getKey(), randomIntBetween(-1, 300))
.put(RemoteClusterPortSettings.TCP_KEEP_INTERVAL.getKey(), randomIntBetween(-1, 300))
.put(RemoteClusterPortSettings.TCP_KEEP_COUNT.getKey(), randomIntBetween(-1, 300))
.build();
final var options6 = RemoteClusterClientBootstrapOptions.fromSettings(settings6);
assertThat(options6.isEmpty(), is(true));
}
}
| SecurityNetty4TransportTests |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java | {
"start": 36087,
"end": 36267
} | class ____ implements DialectFeatureCheck {
public boolean apply(Dialect dialect) {
return definesFunction( dialect, "array_replace" );
}
}
public static | SupportsArrayReplace |
java | playframework__playframework | documentation/manual/working/javaGuide/main/http/code/javaguide/http/routing/controllers/Application.java | {
"start": 283,
"end": 647
} | class ____ extends Controller {
public Result download(String path) {
return ok("download " + path);
}
public Result homePage() {
return ok("home page");
}
// #show-page-action
public Result show(String page) {
String content = Page.getContentOf(page);
return ok(content).as("text/html");
}
// #show-page-action
static | Application |
java | spring-projects__spring-boot | cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHelp.java | {
"start": 793,
"end": 1043
} | interface ____ {
/**
* Returns the set of options that are mutually synonymous.
* @return the options
*/
Set<String> getOptions();
/**
* Returns usage help for the option.
* @return the usage help
*/
String getUsageHelp();
}
| OptionHelp |
java | quarkusio__quarkus | extensions/smallrye-graphql-client/deployment/src/test/java/io/quarkus/smallrye/graphql/client/deployment/GraphQLClientUnexpectedFieldsTest.java | {
"start": 943,
"end": 1936
} | class ____ {
static String url = "http://" + System.getProperty("quarkus.http.host", "localhost") + ":"
+ System.getProperty("quarkus.http.test-port", "8081") + "/invalid-graphql-endpoint";
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addAsResource(
new StringAsset(
"quarkus.smallrye-graphql-client.client1.url=" + url + "\n" +
"quarkus.smallrye-graphql-client.client1.allow-unexpected-response-fields=true\n"),
"application.properties")
.addClass(MockGraphQLEndpoint.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"));
@Path("/invalid-graphql-endpoint")
@Produces("application/json+graphql")
@Consumes("application/json")
public static | GraphQLClientUnexpectedFieldsTest |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/jdk8/ObservableLastStageObserver.java | {
"start": 941,
"end": 1676
} | class ____<T> extends ObservableStageObserver<T> {
final boolean hasDefault;
final T defaultItem;
public ObservableLastStageObserver(boolean hasDefault, T defaultItem) {
this.hasDefault = hasDefault;
this.defaultItem = defaultItem;
}
@Override
public void onNext(T t) {
value = t;
}
@Override
public void onComplete() {
if (!isDone()) {
T v = value;
clear();
if (v != null) {
complete(v);
} else if (hasDefault) {
complete(defaultItem);
} else {
completeExceptionally(new NoSuchElementException());
}
}
}
}
| ObservableLastStageObserver |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/connector/source/ScanTableSource.java | {
"start": 5036,
"end": 5762
} | interface ____ extends DynamicTableSource.Context {
// may introduce scan specific methods in the future
}
/**
* Provides actual runtime implementation for reading the data.
*
* <p>There might exist different interfaces for runtime implementation which is why {@link
* ScanRuntimeProvider} serves as the base interface. Concrete {@link ScanRuntimeProvider}
* interfaces might be located in other Flink modules.
*
* <p>{@link SourceProvider} is the recommended core interface. {@code SourceFunctionProvider}
* in {@code flink-table-api-java-bridge} and {@link InputFormatProvider} are available for
* backwards compatibility.
*/
@PublicEvolving
| ScanContext |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/jdbc/mutation/spi/BatchKeyAccess.java | {
"start": 370,
"end": 458
} | interface ____ {
/**
* The BatchKey to use
*/
BatchKey getBatchKey();
}
| BatchKeyAccess |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/output/MapOutputUnitTests.java | {
"start": 357,
"end": 1550
} | class ____ {
@Test
void shouldAcceptValue() {
MapOutput<String, String> sut = new MapOutput<>(StringCodec.UTF8);
sut.multi(2);
sut.set(ByteBuffer.wrap("hello".getBytes()));
sut.set(ByteBuffer.wrap("world".getBytes()));
assertThat(sut.get()).containsEntry("hello", "world");
}
@Test
void shouldAcceptBoolean() {
MapOutput<String, Object> sut = new MapOutput(StringCodec.UTF8);
sut.multi(2);
sut.set(ByteBuffer.wrap("hello".getBytes()));
sut.set(true);
assertThat(sut.get()).containsEntry("hello", true);
}
@Test
void shouldAcceptDouble() {
MapOutput<String, Object> sut = new MapOutput(StringCodec.UTF8);
sut.multi(2);
sut.set(ByteBuffer.wrap("hello".getBytes()));
sut.set(1.2);
assertThat(sut.get()).containsEntry("hello", 1.2);
}
@Test
void shouldAcceptInteger() {
MapOutput<String, Object> sut = new MapOutput(StringCodec.UTF8);
sut.multi(2);
sut.set(ByteBuffer.wrap("hello".getBytes()));
sut.set(1L);
assertThat(sut.get()).containsEntry("hello", 1L);
}
}
| MapOutputUnitTests |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/AnnotationInfo.java | {
"start": 1151,
"end": 1640
} | class ____ {
public abstract String typeName();
public Set<String> containerOf() {
return internalContainerOf();
}
abstract ImmutableSet<String> internalContainerOf();
public static AnnotationInfo create(String typeName, Iterable<String> containerOf) {
return new AutoValue_AnnotationInfo(typeName, ImmutableSet.copyOf(containerOf));
}
public static AnnotationInfo create(String typeName) {
return create(typeName, ImmutableSet.<String>of());
}
}
| AnnotationInfo |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesReplicationControllersEndpointBuilderFactory.java | {
"start": 1504,
"end": 1690
} | interface ____ {
/**
* Builder for endpoint consumers for the Kubernetes Replication Controller component.
*/
public | KubernetesReplicationControllersEndpointBuilderFactory |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/ApplicationPermission.java | {
"start": 9155,
"end": 10677
} | class ____ {
private final ApplicationPrivilege privilege;
private final Predicate<String> application;
private final Set<String> resourceNames;
private final Automaton resourceAutomaton;
private PermissionEntry(ApplicationPrivilege privilege, Set<String> resourceNames, Automaton resourceAutomaton) {
this.privilege = privilege;
this.application = Automatons.predicate(privilege.getApplication());
this.resourceNames = resourceNames;
this.resourceAutomaton = resourceAutomaton;
}
private boolean grants(ApplicationPrivilege other, Automaton resource) {
return matchesPrivilege(other) && Automatons.subsetOf(resource, this.resourceAutomaton);
}
private boolean matchesPrivilege(ApplicationPrivilege other) {
if (this.privilege.equals(other)) {
return true;
}
if (this.application.test(other.getApplication()) == false) {
return false;
}
if (privilege.grantsAll()) {
return true;
}
return Operations.isEmpty(privilege.getAutomaton()) == false
&& Operations.isEmpty(other.getAutomaton()) == false
&& Automatons.subsetOf(other.getAutomaton(), privilege.getAutomaton());
}
@Override
public String toString() {
return privilege.toString() + ":" + resourceNames;
}
}
}
| PermissionEntry |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.