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
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/selection/methodgenerics/array/SourceTypeIsTypeVarArrayMapper.java
|
{
"start": 939,
"end": 1197
}
|
class ____ {
private GenericWrapper<String> prop;
public GenericWrapper<String> getProp() {
return prop;
}
public void setProp(GenericWrapper<String> prop) {
this.prop = prop;
}
}
|
Target
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/context/annotation/AutoProxyLazyInitTests.java
|
{
"start": 3214,
"end": 3767
}
|
class ____ {
@Bean
BeanNameAutoProxyCreator lazyInitAutoProxyCreator() {
BeanNameAutoProxyCreator autoProxyCreator = new BeanNameAutoProxyCreator();
autoProxyCreator.setBeanNames("*");
autoProxyCreator.setCustomTargetSourceCreators(lazyInitTargetSourceCreator());
return autoProxyCreator;
}
@Bean
LazyInitTargetSourceCreator lazyInitTargetSourceCreator() {
return new StrictLazyInitTargetSourceCreator();
}
@Bean
@Lazy
static MyBean myBean() {
return new MyBeanImpl();
}
}
@Configuration
static
|
ConfigWithStatic
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/bug/Bug_for_ludong.java
|
{
"start": 2783,
"end": 20636
}
|
class ____ implements Cloneable, Serializable {
public static String ORDER_ID = "orderId";
private Object orderId;
public static String PARENT_ID = "parentId";
private Integer parentId;
public static String SERIAL_NUM = "serialNum";
private String serialNum;
public static String ITEM_NUM = "itemNum";
private String itemNum;
public static String PURCHASE_TYPE = "purchaseType";
private String purchaseType;
public static String ATTRIBUTE = "attribute";
private String attribute;
public static String MEMBER_ID = "memberId";
private String memberId;
public static String PRODUCT_CODE = "productCode";
private String productCode;
public static String NUM = "num";
private Integer num;
public static String UNIT = "unit";
private String unit;
public static String PRICE = "price";
private java.math.BigDecimal price;
public static String DISCOUNT_RATE = "discountRate";
private java.math.BigDecimal discountRate;
public static String QUOTED_PRICE = "quotedPrice";
private java.math.BigDecimal quotedPrice;
public static String ULTIMATE_PRICE = "ultimatePrice";
private java.math.BigDecimal ultimatePrice;
public static String EXECUTE_AMOUNT = "executeAmount";
private java.math.BigDecimal executeAmount;
public static String GMT_TARGET_BEGIN = "gmtTargetBegin";
private java.util.Date gmtTargetBegin;
public static String GMT_TARGET_END = "gmtTargetEnd";
private java.util.Date gmtTargetEnd;
public static String GMT_ACTUAL_BEGIN = "gmtActualBegin";
private java.util.Date gmtActualBegin;
public static String GMT_ACTUAL_END = "gmtActualEnd";
private java.util.Date gmtActualEnd;
public static String SERVICE_SUPPLY_COMPANY = "serviceSupplyCompany";
private String serviceSupplyCompany;
public static String BENEFIT_CUSTOMER = "benefitCustomer";
private String benefitCustomer;
public static String BENEFIT_CUSTOMER_ID = "benefitCustomerId";
private Integer benefitCustomerId;
public static String BENEFIT_CUSTOMER_CONTACTOR = "benefitCustomerContactor";
private Integer benefitCustomerContactor;
public static String BIZ_STATUS = "bizStatus";
private String bizStatus;
public static String VOUCHER_STATUS = "voucherStatus";
private String voucherStatus;
public static String PAYMENT_STATUS = "paymentStatus";
private String paymentStatus;
public static String PAYMENT_AMOUNT = "paymentAmount";
private java.math.BigDecimal paymentAmount;
public static String POLICY_ID = "policyId";
private Integer policyId;
public static String MEMO = "memo";
private String memo;
public static String SUPPORTER = "supporter";
private String supporter;
public static String SUPPORTER_ORG_ID = "supporterOrgId";
private Integer supporterOrgId;
public static String SUPPORTER_ORG_FULLID = "supporterOrgFullid";
private String supporterOrgFullid;
public static String SALES_ORG_FULLID = "salesOrgFullid";
private String salesOrgFullid;
public static String SIGN_SALES_ORG_FULLID = "signSalesOrgFullId";
private String signSalesOrgFullId;
public static String OPP_ID = "oppId";
private Integer oppId;
public static String DOMAIN = "domain";
private String domain;
public static String UN_SERVICE_DAY = "unServiceDay";
private java.math.BigDecimal unServiceDay;
public static String PROCESS_ID = "processId";
private Long processId;
public static String LAST_OPER_TYPE = "lastOperType";
private String lastOperType;
public static String UNVOUCHER_AMOUNT = "unvoucherAmount";
private java.math.BigDecimal unvoucherAmount;
public static String GMT_VOUCHER_RECEIVE = "gmtVoucherReceive";
private java.util.Date gmtVoucherReceive;
public static String GMT_PAYMENT_REMIT = "gmtPaymentRemit";
private java.util.Date gmtPaymentRemit;
public static String SERVICE_JUMP_DAYS = "serviceJumpDays";
private Integer serviceJumpDays;
public static String SIGN_SALES_ID = "signSalesId";
private String signSalesId;
public static String SALES_ORG_ID = "salesOrgId";
private Integer salesOrgId;
public static String SIGN_SALES_ORG_ID = "signSalesOrgId";
private Integer signSalesOrgId;
public Integer getSignSalesOrgId() {
return signSalesOrgId;
}
public void setSignSalesOrgId(Integer signSalesOrgId) {
this.signSalesOrgId = signSalesOrgId;
}
public Integer getSalesOrgId() {
return salesOrgId;
}
public void setSalesOrgId(Integer salesOrgId) {
this.salesOrgId = salesOrgId;
}
public static String SIGN_SELLER_COMPANY = "signSellerCompany";
private String signSellerCompany;
public static String BARGAIN_ID = "bargainId";
private Integer bargainId;
public Integer getBargainId() {
return bargainId;
}
public void setBargainId(Integer bargainId) {
this.bargainId = bargainId;
}
public String getSignSellerCompany() {
return signSellerCompany;
}
public void setSignSellerCompany(String signSellerCompany) {
this.signSellerCompany = signSellerCompany;
}
// 增加了新签和续签销售的id
public static String SALES_ID = "salesId";
private String salesId;
public String getSalesId() {
return salesId;
}
public void setSalesId(String salesId) {
this.salesId = salesId;
}
public String getRenewSalesId() {
return renewSalesId;
}
public void setRenewSalesId(String renewSalesId) {
this.renewSalesId = renewSalesId;
}
public static String RENEW_SALES_ID = "renewSalesId";
private String renewSalesId;
public static String GMT_SIGN = "gmtSign";
private java.util.Date gmtSign;
public Object getOrderId() {
return this.orderId;
}
public void setOrderId(Object orderId) {
this.orderId = orderId;
}
public Integer getParentId() {
return this.parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getSerialNum() {
return this.serialNum;
}
public void setSerialNum(String serialNum) {
this.serialNum = serialNum;
}
public String getItemNum() {
return this.itemNum;
}
public void setItemNum(String itemNum) {
this.itemNum = itemNum;
}
public String getPurchaseType() {
return this.purchaseType;
}
public void setPurchaseType(String purchaseType) {
this.purchaseType = purchaseType;
}
public String getAttribute() {
return this.attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getMemberId() {
return this.memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getProductCode() {
return this.productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public Integer getNum() {
return this.num;
}
public void setNum(Integer num) {
this.num = num;
}
public String getUnit() {
return this.unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public java.math.BigDecimal getPrice() {
return this.price;
}
public void setPrice(java.math.BigDecimal price) {
this.price = price;
}
public java.math.BigDecimal getDiscountRate() {
return this.discountRate;
}
public void setDiscountRate(java.math.BigDecimal discountRate) {
this.discountRate = discountRate;
}
public java.math.BigDecimal getQuotedPrice() {
return this.quotedPrice;
}
public void setQuotedPrice(java.math.BigDecimal quotedPrice) {
this.quotedPrice = quotedPrice;
}
public java.math.BigDecimal getUltimatePrice() {
return this.ultimatePrice;
}
public void setUltimatePrice(java.math.BigDecimal ultimatePrice) {
this.ultimatePrice = ultimatePrice;
}
public java.math.BigDecimal getExecuteAmount() {
return this.executeAmount;
}
public void setExecuteAmount(java.math.BigDecimal executeAmount) {
this.executeAmount = executeAmount;
}
public java.util.Date getGmtTargetBegin() {
return this.gmtTargetBegin;
}
public void setGmtTargetBegin(java.util.Date gmtTargetBegin) {
this.gmtTargetBegin = gmtTargetBegin;
}
public java.util.Date getGmtTargetEnd() {
return this.gmtTargetEnd;
}
public void setGmtTargetEnd(java.util.Date gmtTargetEnd) {
this.gmtTargetEnd = gmtTargetEnd;
}
public java.util.Date getGmtActualBegin() {
return this.gmtActualBegin;
}
public void setGmtActualBegin(java.util.Date gmtActualBegin) {
this.gmtActualBegin = gmtActualBegin;
}
public java.util.Date getGmtActualEnd() {
return this.gmtActualEnd;
}
public void setGmtActualEnd(java.util.Date gmtActualEnd) {
this.gmtActualEnd = gmtActualEnd;
}
public String getServiceSupplyCompany() {
return this.serviceSupplyCompany;
}
public void setServiceSupplyCompany(String serviceSupplyCompany) {
this.serviceSupplyCompany = serviceSupplyCompany;
}
public String getBenefitCustomer() {
return this.benefitCustomer;
}
public void setBenefitCustomer(String benefitCustomer) {
this.benefitCustomer = benefitCustomer;
}
public Integer getBenefitCustomerId() {
return this.benefitCustomerId;
}
public void setBenefitCustomerId(Integer benefitCustomerId) {
this.benefitCustomerId = benefitCustomerId;
}
public Integer getBenefitCustomerContactor() {
return this.benefitCustomerContactor;
}
public void setBenefitCustomerContactor(Integer benefitCustomerContactor) {
this.benefitCustomerContactor = benefitCustomerContactor;
}
public String getBizStatus() {
return this.bizStatus;
}
public void setBizStatus(String bizStatus) {
this.bizStatus = bizStatus;
}
public String getVoucherStatus() {
return this.voucherStatus;
}
public void setVoucherStatus(String voucherStatus) {
this.voucherStatus = voucherStatus;
}
public String getPaymentStatus() {
return this.paymentStatus;
}
public void setPaymentStatus(String paymentStatus) {
this.paymentStatus = paymentStatus;
}
public java.math.BigDecimal getPaymentAmount() {
return this.paymentAmount;
}
public void setPaymentAmount(java.math.BigDecimal paymentAmount) {
this.paymentAmount = paymentAmount;
}
public Integer getPolicyId() {
return this.policyId;
}
public void setPolicyId(Integer policyId) {
this.policyId = policyId;
}
public String getMemo() {
return this.memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getSupporter() {
return this.supporter;
}
public void setSupporter(String supporter) {
this.supporter = supporter;
}
public Integer getSupporterOrgId() {
return this.supporterOrgId;
}
public void setSupporterOrgId(Integer supporterOrgId) {
this.supporterOrgId = supporterOrgId;
}
public String getSupporterOrgFullid() {
return this.supporterOrgFullid;
}
public void setSupporterOrgFullid(String supporterOrgFullid) {
this.supporterOrgFullid = supporterOrgFullid;
}
public Integer getOppId() {
return this.oppId;
}
public void setOppId(Integer oppId) {
this.oppId = oppId;
}
public String getDomain() {
return this.domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public java.math.BigDecimal getUnServiceDay() {
return this.unServiceDay;
}
public void setUnServiceDay(java.math.BigDecimal unServiceDay) {
this.unServiceDay = unServiceDay;
}
public Long getProcessId() {
return this.processId;
}
public void setProcessId(Long processId) {
this.processId = processId;
}
public String getLastOperType() {
return this.lastOperType;
}
public void setLastOperType(String lastOperType) {
this.lastOperType = lastOperType;
}
public java.math.BigDecimal getUnvoucherAmount() {
return this.unvoucherAmount;
}
public void setUnvoucherAmount(java.math.BigDecimal unvoucherAmount) {
this.unvoucherAmount = unvoucherAmount;
}
public java.util.Date getGmtVoucherReceive() {
return this.gmtVoucherReceive;
}
public void setGmtVoucherReceive(java.util.Date gmtVoucherReceive) {
this.gmtVoucherReceive = gmtVoucherReceive;
}
public java.util.Date getGmtPaymentRemit() {
return this.gmtPaymentRemit;
}
public void setGmtPaymentRemit(java.util.Date gmtPaymentRemit) {
this.gmtPaymentRemit = gmtPaymentRemit;
}
public Integer getServiceJumpDays() {
return this.serviceJumpDays;
}
public void setServiceJumpDays(Integer serviceJumpDays) {
this.serviceJumpDays = serviceJumpDays;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public String getSignSalesId() {
return signSalesId;
}
public void setSignSalesId(String signSalesId) {
this.signSalesId = signSalesId;
}
public String getSalesOrgFullid() {
return salesOrgFullid;
}
public void setSalesOrgFullid(String salesOrgFullid) {
this.salesOrgFullid = salesOrgFullid;
}
public String getSignSalesOrgFullId() {
return signSalesOrgFullId;
}
public void setSignSalesOrgFullId(String signSalesOrgFullId) {
this.signSalesOrgFullId = signSalesOrgFullId;
}
public java.util.Date getGmtSign() {
return gmtSign;
}
public void setGmtSign(java.util.Date gmtSign) {
this.gmtSign = gmtSign;
}
}
public static
|
OrdOrderItem
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/PathMapper.java
|
{
"start": 912,
"end": 1120
}
|
interface ____ to provide a mapping between an endpoint ID and the root path
* where it will be exposed.
*
* @author Stephane Nicoll
* @author Phillip Webb
* @since 2.0.0
*/
@FunctionalInterface
public
|
used
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/AuditReaderImpl.java
|
{
"start": 5339,
"end": 12643
}
|
class ____ not versioned from the beginning, there's a missing ADD rev - what then?
cls = getTargetClassIfProxied( cls );
checkNotNull( cls, "Entity class" );
checkNotNull( entityName, "Entity name" );
checkNotNull( primaryKey, "Primary key" );
checkSession();
return createQuery().forRevisionsOfEntity( cls, entityName, false, true )
.addProjection( AuditEntity.revisionNumber() )
.addOrder( AuditEntity.revisionNumber().asc() )
.add( AuditEntity.id().eq( primaryKey ) )
.getResultList();
}
@Override
public Date getRevisionDate(Number revision)
throws IllegalArgumentException, RevisionDoesNotExistException, IllegalStateException {
checkNotNull( revision, "Entity revision" );
checkPositive( revision, "Entity revision" );
checkSession();
final Query<?> query = enversService.getRevisionInfoQueryCreator().getRevisionDateQuery( session, revision );
try {
final Object timestampObject = query.uniqueResult();
if ( timestampObject == null ) {
throw new RevisionDoesNotExistException( revision );
}
// The timestamp object is either a date, instant, or a long
if ( timestampObject instanceof Date ) {
return (Date) timestampObject;
}
else if ( timestampObject instanceof Instant ) {
return Date.from( (Instant) timestampObject );
}
else {
return new Date( (Long) timestampObject );
}
}
catch (NonUniqueResultException e) {
throw new AuditException( e );
}
}
@Override
public Number getRevisionNumberForDate(Date date) {
checkNotNull( date, "Date of revision" );
checkSession();
final Query<?> query = enversService.getRevisionInfoQueryCreator().getRevisionNumberForDateQuery( session, date );
try {
final Number res = (Number) query.uniqueResult();
if ( res == null ) {
throw new RevisionDoesNotExistException( date );
}
return res;
}
catch (NonUniqueResultException e) {
throw new AuditException( e );
}
}
@Override
public Number getRevisionNumberForDate(LocalDateTime date) {
checkNotNull( date, "Date of revision" );
checkSession();
final Query<?> query = enversService.getRevisionInfoQueryCreator().getRevisionNumberForDateQuery( session, date );
try {
final Number res = (Number) query.uniqueResult();
if ( res == null ) {
throw new RevisionDoesNotExistException( date );
}
return res;
}
catch (NonUniqueResultException e) {
throw new AuditException( e );
}
}
@Override
public Number getRevisionNumberForDate(Instant date) {
checkNotNull( date, "Date of revision" );
checkSession();
final Query<?> query = enversService.getRevisionInfoQueryCreator().getRevisionNumberForDateQuery( session, date );
try {
final Number res = (Number) query.uniqueResult();
if ( res == null ) {
throw new RevisionDoesNotExistException( date );
}
return res;
}
catch (NonUniqueResultException e) {
throw new AuditException( e );
}
}
@Override
@SuppressWarnings("unchecked")
public <T> T findRevision(Class<T> revisionEntityClass, Number revision)
throws IllegalArgumentException, RevisionDoesNotExistException, IllegalStateException {
revisionEntityClass = getTargetClassIfProxied( revisionEntityClass );
checkNotNull( revision, "Entity revision" );
checkPositive( revision, "Entity revision" );
checkSession();
final Set<Number> revisions = new HashSet<>( 1 );
revisions.add( revision );
final Query<?> query = enversService.getRevisionInfoQueryCreator().getRevisionsQuery( session, revisions );
try {
final T revisionData = (T) query.uniqueResult();
if ( revisionData == null ) {
throw new RevisionDoesNotExistException( revision );
}
return revisionData;
}
catch (NonUniqueResultException e) {
throw new AuditException( e );
}
}
@Override
@SuppressWarnings("unchecked")
public <T> Map<Number, T> findRevisions(Class<T> revisionEntityClass, Set<Number> revisions)
throws IllegalArgumentException,
IllegalStateException {
revisionEntityClass = getTargetClassIfProxied( revisionEntityClass );
final Map<Number, T> result = new HashMap<>( revisions.size() );
for ( Number revision : revisions ) {
checkNotNull( revision, "Entity revision" );
checkPositive( revision, "Entity revision" );
}
checkSession();
final Query<?> query = enversService.getRevisionInfoQueryCreator().getRevisionsQuery( session, revisions );
try {
final List<?> revisionList = query.getResultList();
for ( Object revision : revisionList ) {
final Number revNo = enversService.getRevisionInfoNumberReader().getRevisionNumber( revision );
result.put( revNo, (T) revision );
}
return result;
}
catch (HibernateException e) {
throw new AuditException( e );
}
}
@Override
public CrossTypeRevisionChangesReader getCrossTypeRevisionChangesReader() throws AuditException {
if ( !enversService.getConfig().isTrackEntitiesChanged() ) {
throw new AuditException(
"This API is designed for Envers default mechanism of tracking entities modified in a given revision."
+ " Extend DefaultTrackingModifiedEntitiesRevisionEntity, utilize @ModifiedEntityNames annotation or set "
+ "'org.hibernate.envers.track_entities_changed_in_revision' parameter to true."
);
}
return crossTypeRevisionChangesReader;
}
@Override
@SuppressWarnings("unchecked")
public <T> T getCurrentRevision(Class<T> revisionEntityClass, boolean persist) {
revisionEntityClass = getTargetClassIfProxied( revisionEntityClass );
if ( !(session instanceof EventSource) ) {
throw new IllegalArgumentException( "The provided session is not an EventSource!" );
}
// Obtaining the current audit sync
final AuditProcess auditProcess = enversService.getAuditProcessManager().get( (EventSource) session );
// And getting the current revision data
return (T) auditProcess.getCurrentRevisionData( (SessionImplementor) session, persist );
}
@Override
public AuditQueryCreator createQuery() {
return new AuditQueryCreator( enversService, this );
}
@Override
public boolean isEntityClassAudited(Class<?> entityClass) {
entityClass = getTargetClassIfProxied( entityClass );
return this.isEntityNameAudited( entityClass.getName() );
}
@Override
public boolean isEntityNameAudited(String entityName) {
checkNotNull( entityName, "Entity name" );
checkSession();
return enversService.getEntitiesConfigurations().isVersioned( entityName );
}
@Override
public String getEntityName(Object primaryKey, Number revision, Object entity) throws HibernateException {
checkNotNull( primaryKey, "Primary key" );
checkNotNull( revision, "Entity revision" );
checkPositive( revision, "Entity revision" );
checkNotNull( entity, "Entity" );
checkSession();
// Unwrap if necessary
if ( entity instanceof HibernateProxy ) {
entity = ( (HibernateProxy) entity ).getHibernateLazyInitializer().getImplementation();
}
if ( firstLevelCache.containsEntityName( primaryKey, revision, entity ) ) {
// it's on envers FLC!
return firstLevelCache.getFromEntityNameCache( primaryKey, revision, entity );
}
else {
throw new HibernateException(
"Envers can't resolve entityName for historic entity. The id, revision and entity is not on envers first level cache."
);
}
}
}
|
is
|
java
|
reactor__reactor-core
|
reactor-core/src/main/java/reactor/core/publisher/QueueDrainSubscriber.java
|
{
"start": 8130,
"end": 9339
}
|
class ____ extends QueueDrainSubscriberWip {
byte pad000,pad001,pad002,pad003,pad004,pad005,pad006,pad007;// 8b
byte pad010,pad011,pad012,pad013,pad014,pad015,pad016,pad017;// 16b
byte pad020,pad021,pad022,pad023,pad024,pad025,pad026,pad027;// 24b
byte pad030,pad031,pad032,pad033,pad034,pad035,pad036,pad037;// 32b
byte pad040,pad041,pad042,pad043,pad044,pad045,pad046,pad047;// 40b
byte pad050,pad051,pad052,pad053,pad054,pad055,pad056,pad057;// 48b
byte pad060,pad061,pad062,pad063,pad064,pad065,pad066,pad067;// 56b
byte pad070,pad071,pad072,pad073,pad074,pad075,pad076,pad077;// 64b
byte pad100,pad101,pad102,pad103,pad104,pad105,pad106,pad107;// 72b
byte pad110,pad111,pad112,pad113,pad114,pad115,pad116,pad117;// 80b
byte pad120,pad121,pad122,pad123,pad124,pad125,pad126,pad127;// 88b
byte pad130,pad131,pad132,pad133,pad134,pad135,pad136,pad137;// 96b
byte pad140,pad141,pad142,pad143,pad144,pad145,pad146,pad147;//104b
byte pad150,pad151,pad152,pad153,pad154,pad155,pad156,pad157;//112b
byte pad160,pad161,pad162,pad163,pad164,pad165,pad166,pad167;//120b
byte pad170,pad171,pad172,pad173,pad174,pad175,pad176,pad177;//128b
}
/** Contains the requested field. */
|
QueueDrainSubscriberPad2
|
java
|
spring-projects__spring-boot
|
module/spring-boot-webclient/src/test/java/org/springframework/boot/webclient/autoconfigure/WebClientObservationAutoConfigurationTests.java
|
{
"start": 2563,
"end": 5002
}
|
class ____ {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withBean(ObservationRegistry.class, TestObservationRegistry::create)
.withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class, WebClientAutoConfiguration.class))
.withUserConfiguration(WebClientObservationAutoConfiguration.class);
@Test
void contributesCustomizerBean() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ObservationWebClientCustomizer.class));
}
@Test
void webClientCreatedWithBuilderIsInstrumented() {
this.contextRunner.run((context) -> {
TestObservationRegistry registry = context.getBean(TestObservationRegistry.class);
WebClient.Builder builder = context.getBean(WebClient.Builder.class);
validateWebClient(builder, registry);
});
}
@Test
void shouldUseCustomConventionIfAvailable() {
this.contextRunner.withUserConfiguration(CustomConvention.class).run((context) -> {
TestObservationRegistry registry = context.getBean(TestObservationRegistry.class);
WebClient.Builder builder = context.getBean(WebClient.Builder.class);
WebClient webClient = mockWebClient(builder);
assertThat(registry).doesNotHaveAnyObservation();
webClient.get()
.uri("https://example.org/projects/{project}", "spring-boot")
.retrieve()
.toBodilessEntity()
.block(Duration.ofSeconds(30));
assertThat(registry).hasObservationWithNameEqualTo("http.client.requests")
.that()
.hasLowCardinalityKeyValue("project", "spring-boot");
});
}
private void validateWebClient(WebClient.Builder builder, TestObservationRegistry registry) {
WebClient webClient = mockWebClient(builder);
assertThat(registry).doesNotHaveAnyObservation();
webClient.get()
.uri("https://example.org/projects/{project}", "spring-boot")
.retrieve()
.toBodilessEntity()
.block(Duration.ofSeconds(30));
assertThat(registry).hasObservationWithNameEqualTo("http.client.requests")
.that()
.hasLowCardinalityKeyValue("uri", "/projects/{project}");
}
private WebClient mockWebClient(WebClient.Builder builder) {
ClientHttpConnector connector = mock(ClientHttpConnector.class);
given(connector.connect(any(), any(), any())).willReturn(Mono.just(new MockClientHttpResponse(HttpStatus.OK)));
return builder.clientConnector(connector).build();
}
@Configuration(proxyBeanMethods = false)
static
|
WebClientObservationAutoConfigurationTests
|
java
|
spring-projects__spring-framework
|
spring-jms/src/main/java/org/springframework/jms/core/support/package-info.java
|
{
"start": 95,
"end": 231
}
|
class ____ JmsTemplate usage.
*/
@NullMarked
package org.springframework.jms.core.support;
import org.jspecify.annotations.NullMarked;
|
for
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/EntityGraphTest.java
|
{
"start": 20881,
"end": 21161
}
|
class ____ {
@Id
@GeneratedValue
public Integer id;
@ManyToOne(fetch = FetchType.LAZY)
private Author author;
public Prize() {
}
public Prize(Author author) {
this.author = author;
}
}
@Entity(name = "Author")
@Table(name = "author")
public static
|
Prize
|
java
|
apache__flink
|
flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/SavepointWriterWindowITCase.java
|
{
"start": 3215,
"end": 16395
}
|
class ____ extends AbstractTestBaseJUnit4 {
private static final String UID = "uid";
private static final Collection<String> WORDS =
Arrays.asList("hello", "world", "hello", "everyone");
private static final Iterable<? extends Tuple2<String, Integer>> STANDARD_MATCHER =
Arrays.asList(Tuple2.of("hello", 2), Tuple2.of("world", 1), Tuple2.of("everyone", 1));
private static final Iterable<? extends Tuple2<String, Integer>> EVICTOR_MATCHER =
Arrays.asList(Tuple2.of("hello", 1), Tuple2.of("world", 1), Tuple2.of("everyone", 1));
private static final TypeInformation<Tuple2<String, Integer>> TUPLE_TYPE_INFO =
new TypeHint<Tuple2<String, Integer>>() {}.getTypeInfo();
private static final List<Tuple3<String, WindowBootstrap, WindowStream>> SETUP_FUNCTIONS =
Arrays.asList(
Tuple3.of(
"reduce",
transformation -> transformation.reduce(new Reducer()),
stream -> stream.reduce(new Reducer())),
Tuple3.of(
"aggregate",
transformation -> transformation.aggregate(new Aggregator()),
stream -> stream.aggregate(new Aggregator())),
Tuple3.of(
"apply",
transformation -> transformation.apply(new CustomWindowFunction()),
stream -> stream.apply(new CustomWindowFunction())),
Tuple3.of(
"process",
transformation ->
transformation.process(new CustomProcessWindowFunction()),
stream -> stream.process(new CustomProcessWindowFunction())));
private static final List<Tuple3<String, StateBackend, Configuration>> STATE_BACKENDS =
Arrays.asList(
Tuple3.of(
"HashMap",
new HashMapStateBackend(),
new Configuration().set(StateBackendOptions.STATE_BACKEND, "hashmap")),
Tuple3.of(
"EmbeddedRocksDB",
new EmbeddedRocksDBStateBackend(),
new Configuration().set(StateBackendOptions.STATE_BACKEND, "rocksdb")));
@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> data() {
List<Object[]> parameterList = new ArrayList<>();
for (Tuple3<String, StateBackend, Configuration> stateBackend : STATE_BACKENDS) {
for (Tuple3<String, WindowBootstrap, WindowStream> setup : SETUP_FUNCTIONS) {
Object[] parameters =
new Object[] {
stateBackend.f0 + ": " + setup.f0,
setup.f1,
setup.f2,
stateBackend.f1,
stateBackend.f2
};
parameterList.add(parameters);
}
}
return parameterList;
}
private final WindowBootstrap windowBootstrap;
private final WindowStream windowStream;
private final StateBackend stateBackend;
private final Configuration configuration;
@SuppressWarnings("unused")
public SavepointWriterWindowITCase(
String ignore,
WindowBootstrap windowBootstrap,
WindowStream windowStream,
StateBackend stateBackend,
Configuration configuration) {
this.windowBootstrap = windowBootstrap;
this.windowStream = windowStream;
this.stateBackend = stateBackend;
this.configuration = configuration;
}
@Test
public void testTumbleWindow() throws Exception {
final String savepointPath = getTempDirPath(new AbstractID().toHexString());
StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment(configuration);
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
DataStream<Tuple2<String, Integer>> bootstrapData =
env.fromData(WORDS)
.map(word -> Tuple2.of(word, 1))
.returns(TUPLE_TYPE_INFO)
.assignTimestampsAndWatermarks(
WatermarkStrategy.<Tuple2<String, Integer>>noWatermarks()
.withTimestampAssigner((record, ts) -> 2L));
WindowedStateTransformation<Tuple2<String, Integer>, String, TimeWindow> transformation =
OperatorTransformation.bootstrapWith(bootstrapData)
.keyBy(tuple -> tuple.f0, Types.STRING)
.window(TumblingEventTimeWindows.of(Duration.ofMillis(5)));
SavepointWriter.newSavepoint(env, stateBackend, 128)
.withOperator(
OperatorIdentifier.forUid(UID), windowBootstrap.bootstrap(transformation))
.write(savepointPath);
env.execute("write state");
WindowedStream<Tuple2<String, Integer>, String, TimeWindow> stream =
env.addSource(new MaxWatermarkSource<Tuple2<String, Integer>>())
.returns(TUPLE_TYPE_INFO)
.keyBy(tuple -> tuple.f0)
.window(TumblingEventTimeWindows.of(Duration.ofMillis(5)));
DataStream<Tuple2<String, Integer>> windowed = windowStream.window(stream).uid(UID);
CloseableIterator<Tuple2<String, Integer>> future = windowed.collectAsync();
submitJob(savepointPath, env);
assertThat(future)
.toIterable()
.as("Incorrect results from bootstrapped windows")
.containsAll(STANDARD_MATCHER);
}
@Test
public void testTumbleWindowWithEvictor() throws Exception {
final String savepointPath = getTempDirPath(new AbstractID().toHexString());
StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment(configuration);
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
DataStream<Tuple2<String, Integer>> bootstrapData =
env.fromData(WORDS)
.map(word -> Tuple2.of(word, 1))
.returns(TUPLE_TYPE_INFO)
.assignTimestampsAndWatermarks(
WatermarkStrategy.<Tuple2<String, Integer>>noWatermarks()
.withTimestampAssigner((record, ts) -> 2L));
WindowedStateTransformation<Tuple2<String, Integer>, String, TimeWindow> transformation =
OperatorTransformation.bootstrapWith(bootstrapData)
.keyBy(tuple -> tuple.f0, Types.STRING)
.window(TumblingEventTimeWindows.of(Duration.ofMillis(5)))
.evictor(CountEvictor.of(1));
SavepointWriter.newSavepoint(env, stateBackend, 128)
.withOperator(
OperatorIdentifier.forUid(UID), windowBootstrap.bootstrap(transformation))
.write(savepointPath);
env.execute("write state");
WindowedStream<Tuple2<String, Integer>, String, TimeWindow> stream =
env.addSource(new MaxWatermarkSource<Tuple2<String, Integer>>())
.returns(TUPLE_TYPE_INFO)
.keyBy(tuple -> tuple.f0)
.window(TumblingEventTimeWindows.of(Duration.ofMillis(5)))
.evictor(CountEvictor.of(1));
DataStream<Tuple2<String, Integer>> windowed = windowStream.window(stream).uid(UID);
CloseableIterator<Tuple2<String, Integer>> future = windowed.collectAsync();
submitJob(savepointPath, env);
assertThat(future)
.toIterable()
.as("Incorrect results from bootstrapped windows")
.containsAll(EVICTOR_MATCHER);
}
@Test
public void testSlideWindow() throws Exception {
final String savepointPath = getTempDirPath(new AbstractID().toHexString());
StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment(configuration);
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
DataStream<Tuple2<String, Integer>> bootstrapData =
env.fromData(WORDS)
.map(word -> Tuple2.of(word, 1), TUPLE_TYPE_INFO)
.assignTimestampsAndWatermarks(
WatermarkStrategy.<Tuple2<String, Integer>>noWatermarks()
.withTimestampAssigner((record, ts) -> 2L));
WindowedStateTransformation<Tuple2<String, Integer>, String, TimeWindow> transformation =
OperatorTransformation.bootstrapWith(bootstrapData)
.keyBy(tuple -> tuple.f0, Types.STRING)
.window(
SlidingEventTimeWindows.of(
Duration.ofMillis(5), Duration.ofMillis(1)));
SavepointWriter.newSavepoint(env, stateBackend, 128)
.withOperator(
OperatorIdentifier.forUid(UID), windowBootstrap.bootstrap(transformation))
.write(savepointPath);
env.execute("write state");
WindowedStream<Tuple2<String, Integer>, String, TimeWindow> stream =
env.addSource(new MaxWatermarkSource<Tuple2<String, Integer>>())
.returns(TUPLE_TYPE_INFO)
.keyBy(tuple -> tuple.f0)
.window(
SlidingEventTimeWindows.of(
Duration.ofMillis(5), Duration.ofMillis(1)));
DataStream<Tuple2<String, Integer>> windowed = windowStream.window(stream).uid(UID);
CloseableIterator<Tuple2<String, Integer>> future = windowed.collectAsync();
submitJob(savepointPath, env);
assertThat(future)
.toIterable()
.as("Incorrect results from bootstrapped windows")
.containsAll(STANDARD_MATCHER);
}
@Test
public void testSlideWindowWithEvictor() throws Exception {
final String savepointPath = getTempDirPath(new AbstractID().toHexString());
StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment(configuration);
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
DataStream<Tuple2<String, Integer>> bootstrapData =
env.fromData(WORDS)
.map(word -> Tuple2.of(word, 1))
.returns(TUPLE_TYPE_INFO)
.assignTimestampsAndWatermarks(
WatermarkStrategy.<Tuple2<String, Integer>>noWatermarks()
.withTimestampAssigner((record, ts) -> 2L));
WindowedStateTransformation<Tuple2<String, Integer>, String, TimeWindow> transformation =
OperatorTransformation.bootstrapWith(bootstrapData)
.keyBy(tuple -> tuple.f0, Types.STRING)
.window(
SlidingEventTimeWindows.of(
Duration.ofMillis(5), Duration.ofMillis(1)))
.evictor(CountEvictor.of(1));
SavepointWriter.newSavepoint(env, stateBackend, 128)
.withOperator(
OperatorIdentifier.forUid(UID), windowBootstrap.bootstrap(transformation))
.write(savepointPath);
env.execute("write state");
WindowedStream<Tuple2<String, Integer>, String, TimeWindow> stream =
env.addSource(new MaxWatermarkSource<Tuple2<String, Integer>>())
.returns(TUPLE_TYPE_INFO)
.keyBy(tuple -> tuple.f0)
.window(
SlidingEventTimeWindows.of(
Duration.ofMillis(5), Duration.ofMillis(1)))
.evictor(CountEvictor.of(1));
DataStream<Tuple2<String, Integer>> windowed = windowStream.window(stream).uid(UID);
CloseableIterator<Tuple2<String, Integer>> future = windowed.collectAsync();
submitJob(savepointPath, env);
assertThat(future)
.toIterable()
.as("Incorrect results from bootstrapped windows")
.containsAll(EVICTOR_MATCHER);
}
private void submitJob(String savepointPath, StreamExecutionEnvironment sEnv) throws Exception {
StreamGraph streamGraph = sEnv.getStreamGraph();
streamGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepointPath, true));
sEnv.execute(streamGraph);
}
private static
|
SavepointWriterWindowITCase
|
java
|
google__guava
|
guava/src/com/google/common/util/concurrent/Internal.java
|
{
"start": 786,
"end": 917
}
|
class ____ for {@code com.google.common.util.concurrent} use only! */
@J2ktIncompatible
@GwtIncompatible // java.time.Duration
final
|
is
|
java
|
spring-projects__spring-security
|
core/src/test/java/org/springframework/security/authorization/method/Jsr250AuthorizationManagerTests.java
|
{
"start": 11593,
"end": 11699
}
|
interface ____ {
@RolesAllowed("ADMIN")
void inheritedAnnotations();
}
public
|
InterfaceAnnotationsOne
|
java
|
grpc__grpc-java
|
grpclb/src/main/java/io/grpc/grpclb/SubchannelPool.java
|
{
"start": 982,
"end": 1911
}
|
interface ____ {
/**
* Registers a listener to received Subchannel status updates.
*/
void registerListener(PooledSubchannelStateListener listener);
/**
* Takes a {@link Subchannel} from the pool for the given {@code eag} if there is one available.
* Otherwise, creates and returns a new {@code Subchannel} with the given {@code eag} and {@code
* defaultAttributes}.
*/
Subchannel takeOrCreateSubchannel(EquivalentAddressGroup eag, Attributes defaultAttributes);
/**
* Puts a {@link Subchannel} back to the pool. From this point the Subchannel is owned by the
* pool, and the caller should stop referencing to this Subchannel.
*/
void returnSubchannel(Subchannel subchannel, ConnectivityStateInfo lastKnownState);
/**
* Shuts down all subchannels in the pool immediately.
*/
void clear();
/**
* Receives state changes for a pooled {@link Subchannel}.
*/
|
SubchannelPool
|
java
|
google__gson
|
gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java
|
{
"start": 15684,
"end": 16995
}
|
class ____<A, B, C, D, E> {
A a;
B b;
C c;
D d;
E e;
// For use by Gson
@SuppressWarnings("unused")
private MultiParameters() {}
MultiParameters(A a, B b, C c, D d, E e) {
super();
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result + ((b == null) ? 0 : b.hashCode());
result = prime * result + ((c == null) ? 0 : c.hashCode());
result = prime * result + ((d == null) ? 0 : d.hashCode());
result = prime * result + ((e == null) ? 0 : e.hashCode());
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof MultiParameters<?, ?, ?, ?, ?>)) {
return false;
}
MultiParameters<?, ?, ?, ?, ?> that = (MultiParameters<?, ?, ?, ?, ?>) o;
return Objects.equal(a, that.a)
&& Objects.equal(b, that.b)
&& Objects.equal(c, that.c)
&& Objects.equal(d, that.d)
&& Objects.equal(e, that.e);
}
}
// Begin: tests to reproduce issue 103
private static
|
MultiParameters
|
java
|
spring-projects__spring-security
|
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/JdbcAssertingPartyMetadataRepository.java
|
{
"start": 1925,
"end": 5862
}
|
class ____ implements AssertingPartyMetadataRepository {
private final JdbcOperations jdbcOperations;
private final RowMapper<AssertingPartyMetadata> assertingPartyMetadataRowMapper = new AssertingPartyMetadataRowMapper();
private final AssertingPartyMetadataParametersMapper assertingPartyMetadataParametersMapper = new AssertingPartyMetadataParametersMapper();
// @formatter:off
static final String[] COLUMN_NAMES = { "entity_id",
"single_sign_on_service_location",
"single_sign_on_service_binding",
"want_authn_requests_signed",
"signing_algorithms",
"verification_credentials",
"encryption_credentials",
"single_logout_service_location",
"single_logout_service_response_location",
"single_logout_service_binding" };
// @formatter:on
private static final String TABLE_NAME = "saml2_asserting_party_metadata";
private static final String ENTITY_ID_FILTER = "entity_id = ?";
// @formatter:off
private static final String LOAD_BY_ID_SQL = "SELECT " + String.join(",", COLUMN_NAMES)
+ " FROM " + TABLE_NAME
+ " WHERE " + ENTITY_ID_FILTER;
private static final String LOAD_ALL_SQL = "SELECT " + String.join(",", COLUMN_NAMES)
+ " FROM " + TABLE_NAME;
// @formatter:on
// @formatter:off
private static final String SAVE_CREDENTIAL_RECORD_SQL = "INSERT INTO " + TABLE_NAME
+ " (" + String.join(",", COLUMN_NAMES) + ") VALUES (" + String.join(",", Collections.nCopies(COLUMN_NAMES.length, "?")) + ")";
// @formatter:on
// @formatter:off
private static final String UPDATE_CREDENTIAL_RECORD_SQL = "UPDATE " + TABLE_NAME
+ " SET " + String.join(" = ?,", Arrays.copyOfRange(COLUMN_NAMES, 1, COLUMN_NAMES.length))
+ " = ?"
+ " WHERE " + ENTITY_ID_FILTER;
// @formatter:on
/**
* Constructs a {@code JdbcRelyingPartyRegistrationRepository} using the provided
* parameters.
* @param jdbcOperations the JDBC operations
*/
public JdbcAssertingPartyMetadataRepository(JdbcOperations jdbcOperations) {
Assert.notNull(jdbcOperations, "jdbcOperations cannot be null");
this.jdbcOperations = jdbcOperations;
}
@Override
public AssertingPartyMetadata findByEntityId(String entityId) {
Assert.hasText(entityId, "entityId cannot be empty");
SqlParameterValue[] parameters = new SqlParameterValue[] { new SqlParameterValue(Types.VARCHAR, entityId) };
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters);
List<AssertingPartyMetadata> result = this.jdbcOperations.query(LOAD_BY_ID_SQL, pss,
this.assertingPartyMetadataRowMapper);
return !result.isEmpty() ? result.get(0) : null;
}
@Override
public Iterator<AssertingPartyMetadata> iterator() {
List<AssertingPartyMetadata> result = this.jdbcOperations.query(LOAD_ALL_SQL,
this.assertingPartyMetadataRowMapper);
return result.iterator();
}
/**
* Persist this {@link AssertingPartyMetadata}
* @param metadata the metadata to persist
*/
public void save(AssertingPartyMetadata metadata) {
Assert.notNull(metadata, "metadata cannot be null");
int rows = updateCredentialRecord(metadata);
if (rows == 0) {
insertCredentialRecord(metadata);
}
}
private void insertCredentialRecord(AssertingPartyMetadata metadata) {
List<SqlParameterValue> parameters = this.assertingPartyMetadataParametersMapper.apply(metadata);
this.jdbcOperations.update(SAVE_CREDENTIAL_RECORD_SQL, parameters.toArray());
}
private int updateCredentialRecord(AssertingPartyMetadata metadata) {
List<SqlParameterValue> parameters = this.assertingPartyMetadataParametersMapper.apply(metadata);
SqlParameterValue credentialId = parameters.remove(0);
parameters.add(credentialId);
return this.jdbcOperations.update(UPDATE_CREDENTIAL_RECORD_SQL, parameters.toArray());
}
/**
* The default {@link RowMapper} that maps the current row in
* {@code java.sql.ResultSet} to {@link AssertingPartyMetadata}.
*/
private static final
|
JdbcAssertingPartyMetadataRepository
|
java
|
apache__camel
|
components/camel-kudu/src/generated/java/org/apache/camel/component/kudu/KuduEndpointConfigurer.java
|
{
"start": 731,
"end": 2227
}
|
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
KuduEndpoint target = (KuduEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "operation": target.setOperation(property(camelContext, org.apache.camel.component.kudu.KuduOperations.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "operation": return org.apache.camel.component.kudu.KuduOperations.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
KuduEndpoint target = (KuduEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "operation": return target.getOperation();
default: return null;
}
}
}
|
KuduEndpointConfigurer
|
java
|
apache__camel
|
core/camel-core-languages/src/main/java/org/apache/camel/language/simple/ast/BlockStart.java
|
{
"start": 894,
"end": 933
}
|
interface ____ extends Block {
}
|
BlockStart
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java
|
{
"start": 2962,
"end": 3744
}
|
class ____ {
public final SpringTestContext spring = new SpringTestContext(this);
@Autowired
MockMvc mvc;
@Autowired(required = false)
Service service;
@WithMockUser(authorities = "CUSTOM")
@Test
public void requestWhenNullifyingRolePrefixThenPassivityRestored() throws Exception {
this.spring.register(SecurityConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@WithMockUser(authorities = "CUSTOM")
@Test
public void methodSecurityWhenNullifyingRolePrefixThenPassivityRestored() {
this.spring.register(SecurityConfig.class).autowire();
this.service.doJsr250();
this.service.doPreAuthorize();
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
static
|
Sec2758Tests
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/context/annotation/Proxyable.java
|
{
"start": 1600,
"end": 2132
}
|
interface ____ {
/**
* Suggest a specific proxy type, either {@link ProxyType#INTERFACES} for
* a JDK dynamic proxy or {@link ProxyType#TARGET_CLASS} for a CGLIB proxy,
* overriding a globally configured default.
*/
ProxyType value() default ProxyType.DEFAULT;
/**
* Suggest a JDK dynamic proxy with specific interfaces to expose, overriding
* a globally configured default.
* <p>Only taken into account if {@link #value()} is not {@link ProxyType#TARGET_CLASS}.
*/
Class<?>[] interfaces() default {};
}
|
Proxyable
|
java
|
apache__kafka
|
test-common/test-common-runtime/src/test/java/org/apache/kafka/common/test/junit/ClusterTestExtensionsTest.java
|
{
"start": 5773,
"end": 27144
}
|
class ____ default
assertEquals("default.value", clusterInstance.config().serverProperties().get("default.key"));
}
// generate1 is a template method which generates any number of cluster configs
@ClusterTemplate("generate1")
public void testClusterTemplate() {
assertEquals(Type.KRAFT, clusterInstance.type(),
"generate1 provided a KRAFT cluster, so we should see that here");
assertEquals("bar", clusterInstance.config().serverProperties().get("foo"));
assertEquals(List.of("Generated Test"), clusterInstance.config().tags());
}
// Multiple @ClusterTest can be used with @ClusterTests
@ClusterTests({
@ClusterTest(types = {Type.KRAFT}, serverProperties = {
@ClusterConfigProperty(key = "foo", value = "baz"),
@ClusterConfigProperty(key = "spam", value = "eggz"),
@ClusterConfigProperty(key = "default.key", value = "overwrite.value"),
@ClusterConfigProperty(id = 0, key = "queued.max.requests", value = "200"),
@ClusterConfigProperty(id = 3000, key = "queued.max.requests", value = "300"),
@ClusterConfigProperty(key = "spam", value = "eggs"),
@ClusterConfigProperty(key = "default.key", value = "overwrite.value")
}, tags = {
"default.display.key1", "default.display.key2"
}),
@ClusterTest(types = {Type.CO_KRAFT}, serverProperties = {
@ClusterConfigProperty(key = "foo", value = "baz"),
@ClusterConfigProperty(key = "spam", value = "eggz"),
@ClusterConfigProperty(key = "default.key", value = "overwrite.value"),
@ClusterConfigProperty(id = 0, key = "queued.max.requests", value = "200"),
@ClusterConfigProperty(key = "spam", value = "eggs"),
@ClusterConfigProperty(key = "default.key", value = "overwrite.value")
}, tags = {
"default.display.key1", "default.display.key2"
})
})
public void testClusterTests() throws ExecutionException, InterruptedException {
assertEquals("baz", clusterInstance.config().serverProperties().get("foo"));
assertEquals("eggs", clusterInstance.config().serverProperties().get("spam"));
assertEquals("overwrite.value", clusterInstance.config().serverProperties().get("default.key"));
assertEquals(List.of("default.display.key1", "default.display.key2"), clusterInstance.config().tags());
// assert broker server 0 contains property queued.max.requests 200 from ClusterTest which overrides
// the value 100 in server property in ClusterTestDefaults
try (Admin admin = clusterInstance.admin()) {
ConfigResource configResource = new ConfigResource(ConfigResource.Type.BROKER, "0");
Map<ConfigResource, Config> configs = admin.describeConfigs(List.of(configResource)).all().get();
assertEquals(1, configs.size());
assertEquals("200", configs.get(configResource).get("queued.max.requests").value());
}
// In KRaft cluster non-combined mode, assert the controller server 3000 contains the property queued.max.requests 300
if (clusterInstance.type() == Type.KRAFT) {
try (Admin admin = Admin.create(Map.of(
AdminClientConfig.BOOTSTRAP_CONTROLLERS_CONFIG, clusterInstance.bootstrapControllers()))) {
ConfigResource configResource = new ConfigResource(ConfigResource.Type.BROKER, "3000");
Map<ConfigResource, Config> configs = admin.describeConfigs(List.of(configResource)).all().get();
assertEquals(1, configs.size());
assertEquals("300", configs.get(configResource).get("queued.max.requests").value());
}
}
}
@ClusterTests({
@ClusterTest(types = {Type.KRAFT, Type.CO_KRAFT}),
@ClusterTest(types = {Type.KRAFT, Type.CO_KRAFT}, disksPerBroker = 2),
})
public void testClusterTestWithDisksPerBroker() throws ExecutionException, InterruptedException {
try (Admin admin = clusterInstance.admin()) {
DescribeLogDirsResult result = admin.describeLogDirs(clusterInstance.brokerIds());
result.allDescriptions().get().forEach((brokerId, logDirDescriptionMap) ->
assertEquals(clusterInstance.config().numDisksPerBroker(), logDirDescriptionMap.size()));
}
}
@ClusterTest(autoStart = AutoStart.NO)
public void testNoAutoStart() {
Assertions.assertThrows(RuntimeException.class, () -> clusterInstance.brokers().values().stream().map(KafkaBroker::socketServer).findFirst());
clusterInstance.start();
assertTrue(clusterInstance.brokers().values().stream().map(KafkaBroker::socketServer).findFirst().isPresent());
}
@ClusterTest
public void testDefaults(ClusterInstance clusterInstance) {
assertEquals(MetadataVersion.latestTesting(), clusterInstance.config().metadataVersion());
}
@ClusterTest(types = {Type.KRAFT, Type.CO_KRAFT})
public void testSupportedNewGroupProtocols(ClusterInstance clusterInstance) {
Set<GroupProtocol> supportedGroupProtocols = new HashSet<>();
supportedGroupProtocols.add(CLASSIC);
supportedGroupProtocols.add(CONSUMER);
assertEquals(supportedGroupProtocols, clusterInstance.supportedGroupProtocols());
}
@ClusterTests({
@ClusterTest(types = {Type.KRAFT, Type.CO_KRAFT}, serverProperties = {
@ClusterConfigProperty(key = GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG, value = "classic"),
})
})
public void testNotSupportedNewGroupProtocols(ClusterInstance clusterInstance) {
assertEquals(Set.of(CLASSIC), clusterInstance.supportedGroupProtocols());
}
@ClusterTest(types = {Type.CO_KRAFT, Type.KRAFT}, brokers = 3)
public void testCreateTopic(ClusterInstance clusterInstance) throws Exception {
String topicName = "test";
int numPartition = 3;
short numReplicas = 3;
clusterInstance.createTopic(topicName, numPartition, numReplicas);
try (Admin admin = clusterInstance.admin()) {
Assertions.assertTrue(admin.listTopics().listings().get().stream().anyMatch(s -> s.name().equals(topicName)));
List<TopicPartitionInfo> partitions = admin.describeTopics(Set.of(topicName)).allTopicNames().get()
.get(topicName).partitions();
assertEquals(numPartition, partitions.size());
Assertions.assertTrue(partitions.stream().allMatch(partition -> partition.replicas().size() == numReplicas));
}
}
@ClusterTest(types = {Type.CO_KRAFT, Type.KRAFT}, brokers = 4)
public void testShutdownAndSyncMetadata(ClusterInstance clusterInstance) throws Exception {
String topicName = "test";
int numPartition = 3;
short numReplicas = 3;
clusterInstance.createTopic(topicName, numPartition, numReplicas);
clusterInstance.shutdownBroker(0);
clusterInstance.waitTopicCreation(topicName, numPartition);
}
@ClusterTest(types = {Type.CO_KRAFT, Type.KRAFT}, brokers = 4)
public void testClusterAliveBrokers(ClusterInstance clusterInstance) throws Exception {
clusterInstance.waitForReadyBrokers();
// Remove broker id 0
clusterInstance.shutdownBroker(0);
Assertions.assertFalse(clusterInstance.aliveBrokers().containsKey(0));
Assertions.assertTrue(clusterInstance.brokers().containsKey(0));
// add broker id 0 back
clusterInstance.startBroker(0);
Assertions.assertTrue(clusterInstance.aliveBrokers().containsKey(0));
Assertions.assertTrue(clusterInstance.brokers().containsKey(0));
}
@ClusterTest(
types = {Type.CO_KRAFT, Type.KRAFT},
brokers = 4,
serverProperties = {
@ClusterConfigProperty(key = "log.initial.task.delay.ms", value = "100"),
@ClusterConfigProperty(key = "log.segment.delete.delay.ms", value = "1000")
}
)
public void testVerifyTopicDeletion(ClusterInstance clusterInstance) throws Exception {
try (Admin admin = clusterInstance.admin()) {
String testTopic = "testTopic";
admin.createTopics(List.of(new NewTopic(testTopic, 1, (short) 1)));
clusterInstance.waitTopicCreation(testTopic, 1);
admin.deleteTopics(List.of(testTopic));
clusterInstance.waitTopicDeletion(testTopic);
Assertions.assertTrue(admin.listTopics().listings().get().stream().noneMatch(
topic -> topic.name().equals(testTopic)
));
}
}
@ClusterTest(types = {Type.CO_KRAFT, Type.KRAFT}, brokers = 3)
public void testCreateProducerAndConsumer(ClusterInstance cluster) throws InterruptedException {
String topic = "topic";
String key = "key";
String value = "value";
try (Admin adminClient = cluster.admin();
Producer<String, String> producer = cluster.producer(Map.of(
ACKS_CONFIG, "all",
KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName(),
VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()));
Consumer<String, String> consumer = cluster.consumer(Map.of(
KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName(),
VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()))
) {
adminClient.createTopics(Set.of(new NewTopic(topic, 1, (short) 1)));
assertNotNull(producer);
assertNotNull(consumer);
producer.send(new ProducerRecord<>(topic, key, value));
producer.flush();
consumer.subscribe(List.of(topic));
List<ConsumerRecord<String, String>> records = new ArrayList<>();
RaftClusterInvocationContext.waitForCondition(() -> {
consumer.poll(Duration.ofMillis(100)).forEach(records::add);
return records.size() == 1;
}, "Failed to receive message");
assertEquals(key, records.get(0).key());
assertEquals(value, records.get(0).value());
}
}
@ClusterTest(types = {Type.CO_KRAFT, Type.KRAFT}, serverProperties = {
@ClusterConfigProperty(key = GroupCoordinatorConfig.OFFSETS_TOPIC_PARTITIONS_CONFIG, value = "1"),
@ClusterConfigProperty(key = GroupCoordinatorConfig.OFFSETS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1")
})
public void testCreateDefaultProducerAndConsumer(ClusterInstance cluster) throws InterruptedException {
String topic = "topic";
byte[] key = "key".getBytes(StandardCharsets.UTF_8);
byte[] value = "value".getBytes(StandardCharsets.UTF_8);
try (Admin adminClient = cluster.admin();
Producer<byte[], byte[]> producer = cluster.producer();
Consumer<byte[], byte[]> consumer = cluster.consumer()
) {
adminClient.createTopics(Set.of(new NewTopic(topic, 1, (short) 1)));
assertNotNull(producer);
assertNotNull(consumer);
producer.send(new ProducerRecord<>(topic, key, value));
producer.flush();
consumer.subscribe(List.of(topic));
List<ConsumerRecord<byte[], byte[]>> records = new ArrayList<>();
RaftClusterInvocationContext.waitForCondition(() -> {
consumer.poll(Duration.ofMillis(100)).forEach(records::add);
return records.size() == 1;
}, "Failed to receive message");
assertArrayEquals(key, records.get(0).key());
assertArrayEquals(value, records.get(0).value());
}
}
@ClusterTest(types = {Type.CO_KRAFT, Type.KRAFT}, controllerListener = "FOO")
public void testControllerListenerName(ClusterInstance cluster) throws ExecutionException, InterruptedException {
assertEquals("FOO", cluster.controllerListenerName().value());
try (Admin admin = cluster.admin(Map.of(), true)) {
assertEquals(1, admin.describeMetadataQuorum().quorumInfo().get().nodes().size());
}
}
@ClusterTest(types = {Type.CO_KRAFT, Type.KRAFT}, brokers = 1)
public void testBrokerRestart(ClusterInstance cluster) throws ExecutionException, InterruptedException {
final String topicName = "topic";
try (Admin admin = cluster.admin();
Producer<String, String> producer = cluster.producer(Map.of(
ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName(),
ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()))) {
admin.createTopics(List.of(new NewTopic(topicName, 1, (short) 1))).all().get();
cluster.waitTopicCreation(topicName, 1);
cluster.brokers().values().forEach(broker -> {
broker.shutdown();
broker.awaitShutdown();
broker.startup();
});
RecordMetadata recordMetadata0 = producer.send(new ProducerRecord<>(topicName, 0, "key 0", "value 0")).get();
assertEquals(0, recordMetadata0.offset());
}
}
@ClusterTest(types = {Type.KRAFT})
public void testControllerRestart(ClusterInstance cluster) throws ExecutionException, InterruptedException {
try (Admin admin = cluster.admin()) {
ControllerServer controller = cluster.controllers().values().iterator().next();
controller.shutdown();
controller.awaitShutdown();
controller.startup();
assertEquals(1, admin.describeMetadataQuorum().quorumInfo().get().nodes().size());
}
}
@ClusterTest(
types = {Type.KRAFT, Type.CO_KRAFT},
brokerSecurityProtocol = SecurityProtocol.SASL_PLAINTEXT,
controllerSecurityProtocol = SecurityProtocol.SASL_PLAINTEXT,
serverProperties = {
@ClusterConfigProperty(key = GroupCoordinatorConfig.OFFSETS_TOPIC_PARTITIONS_CONFIG, value = "1"),
@ClusterConfigProperty(key = GroupCoordinatorConfig.OFFSETS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1")
}
)
public void testSaslPlaintext(ClusterInstance clusterInstance) throws CancellationException, ExecutionException, InterruptedException {
assertEquals(SecurityProtocol.SASL_PLAINTEXT, clusterInstance.config().brokerSecurityProtocol());
// default ClusterInstance#admin helper with admin credentials
try (Admin admin = clusterInstance.admin()) {
admin.describeAcls(AclBindingFilter.ANY).values().get();
}
String topic = "sasl-plaintext-topic";
clusterInstance.createTopic(topic, 1, (short) 1);
try (Producer<byte[], byte[]> producer = clusterInstance.producer()) {
producer.send(new ProducerRecord<>(topic, Utils.utf8("key"), Utils.utf8("value"))).get();
producer.flush();
}
try (Consumer<byte[], byte[]> consumer = clusterInstance.consumer()) {
consumer.subscribe(List.of(topic));
RaftClusterInvocationContext.waitForCondition(() -> {
ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(100));
return records.count() == 1;
}, "Failed to receive message");
}
// client with non-admin credentials
Map<String, Object> nonAdminConfig = Map.of(
SaslConfigs.SASL_JAAS_CONFIG,
String.format(
"org.apache.kafka.common.security.plain.PlainLoginModule required username=\"%s\" password=\"%s\";",
JaasUtils.KAFKA_PLAIN_USER1, JaasUtils.KAFKA_PLAIN_USER1_PASSWORD
)
);
try (Admin admin = clusterInstance.admin(nonAdminConfig)) {
ExecutionException exception = assertThrows(
ExecutionException.class,
() -> admin.describeAcls(AclBindingFilter.ANY).values().get()
);
assertInstanceOf(ClusterAuthorizationException.class, exception.getCause());
}
try (Producer<byte[], byte[]> producer = clusterInstance.producer(nonAdminConfig)) {
ExecutionException exception = assertThrows(
ExecutionException.class,
() -> producer.send(new ProducerRecord<>(topic, Utils.utf8("key"), Utils.utf8("value"))).get()
);
assertInstanceOf(TopicAuthorizationException.class, exception.getCause());
}
try (Consumer<byte[], byte[]> consumer = clusterInstance.consumer(nonAdminConfig)) {
consumer.subscribe(List.of(topic));
AtomicBoolean hasException = new AtomicBoolean(false);
RaftClusterInvocationContext.waitForCondition(() -> {
if (hasException.get()) {
return true;
}
try {
consumer.poll(Duration.ofMillis(100));
} catch (TopicAuthorizationException e) {
hasException.set(true);
}
return false;
}, "Failed to get exception");
}
// client with unknown credentials
Map<String, Object> unknownUserConfig = Map.of(
SaslConfigs.SASL_JAAS_CONFIG,
String.format(
"org.apache.kafka.common.security.plain.PlainLoginModule required username=\"%s\" password=\"%s\";",
"unknown", "unknown"
)
);
try (Admin admin = clusterInstance.admin(unknownUserConfig)) {
ExecutionException exception = assertThrows(
ExecutionException.class,
() -> admin.describeAcls(AclBindingFilter.ANY).values().get()
);
assertInstanceOf(SaslAuthenticationException.class, exception.getCause());
}
try (Producer<byte[], byte[]> producer = clusterInstance.producer(unknownUserConfig)) {
ExecutionException exception = assertThrows(
ExecutionException.class,
() -> producer.send(new ProducerRecord<>(topic, Utils.utf8("key"), Utils.utf8("value"))).get()
);
assertInstanceOf(SaslAuthenticationException.class, exception.getCause());
}
try (Consumer<byte[], byte[]> consumer = clusterInstance.consumer(unknownUserConfig)) {
consumer.subscribe(List.of(topic));
AtomicBoolean hasException = new AtomicBoolean(false);
RaftClusterInvocationContext.waitForCondition(() -> {
if (hasException.get()) {
return true;
}
try {
consumer.poll(Duration.ofMillis(100));
} catch (SaslAuthenticationException e) {
hasException.set(true);
}
return false;
}, "Failed to get exception");
}
}
@ClusterTest(
types = {Type.KRAFT, Type.CO_KRAFT},
brokerSecurityProtocol = SecurityProtocol.SASL_PLAINTEXT,
controllerSecurityProtocol = SecurityProtocol.SASL_PLAINTEXT,
serverProperties = {
@ClusterConfigProperty(key = GroupCoordinatorConfig.OFFSETS_TOPIC_PARTITIONS_CONFIG, value = "1"),
@ClusterConfigProperty(key = GroupCoordinatorConfig.OFFSETS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1")
}
)
public void testSaslPlaintextWithController(ClusterInstance clusterInstance) throws CancellationException, ExecutionException, InterruptedException {
// default ClusterInstance#admin helper with admin credentials
try (Admin admin = clusterInstance.admin(Map.of(), true)) {
admin.describeAcls(AclBindingFilter.ANY).values().get();
}
// client with non-admin credentials
Map<String, Object> nonAdminConfig = Map.of(
SaslConfigs.SASL_JAAS_CONFIG,
String.format(
"org.apache.kafka.common.security.plain.PlainLoginModule required username=\"%s\" password=\"%s\";",
JaasUtils.KAFKA_PLAIN_USER1, JaasUtils.KAFKA_PLAIN_USER1_PASSWORD
)
);
try (Admin admin = clusterInstance.admin(nonAdminConfig, true)) {
ExecutionException exception = assertThrows(
ExecutionException.class,
() -> admin.describeAcls(AclBindingFilter.ANY).values().get()
);
assertInstanceOf(ClusterAuthorizationException.class, exception.getCause());
}
// client with unknown credentials
Map<String, Object> unknownUserConfig = Map.of(
SaslConfigs.SASL_JAAS_CONFIG,
String.format(
"org.apache.kafka.common.security.plain.PlainLoginModule required username=\"%s\" password=\"%s\";",
"unknown", "unknown"
)
);
try (Admin admin = clusterInstance.admin(unknownUserConfig)) {
ExecutionException exception = assertThrows(
ExecutionException.class,
() -> admin.describeAcls(AclBindingFilter.ANY).values().get()
);
assertInstanceOf(SaslAuthenticationException.class, exception.getCause());
}
}
}
|
level
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProviderTests.java
|
{
"start": 23776,
"end": 24001
}
|
class ____ {
static final String BEAN_NAME = "defaultAndDevProfileAnnotatedComponent";
}
@DefaultProfile @DevProfile
@Component(MetaProfileAnnotatedComponent.BEAN_NAME)
private static
|
DefaultAndDevProfileAnnotatedComponent
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/action/profile/ProfileHasPrivilegesResponseTests.java
|
{
"start": 1319,
"end": 6410
}
|
class ____ extends AbstractWireSerializingTestCase<ProfileHasPrivilegesResponse> {
@Override
protected Writeable.Reader<ProfileHasPrivilegesResponse> instanceReader() {
return ProfileHasPrivilegesResponse::new;
}
@Override
protected ProfileHasPrivilegesResponse createTestInstance() {
return new ProfileHasPrivilegesResponse(
randomUnique(() -> randomAlphaOfLengthBetween(0, 5), randomIntBetween(0, 5)),
randomErrors()
);
}
@Override
protected ProfileHasPrivilegesResponse mutateInstance(ProfileHasPrivilegesResponse instance) {
return randomFrom(
new ProfileHasPrivilegesResponse(newMutatedSet(instance.hasPrivilegeUids()), instance.errors()),
new ProfileHasPrivilegesResponse(instance.hasPrivilegeUids(), randomValueOtherThan(instance.errors(), this::randomErrors)),
new ProfileHasPrivilegesResponse(
newMutatedSet(instance.hasPrivilegeUids()),
randomValueOtherThan(instance.errors(), this::randomErrors)
)
);
}
public void testToXContent() throws IOException {
final ProfileHasPrivilegesResponse response = createTestInstance();
XContentBuilder builder = XContentFactory.jsonBuilder();
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
final Map<String, Object> responseMap = XContentHelper.convertToMap(BytesReference.bytes(builder), false, builder.contentType())
.v2();
if (response.errors().isEmpty()) {
assertThat(responseMap, equalTo(Map.of("has_privilege_uids", new ArrayList<>(response.hasPrivilegeUids()))));
} else {
assertThat(responseMap, hasEntry("has_privilege_uids", List.copyOf(response.hasPrivilegeUids())));
@SuppressWarnings("unchecked")
final Map<String, Object> errorsMap = (Map<String, Object>) responseMap.get("errors");
assertThat(errorsMap.get("count"), equalTo(response.errors().size()));
@SuppressWarnings("unchecked")
final Map<String, Object> detailsMap = (Map<String, Object>) errorsMap.get("details");
assertThat(detailsMap.keySet(), equalTo(response.errors().keySet()));
detailsMap.forEach((k, v) -> {
final String errorString;
final Exception e = response.errors().get(k);
if (e instanceof IllegalArgumentException illegalArgumentException) {
errorString = Strings.format("""
{
"type": "illegal_argument_exception",
"reason": "%s"
}""", illegalArgumentException.getMessage());
} else if (e instanceof ResourceNotFoundException resourceNotFoundException) {
errorString = Strings.format("""
{
"type": "resource_not_found_exception",
"reason": "%s"
}""", resourceNotFoundException.getMessage());
} else if (e instanceof ElasticsearchException elasticsearchException) {
errorString = Strings.format("""
{
"type": "exception",
"reason": "%s",
"caused_by": {
"type": "illegal_argument_exception",
"reason": "%s"
}
}""", elasticsearchException.getMessage(), elasticsearchException.getCause().getMessage());
} else {
throw new IllegalArgumentException("unknown exception type: " + e);
}
assertThat(v, equalTo(XContentHelper.convertToMap(JsonXContent.jsonXContent, errorString, false)));
});
}
}
private Set<String> newMutatedSet(Set<String> in) {
Set<String> mutated = new HashSet<>(in);
if (randomBoolean()) {
mutated = new HashSet<>(randomSubsetOf(mutated));
}
if (randomBoolean()) {
mutated.addAll(randomList(5, () -> randomAlphaOfLengthBetween(0, 5)));
}
if (mutated.equals(in)) {
// try again
return newMutatedSet(in);
}
return mutated;
}
private Map<String, Exception> randomErrors() {
final Map<String, Exception> errors = new TreeMap<>();
final Supplier<Exception> randomExceptionSupplier = () -> randomFrom(
new IllegalArgumentException(randomAlphaOfLengthBetween(0, 18)),
new ResourceNotFoundException(randomAlphaOfLengthBetween(0, 18)),
new ElasticsearchException(randomAlphaOfLengthBetween(0, 18), new IllegalArgumentException(randomAlphaOfLengthBetween(0, 18)))
);
IntStream.range(0, randomIntBetween(0, 3)).forEach(i -> errors.put(randomAlphaOfLength(20) + i, randomExceptionSupplier.get()));
return errors;
}
}
|
ProfileHasPrivilegesResponseTests
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/datatypes/DefaultDataType.java
|
{
"start": 948,
"end": 1212
}
|
class ____ implements DataType<String> {
private String value;
public DefaultDataType(String value) {
this.value = value;
}
/**
* Get the value of the attribute.
*/
@Override
public String getValue() {
return value;
}
}
|
DefaultDataType
|
java
|
apache__camel
|
components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAllPropertiesTest.java
|
{
"start": 1332,
"end": 3166
}
|
class ____ extends ExchangeTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(MDCSelectedPropertiesTest.class);
@Override
protected CamelContext createCamelContext() throws Exception {
MDCService mdcSvc = new MDCService();
mdcSvc.setCustomProperties("*");
CamelContext context = super.createCamelContext();
CamelContextAware.trySetCamelContext(mdcSvc, context);
mdcSvc.init(context);
return context;
}
@Test
void testRouteSingleRequest() throws IOException {
template.request("direct:start", null);
// We should get no MDC after the route has been executed
assertEquals(0, MDC.getCopyOfContextMap().size());
}
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.routeId("start")
.log("A message")
.setProperty("prop1", simple("Property1"))
.setProperty("prop2", simple("Property2"))
.process(exchange -> {
LOG.info("A process");
assertNotNull(MDC.get(MDCService.MDC_MESSAGE_ID));
assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
assertEquals("Property1", MDC.get("prop1"));
assertEquals("Property2", MDC.get("prop2"));
})
.to("log:info");
}
};
}
}
|
MDCAllPropertiesTest
|
java
|
spring-projects__spring-framework
|
spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/SockJsServiceRegistration.java
|
{
"start": 1403,
"end": 1640
}
|
class ____ configuring SockJS fallback options for use with an
* {@link org.springframework.web.socket.config.annotation.EnableWebSocket} and
* {@link WebSocketConfigurer} setup.
*
* @author Rossen Stoyanchev
* @since 4.0
*/
public
|
for
|
java
|
quarkusio__quarkus
|
extensions/oidc-common/runtime/src/main/java/io/quarkus/oidc/common/runtime/config/OidcClientCommonConfig.java
|
{
"start": 1826,
"end": 3031
}
|
interface ____ {
/**
* The client secret used by the `client_secret_basic` authentication method.
* Must be set unless a secret is set in {@link #clientSecret} or {@link #jwt} client authentication is required.
* You can use `client-secret.value` instead, but both properties are mutually exclusive.
*/
Optional<String> secret();
/**
* The client secret used by the `client_secret_basic` (default), `client_secret_post`, or `client_secret_jwt`
* authentication methods.
* Note that a `secret.value` property can be used instead to support the `client_secret_basic` method
* but both properties are mutually exclusive.
*/
Secret clientSecret();
/**
* Client JSON Web Token (JWT) authentication methods
*/
Jwt jwt();
/**
* Supports the client authentication methods that involve sending a client secret.
*
* @see <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication">https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication</a>
*/
|
Credentials
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/protocolPB/RouterClientProtocolTranslatorPB.java
|
{
"start": 15704,
"end": 77691
}
|
class ____ extends ClientNamenodeProtocolTranslatorPB {
private final ClientNamenodeProtocolPB rpcProxy;
public RouterClientProtocolTranslatorPB(ClientNamenodeProtocolPB proxy) {
super(proxy);
rpcProxy = proxy;
}
@Override
public void close() {
super.close();
}
@Override
public LocatedBlocks getBlockLocations(String src, long offset, long length)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getBlockLocations(src, offset, length);
}
GetBlockLocationsRequestProto req = GetBlockLocationsRequestProto
.newBuilder()
.setSrc(src)
.setOffset(offset)
.setLength(length)
.build();
return asyncIpcClient(() -> rpcProxy.getBlockLocations(null, req),
res -> res.hasLocations() ? PBHelperClient.convert(res.getLocations()) : null,
LocatedBlocks.class);
}
@Override
public FsServerDefaults getServerDefaults() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getServerDefaults();
}
GetServerDefaultsRequestProto req = VOID_GET_SERVER_DEFAULT_REQUEST;
return asyncIpcClient(() -> rpcProxy.getServerDefaults(null, req),
res -> PBHelperClient.convert(res.getServerDefaults()),
FsServerDefaults.class);
}
@Override
public HdfsFileStatus create(
String src, FsPermission masked,
String clientName, EnumSetWritable<CreateFlag> flag,
boolean createParent, short replication, long blockSize,
CryptoProtocolVersion[] supportedVersions, String ecPolicyName,
String storagePolicy) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.create(
src, masked, clientName, flag, createParent, replication,
blockSize, supportedVersions, ecPolicyName, storagePolicy);
}
CreateRequestProto.Builder builder = CreateRequestProto.newBuilder()
.setSrc(src)
.setMasked(PBHelperClient.convert(masked))
.setClientName(clientName)
.setCreateFlag(PBHelperClient.convertCreateFlag(flag))
.setCreateParent(createParent)
.setReplication(replication)
.setBlockSize(blockSize);
if (ecPolicyName != null) {
builder.setEcPolicyName(ecPolicyName);
}
if (storagePolicy != null) {
builder.setStoragePolicy(storagePolicy);
}
FsPermission unmasked = masked.getUnmasked();
if (unmasked != null) {
builder.setUnmasked(PBHelperClient.convert(unmasked));
}
builder.addAllCryptoProtocolVersion(
PBHelperClient.convert(supportedVersions));
CreateRequestProto req = builder.build();
return asyncIpcClient(() -> rpcProxy.create(null, req),
res -> res.hasFs() ? PBHelperClient.convert(res.getFs()) : null,
HdfsFileStatus.class);
}
@Override
public boolean truncate(String src, long newLength, String clientName)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.truncate(src, newLength, clientName);
}
TruncateRequestProto req = TruncateRequestProto.newBuilder()
.setSrc(src)
.setNewLength(newLength)
.setClientName(clientName)
.build();
return asyncIpcClient(() -> rpcProxy.truncate(null, req),
res -> res.getResult(), Boolean.class);
}
@Override
public LastBlockWithStatus append(String src, String clientName,
EnumSetWritable<CreateFlag> flag) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.append(src, clientName, flag);
}
AppendRequestProto req = AppendRequestProto.newBuilder().setSrc(src)
.setClientName(clientName).setFlag(
PBHelperClient.convertCreateFlag(flag))
.build();
return asyncIpcClient(() -> rpcProxy.append(null, req),
res -> {
LocatedBlock lastBlock = res.hasBlock() ? PBHelperClient
.convertLocatedBlockProto(res.getBlock()) : null;
HdfsFileStatus stat = (res.hasStat()) ?
PBHelperClient.convert(res.getStat()) : null;
return new LastBlockWithStatus(lastBlock, stat);
}, LastBlockWithStatus.class);
}
@Override
public boolean setReplication(String src, short replication)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.setReplication(src, replication);
}
SetReplicationRequestProto req = SetReplicationRequestProto.newBuilder()
.setSrc(src)
.setReplication(replication)
.build();
return asyncIpcClient(() -> rpcProxy.setReplication(null, req),
res -> res.getResult(), Boolean.class);
}
@Override
public void setPermission(String src, FsPermission permission)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.setPermission(src, permission);
return;
}
SetPermissionRequestProto req = SetPermissionRequestProto.newBuilder()
.setSrc(src)
.setPermission(PBHelperClient.convert(permission))
.build();
asyncIpcClient(() -> rpcProxy.setPermission(null, req),
res -> null, null);
}
@Override
public void setOwner(String src, String username, String groupname)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.setOwner(src, username, groupname);
return;
}
SetOwnerRequestProto.Builder req = SetOwnerRequestProto.newBuilder()
.setSrc(src);
if (username != null) {
req.setUsername(username);
}
if (groupname != null) {
req.setGroupname(groupname);
}
asyncIpcClient(() -> rpcProxy.setOwner(null, req.build()),
res -> null, null);
}
@Override
public void abandonBlock(ExtendedBlock b, long fileId, String src,
String holder) throws IOException {
if (!Client.isAsynchronousMode()) {
super.abandonBlock(b, fileId, src, holder);
return;
}
AbandonBlockRequestProto req = AbandonBlockRequestProto.newBuilder()
.setB(PBHelperClient.convert(b)).setSrc(src).setHolder(holder)
.setFileId(fileId).build();
asyncIpcClient(() -> rpcProxy.abandonBlock(null, req),
res -> null, null);
}
@Override
public LocatedBlock addBlock(
String src, String clientName,
ExtendedBlock previous, DatanodeInfo[] excludeNodes, long fileId,
String[] favoredNodes, EnumSet<AddBlockFlag> addBlockFlags)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.addBlock(src, clientName, previous, excludeNodes,
fileId, favoredNodes, addBlockFlags);
}
AddBlockRequestProto.Builder req = AddBlockRequestProto.newBuilder()
.setSrc(src).setClientName(clientName).setFileId(fileId);
if (previous != null) {
req.setPrevious(PBHelperClient.convert(previous));
}
if (excludeNodes != null) {
req.addAllExcludeNodes(PBHelperClient.convert(excludeNodes));
}
if (favoredNodes != null) {
req.addAllFavoredNodes(Arrays.asList(favoredNodes));
}
if (addBlockFlags != null) {
req.addAllFlags(PBHelperClient.convertAddBlockFlags(
addBlockFlags));
}
return asyncIpcClient(() -> rpcProxy.addBlock(null, req.build()),
res -> PBHelperClient.convertLocatedBlockProto(res.getBlock()),
LocatedBlock.class);
}
@Override
public LocatedBlock getAdditionalDatanode(
String src, long fileId,
ExtendedBlock blk, DatanodeInfo[] existings, String[] existingStorageIDs,
DatanodeInfo[] excludes, int numAdditionalNodes, String clientName)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getAdditionalDatanode(src, fileId, blk, existings,
existingStorageIDs, excludes, numAdditionalNodes, clientName);
}
GetAdditionalDatanodeRequestProto req = GetAdditionalDatanodeRequestProto
.newBuilder()
.setSrc(src)
.setFileId(fileId)
.setBlk(PBHelperClient.convert(blk))
.addAllExistings(PBHelperClient.convert(existings))
.addAllExistingStorageUuids(Arrays.asList(existingStorageIDs))
.addAllExcludes(PBHelperClient.convert(excludes))
.setNumAdditionalNodes(numAdditionalNodes)
.setClientName(clientName)
.build();
return asyncIpcClient(() -> rpcProxy.getAdditionalDatanode(null, req),
res -> PBHelperClient.convertLocatedBlockProto(res.getBlock()),
LocatedBlock.class);
}
@Override
public boolean complete(String src, String clientName,
ExtendedBlock last, long fileId) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.complete(src, clientName, last, fileId);
}
CompleteRequestProto.Builder req = CompleteRequestProto.newBuilder()
.setSrc(src)
.setClientName(clientName)
.setFileId(fileId);
if (last != null) {
req.setLast(PBHelperClient.convert(last));
}
return asyncIpcClient(() -> rpcProxy.complete(null, req.build()),
res -> res.getResult(),
Boolean.class);
}
@Override
public void reportBadBlocks(LocatedBlock[] blocks) throws IOException {
if (!Client.isAsynchronousMode()) {
super.reportBadBlocks(blocks);
return;
}
ReportBadBlocksRequestProto req = ReportBadBlocksRequestProto.newBuilder()
.addAllBlocks(Arrays.asList(
PBHelperClient.convertLocatedBlocks(blocks)))
.build();
asyncIpcClient(() -> rpcProxy.reportBadBlocks(null, req),
res -> null, Void.class);
}
@Override
public boolean rename(String src, String dst) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.rename(src, dst);
}
RenameRequestProto req = RenameRequestProto.newBuilder()
.setSrc(src)
.setDst(dst).build();
return asyncIpcClient(() -> rpcProxy.rename(null, req),
res -> res.getResult(),
Boolean.class);
}
@Override
public void rename2(String src, String dst, Rename... options)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.rename2(src, dst, options);
return;
}
boolean overwrite = false;
boolean toTrash = false;
if (options != null) {
for (Rename option : options) {
if (option == Rename.OVERWRITE) {
overwrite = true;
}
if (option == Rename.TO_TRASH) {
toTrash = true;
}
}
}
Rename2RequestProto req = Rename2RequestProto.newBuilder().
setSrc(src).
setDst(dst).
setOverwriteDest(overwrite).
setMoveToTrash(toTrash).
build();
asyncIpcClient(() -> rpcProxy.rename2(null, req),
res -> null, Void.class);
}
@Override
public void concat(String trg, String[] srcs) throws IOException {
if (!Client.isAsynchronousMode()) {
super.concat(trg, srcs);
return;
}
ConcatRequestProto req = ConcatRequestProto.newBuilder().
setTrg(trg).
addAllSrcs(Arrays.asList(srcs)).build();
asyncIpcClient(() -> rpcProxy.concat(null, req),
res -> null, Void.class);
}
@Override
public boolean delete(String src, boolean recursive) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.delete(src, recursive);
}
DeleteRequestProto req = DeleteRequestProto.newBuilder().setSrc(src)
.setRecursive(recursive).build();
return asyncIpcClient(() -> rpcProxy.delete(null, req),
res -> res.getResult(), Boolean.class);
}
@Override
public boolean mkdirs(String src, FsPermission masked, boolean createParent)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.mkdirs(src, masked, createParent);
}
MkdirsRequestProto.Builder builder = MkdirsRequestProto.newBuilder()
.setSrc(src)
.setMasked(PBHelperClient.convert(masked))
.setCreateParent(createParent);
FsPermission unmasked = masked.getUnmasked();
if (unmasked != null) {
builder.setUnmasked(PBHelperClient.convert(unmasked));
}
MkdirsRequestProto req = builder.build();
return asyncIpcClient(() -> rpcProxy.mkdirs(null, req),
res -> res.getResult(), Boolean.class);
}
@Override
public DirectoryListing getListing(
String src, byte[] startAfter, boolean needLocation) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getListing(src, startAfter, needLocation);
}
GetListingRequestProto req = GetListingRequestProto.newBuilder()
.setSrc(src)
.setStartAfter(ByteString.copyFrom(startAfter))
.setNeedLocation(needLocation).build();
return asyncIpcClient(() -> rpcProxy.getListing(null, req),
res -> {
if (res.hasDirList()) {
return PBHelperClient.convert(res.getDirList());
}
return null;
}, DirectoryListing.class);
}
@Override
public BatchedDirectoryListing getBatchedListing(
String[] srcs, byte[] startAfter, boolean needLocation)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getBatchedListing(srcs, startAfter, needLocation);
}
GetBatchedListingRequestProto req = GetBatchedListingRequestProto
.newBuilder()
.addAllPaths(Arrays.asList(srcs))
.setStartAfter(ByteString.copyFrom(startAfter))
.setNeedLocation(needLocation).build();
return asyncIpcClient(() -> rpcProxy.getBatchedListing(null, req),
res -> {
if (res.getListingsCount() > 0) {
HdfsPartialListing[] listingArray =
new HdfsPartialListing[res.getListingsCount()];
int listingIdx = 0;
for (BatchedDirectoryListingProto proto : res.getListingsList()) {
HdfsPartialListing listing;
if (proto.hasException()) {
HdfsProtos.RemoteExceptionProto reProto = proto.getException();
RemoteException ex = new RemoteException(
reProto.getClassName(), reProto.getMessage());
listing = new HdfsPartialListing(proto.getParentIdx(), ex);
} else {
List<HdfsFileStatus> statuses =
PBHelperClient.convertHdfsFileStatus(
proto.getPartialListingList());
listing = new HdfsPartialListing(proto.getParentIdx(), statuses);
}
listingArray[listingIdx++] = listing;
}
BatchedDirectoryListing batchedListing =
new BatchedDirectoryListing(listingArray, res.getHasMore(),
res.getStartAfter().toByteArray());
return batchedListing;
}
return null;
}, BatchedDirectoryListing.class);
}
@Override
public void renewLease(String clientName, List<String> namespaces)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.renewLease(clientName, namespaces);
return;
}
RenewLeaseRequestProto.Builder builder = RenewLeaseRequestProto
.newBuilder().setClientName(clientName);
if (namespaces != null && !namespaces.isEmpty()) {
builder.addAllNamespaces(namespaces);
}
asyncIpcClient(() -> rpcProxy.renewLease(null, builder.build()),
res -> null, Void.class);
}
@Override
public boolean recoverLease(String src, String clientName)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.recoverLease(src, clientName);
}
RecoverLeaseRequestProto req = RecoverLeaseRequestProto.newBuilder()
.setSrc(src)
.setClientName(clientName).build();
return asyncIpcClient(() -> rpcProxy.recoverLease(null, req),
res -> res.getResult(), Boolean.class);
}
@Override
public long[] getStats() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getStats();
}
return asyncIpcClient(() -> rpcProxy.getFsStats(null, VOID_GET_FSSTATUS_REQUEST),
res -> PBHelperClient.convert(res), long[].class);
}
@Override
public ReplicatedBlockStats getReplicatedBlockStats() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getReplicatedBlockStats();
}
return asyncIpcClient(() -> rpcProxy.getFsReplicatedBlockStats(null,
VOID_GET_FS_REPLICATED_BLOCK_STATS_REQUEST),
res -> PBHelperClient.convert(res), ReplicatedBlockStats.class);
}
@Override
public ECBlockGroupStats getECBlockGroupStats() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getECBlockGroupStats();
}
return asyncIpcClient(() -> rpcProxy.getFsECBlockGroupStats(null,
VOID_GET_FS_ECBLOCKGROUP_STATS_REQUEST),
res -> PBHelperClient.convert(res), ECBlockGroupStats.class);
}
@Override
public DatanodeInfo[] getDatanodeReport(DatanodeReportType type)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getDatanodeReport(type);
}
GetDatanodeReportRequestProto req = GetDatanodeReportRequestProto
.newBuilder()
.setType(PBHelperClient.convert(type)).build();
return asyncIpcClient(() -> rpcProxy.getDatanodeReport(null, req),
res -> PBHelperClient.convert(res.getDiList()), DatanodeInfo[].class);
}
@Override
public DatanodeStorageReport[] getDatanodeStorageReport(
DatanodeReportType type) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getDatanodeStorageReport(type);
}
final GetDatanodeStorageReportRequestProto req
= GetDatanodeStorageReportRequestProto.newBuilder()
.setType(PBHelperClient.convert(type)).build();
return asyncIpcClient(() -> rpcProxy.getDatanodeStorageReport(null, req),
res -> PBHelperClient.convertDatanodeStorageReports(
res.getDatanodeStorageReportsList()), DatanodeStorageReport[].class);
}
@Override
public long getPreferredBlockSize(String filename) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getPreferredBlockSize(filename);
}
GetPreferredBlockSizeRequestProto req = GetPreferredBlockSizeRequestProto
.newBuilder()
.setFilename(filename)
.build();
return asyncIpcClient(() -> rpcProxy.getPreferredBlockSize(null, req),
res -> res.getBsize(), Long.class);
}
@Override
public boolean setSafeMode(SafeModeAction action, boolean isChecked)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.setSafeMode(action, isChecked);
}
SetSafeModeRequestProto req = SetSafeModeRequestProto.newBuilder()
.setAction(PBHelperClient.convert(action))
.setChecked(isChecked).build();
return asyncIpcClient(() -> rpcProxy.setSafeMode(null, req),
res -> res.getResult(), Boolean.class);
}
@Override
public boolean saveNamespace(long timeWindow, long txGap) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.saveNamespace(timeWindow, txGap);
}
SaveNamespaceRequestProto req = SaveNamespaceRequestProto.newBuilder()
.setTimeWindow(timeWindow).setTxGap(txGap).build();
return asyncIpcClient(() -> rpcProxy.saveNamespace(null, req),
res -> res.getSaved(), Boolean.class);
}
@Override
public long rollEdits() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.rollEdits();
}
return asyncIpcClient(() -> rpcProxy.rollEdits(null, VOID_ROLLEDITS_REQUEST),
res -> res.getNewSegmentTxId(), Long.class);
}
@Override
public boolean restoreFailedStorage(String arg) throws IOException{
if (!Client.isAsynchronousMode()) {
return super.restoreFailedStorage(arg);
}
RestoreFailedStorageRequestProto req = RestoreFailedStorageRequestProto
.newBuilder()
.setArg(arg).build();
return asyncIpcClient(() -> rpcProxy.restoreFailedStorage(null, req),
res -> res.getResult(), Boolean.class);
}
@Override
public void refreshNodes() throws IOException {
if (!Client.isAsynchronousMode()) {
super.refreshNodes();
return;
}
asyncIpcClient(() -> rpcProxy.refreshNodes(null, VOID_REFRESH_NODES_REQUEST),
res -> null, Void.class);
}
@Override
public void finalizeUpgrade() throws IOException {
if (!Client.isAsynchronousMode()) {
super.finalizeUpgrade();
return;
}
asyncIpcClient(() -> rpcProxy.finalizeUpgrade(null, VOID_FINALIZE_UPGRADE_REQUEST),
res -> null, Void.class);
}
@Override
public boolean upgradeStatus() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.upgradeStatus();
}
return asyncIpcClient(() -> rpcProxy.upgradeStatus(null, VOID_UPGRADE_STATUS_REQUEST),
res -> res.getUpgradeFinalized(), Boolean.class);
}
@Override
public RollingUpgradeInfo rollingUpgrade(RollingUpgradeAction action)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.rollingUpgrade(action);
}
final RollingUpgradeRequestProto r = RollingUpgradeRequestProto.newBuilder()
.setAction(PBHelperClient.convert(action)).build();
return asyncIpcClient(() -> rpcProxy.rollingUpgrade(null, r),
res -> PBHelperClient.convert(res.getRollingUpgradeInfo()),
RollingUpgradeInfo.class);
}
@Override
public CorruptFileBlocks listCorruptFileBlocks(String path, String cookie)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.listCorruptFileBlocks(path, cookie);
}
ListCorruptFileBlocksRequestProto.Builder req =
ListCorruptFileBlocksRequestProto.newBuilder().setPath(path);
if (cookie != null) {
req.setCookie(cookie);
}
return asyncIpcClient(() -> rpcProxy.listCorruptFileBlocks(null, req.build()),
res ->PBHelperClient.convert(res.getCorrupt()), CorruptFileBlocks.class);
}
@Override
public void metaSave(String filename) throws IOException {
if (!Client.isAsynchronousMode()) {
super.metaSave(filename);
return;
}
MetaSaveRequestProto req = MetaSaveRequestProto.newBuilder()
.setFilename(filename).build();
asyncIpcClient(() -> rpcProxy.metaSave(null, req),
res -> null, Void.class);
}
@Override
public HdfsFileStatus getFileInfo(String src) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getFileInfo(src);
}
GetFileInfoRequestProto req = GetFileInfoRequestProto.newBuilder()
.setSrc(src)
.build();
return asyncIpcClient(() -> rpcProxy.getFileInfo(null, req),
res -> res.hasFs() ? PBHelperClient.convert(res.getFs()) : null,
HdfsFileStatus.class);
}
@Override
public HdfsLocatedFileStatus getLocatedFileInfo(
String src, boolean needBlockToken) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getLocatedFileInfo(src, needBlockToken);
}
GetLocatedFileInfoRequestProto req =
GetLocatedFileInfoRequestProto.newBuilder()
.setSrc(src)
.setNeedBlockToken(needBlockToken)
.build();
return asyncIpcClient(() -> rpcProxy.getLocatedFileInfo(null, req),
res -> (HdfsLocatedFileStatus) (res.hasFs() ? PBHelperClient.convert(res.getFs()) : null),
HdfsLocatedFileStatus.class);
}
@Override
public HdfsFileStatus getFileLinkInfo(String src) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getFileLinkInfo(src);
}
GetFileLinkInfoRequestProto req = GetFileLinkInfoRequestProto.newBuilder()
.setSrc(src).build();
return asyncIpcClient(() -> rpcProxy.getFileLinkInfo(null, req),
res -> res.hasFs() ? PBHelperClient.convert(res.getFs()) : null,
HdfsFileStatus.class);
}
@Override
public ContentSummary getContentSummary(String path) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getContentSummary(path);
}
GetContentSummaryRequestProto req = GetContentSummaryRequestProto
.newBuilder()
.setPath(path)
.build();
return asyncIpcClient(() -> rpcProxy.getContentSummary(null, req),
res -> PBHelperClient.convert(res.getSummary()), ContentSummary.class);
}
@Override
public void setQuota(
String path, long namespaceQuota, long storagespaceQuota,
StorageType type) throws IOException {
if (!Client.isAsynchronousMode()) {
super.setQuota(path, namespaceQuota, storagespaceQuota, type);
return;
}
final SetQuotaRequestProto.Builder builder
= SetQuotaRequestProto.newBuilder()
.setPath(path)
.setNamespaceQuota(namespaceQuota)
.setStoragespaceQuota(storagespaceQuota);
if (type != null) {
builder.setStorageType(PBHelperClient.convertStorageType(type));
}
final SetQuotaRequestProto req = builder.build();
asyncIpcClient(() -> rpcProxy.setQuota(null, req),
res -> null, Void.class);
}
@Override
public void fsync(
String src, long fileId, String client, long lastBlockLength) throws IOException {
if (!Client.isAsynchronousMode()) {
super.fsync(src, fileId, client, lastBlockLength);
return;
}
FsyncRequestProto req = FsyncRequestProto.newBuilder().setSrc(src)
.setClient(client).setLastBlockLength(lastBlockLength)
.setFileId(fileId).build();
asyncIpcClient(() -> rpcProxy.fsync(null, req),
res -> null, Void.class);
}
@Override
public void setTimes(String src, long mtime, long atime) throws IOException {
if (!Client.isAsynchronousMode()) {
super.setTimes(src, mtime, atime);
return;
}
SetTimesRequestProto req = SetTimesRequestProto.newBuilder()
.setSrc(src)
.setMtime(mtime)
.setAtime(atime)
.build();
asyncIpcClient(() -> rpcProxy.setTimes(null, req),
res -> null, Void.class);
}
@Override
public void createSymlink(
String target, String link, FsPermission dirPerm,
boolean createParent) throws IOException {
if (!Client.isAsynchronousMode()) {
super.createSymlink(target, link, dirPerm, createParent);
return;
}
CreateSymlinkRequestProto req = CreateSymlinkRequestProto.newBuilder()
.setTarget(target)
.setLink(link)
.setDirPerm(PBHelperClient.convert(dirPerm))
.setCreateParent(createParent)
.build();
asyncIpcClient(() -> rpcProxy.createSymlink(null, req),
res -> null, Void.class);
}
@Override
public String getLinkTarget(String path) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getLinkTarget(path);
}
GetLinkTargetRequestProto req = GetLinkTargetRequestProto.newBuilder()
.setPath(path).build();
return asyncIpcClient(() -> rpcProxy.getLinkTarget(null, req),
res -> res.hasTargetPath() ? res.getTargetPath() : null,
String.class);
}
@Override
public LocatedBlock updateBlockForPipeline(
ExtendedBlock block, String clientName) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.updateBlockForPipeline(block, clientName);
}
UpdateBlockForPipelineRequestProto req = UpdateBlockForPipelineRequestProto
.newBuilder()
.setBlock(PBHelperClient.convert(block))
.setClientName(clientName)
.build();
return asyncIpcClient(() -> rpcProxy.updateBlockForPipeline(null, req),
res -> PBHelperClient.convertLocatedBlockProto(res.getBlock()),
LocatedBlock.class);
}
@Override
public void updatePipeline(
String clientName, ExtendedBlock oldBlock, ExtendedBlock newBlock,
DatanodeID[] newNodes, String[] storageIDs) throws IOException {
if (!Client.isAsynchronousMode()) {
super.updatePipeline(clientName, oldBlock, newBlock, newNodes, storageIDs);
return;
}
UpdatePipelineRequestProto req = UpdatePipelineRequestProto.newBuilder()
.setClientName(clientName)
.setOldBlock(PBHelperClient.convert(oldBlock))
.setNewBlock(PBHelperClient.convert(newBlock))
.addAllNewNodes(Arrays.asList(PBHelperClient.convert(newNodes)))
.addAllStorageIDs(storageIDs == null ? null : Arrays.asList(storageIDs))
.build();
asyncIpcClient(() -> rpcProxy.updatePipeline(null, req),
res -> null, Void.class);
}
@Override
public Token<DelegationTokenIdentifier> getDelegationToken(
Text renewer) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getDelegationToken(renewer);
}
GetDelegationTokenRequestProto req = GetDelegationTokenRequestProto
.newBuilder()
.setRenewer(renewer == null ? "" : renewer.toString())
.build();
return asyncIpcClient(() -> rpcProxy.getDelegationToken(null, req),
res -> res.hasToken() ?
PBHelperClient.convertDelegationToken(res.getToken()) : null, Token.class);
}
@Override
public long renewDelegationToken(
Token<DelegationTokenIdentifier> token) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.renewDelegationToken(token);
}
RenewDelegationTokenRequestProto req =
RenewDelegationTokenRequestProto.newBuilder().
setToken(PBHelperClient.convert(token)).
build();
return asyncIpcClient(() -> rpcProxy.renewDelegationToken(null, req),
res -> res.getNewExpiryTime(), Long.class);
}
@Override
public void cancelDelegationToken(
Token<DelegationTokenIdentifier> token) throws IOException {
if (!Client.isAsynchronousMode()) {
super.cancelDelegationToken(token);
return;
}
CancelDelegationTokenRequestProto req = CancelDelegationTokenRequestProto
.newBuilder()
.setToken(PBHelperClient.convert(token))
.build();
asyncIpcClient(() -> rpcProxy.cancelDelegationToken(null, req),
res -> null, Void.class);
}
@Override
public void setBalancerBandwidth(long bandwidth) throws IOException {
if (!Client.isAsynchronousMode()) {
super.setBalancerBandwidth(bandwidth);
return;
}
SetBalancerBandwidthRequestProto req =
SetBalancerBandwidthRequestProto.newBuilder()
.setBandwidth(bandwidth)
.build();
asyncIpcClient(() -> rpcProxy.setBalancerBandwidth(null, req),
res -> null, Void.class);
}
@Override
public DataEncryptionKey getDataEncryptionKey() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getDataEncryptionKey();
}
return asyncIpcClient(() -> rpcProxy.getDataEncryptionKey(null,
VOID_GET_DATA_ENCRYPTIONKEY_REQUEST),
res -> res.hasDataEncryptionKey() ?
PBHelperClient.convert(res.getDataEncryptionKey()) : null,
DataEncryptionKey.class);
}
@Override
public boolean isFileClosed(String src) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.isFileClosed(src);
}
IsFileClosedRequestProto req = IsFileClosedRequestProto.newBuilder()
.setSrc(src).build();
return asyncIpcClient(() -> rpcProxy.isFileClosed(null, req),
res -> res.getResult(), Boolean.class);
}
@Override
public String createSnapshot(
String snapshotRoot, String snapshotName) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.createSnapshot(snapshotRoot, snapshotName);
}
final CreateSnapshotRequestProto.Builder builder
= CreateSnapshotRequestProto.newBuilder().setSnapshotRoot(snapshotRoot);
if (snapshotName != null) {
builder.setSnapshotName(snapshotName);
}
final CreateSnapshotRequestProto req = builder.build();
return asyncIpcClient(() -> rpcProxy.createSnapshot(null, req),
res -> res.getSnapshotPath(), String.class);
}
@Override
public void deleteSnapshot(String snapshotRoot, String snapshotName)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.deleteSnapshot(snapshotRoot, snapshotName);
return;
}
DeleteSnapshotRequestProto req = DeleteSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).setSnapshotName(snapshotName).build();
asyncIpcClient(() -> rpcProxy.deleteSnapshot(null, req),
res -> null, Void.class);
}
@Override
public void allowSnapshot(String snapshotRoot) throws IOException {
if (!Client.isAsynchronousMode()) {
super.allowSnapshot(snapshotRoot);
return;
}
AllowSnapshotRequestProto req = AllowSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).build();
asyncIpcClient(() -> rpcProxy.allowSnapshot(null, req),
res -> null, Void.class);
}
@Override
public void disallowSnapshot(String snapshotRoot) throws IOException {
if (!Client.isAsynchronousMode()) {
super.disallowSnapshot(snapshotRoot);
return;
}
DisallowSnapshotRequestProto req = DisallowSnapshotRequestProto
.newBuilder().setSnapshotRoot(snapshotRoot).build();
asyncIpcClient(() -> rpcProxy.disallowSnapshot(null, req),
res -> null, Void.class);
}
@Override
public void renameSnapshot(
String snapshotRoot, String snapshotOldName,
String snapshotNewName) throws IOException {
if (!Client.isAsynchronousMode()) {
super.renameSnapshot(snapshotRoot, snapshotOldName, snapshotNewName);
return;
}
RenameSnapshotRequestProto req = RenameSnapshotRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).setSnapshotOldName(snapshotOldName)
.setSnapshotNewName(snapshotNewName).build();
asyncIpcClient(() -> rpcProxy.renameSnapshot(null, req),
res -> null, Void.class);
}
@Override
public SnapshottableDirectoryStatus[] getSnapshottableDirListing() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getSnapshottableDirListing();
}
GetSnapshottableDirListingRequestProto req =
GetSnapshottableDirListingRequestProto.newBuilder().build();
return asyncIpcClient(() -> rpcProxy.getSnapshottableDirListing(null, req),
res -> {
if (res.hasSnapshottableDirList()) {
return PBHelperClient.convert(res.getSnapshottableDirList());
}
return null;
}, SnapshottableDirectoryStatus[].class);
}
@Override
public SnapshotStatus[] getSnapshotListing(String path) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getSnapshotListing(path);
}
GetSnapshotListingRequestProto req =
GetSnapshotListingRequestProto.newBuilder()
.setSnapshotRoot(path).build();
return asyncIpcClient(() -> rpcProxy.getSnapshotListing(null, req),
res -> {
if (res.hasSnapshotList()) {
return PBHelperClient.convert(res.getSnapshotList());
}
return null;
}, SnapshotStatus[].class);
}
@Override
public SnapshotDiffReport getSnapshotDiffReport(
String snapshotRoot, String fromSnapshot, String toSnapshot) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getSnapshotDiffReport(snapshotRoot, fromSnapshot, toSnapshot);
}
GetSnapshotDiffReportRequestProto req = GetSnapshotDiffReportRequestProto
.newBuilder().setSnapshotRoot(snapshotRoot)
.setFromSnapshot(fromSnapshot).setToSnapshot(toSnapshot).build();
return asyncIpcClient(() -> rpcProxy.getSnapshotDiffReport(null, req),
res -> PBHelperClient.convert(res.getDiffReport()), SnapshotDiffReport.class);
}
@Override
public SnapshotDiffReportListing getSnapshotDiffReportListing(
String snapshotRoot, String fromSnapshot, String toSnapshot,
byte[] startPath, int index) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getSnapshotDiffReportListing(snapshotRoot, fromSnapshot,
toSnapshot, startPath, index);
}
GetSnapshotDiffReportListingRequestProto req =
GetSnapshotDiffReportListingRequestProto.newBuilder()
.setSnapshotRoot(snapshotRoot).setFromSnapshot(fromSnapshot)
.setToSnapshot(toSnapshot).setCursor(
HdfsProtos.SnapshotDiffReportCursorProto.newBuilder()
.setStartPath(PBHelperClient.getByteString(startPath))
.setIndex(index).build()).build();
return asyncIpcClient(() -> rpcProxy.getSnapshotDiffReportListing(null, req),
res -> PBHelperClient.convert(res.getDiffReport()),
SnapshotDiffReportListing.class);
}
@Override
public long addCacheDirective(
CacheDirectiveInfo directive, EnumSet<CacheFlag> flags) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.addCacheDirective(directive, flags);
}
AddCacheDirectiveRequestProto.Builder builder =
AddCacheDirectiveRequestProto.newBuilder().
setInfo(PBHelperClient.convert(directive));
if (!flags.isEmpty()) {
builder.setCacheFlags(PBHelperClient.convertCacheFlags(flags));
}
return asyncIpcClient(() -> rpcProxy.addCacheDirective(null, builder.build()),
res -> res.getId(), Long.class);
}
@Override
public void modifyCacheDirective(
CacheDirectiveInfo directive, EnumSet<CacheFlag> flags) throws IOException {
if (!Client.isAsynchronousMode()) {
super.modifyCacheDirective(directive, flags);
return;
}
ModifyCacheDirectiveRequestProto.Builder builder =
ModifyCacheDirectiveRequestProto.newBuilder().
setInfo(PBHelperClient.convert(directive));
if (!flags.isEmpty()) {
builder.setCacheFlags(PBHelperClient.convertCacheFlags(flags));
}
asyncIpcClient(() -> rpcProxy.modifyCacheDirective(null, builder.build()),
res -> null, Void.class);
}
@Override
public void removeCacheDirective(long id) throws IOException {
if (!Client.isAsynchronousMode()) {
super.removeCacheDirective(id);
return;
}
asyncIpcClient(() -> rpcProxy.removeCacheDirective(null,
RemoveCacheDirectiveRequestProto.newBuilder().
setId(id).build()),
res -> null, Void.class);
}
@Override
public BatchedEntries<CacheDirectiveEntry> listCacheDirectives(
long prevId, CacheDirectiveInfo filter) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.listCacheDirectives(prevId, filter);
}
if (filter == null) {
filter = new CacheDirectiveInfo.Builder().build();
}
CacheDirectiveInfo f = filter;
return asyncIpcClient(() -> rpcProxy.listCacheDirectives(null,
ListCacheDirectivesRequestProto.newBuilder().
setPrevId(prevId).
setFilter(PBHelperClient.convert(f)).
build()),
res -> new BatchedCacheEntries(res), BatchedEntries.class);
}
@Override
public void addCachePool(CachePoolInfo info) throws IOException {
if (!Client.isAsynchronousMode()) {
super.addCachePool(info);
return;
}
AddCachePoolRequestProto.Builder builder =
AddCachePoolRequestProto.newBuilder();
builder.setInfo(PBHelperClient.convert(info));
asyncIpcClient(() -> rpcProxy.addCachePool(null, builder.build()),
res -> null, Void.class);
}
@Override
public void modifyCachePool(CachePoolInfo req) throws IOException {
if (!Client.isAsynchronousMode()) {
super.modifyCachePool(req);
return;
}
ModifyCachePoolRequestProto.Builder builder =
ModifyCachePoolRequestProto.newBuilder();
builder.setInfo(PBHelperClient.convert(req));
asyncIpcClient(() -> rpcProxy.modifyCachePool(null, builder.build()),
res -> null, Void.class);
}
@Override
public void removeCachePool(String cachePoolName) throws IOException {
if (!Client.isAsynchronousMode()) {
super.removeCachePool(cachePoolName);
return;
}
asyncIpcClient(() -> rpcProxy.removeCachePool(null,
RemoveCachePoolRequestProto.newBuilder().
setPoolName(cachePoolName).build()),
res -> null, Void.class);
}
@Override
public BatchedEntries<CachePoolEntry> listCachePools(String prevKey)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.listCachePools(prevKey);
}
return asyncIpcClient(() -> rpcProxy.listCachePools(null,
ListCachePoolsRequestProto.newBuilder().setPrevPoolName(prevKey).build()),
res -> new BatchedCachePoolEntries(res), BatchedEntries.class);
}
@Override
public void modifyAclEntries(String src, List<AclEntry> aclSpec)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.modifyAclEntries(src, aclSpec);
return;
}
ModifyAclEntriesRequestProto req = ModifyAclEntriesRequestProto
.newBuilder().setSrc(src)
.addAllAclSpec(PBHelperClient.convertAclEntryProto(aclSpec)).build();
asyncIpcClient(() -> rpcProxy.modifyAclEntries(null, req),
res -> null, Void.class);
}
@Override
public void removeAclEntries(String src, List<AclEntry> aclSpec)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.removeAclEntries(src, aclSpec);
return;
}
RemoveAclEntriesRequestProto req = RemoveAclEntriesRequestProto
.newBuilder().setSrc(src)
.addAllAclSpec(PBHelperClient.convertAclEntryProto(aclSpec)).build();
asyncIpcClient(() -> rpcProxy.removeAclEntries(null, req),
res -> null, Void.class);
}
@Override
public void removeDefaultAcl(String src) throws IOException {
if (!Client.isAsynchronousMode()) {
super.removeDefaultAcl(src);
return;
}
RemoveDefaultAclRequestProto req = RemoveDefaultAclRequestProto
.newBuilder().setSrc(src).build();
asyncIpcClient(() -> rpcProxy.removeDefaultAcl(null, req),
res -> null, Void.class);
}
@Override
public void removeAcl(String src) throws IOException {
if (!Client.isAsynchronousMode()) {
super.removeAcl(src);
return;
}
RemoveAclRequestProto req = RemoveAclRequestProto.newBuilder()
.setSrc(src).build();
asyncIpcClient(() -> rpcProxy.removeAcl(null, req),
res -> null, Void.class);
}
@Override
public void setAcl(String src, List<AclEntry> aclSpec) throws IOException {
if (!Client.isAsynchronousMode()) {
super.setAcl(src, aclSpec);
return;
}
SetAclRequestProto req = SetAclRequestProto.newBuilder()
.setSrc(src)
.addAllAclSpec(PBHelperClient.convertAclEntryProto(aclSpec))
.build();
asyncIpcClient(() -> rpcProxy.setAcl(null, req),
res -> null, Void.class);
}
@Override
public AclStatus getAclStatus(String src) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getAclStatus(src);
}
GetAclStatusRequestProto req = GetAclStatusRequestProto.newBuilder()
.setSrc(src).build();
return asyncIpcClient(() -> rpcProxy.getAclStatus(null, req),
res -> PBHelperClient.convert(res), AclStatus.class);
}
@Override
public void createEncryptionZone(String src, String keyName)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.createEncryptionZone(src, keyName);
return;
}
final CreateEncryptionZoneRequestProto.Builder builder =
CreateEncryptionZoneRequestProto.newBuilder();
builder.setSrc(src);
if (keyName != null && !keyName.isEmpty()) {
builder.setKeyName(keyName);
}
CreateEncryptionZoneRequestProto req = builder.build();
asyncIpcClient(() -> rpcProxy.createEncryptionZone(null, req),
res -> null, Void.class);
}
@Override
public EncryptionZone getEZForPath(String src) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getEZForPath(src);
}
final GetEZForPathRequestProto.Builder builder =
GetEZForPathRequestProto.newBuilder();
builder.setSrc(src);
final GetEZForPathRequestProto req = builder.build();
return asyncIpcClient(() -> rpcProxy.getEZForPath(null, req),
res -> {
if (res.hasZone()) {
return PBHelperClient.convert(res.getZone());
} else {
return null;
}
}, EncryptionZone.class);
}
@Override
public BatchedEntries<EncryptionZone> listEncryptionZones(long id)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.listEncryptionZones(id);
}
final ListEncryptionZonesRequestProto req =
ListEncryptionZonesRequestProto.newBuilder()
.setId(id)
.build();
return asyncIpcClient(() -> rpcProxy.listEncryptionZones(null, req),
res -> {
List<EncryptionZone> elements =
Lists.newArrayListWithCapacity(res.getZonesCount());
for (EncryptionZoneProto p : res.getZonesList()) {
elements.add(PBHelperClient.convert(p));
}
return new BatchedListEntries<>(elements, res.getHasMore());
}, BatchedEntries.class);
}
@Override
public void setErasureCodingPolicy(String src, String ecPolicyName)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.setErasureCodingPolicy(src, ecPolicyName);
return;
}
final SetErasureCodingPolicyRequestProto.Builder builder =
SetErasureCodingPolicyRequestProto.newBuilder();
builder.setSrc(src);
if (ecPolicyName != null) {
builder.setEcPolicyName(ecPolicyName);
}
SetErasureCodingPolicyRequestProto req = builder.build();
asyncIpcClient(() -> rpcProxy.setErasureCodingPolicy(null, req),
res -> null, Void.class);
}
@Override
public void unsetErasureCodingPolicy(String src) throws IOException {
if (!Client.isAsynchronousMode()) {
super.unsetErasureCodingPolicy(src);
return;
}
final UnsetErasureCodingPolicyRequestProto.Builder builder =
UnsetErasureCodingPolicyRequestProto.newBuilder();
builder.setSrc(src);
UnsetErasureCodingPolicyRequestProto req = builder.build();
asyncIpcClient(() -> rpcProxy.unsetErasureCodingPolicy(null, req),
res -> null, Void.class);
}
@Override
public ECTopologyVerifierResult getECTopologyResultForPolicies(
final String... policyNames) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getECTopologyResultForPolicies(policyNames);
}
final GetECTopologyResultForPoliciesRequestProto.Builder builder =
GetECTopologyResultForPoliciesRequestProto.newBuilder();
builder.addAllPolicies(Arrays.asList(policyNames));
GetECTopologyResultForPoliciesRequestProto req = builder.build();
return asyncIpcClient(() -> rpcProxy.getECTopologyResultForPolicies(null, req),
res -> PBHelperClient.convertECTopologyVerifierResultProto(res.getResponse()),
ECTopologyVerifierResult.class);
}
@Override
public void reencryptEncryptionZone(String zone, ReencryptAction action)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.reencryptEncryptionZone(zone, action);
return;
}
final ReencryptEncryptionZoneRequestProto.Builder builder =
ReencryptEncryptionZoneRequestProto.newBuilder();
builder.setZone(zone).setAction(PBHelperClient.convert(action));
ReencryptEncryptionZoneRequestProto req = builder.build();
asyncIpcClient(() -> rpcProxy.reencryptEncryptionZone(null, req),
res -> null, Void.class);
}
@Override
public BatchedEntries<ZoneReencryptionStatus> listReencryptionStatus(long id)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.listReencryptionStatus(id);
}
final ListReencryptionStatusRequestProto req =
ListReencryptionStatusRequestProto.newBuilder().setId(id).build();
return asyncIpcClient(() -> rpcProxy.listReencryptionStatus(null, req),
res -> {
List<ZoneReencryptionStatus> elements =
Lists.newArrayListWithCapacity(res.getStatusesCount());
for (ZoneReencryptionStatusProto p : res.getStatusesList()) {
elements.add(PBHelperClient.convert(p));
}
return new BatchedListEntries<>(elements, res.getHasMore());
}, BatchedEntries.class);
}
@Override
public void setXAttr(String src, XAttr xAttr, EnumSet<XAttrSetFlag> flag)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.setXAttr(src, xAttr, flag);
return;
}
SetXAttrRequestProto req = SetXAttrRequestProto.newBuilder()
.setSrc(src)
.setXAttr(PBHelperClient.convertXAttrProto(xAttr))
.setFlag(PBHelperClient.convert(flag))
.build();
asyncIpcClient(() -> rpcProxy.setXAttr(null, req),
res -> null, Void.class);
}
@Override
public List<XAttr> getXAttrs(String src, List<XAttr> xAttrs)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getXAttrs(src, xAttrs);
}
GetXAttrsRequestProto.Builder builder = GetXAttrsRequestProto.newBuilder();
builder.setSrc(src);
if (xAttrs != null) {
builder.addAllXAttrs(PBHelperClient.convertXAttrProto(xAttrs));
}
GetXAttrsRequestProto req = builder.build();
return asyncIpcClient(() -> rpcProxy.getXAttrs(null, req),
res -> PBHelperClient.convert(res), List.class);
}
@Override
public List<XAttr> listXAttrs(String src) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.listXAttrs(src);
}
ListXAttrsRequestProto.Builder builder =
ListXAttrsRequestProto.newBuilder();
builder.setSrc(src);
ListXAttrsRequestProto req = builder.build();
return asyncIpcClient(() -> rpcProxy.listXAttrs(null, req),
res -> PBHelperClient.convert(res), List.class);
}
@Override
public void removeXAttr(String src, XAttr xAttr) throws IOException {
if (!Client.isAsynchronousMode()) {
super.removeXAttr(src, xAttr);
return;
}
RemoveXAttrRequestProto req = RemoveXAttrRequestProto
.newBuilder().setSrc(src)
.setXAttr(PBHelperClient.convertXAttrProto(xAttr)).build();
asyncIpcClient(() -> rpcProxy.removeXAttr(null, req),
res -> null, Void.class);
}
@Override
public void checkAccess(String path, FsAction mode) throws IOException {
if (!Client.isAsynchronousMode()) {
super.checkAccess(path, mode);
return;
}
CheckAccessRequestProto req = CheckAccessRequestProto.newBuilder()
.setPath(path).setMode(PBHelperClient.convert(mode)).build();
asyncIpcClient(() -> rpcProxy.checkAccess(null, req),
res -> null, Void.class);
}
@Override
public void setStoragePolicy(String src, String policyName)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.setStoragePolicy(src, policyName);
return;
}
SetStoragePolicyRequestProto req = SetStoragePolicyRequestProto
.newBuilder().setSrc(src).setPolicyName(policyName).build();
asyncIpcClient(() -> rpcProxy.setStoragePolicy(null, req),
res -> null, Void.class);
}
@Override
public void unsetStoragePolicy(String src) throws IOException {
if (!Client.isAsynchronousMode()) {
super.unsetStoragePolicy(src);
return;
}
UnsetStoragePolicyRequestProto req = UnsetStoragePolicyRequestProto
.newBuilder().setSrc(src).build();
asyncIpcClient(() -> rpcProxy.unsetStoragePolicy(null, req),
res -> null, Void.class);
}
@Override
public BlockStoragePolicy getStoragePolicy(String path) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getStoragePolicy(path);
}
GetStoragePolicyRequestProto request = GetStoragePolicyRequestProto
.newBuilder().setPath(path).build();
return asyncIpcClient(() -> rpcProxy.getStoragePolicy(null, request),
res -> PBHelperClient.convert(res.getStoragePolicy()),
BlockStoragePolicy.class);
}
@Override
public BlockStoragePolicy[] getStoragePolicies() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getStoragePolicies();
}
return asyncIpcClient(() -> rpcProxy.getStoragePolicies(null,
VOID_GET_STORAGE_POLICIES_REQUEST),
res -> PBHelperClient.convertStoragePolicies(res.getPoliciesList()),
BlockStoragePolicy[].class);
}
public long getCurrentEditLogTxid() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getCurrentEditLogTxid();
}
GetCurrentEditLogTxidRequestProto req = GetCurrentEditLogTxidRequestProto
.getDefaultInstance();
return asyncIpcClient(() -> rpcProxy.getCurrentEditLogTxid(null, req),
res -> res.getTxid(), Long.class);
}
@Override
public EventBatchList getEditsFromTxid(long txid) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getEditsFromTxid(txid);
}
GetEditsFromTxidRequestProto req = GetEditsFromTxidRequestProto.newBuilder()
.setTxid(txid).build();
return asyncIpcClient(() -> rpcProxy.getEditsFromTxid(null, req),
res -> PBHelperClient.convert(res), EventBatchList.class);
}
@Override
public AddErasureCodingPolicyResponse[] addErasureCodingPolicies(
ErasureCodingPolicy[] policies) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.addErasureCodingPolicies(policies);
}
List<ErasureCodingPolicyProto> protos = Arrays.stream(policies)
.map(PBHelperClient::convertErasureCodingPolicy)
.collect(Collectors.toList());
AddErasureCodingPoliciesRequestProto req =
AddErasureCodingPoliciesRequestProto.newBuilder()
.addAllEcPolicies(protos).build();
return asyncIpcClient(() -> rpcProxy.addErasureCodingPolicies(null, req),
res -> res.getResponsesList().stream()
.map(PBHelperClient::convertAddErasureCodingPolicyResponse)
.toArray(AddErasureCodingPolicyResponse[]::new),
AddErasureCodingPolicyResponse[].class);
}
@Override
public void removeErasureCodingPolicy(String ecPolicyName)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.removeErasureCodingPolicy(ecPolicyName);
return;
}
RemoveErasureCodingPolicyRequestProto.Builder builder =
RemoveErasureCodingPolicyRequestProto.newBuilder();
builder.setEcPolicyName(ecPolicyName);
RemoveErasureCodingPolicyRequestProto req = builder.build();
asyncIpcClient(() -> rpcProxy.removeErasureCodingPolicy(null, req),
res -> null, Void.class);
}
@Override
public void enableErasureCodingPolicy(String ecPolicyName)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.enableErasureCodingPolicy(ecPolicyName);
return;
}
EnableErasureCodingPolicyRequestProto.Builder builder =
EnableErasureCodingPolicyRequestProto.newBuilder();
builder.setEcPolicyName(ecPolicyName);
EnableErasureCodingPolicyRequestProto req = builder.build();
asyncIpcClient(() -> rpcProxy.enableErasureCodingPolicy(null, req),
res -> null, Void.class);
}
@Override
public void disableErasureCodingPolicy(String ecPolicyName)
throws IOException {
if (!Client.isAsynchronousMode()) {
super.disableErasureCodingPolicy(ecPolicyName);
return;
}
DisableErasureCodingPolicyRequestProto.Builder builder =
DisableErasureCodingPolicyRequestProto.newBuilder();
builder.setEcPolicyName(ecPolicyName);
DisableErasureCodingPolicyRequestProto req = builder.build();
asyncIpcClient(() -> rpcProxy.disableErasureCodingPolicy(null, req),
res -> null, Void.class);
}
@Override
public ErasureCodingPolicyInfo[] getErasureCodingPolicies()
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getErasureCodingPolicies();
}
return asyncIpcClient(() -> rpcProxy.getErasureCodingPolicies(
null, VOID_GET_EC_POLICIES_REQUEST),
res -> {
ErasureCodingPolicyInfo[] ecPolicies =
new ErasureCodingPolicyInfo[res.getEcPoliciesCount()];
int i = 0;
for (ErasureCodingPolicyProto proto : res.getEcPoliciesList()) {
ecPolicies[i++] =
PBHelperClient.convertErasureCodingPolicyInfo(proto);
}
return ecPolicies;
}, ErasureCodingPolicyInfo[].class);
}
@Override
public Map<String, String> getErasureCodingCodecs() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getErasureCodingCodecs();
}
return asyncIpcClient(() -> rpcProxy
.getErasureCodingCodecs(null, VOID_GET_EC_CODEC_REQUEST),
res -> {
Map<String, String> ecCodecs = new HashMap<>();
for (CodecProto codec : res.getCodecList()) {
ecCodecs.put(codec.getCodec(), codec.getCoders());
}
return ecCodecs;
}, Map.class);
}
@Override
public ErasureCodingPolicy getErasureCodingPolicy(String src)
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getErasureCodingPolicy(src);
}
GetErasureCodingPolicyRequestProto req =
GetErasureCodingPolicyRequestProto.newBuilder().setSrc(src).build();
return asyncIpcClient(() -> rpcProxy.getErasureCodingPolicy(null, req),
res -> {
if (res.hasEcPolicy()) {
return PBHelperClient.convertErasureCodingPolicy(
res.getEcPolicy());
}
return null;
}, ErasureCodingPolicy.class);
}
@Override
public QuotaUsage getQuotaUsage(String path) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getQuotaUsage(path);
}
GetQuotaUsageRequestProto req =
GetQuotaUsageRequestProto.newBuilder().setPath(path).build();
return asyncIpcClient(() -> rpcProxy.getQuotaUsage(null, req),
res -> PBHelperClient.convert(res.getUsage()), QuotaUsage.class);
}
@Override
public BatchedEntries<OpenFileEntry> listOpenFiles(
long prevId, EnumSet<OpenFilesType> openFilesTypes,
String path) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.listOpenFiles(prevId, openFilesTypes, path);
}
ListOpenFilesRequestProto.Builder req =
ListOpenFilesRequestProto.newBuilder().setId(prevId);
if (openFilesTypes != null) {
req.addAllTypes(PBHelperClient.convertOpenFileTypes(openFilesTypes));
}
req.setPath(path);
return asyncIpcClient(() -> rpcProxy.listOpenFiles(null, req.build()),
res -> {
List<OpenFileEntry> openFileEntries =
Lists.newArrayListWithCapacity(res.getEntriesCount());
for (OpenFilesBatchResponseProto p : res.getEntriesList()) {
openFileEntries.add(PBHelperClient.convert(p));
}
return new BatchedListEntries<>(openFileEntries, res.getHasMore());
}, BatchedEntries.class);
}
@Override
public void msync() throws IOException {
if (!Client.isAsynchronousMode()) {
super.msync();
return;
}
MsyncRequestProto.Builder req = MsyncRequestProto.newBuilder();
asyncIpcClient(() -> rpcProxy.msync(null, req.build()),
res -> null, Void.class);
}
@Override
public void satisfyStoragePolicy(String src) throws IOException {
if (!Client.isAsynchronousMode()) {
super.satisfyStoragePolicy(src);
return;
}
SatisfyStoragePolicyRequestProto req =
SatisfyStoragePolicyRequestProto.newBuilder().setSrc(src).build();
asyncIpcClient(() -> rpcProxy.satisfyStoragePolicy(null, req),
res -> null, Void.class);
}
@Override
public DatanodeInfo[] getSlowDatanodeReport() throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getSlowDatanodeReport();
}
GetSlowDatanodeReportRequestProto req =
GetSlowDatanodeReportRequestProto.newBuilder().build();
return asyncIpcClient(() -> rpcProxy.getSlowDatanodeReport(null, req),
res -> PBHelperClient.convert(res.getDatanodeInfoProtoList()),
DatanodeInfo[].class);
}
@Override
public HAServiceProtocol.HAServiceState getHAServiceState()
throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getHAServiceState();
}
HAServiceStateRequestProto req =
HAServiceStateRequestProto.newBuilder().build();
return asyncIpcClient(() -> rpcProxy.getHAServiceState(null, req),
res -> {
switch(res.getState()) {
case ACTIVE:
return HAServiceProtocol.HAServiceState.ACTIVE;
case STANDBY:
return HAServiceProtocol.HAServiceState.STANDBY;
case OBSERVER:
return HAServiceProtocol.HAServiceState.OBSERVER;
case INITIALIZING:
default:
return HAServiceProtocol.HAServiceState.INITIALIZING;
}
}, HAServiceProtocol.HAServiceState.class);
}
@Override
public Path getEnclosingRoot(String filename) throws IOException {
if (!Client.isAsynchronousMode()) {
return super.getEnclosingRoot(filename);
}
final GetEnclosingRootRequestProto.Builder builder =
GetEnclosingRootRequestProto.newBuilder();
builder.setFilename(filename);
final GetEnclosingRootRequestProto req = builder.build();
return asyncIpcClient(() -> rpcProxy.getEnclosingRoot(null, req),
res -> new Path(res.getEnclosingRootPath()),
Path.class);
}
}
|
RouterClientProtocolTranslatorPB
|
java
|
apache__camel
|
core/camel-support/src/main/java/org/apache/camel/support/SimpleRegistry.java
|
{
"start": 1308,
"end": 4649
}
|
class ____ extends LinkedHashMap<String, Map<Class<?>, Object>> implements Registry, Closeable {
@Override
public Object lookupByName(String name) {
return lookupByNameAndType(name, Object.class);
}
@Override
public <T> T lookupByNameAndType(String name, Class<T> type) {
Map<Class<?>, Object> map = this.get(name);
if (map == null) {
return null;
}
Object answer = map.get(type);
if (answer == null) {
// look for first entry that is the type
for (Object value : map.values()) {
if (type.isInstance(value)) {
answer = value;
break;
}
}
}
if (answer == null) {
return null;
}
try {
answer = unwrap(answer);
return type.cast(answer);
} catch (Exception e) {
String msg = "Found bean: " + name + " in SimpleRegistry: " + this
+ " of type: " + answer.getClass().getName() + " expected type was: " + type;
throw new NoSuchBeanException(name, msg, e);
}
}
@Override
public <T> Map<String, T> findByTypeWithName(Class<T> type) {
Map<String, T> result = new LinkedHashMap<>();
for (Map.Entry<String, Map<Class<?>, Object>> entry : entrySet()) {
for (Object value : entry.getValue().values()) {
if (type.isInstance(value)) {
value = unwrap(value);
result.put(entry.getKey(), type.cast(value));
}
}
}
return result;
}
@Override
public <T> Set<T> findByType(Class<T> type) {
Set<T> result = new LinkedHashSet<>();
for (Map.Entry<String, Map<Class<?>, Object>> entry : entrySet()) {
for (Object value : entry.getValue().values()) {
if (type.isInstance(value)) {
value = unwrap(value);
result.add(type.cast(value));
}
}
}
return result;
}
@Override
public void bind(String id, Class<?> type, Object bean) {
if (bean != null) {
computeIfAbsent(id, k -> new LinkedHashMap<>()).put(type, wrap(bean));
}
}
@Override
public void bind(String id, Class<?> type, Object bean, String initMethod, String destroyMethod)
throws RuntimeCamelException {
throw new UnsupportedOperationException("Use DefaultRegistry");
}
@Override
public void bind(String id, Class<?> type, Supplier<Object> bean) {
throw new UnsupportedOperationException("Use SupplierRegistry");
}
@Override
public void bind(String id, Class<?> type, Supplier<Object> bean, String initMethod, String destroyMethod)
throws RuntimeCamelException {
throw new UnsupportedOperationException("Use SupplierRegistry");
}
@Override
public void bindAsPrototype(String id, Class<?> type, Supplier<Object> bean) {
throw new UnsupportedOperationException("Use SupplierRegistry");
}
@Override
public void unbind(String id) {
remove(id);
}
@Override
public void close() throws IOException {
clear();
}
}
|
SimpleRegistry
|
java
|
apache__flink
|
flink-rpc/flink-rpc-akka/src/main/java/org/apache/flink/runtime/rpc/pekko/PekkoUtils.java
|
{
"start": 2350,
"end": 7787
}
|
class ____ {
private static final Logger LOG = LoggerFactory.getLogger(PekkoUtils.class);
private static final String FLINK_ACTOR_SYSTEM_NAME = "flink";
public static String getFlinkActorSystemName() {
return FLINK_ACTOR_SYSTEM_NAME;
}
/**
* Gets the basic Pekko config which is shared by remote and local actor systems.
*
* @param configuration instance which contains the user specified values for the configuration
* @return Flink's basic Pekko config
*/
private static Config getBasicConfig(Configuration configuration) {
final int throughput = configuration.get(RpcOptions.DISPATCHER_THROUGHPUT);
final String jvmExitOnFatalError =
booleanToOnOrOff(configuration.get(RpcOptions.JVM_EXIT_ON_FATAL_ERROR));
final String logLifecycleEvents =
booleanToOnOrOff(configuration.get(RpcOptions.LOG_LIFECYCLE_EVENTS));
final String supervisorStrategy = EscalatingSupervisorStrategy.class.getCanonicalName();
return new ConfigBuilder()
.add("pekko {")
.add(" daemonic = off")
.add(" loggers = [\"org.apache.pekko.event.slf4j.Slf4jLogger\"]")
.add(" logging-filter = \"org.apache.pekko.event.slf4j.Slf4jLoggingFilter\"")
.add(" log-config-on-start = off")
.add(" logger-startup-timeout = 50s")
.add(" loglevel = " + getLogLevel())
.add(" stdout-loglevel = OFF")
.add(" log-dead-letters = " + logLifecycleEvents)
.add(" log-dead-letters-during-shutdown = " + logLifecycleEvents)
.add(" jvm-exit-on-fatal-error = " + jvmExitOnFatalError)
.add(" serialize-messages = off")
.add(" actor {")
.add(" guardian-supervisor-strategy = " + supervisorStrategy)
.add(" warn-about-java-serializer-usage = off")
.add(" allow-java-serialization = on")
.add(" default-dispatcher {")
.add(" throughput = " + throughput)
.add(" }")
.add(" supervisor-dispatcher {")
.add(" type = Dispatcher")
.add(" executor = \"thread-pool-executor\"")
.add(" thread-pool-executor {")
.add(" core-pool-size-min = 1")
.add(" core-pool-size-max = 1")
.add(" }")
.add(" }")
.add(" }")
.add("}")
.build();
}
private static String getLogLevel() {
if (LOG.isTraceEnabled()) {
// TRACE is not supported by Pekko
return "DEBUG";
}
if (LOG.isDebugEnabled()) {
return "DEBUG";
}
if (LOG.isInfoEnabled()) {
return "INFO";
}
if (LOG.isWarnEnabled()) {
return "WARNING";
}
if (LOG.isErrorEnabled()) {
return "ERROR";
}
return "OFF";
}
public static Config getThreadPoolExecutorConfig(
RpcSystem.FixedThreadPoolExecutorConfiguration configuration) {
final int threadPriority = configuration.getThreadPriority();
final int minNumThreads = configuration.getMinNumThreads();
final int maxNumThreads = configuration.getMaxNumThreads();
return new ConfigBuilder()
.add("pekko {")
.add(" actor {")
.add(" default-dispatcher {")
.add(" type = " + PriorityThreadsDispatcher.class.getCanonicalName())
.add(" executor = thread-pool-executor")
.add(" thread-priority = " + threadPriority)
.add(" thread-pool-executor {")
.add(" core-pool-size-min = " + minNumThreads)
.add(" core-pool-size-max = " + maxNumThreads)
.add(" }")
.add(" }")
.add(" }")
.add("}")
.build();
}
public static Config getForkJoinExecutorConfig(
RpcSystem.ForkJoinExecutorConfiguration configuration) {
final double parallelismFactor = configuration.getParallelismFactor();
final int minNumThreads = configuration.getMinParallelism();
final int maxNumThreads = configuration.getMaxParallelism();
return new ConfigBuilder()
.add("pekko {")
.add(" actor {")
.add(" default-dispatcher {")
.add(" executor = fork-join-executor")
.add(" fork-join-executor {")
.add(" parallelism-factor = " + parallelismFactor)
.add(" parallelism-min = " + minNumThreads)
.add(" parallelism-max = " + maxNumThreads)
.add(" }")
.add(" }")
.add(" }")
.add("}")
.build();
}
/**
* Creates a Pekko config for a remote actor system listening on port on the network interface
* identified by bindAddress.
*
* @param configuration instance containing the user provided configuration values
* @param bindAddress of the network
|
PekkoUtils
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/issue_1400/Issue1449.java
|
{
"start": 2002,
"end": 2840
}
|
class ____ implements ObjectDeserializer {
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
String code;
Object object = parser.parse();
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
code = jsonObject.getString("code");
} else {
code = (String) object;
}
if ("0".equals(code)) {
return (T) Sex.NONE;
} else if ("1".equals(code)) {
return (T) Sex.MAN;
} else if ("2".equals(code)) {
return (T) Sex.WOMAN;
}
return (T) Sex.NONE;
}
public int getFastMatchToken() {
return 0;
}
}
public static
|
SexDeserializer
|
java
|
spring-projects__spring-framework
|
spring-core/src/jmh/java/org/springframework/core/env/CompositePropertySourceBenchmark.java
|
{
"start": 1851,
"end": 2726
}
|
class ____ {
private static final IdGenerator ID_GENERATOR = new AlternativeJdkIdGenerator();
private static final Object VALUE = new Object();
CompositePropertySource composite;
@Param({ "2", "5", "10" })
int numberOfPropertySources;
@Param({ "10", "100", "1000" })
int numberOfPropertyNamesPerSource;
@Setup(Level.Trial)
public void setUp() {
this.composite = new CompositePropertySource("benchmark");
for (int i = 0; i < this.numberOfPropertySources; i++) {
Map<String, Object> map = new HashMap<>(this.numberOfPropertyNamesPerSource);
for (int j = 0; j < this.numberOfPropertyNamesPerSource; j++) {
map.put(ID_GENERATOR.generateId().toString(), VALUE);
}
PropertySource<?> propertySource = new MapPropertySource("propertySource" + i, map);
this.composite.addPropertySource(propertySource);
}
}
}
}
|
BenchmarkState
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/DiscriminatorValueJpaAnnotation.java
|
{
"start": 471,
"end": 1395
}
|
class ____ implements DiscriminatorValue {
private String value;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public DiscriminatorValueJpaAnnotation(ModelsContext modelContext) {
}
/**
* Used in creating annotation instances from JDK variant
*/
public DiscriminatorValueJpaAnnotation(DiscriminatorValue annotation, ModelsContext modelContext) {
this.value = annotation.value();
}
/**
* Used in creating annotation instances from Jandex variant
*/
public DiscriminatorValueJpaAnnotation(
Map<String, Object> attributeValues,
ModelsContext modelContext) {
this.value = (String) attributeValues.get( "value" );
}
@Override
public Class<? extends Annotation> annotationType() {
return DiscriminatorValue.class;
}
@Override
public String value() {
return value;
}
public void value(String value) {
this.value = value;
}
}
|
DiscriminatorValueJpaAnnotation
|
java
|
playframework__playframework
|
documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/customconstraint/nopayload/DBAccessForm.java
|
{
"start": 353,
"end": 1775
}
|
class ____ implements ValidatableWithDB<ValidationError> {
@Constraints.Required @Constraints.Email private String email;
@Constraints.Required private String firstName;
@Constraints.Required private String lastName;
@Constraints.Required private String password;
@Constraints.Required private String repeatPassword;
@Override
public ValidationError validate(final Database db) {
// Access the database to check if the email already exists
if (User.byEmail(email, db) != null) {
return new ValidationError("email", "This e-mail is already registered.");
}
return null;
}
// getters and setters
// ###skip: 46
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRepeatPassword() {
return this.repeatPassword;
}
public void setRepeatPassword(String repeatPassword) {
this.repeatPassword = repeatPassword;
}
public static
|
DBAccessForm
|
java
|
alibaba__nacos
|
config/src/main/java/com/alibaba/nacos/config/server/constant/PropertiesConstant.java
|
{
"start": 733,
"end": 2710
}
|
class ____ {
public static final String NOTIFY_CONNECT_TIMEOUT = "notifyConnectTimeout";
public static final String NOTIFY_SOCKET_TIMEOUT = "notifySocketTimeout";
public static final String IS_HEALTH_CHECK = "isHealthCheck";
public static final String MAX_HEALTH_CHECK_FAIL_COUNT = "maxHealthCheckFailCount";
public static final String MAX_CONTENT = "maxContent";
public static final String IS_MANAGE_CAPACITY = "isManageCapacity";
public static final String IS_CAPACITY_LIMIT_CHECK = "isCapacityLimitCheck";
public static final String DEFAULT_CLUSTER_QUOTA = "defaultClusterQuota";
public static final String DEFAULT_GROUP_QUOTA = "defaultGroupQuota";
public static final String DEFAULT_TENANT_QUOTA = "defaultTenantQuota";
public static final String DEFAULT_MAX_SIZE = "defaultMaxSize";
public static final String DEFAULT_MAX_AGGR_COUNT = "defaultMaxAggrCount";
public static final String DEFAULT_MAX_AGGR_SIZE = "defaultMaxAggrSize";
public static final String CORRECT_USAGE_DELAY = "correctUsageDelay";
public static final String INITIAL_EXPANSION_PERCENT = "initialExpansionPercent";
public static final String SEARCH_MAX_CAPACITY = "nacos.config.search.max_capacity";
public static final String SEARCH_MAX_THREAD = "nacos.config.search.max_thread";
public static final String SEARCH_WAIT_TIMEOUT = "nacos.config.search.wait_timeout";
public static final String DUMP_CHANGE_ON = "dumpChangeOn";
public static final String DUMP_CHANGE_WORKER_INTERVAL = "dumpChangeWorkerInterval";
public static final String CONFIG_RENTENTION_DAYS = "nacos.config.retention.days";
public static final String GRAY_CAPATIBEL_MODEL = "nacos.config.gray.compatible.model";
public static final String NAMESPACE_COMPATIBLE_MODE = "nacos.config.namespace.compatible.mode";
}
|
PropertiesConstant
|
java
|
google__gson
|
gson/src/test/java/com/google/gson/functional/ObjectTest.java
|
{
"start": 25282,
"end": 26474
}
|
class ____ {
@SuppressWarnings("StaticAssignmentOfThrowable")
static final RuntimeException thrownException = new RuntimeException("Custom exception");
public ClassWithThrowingConstructor() {
throw thrownException;
}
}
@Test
public void testDeeplyNested() {
int defaultLimit = 255;
// json = {"r":{"r": ... {"r":null} ... }}
String json = "{\"r\":".repeat(defaultLimit) + "null" + "}".repeat(defaultLimit);
RecursiveClass deserialized = gson.fromJson(json, RecursiveClass.class);
assertThat(deserialized).isNotNull();
assertThat(deserialized.r).isNotNull();
// json = {"r":{"r": ... {"r":null} ... }}
String json2 = "{\"r\":".repeat(defaultLimit + 1) + "null" + "}".repeat(defaultLimit + 1);
JsonSyntaxException e =
assertThrows(JsonSyntaxException.class, () -> gson.fromJson(json2, RecursiveClass.class));
assertThat(e).hasCauseThat().isInstanceOf(MalformedJsonException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.isEqualTo(
"Nesting limit 255 reached at line 1 column 1277 path $" + ".r".repeat(defaultLimit));
}
private static
|
ClassWithThrowingConstructor
|
java
|
apache__kafka
|
coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorRuntime.java
|
{
"start": 49375,
"end": 50214
}
|
class ____ extends TimerTask {
private final TopicPartition tp;
private final DeferredEvent event;
public OperationTimeout(
TopicPartition tp,
DeferredEvent event,
long delayMs
) {
super(delayMs);
this.event = event;
this.tp = tp;
}
@Override
public void run() {
String name = event.toString();
scheduleInternalOperation("OperationTimeout(name=" + name + ", tp=" + tp + ")", tp,
() -> event.complete(new TimeoutException(name + " timed out after " + delayMs + "ms")));
}
}
/**
* A collection of {@link DeferredEvent}. When completed, completes all the events in the collection
* and logs any exceptions thrown.
*/
static
|
OperationTimeout
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FSInputChecker.java
|
{
"start": 1427,
"end": 17260
}
|
class ____ extends FSInputStream {
public static final Logger LOG =
LoggerFactory.getLogger(FSInputChecker.class);
/** The file name from which data is read from */
protected Path file;
private Checksum sum;
private boolean verifyChecksum = true;
private int maxChunkSize; // data bytes for checksum (eg 512)
private byte[] buf; // buffer for non-chunk-aligned reading
private byte[] checksum;
private IntBuffer checksumInts; // wrapper on checksum buffer
private int pos; // the position of the reader inside buf
private int count; // the number of bytes currently in buf
private int numOfRetries;
// cached file position
// this should always be a multiple of maxChunkSize
private long chunkPos = 0;
// Number of checksum chunks that can be read at once into a user
// buffer. Chosen by benchmarks - higher values do not reduce
// CPU usage. The size of the data reads made to the underlying stream
// will be CHUNKS_PER_READ * maxChunkSize.
private static final int CHUNKS_PER_READ = 32;
protected static final int CHECKSUM_SIZE = 4; // 32-bit checksum
/** Constructor
*
* @param file The name of the file to be read
* @param numOfRetries Number of read retries when ChecksumError occurs
*/
protected FSInputChecker( Path file, int numOfRetries) {
this.file = file;
this.numOfRetries = numOfRetries;
}
/** Constructor
*
* @param file The name of the file to be read
* @param numOfRetries Number of read retries when ChecksumError occurs
* @param sum the type of Checksum engine
* @param chunkSize maximun chunk size
* @param checksumSize the number byte of each checksum
* @param verifyChecksum verify check sum.
*/
protected FSInputChecker( Path file, int numOfRetries,
boolean verifyChecksum, Checksum sum, int chunkSize, int checksumSize ) {
this(file, numOfRetries);
set(verifyChecksum, sum, chunkSize, checksumSize);
}
/**
* Reads in checksum chunks into <code>buf</code> at <code>offset</code>
* and checksum into <code>checksum</code>.
* Since checksums can be disabled, there are two cases implementors need
* to worry about:
*
* (a) needChecksum() will return false:
* - len can be any positive value
* - checksum will be null
* Implementors should simply pass through to the underlying data stream.
* or
* (b) needChecksum() will return true:
* - len {@literal >=} maxChunkSize
* - checksum.length is a multiple of CHECKSUM_SIZE
* Implementors should read an integer number of data chunks into
* buf. The amount read should be bounded by len or by
* checksum.length / CHECKSUM_SIZE * maxChunkSize. Note that len may
* be a value that is not a multiple of maxChunkSize, in which case
* the implementation may return less than len.
*
* The method is used for implementing read, therefore, it should be optimized
* for sequential reading.
*
* @param pos chunkPos
* @param buf destination buffer
* @param offset offset in buf at which to store data
* @param len maximum number of bytes to read
* @param checksum the data buffer into which to write checksums
* @return number of bytes read
* @throws IOException raised on errors performing I/O.
*/
abstract protected int readChunk(long pos, byte[] buf, int offset, int len,
byte[] checksum) throws IOException;
/** Return position of beginning of chunk containing pos.
*
* @param pos a position in the file
* @return the starting position of the chunk which contains the byte
*/
abstract protected long getChunkPosition(long pos);
/**
* Return true if there is a need for checksum verification.
* @return if there is a need for checksum verification true, not false.
*/
protected synchronized boolean needChecksum() {
return verifyChecksum && sum != null;
}
/**
* Read one checksum-verified byte
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if an I/O error occurs.
*/
@Override
public synchronized int read() throws IOException {
if (pos >= count) {
fill();
if (pos >= count) {
return -1;
}
}
return buf[pos++] & 0xff;
}
/**
* Read checksum verified bytes from this byte-input stream into
* the specified byte array, starting at the given offset.
*
* <p> This method implements the general contract of the corresponding
* <code>{@link InputStream#read(byte[], int, int) read}</code> method of
* the <code>{@link InputStream}</code> class. As an additional
* convenience, it attempts to read as many bytes as possible by repeatedly
* invoking the <code>read</code> method of the underlying stream. This
* iterated <code>read</code> continues until one of the following
* conditions becomes true: <ul>
*
* <li> The specified number of bytes have been read,
*
* <li> The <code>read</code> method of the underlying stream returns
* <code>-1</code>, indicating end-of-file.
*
* </ul> If the first <code>read</code> on the underlying stream returns
* <code>-1</code> to indicate end-of-file then this method returns
* <code>-1</code>. Otherwise this method returns the number of bytes
* actually read.
*
* @param b destination buffer.
* @param off offset at which to start storing bytes.
* @param len maximum number of bytes to read.
* @return the number of bytes read, or <code>-1</code> if the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
* ChecksumException if any checksum error occurs
*/
@Override
public synchronized int read(byte[] b, int off, int len) throws IOException {
// parameter check
if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
int n = 0;
for (;;) {
int nread = read1(b, off + n, len - n);
if (nread <= 0)
return (n == 0) ? nread : n;
n += nread;
if (n >= len)
return n;
}
}
/**
* Fills the buffer with a chunk data.
* No mark is supported.
* This method assumes that all data in the buffer has already been read in,
* hence pos > count.
*/
private void fill( ) throws IOException {
assert(pos>=count);
// fill internal buffer
count = readChecksumChunk(buf, 0, maxChunkSize);
if (count < 0) count = 0;
}
/**
* Like read(byte[], int, int), but does not provide a dest buffer,
* so the read data is discarded.
* @param len maximum number of bytes to read.
* @return the number of bytes read.
* @throws IOException if an I/O error occurs.
*/
final protected synchronized int readAndDiscard(int len) throws IOException {
int total = 0;
while (total < len) {
if (pos >= count) {
count = readChecksumChunk(buf, 0, maxChunkSize);
if (count <= 0) {
break;
}
}
int rd = Math.min(count - pos, len - total);
pos += rd;
total += rd;
}
return total;
}
/*
* Read characters into a portion of an array, reading from the underlying
* stream at most once if necessary.
*/
private int read1(byte b[], int off, int len)
throws IOException {
int avail = count-pos;
if( avail <= 0 ) {
if(len >= maxChunkSize) {
// read a chunk to user buffer directly; avoid one copy
int nread = readChecksumChunk(b, off, len);
return nread;
} else {
// read a chunk into the local buffer
fill();
if( count <= 0 ) {
return -1;
} else {
avail = count;
}
}
}
// copy content of the local buffer to the user buffer
int cnt = (avail < len) ? avail : len;
System.arraycopy(buf, pos, b, off, cnt);
pos += cnt;
return cnt;
}
/* Read up one or more checksum chunk to array <i>b</i> at pos <i>off</i>
* It requires at least one checksum chunk boundary
* in between <cur_pos, cur_pos+len>
* and it stops reading at the last boundary or at the end of the stream;
* Otherwise an IllegalArgumentException is thrown.
* This makes sure that all data read are checksum verified.
*
* @param b the buffer into which the data is read.
* @param off the start offset in array <code>b</code>
* at which the data is written.
* @param len the maximum number of bytes to read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @throws IOException if an I/O error occurs.
*/
private int readChecksumChunk(byte b[], final int off, final int len)
throws IOException {
// invalidate buffer
count = pos = 0;
int read = 0;
boolean retry = true;
int retriesLeft = numOfRetries;
do {
retriesLeft--;
try {
read = readChunk(chunkPos, b, off, len, checksum);
if( read > 0) {
if( needChecksum() ) {
verifySums(b, off, read);
}
chunkPos += read;
}
retry = false;
} catch (ChecksumException ce) {
LOG.info("Found checksum error: b[" + off + ", " + (off+read) + "]="
+ StringUtils.byteToHexString(b, off, off + read), ce);
if (retriesLeft == 0) {
throw ce;
}
// try a new replica
if (seekToNewSource(chunkPos)) {
// Since at least one of the sources is different,
// the read might succeed, so we'll retry.
seek(chunkPos);
} else {
// Neither the data stream nor the checksum stream are being read
// from different sources, meaning we'll still get a checksum error
// if we try to do the read again. We throw an exception instead.
throw ce;
}
}
} while (retry);
return read;
}
private void verifySums(final byte b[], final int off, int read)
throws ChecksumException
{
int leftToVerify = read;
int verifyOff = 0;
checksumInts.rewind();
checksumInts.limit((read - 1)/maxChunkSize + 1);
while (leftToVerify > 0) {
sum.update(b, off + verifyOff, Math.min(leftToVerify, maxChunkSize));
int expected = checksumInts.get();
int calculated = (int)sum.getValue();
sum.reset();
if (expected != calculated) {
long errPos = chunkPos + verifyOff;
throw new ChecksumException(
"Checksum error: "+file+" at "+ errPos +
" exp: " + expected + " got: " + calculated, errPos);
}
leftToVerify -= maxChunkSize;
verifyOff += maxChunkSize;
}
}
/**
* Convert a checksum byte array to a long
* This is deprecated since 0.22 since it is no longer in use
* by this class.
*
* @param checksum check sum.
* @return crc.
*/
@Deprecated
static public long checksum2long(byte[] checksum) {
long crc = 0L;
for(int i=0; i<checksum.length; i++) {
crc |= (0xffL&(long)checksum[i])<<((checksum.length-i-1)*8);
}
return crc;
}
@Override
public synchronized long getPos() throws IOException {
return chunkPos-Math.max(0L, count - pos);
}
@Override
public synchronized int available() throws IOException {
return Math.max(0, count - pos);
}
/**
* Skips over and discards <code>n</code> bytes of data from the
* input stream.
*
* <p>This method may skip more bytes than are remaining in the backing
* file. This produces no exception and the number of bytes skipped
* may include some number of bytes that were beyond the EOF of the
* backing file. Attempting to read from the stream after skipping past
* the end will result in -1 indicating the end of the file.
*
*<p>If <code>n</code> is negative, no bytes are skipped.
*
* @param n the number of bytes to be skipped.
* @return the actual number of bytes skipped.
* @exception IOException if an I/O error occurs.
* ChecksumException if the chunk to skip to is corrupted
*/
@Override
public synchronized long skip(long n) throws IOException {
if (n <= 0) {
return 0;
}
seek(getPos()+n);
return n;
}
/**
* Seek to the given position in the stream.
* The next read() will be from that position.
*
* <p>This method may seek past the end of the file.
* This produces no exception and an attempt to read from
* the stream will result in -1 indicating the end of the file.
*
* @param pos the position to seek to.
* @exception IOException if an I/O error occurs.
* ChecksumException if the chunk to seek to is corrupted
*/
@Override
public synchronized void seek(long pos) throws IOException {
if( pos < 0 ) {
throw new EOFException(FSExceptionMessages.NEGATIVE_SEEK);
}
// optimize: check if the pos is in the buffer
long start = chunkPos - this.count;
if( pos>=start && pos<chunkPos) {
this.pos = (int)(pos-start);
return;
}
// reset the current state
resetState();
// seek to a checksum boundary
chunkPos = getChunkPosition(pos);
// scan to the desired position
int delta = (int)(pos - chunkPos);
if( delta > 0) {
readFully(this, new byte[delta], 0, delta);
}
}
/**
* A utility function that tries to read up to <code>len</code> bytes from
* <code>stm</code>
*
* @param stm an input stream
* @param buf destination buffer
* @param offset offset at which to store data
* @param len number of bytes to read
* @return actual number of bytes read
* @throws IOException if there is any IO error
*/
protected static int readFully(InputStream stm,
byte[] buf, int offset, int len) throws IOException {
int n = 0;
for (;;) {
int nread = stm.read(buf, offset + n, len - n);
if (nread <= 0)
return (n == 0) ? nread : n;
n += nread;
if (n >= len)
return n;
}
}
/**
* Set the checksum related parameters
* @param verifyChecksum whether to verify checksum
* @param sum which type of checksum to use
* @param maxChunkSize maximun chunk size
* @param checksumSize checksum size
*/
final protected synchronized void set(boolean verifyChecksum,
Checksum sum, int maxChunkSize, int checksumSize) {
// The code makes assumptions that checksums are always 32-bit.
assert !verifyChecksum || sum == null || checksumSize == CHECKSUM_SIZE;
this.maxChunkSize = maxChunkSize;
this.verifyChecksum = verifyChecksum;
this.sum = sum;
this.buf = new byte[maxChunkSize];
// The size of the checksum array here determines how much we can
// read in a single call to readChunk
this.checksum = new byte[CHUNKS_PER_READ * checksumSize];
this.checksumInts = ByteBuffer.wrap(checksum).asIntBuffer();
this.count = 0;
this.pos = 0;
}
@Override
final public boolean markSupported() {
return false;
}
@Override
final public void mark(int readlimit) {
}
@Override
final public void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
/* reset this FSInputChecker's state */
private void resetState() {
// invalidate buffer
count = 0;
pos = 0;
// reset Checksum
if (sum != null) {
sum.reset();
}
}
}
|
FSInputChecker
|
java
|
quarkusio__quarkus
|
integration-tests/openapi/src/test/java/io/quarkus/it/openapi/spring/LongTest.java
|
{
"start": 181,
"end": 7549
}
|
class ____ extends AbstractTest {
// Just Long
@Test
public void testJustLongInSpringServiceRequest() {
testServiceRequest("/spring/defaultContentType/justLong", TEXT_PLAIN, "0");
}
@Test
public void testJustLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/justLong", TEXT_PLAIN, "0");
}
@Test
public void testJustLongInSpringOpenAPIRequest() {
testOpenAPIRequest("/spring/defaultContentType/justLong", TEXT_PLAIN);
}
@Test
public void testJustLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/justLong", TEXT_PLAIN);
}
// Just long
@Test
public void testJustPrimitiveLongInSpringServiceRequest() {
testServiceRequest("/spring/defaultContentType/justPrimitiveLong", TEXT_PLAIN, "0");
}
@Test
public void testJustPrimitiveLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/justPrimitiveLong", TEXT_PLAIN, "0");
}
@Test
public void testJustPrimitiveLongInSpringOpenAPIRequest() {
testOpenAPIRequest("/spring/defaultContentType/justPrimitiveLong", TEXT_PLAIN);
}
@Test
public void testJustPrimitiveLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/justPrimitiveLong", TEXT_PLAIN);
}
// ResponseEntity<Long>
@Test
public void testResponseEntityLongInSpringServiceRequest() {
testServiceRequest("/spring/defaultContentType/responseEntityLong", TEXT_PLAIN, "0");
}
@Test
public void testResponseEntityLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/responseEntityLong", TEXT_PLAIN, "0");
}
@Test
public void testResponseEntityLongInSpringOpenAPIRequest() {
testOpenAPIRequest("/spring/defaultContentType/responseEntityLong", TEXT_PLAIN);
}
@Test
public void testResponseEntityLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/responseEntityLong", TEXT_PLAIN);
}
// Optional<Long>
//@Test
public void testOptionalLongInSpringServiceRequest() {
testServiceRequest("/spring/defaultContentType/optionalLong", TEXT_PLAIN, "0");
}
//@Test
public void testOptionalLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/optionalLong", TEXT_PLAIN, "0");
}
@Test
public void testOptionalLongInSpringOpenAPIRequest() {
testOpenAPIRequest("/spring/defaultContentType/optionalLong", TEXT_PLAIN);
}
@Test
public void testOptionalLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/optionalLong", TEXT_PLAIN);
}
// OptionalLong
//@Test
public void testOptionalPrimitiveLongInSpringServiceRequest() {
testServiceRequest("/spring/defaultContentType/optionalPrimitiveLong", TEXT_PLAIN, "0");
}
//@Test
public void testOptionalPrimitiveLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/optionalPrimitiveLong", TEXT_PLAIN, "0");
}
@Test
public void testOptionalPrimitiveLongInSpringOpenAPIRequest() {
testOpenAPIRequest("/spring/defaultContentType/optionalPrimitiveLong", TEXT_PLAIN);
}
@Test
public void testOptionalPrimitiveLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/optionalPrimitiveLong", TEXT_PLAIN);
}
// Uni<Long>
@Test
public void testUniLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/uniLong", TEXT_PLAIN, "0");
}
@Test
public void testUniLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/uniLong", TEXT_PLAIN);
}
// CompletionStage<Long>
@Test
public void testCompletionStageLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/completionStageLong", TEXT_PLAIN, "0");
}
@Test
public void testCompletionStageLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/completionStageLong", TEXT_PLAIN);
}
// CompletedFuture<Long>
@Test
public void testCompletedFutureLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/completedFutureLong", TEXT_PLAIN, "0");
}
@Test
public void testCompletedFutureLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/completionStageLong", TEXT_PLAIN);
}
// List<Long>
@Test
public void testListLongInSpringServiceRequest() {
testServiceRequest("/spring/defaultContentType/listLong", APPLICATION_JSON, "[0]");
}
@Test
public void testListLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/listLong", APPLICATION_JSON, "[0]");
}
@Test
public void testListLongInSpringOpenAPIRequest() {
testOpenAPIRequest("/spring/defaultContentType/listLong", APPLICATION_JSON);
}
@Test
public void testListLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/listLong", APPLICATION_JSON);
}
// Long[]
@Test
public void testArrayLongInSpringServiceRequest() {
testServiceRequest("/spring/defaultContentType/arrayLong", APPLICATION_JSON, "[0]");
}
@Test
public void testArrayLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/arrayLong", APPLICATION_JSON, "[0]");
}
@Test
public void testArrayLongInSpringOpenAPIRequest() {
testOpenAPIRequest("/spring/defaultContentType/arrayLong", APPLICATION_JSON);
}
@Test
public void testArrayLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/arrayLong", APPLICATION_JSON);
}
// long[]
@Test
public void testArrayPrimitiveLongInSpringServiceRequest() {
testServiceRequest("/spring/defaultContentType/arrayPrimitiveLong", APPLICATION_JSON, "[0]");
}
@Test
public void testArrayPrimitiveLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/arrayPrimitiveLong", APPLICATION_JSON, "[0]");
}
@Test
public void testArrayPrimitiveLongInSpringOpenAPIRequest() {
testOpenAPIRequest("/spring/defaultContentType/arrayPrimitiveLong", APPLICATION_JSON);
}
@Test
public void testArrayPrimitiveLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/arrayPrimitiveLong", APPLICATION_JSON);
}
// Map<Long, Long>
@Test
public void testMapLongInSpringServiceRequest() {
testServiceRequest("/spring/defaultContentType/mapLong", APPLICATION_JSON, "{\"0\":0}");
}
@Test
public void testMapLongInSpringServiceResponse() {
testServiceResponse("/spring/defaultContentType/mapLong", APPLICATION_JSON, "{\"0\":0}");
}
@Test
public void testMapLongInSpringOpenAPIRequest() {
testOpenAPIRequest("/spring/defaultContentType/mapLong", APPLICATION_JSON);
}
@Test
public void testMapLongInSpringOpenAPIResponse() {
testOpenAPIResponse("/spring/defaultContentType/mapLong", APPLICATION_JSON);
}
}
|
LongTest
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/tasks/CancellableTasksTracker.java
|
{
"start": 996,
"end": 7208
}
|
class ____<T> {
public CancellableTasksTracker() {}
private final Map<Long, T> byTaskId = ConcurrentCollections.newConcurrentMapWithAggressiveConcurrency();
private final Map<TaskId, Map<Long, T[]>> byParentTaskId = ConcurrentCollections.newConcurrentMapWithAggressiveConcurrency();
/**
* Gets the cancellable children of a parent task.
*
* Note: children of non-positive request IDs (e.g., -1) may be grouped together.
*/
public Stream<T> getChildrenByRequestId(TaskId parentTaskId, long childRequestId) {
Map<Long, T[]> byRequestId = byParentTaskId.get(parentTaskId);
if (byRequestId != null) {
T[] children = byRequestId.get(childRequestId);
if (children != null) {
return Arrays.stream(children);
}
}
return Stream.empty();
}
/**
* Add an item for the given task. Should only be called once for each task, and {@code item} must be unique per task too.
*/
@SuppressWarnings("unchecked")
public void put(Task task, long requestId, T item) {
final long taskId = task.getId();
if (task.getParentTaskId().isSet()) {
byParentTaskId.compute(task.getParentTaskId(), (taskKey, oldRequestIdMap) -> {
if (oldRequestIdMap == null) {
oldRequestIdMap = ConcurrentCollections.newConcurrentMapWithAggressiveConcurrency();
}
oldRequestIdMap.compute(requestId, (requestIdKey, oldValue) -> {
if (oldValue == null) {
final T[] newValue = (T[]) Array.newInstance(item.getClass(), 1);
newValue[0] = item;
return newValue;
} else {
return ArrayUtils.append(oldValue, item);
}
});
return oldRequestIdMap;
});
}
final T oldItem = byTaskId.put(taskId, item);
assert oldItem == null : "duplicate entry for task [" + taskId + "]";
}
/**
* Get the item that corresponds with the given task, or {@code null} if there is no such item.
*/
public T get(long id) {
return byTaskId.get(id);
}
/**
* Remove (and return) the item that corresponds with the given task and request ID. Return {@code null} if not present. Safe to call
* multiple times for each task. However, {@link #getByParent} may return this task even after a call to this method completes, if
* the removal is actually being completed by a concurrent call that's still ongoing.
*/
public T remove(Task task) {
final long taskId = task.getId();
final T oldItem = byTaskId.remove(taskId);
if (oldItem != null && task.getParentTaskId().isSet()) {
byParentTaskId.compute(task.getParentTaskId(), (taskKey, oldRequestIdMap) -> {
if (oldRequestIdMap == null) {
return null;
}
for (Long requestId : oldRequestIdMap.keySet()) {
oldRequestIdMap.compute(requestId, (requestIdKey, oldValue) -> {
if (oldValue == null) {
return null;
}
if (oldValue.length == 1) {
if (oldValue[0] == oldItem) {
return null;
} else {
return oldValue;
}
}
if (oldValue[0] == oldItem) {
return Arrays.copyOfRange(oldValue, 1, oldValue.length);
}
for (int i = 1; i < oldValue.length; i++) {
if (oldValue[i] == oldItem) {
final T[] newValue = Arrays.copyOf(oldValue, oldValue.length - 1);
System.arraycopy(oldValue, i + 1, newValue, i, oldValue.length - i - 1);
return newValue;
}
}
return oldValue;
});
}
if (oldRequestIdMap.keySet().isEmpty()) {
return null;
}
return oldRequestIdMap;
});
}
return oldItem;
}
/**
* Return a collection of all the tracked items. May be large. In the presence of concurrent calls to {@link #put} and {@link #remove}
* it behaves similarly to {@link ConcurrentHashMap#values()}.
*/
public Collection<T> values() {
return byTaskId.values();
}
/**
* Return a collection of all the tracked items with a given parent, which will include at least every item for which {@link #put}
* completed, but {@link #remove} hasn't started. May include some additional items for which all the calls to {@link #remove} that
* started before this method was called have not completed.
*/
public Stream<T> getByParent(TaskId parentTaskId) {
final Map<Long, T[]> byParent = byParentTaskId.get(parentTaskId);
if (byParent == null) {
return Stream.empty();
}
return byParent.values().stream().flatMap(Stream::of);
}
// assertion for tests, not an invariant but should eventually be true
boolean assertConsistent() {
// mustn't leak any items tracked by parent
assert byTaskId.isEmpty() == false || byParentTaskId.isEmpty();
// every by-parent value must be tracked by task too; the converse isn't true since we don't track values without a parent
final Set<T> byTaskValues = new HashSet<>(byTaskId.values());
byParentTaskId.values().forEach(byParentMap -> {
byParentMap.forEach((requestId, byParentArray) -> {
assert byParentArray.length > 0;
for (T t : byParentArray) {
assert byTaskValues.contains(t);
}
});
});
return true;
}
}
|
CancellableTasksTracker
|
java
|
apache__flink
|
flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/nfa/sharedbuffer/LockableTypeSerializerUpgradeTest.java
|
{
"start": 3515,
"end": 4265
}
|
class ____
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Lockable<String>> {
@Override
public TypeSerializer<Lockable<String>> createUpgradedSerializer() {
return new Lockable.LockableTypeSerializer<>(StringSerializer.INSTANCE);
}
@Override
public Condition<Lockable<String>> testDataCondition() {
return new Condition<>(value -> new Lockable<>("flink", 10).equals(value), "");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Lockable<String>>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
}
|
LockableTypeSerializerVerifier
|
java
|
alibaba__nacos
|
naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/OldDataOperation.java
|
{
"start": 853,
"end": 1227
}
|
enum ____ {
/**
* write ops.
*/
Write("Write"),
/**
* read ops.
*/
Read("Read"),
/**
* delete ops.
*/
Delete("Delete");
private final String desc;
OldDataOperation(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
}
|
OldDataOperation
|
java
|
quarkusio__quarkus
|
extensions/spring-boot-properties/deployment/src/main/java/io/quarkus/spring/boot/properties/deployment/YamlListObjectHandler.java
|
{
"start": 4207,
"end": 10308
}
|
class ____ extends io.quarkus.config.yaml.runtime.AbstractYamlObjectConverter<SomeClass_GeneratedListWrapper_fieldName> {
//
// @Override
// Map<String, String> getFieldNameMap() {
// Map<String, String> result = new HashMap<>();
// result.put("some_field", "someField");
// return result;
// }
//
// @Override
// Class<SomeClass_GeneratedListWrapper_fieldName> getClazz() {
// return SomeClass_GeneratedListWrapper_fieldName.class;
// }
// }
String wrapperConverterClassName = wrapperClassName + "_Converter";
try (ClassCreator cc = ClassCreator.builder().classOutput(classOutput)
.className(wrapperConverterClassName)
.superClass(ABSTRACT_YAML_CONVERTER_CNAME)
.signature(
String.format("L%s<L%s;>;", ABSTRACT_YAML_CONVERTER_CNAME.replace('.', '/'),
wrapperClassName.replace('.', '/')))
.build()) {
MethodCreator getClazz = cc.getMethodCreator("getClazz", Class.class).setModifiers(Modifier.PROTECTED);
getClazz.returnValue(getClazz.loadClassFromTCCL(wrapperClassName));
// generate the getFieldNameMap method by searching for fields annotated with @ConfigProperty
List<AnnotationInstance> configPropertyInstances = classInfo.annotationsMap().get(DotNames.CONFIG_PROPERTY);
Map<String, String> fieldNameMap = new HashMap<>();
if (configPropertyInstances != null) {
for (AnnotationInstance instance : configPropertyInstances) {
if (instance.target().kind() != AnnotationTarget.Kind.FIELD) {
continue;
}
AnnotationValue nameValue = instance.value("name");
if (nameValue != null) {
String nameValueStr = nameValue.asString();
if ((nameValueStr != null) && !nameValueStr.isEmpty()) {
String annotatedFieldName = instance.target().asField().name();
fieldNameMap.put(nameValueStr, annotatedFieldName);
}
}
}
}
if (!fieldNameMap.isEmpty()) {
MethodCreator getFieldNameMap = cc.getMethodCreator("getFieldNameMap", Map.class);
ResultHandle resultHandle = getFieldNameMap.newInstance(MethodDescriptor.ofConstructor(HashMap.class));
for (Map.Entry<String, String> entry : fieldNameMap.entrySet()) {
getFieldNameMap.invokeVirtualMethod(
MethodDescriptor.ofMethod(HashMap.class, "put", Object.class, Object.class, Object.class),
resultHandle, getFieldNameMap.load(entry.getKey()), getFieldNameMap.load(entry.getValue()));
}
getFieldNameMap.returnValue(resultHandle);
}
}
// use the generated converter to convert the string value into the wrapper
ResultHandle smallryeConfig = configPopulator.checkCast(configObject, SmallRyeConfig.class);
ResultHandle getValueHandle = configPopulator.invokeVirtualMethod(
MethodDescriptor.ofMethod(SmallRyeConfig.class, "getValue", Object.class, String.class, Converter.class),
smallryeConfig,
configPopulator.load(fullConfigName),
configPopulator.newInstance(MethodDescriptor.ofConstructor(wrapperConverterClassName)));
ResultHandle wrapperHandle = configPopulator.checkCast(getValueHandle, wrapperClassName);
//pull the actual value out of the wrapper
return configPopulator.invokeVirtualMethod(getterDesc, wrapperHandle);
}
private void validateClass(ClassInfo classInfo, Member member) {
if (Modifier.isInterface(classInfo.flags())) {
throw new IllegalArgumentException(
"The use of interfaces as the generic type of Lists fields / methods is not allowed. Offending field is '"
+ member.name() + "' of class '" + member.declaringClass().name().toString() + "'");
}
if (!classInfo.hasNoArgsConstructor()) {
throw new IllegalArgumentException(
String.format("Class '%s' which is used as %s in class '%s' must have a no-args constructor", classInfo,
member.phraseUsage(), member.declaringClass().name().toString()));
}
if (!Modifier.isPublic(classInfo.flags())) {
throw new IllegalArgumentException(
String.format("Class '%s' which is used as %s in class '%s' must be a public class", classInfo,
member.phraseUsage(), member.declaringClass().name().toString()));
}
}
private ClassInfo validateType(Type type) {
if (type.kind() != Type.Kind.PARAMETERIZED_TYPE) {
throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE);
}
ParameterizedType parameterizedType = (ParameterizedType) type;
if (!DotNames.LIST.equals(parameterizedType.name())) {
throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE);
}
if (parameterizedType.arguments().size() != 1) {
throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE);
}
ClassInfo classInfo = index.getClassByName(parameterizedType.arguments().get(0).name());
if (classInfo == null) {
throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE);
}
return classInfo;
}
private String forSignature(ClassInfo classInfo) {
return classInfo.name().toString().replace('.', '/');
}
/**
* An abstraction over Field and Method which we will use in order to keep the same code for Class and Interface cases
*/
static abstract
|
GeneratedInputsConverter
|
java
|
apache__flink
|
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/DataTypesTest.java
|
{
"start": 22849,
"end": 23067
}
|
class ____ {
public final String name;
public final int count;
public SimplePojo(String name, int count) {
this.name = name;
this.count = count;
}
}
}
|
SimplePojo
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/ser/TestEmptyClass.java
|
{
"start": 498,
"end": 545
}
|
class ____ { }
@JsonSerialize
static
|
Empty
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/StringFormatWithLiteralTest.java
|
{
"start": 6825,
"end": 7088
}
|
class ____ {
String test() {
return String.format("Formatting this integer: %d", 1);
}
}
""")
.addOutputLines(
"ExampleClass.java",
"""
public
|
ExampleClass
|
java
|
quarkusio__quarkus
|
extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/DeploymentResourceKind.java
|
{
"start": 1334,
"end": 3855
}
|
enum ____ {
Deployment(DEPLOYMENT, DEPLOYMENT_GROUP, DEPLOYMENT_VERSION),
@Deprecated(since = "OpenShift 4.14")
DeploymentConfig(DEPLOYMENT_CONFIG, DEPLOYMENT_CONFIG_GROUP, DEPLOYMENT_CONFIG_VERSION, OPENSHIFT),
StatefulSet(STATEFULSET, DEPLOYMENT_GROUP, DEPLOYMENT_VERSION),
Job(JOB, BATCH_GROUP, BATCH_VERSION),
CronJob(CRONJOB, BATCH_GROUP, BATCH_VERSION),
KnativeService(KNATIVE_SERVICE, KNATIVE_SERVICE_GROUP, KNATIVE_SERVICE_VERSION, KNATIVE);
private final String kind;
private final String group;
private final String version;
private final Set<String> requiredTargets;
DeploymentResourceKind(String kind, String group, String version, String... requiredTargets) {
this(kind, group, version, Set.of(requiredTargets));
}
DeploymentResourceKind(String kind, String group, String version, Set<String> requiredTargets) {
this.kind = kind;
this.group = group;
this.version = version;
this.requiredTargets = requiredTargets;
}
public static DeploymentResourceKind find(String apiGroup, String apiVersion, String kind) {
for (DeploymentResourceKind deploymentResourceKind : DeploymentResourceKind.values()) {
if (deploymentResourceKind.kind.equals(kind) && deploymentResourceKind.group.equals(apiGroup)
&& deploymentResourceKind.version.equals(apiVersion)) {
return deploymentResourceKind;
}
}
String apiGroupVersion = Strings.isNullOrEmpty(apiGroup) ? apiVersion : apiGroup + "/" + apiVersion;
throw new IllegalArgumentException("Could not find DeploymentResourceKind for " + apiGroupVersion + " " + kind);
}
public boolean isAvailalbleOn(String target) {
return requiredTargets.isEmpty() || requiredTargets.contains(target);
}
public boolean matches(HasMetadata resource) {
String resourceKind = HasMetadata.getKind(resource.getClass());
String resourceVersion = HasMetadata.getApiVersion(resource.getClass());
return resourceKind.equals(getKind()) && resourceVersion.equals(getApiVersion());
}
public String getKind() {
return kind;
}
public String getGroup() {
return group;
}
public String getVersion() {
return version;
}
public Set<String> getRequiredTargets() {
return requiredTargets;
}
public String getApiVersion() {
return group + "/" + version;
}
}
|
DeploymentResourceKind
|
java
|
micronaut-projects__micronaut-core
|
core-processor/src/main/java/io/micronaut/inject/ast/GenericElement.java
|
{
"start": 1031,
"end": 1268
}
|
interface ____ extends ClassElement {
/**
* The native type that represents the generic element.
* It is expected that the generic element representing `T` extends java.lang.Number`
* should be equal to the
|
GenericElement
|
java
|
micronaut-projects__micronaut-core
|
core-processor/src/main/java/io/micronaut/expressions/parser/ast/operator/unary/NegOperator.java
|
{
"start": 1348,
"end": 2031
}
|
class ____ extends UnaryOperator {
public NegOperator(ExpressionNode operand) {
super(operand);
}
@Override
public TypeDef doResolveType(@NonNull ExpressionVisitorContext ctx) {
TypeDef nodeType = super.doResolveType(ctx);
if (!isNumeric(nodeType)) {
throw new ExpressionCompilationException(
"Invalid unary '-' operation. Unary '-' can only be applied to numeric types");
}
return nodeType;
}
@Override
public ExpressionDef generateExpression(ExpressionCompilationContext ctx) {
return operand.compile(ctx).math(ExpressionDef.MathUnaryOperation.OpType.NEGATE);
}
}
|
NegOperator
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/observers/SerializedObserverTest.java
|
{
"start": 1234,
"end": 18688
}
|
class ____ extends RxJavaTest {
Observer<String> observer;
@Before
public void before() {
observer = TestHelper.mockObserver();
}
private Observer<String> serializedObserver(Observer<String> o) {
return new SerializedObserver<>(o);
}
@Test
public void singleThreadedBasic() {
TestSingleThreadedObservable onSubscribe = new TestSingleThreadedObservable("one", "two", "three");
Observable<String> w = Observable.unsafeCreate(onSubscribe);
Observer<String> aw = serializedObserver(observer);
w.subscribe(aw);
onSubscribe.waitToFinish();
verify(observer, times(1)).onNext("one");
verify(observer, times(1)).onNext("two");
verify(observer, times(1)).onNext("three");
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
// non-deterministic because unsubscribe happens after 'waitToFinish' releases
// so commenting out for now as this is not a critical thing to test here
// verify(s, times(1)).unsubscribe();
}
@Test
public void multiThreadedBasic() {
TestMultiThreadedObservable onSubscribe = new TestMultiThreadedObservable("one", "two", "three");
Observable<String> w = Observable.unsafeCreate(onSubscribe);
BusyObserver busySubscriber = new BusyObserver();
Observer<String> aw = serializedObserver(busySubscriber);
w.subscribe(aw);
onSubscribe.waitToFinish();
assertEquals(3, busySubscriber.onNextCount.get());
assertFalse(busySubscriber.onError);
assertTrue(busySubscriber.onComplete);
// non-deterministic because unsubscribe happens after 'waitToFinish' releases
// so commenting out for now as this is not a critical thing to test here
// verify(s, times(1)).unsubscribe();
// we can have concurrency ...
assertTrue(onSubscribe.maxConcurrentThreads.get() > 1);
// ... but the onNext execution should be single threaded
assertEquals(1, busySubscriber.maxConcurrentThreads.get());
}
@Test
public void multiThreadedWithNPE() throws InterruptedException {
TestMultiThreadedObservable onSubscribe = new TestMultiThreadedObservable("one", "two", "three", null);
Observable<String> w = Observable.unsafeCreate(onSubscribe);
BusyObserver busySubscriber = new BusyObserver();
Observer<String> aw = serializedObserver(busySubscriber);
w.subscribe(aw);
onSubscribe.waitToFinish();
busySubscriber.terminalEvent.await();
System.out.println("OnSubscribe maxConcurrentThreads: " + onSubscribe.maxConcurrentThreads.get() + " Observer maxConcurrentThreads: " + busySubscriber.maxConcurrentThreads.get());
// we can't know how many onNext calls will occur since they each run on a separate thread
// that depends on thread scheduling so 0, 1, 2 and 3 are all valid options
// assertEquals(3, busySubscriber.onNextCount.get());
assertTrue(busySubscriber.onNextCount.get() < 4);
assertTrue(busySubscriber.onError);
// no onComplete because onError was invoked
assertFalse(busySubscriber.onComplete);
// non-deterministic because unsubscribe happens after 'waitToFinish' releases
// so commenting out for now as this is not a critical thing to test here
//verify(s, times(1)).unsubscribe();
// we can have concurrency ...
assertTrue(onSubscribe.maxConcurrentThreads.get() > 1);
// ... but the onNext execution should be single threaded
assertEquals(1, busySubscriber.maxConcurrentThreads.get());
}
@Test
public void multiThreadedWithNPEinMiddle() {
int n = 10;
for (int i = 0; i < n; i++) {
TestMultiThreadedObservable onSubscribe = new TestMultiThreadedObservable("one", "two", "three", null,
"four", "five", "six", "seven", "eight", "nine");
Observable<String> w = Observable.unsafeCreate(onSubscribe);
BusyObserver busySubscriber = new BusyObserver();
Observer<String> aw = serializedObserver(busySubscriber);
w.subscribe(aw);
onSubscribe.waitToFinish();
System.out.println("OnSubscribe maxConcurrentThreads: " + onSubscribe.maxConcurrentThreads.get() + " Observer maxConcurrentThreads: " + busySubscriber.maxConcurrentThreads.get());
// we can have concurrency ...
assertTrue(onSubscribe.maxConcurrentThreads.get() > 1);
// ... but the onNext execution should be single threaded
assertEquals(1, busySubscriber.maxConcurrentThreads.get());
// this should not be the full number of items since the error should stop it before it completes all 9
System.out.println("onNext count: " + busySubscriber.onNextCount.get());
assertFalse(busySubscriber.onComplete);
assertTrue(busySubscriber.onError);
assertTrue(busySubscriber.onNextCount.get() < 9);
// no onComplete because onError was invoked
// non-deterministic because unsubscribe happens after 'waitToFinish' releases
// so commenting out for now as this is not a critical thing to test here
// verify(s, times(1)).unsubscribe();
}
}
/**
* A non-realistic use case that tries to expose thread-safety issues by throwing lots of out-of-order
* events on many threads.
*/
@Test
public void runOutOfOrderConcurrencyTest() {
ExecutorService tp = Executors.newFixedThreadPool(20);
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
TestConcurrencySubscriber tw = new TestConcurrencySubscriber();
// we need Synchronized + SafeObserver to handle synchronization plus life-cycle
Observer<String> w = serializedObserver(new SafeObserver<>(tw));
Future<?> f1 = tp.submit(new OnNextThread(w, 12000));
Future<?> f2 = tp.submit(new OnNextThread(w, 5000));
Future<?> f3 = tp.submit(new OnNextThread(w, 75000));
Future<?> f4 = tp.submit(new OnNextThread(w, 13500));
Future<?> f5 = tp.submit(new OnNextThread(w, 22000));
Future<?> f6 = tp.submit(new OnNextThread(w, 15000));
Future<?> f7 = tp.submit(new OnNextThread(w, 7500));
Future<?> f8 = tp.submit(new OnNextThread(w, 23500));
Future<?> f10 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f1, f2, f3, f4));
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// ignore
}
Future<?> f11 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
Future<?> f12 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
Future<?> f13 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
Future<?> f14 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
// // the next 4 onError events should wait on same as f10
Future<?> f15 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
Future<?> f16 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
Future<?> f17 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
Future<?> f18 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
waitOnThreads(f1, f2, f3, f4, f5, f6, f7, f8, f10, f11, f12, f13, f14, f15, f16, f17, f18);
@SuppressWarnings("unused")
int numNextEvents = tw.assertEvents(null); // no check of type since we don't want to test barging results here, just interleaving behavior
// System.out.println("Number of events executed: " + numNextEvents);
for (int i = 0; i < errors.size(); i++) {
TestHelper.assertUndeliverable(errors, i, RuntimeException.class);
}
} catch (Throwable e) {
fail("Concurrency test failed: " + e.getMessage());
e.printStackTrace();
} finally {
tp.shutdown();
try {
tp.awaitTermination(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
RxJavaPlugins.reset();
}
}
@Test
public void runConcurrencyTest() {
ExecutorService tp = Executors.newFixedThreadPool(20);
try {
TestConcurrencySubscriber tw = new TestConcurrencySubscriber();
// we need Synchronized + SafeObserver to handle synchronization plus life-cycle
Observer<String> w = serializedObserver(new SafeObserver<>(tw));
w.onSubscribe(Disposable.empty());
Future<?> f1 = tp.submit(new OnNextThread(w, 12000));
Future<?> f2 = tp.submit(new OnNextThread(w, 5000));
Future<?> f3 = tp.submit(new OnNextThread(w, 75000));
Future<?> f4 = tp.submit(new OnNextThread(w, 13500));
Future<?> f5 = tp.submit(new OnNextThread(w, 22000));
Future<?> f6 = tp.submit(new OnNextThread(w, 15000));
Future<?> f7 = tp.submit(new OnNextThread(w, 7500));
Future<?> f8 = tp.submit(new OnNextThread(w, 23500));
// 12000 + 5000 + 75000 + 13500 + 22000 + 15000 + 7500 + 23500 = 173500
Future<?> f10 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f1, f2, f3, f4, f5, f6, f7, f8));
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// ignore
}
waitOnThreads(f1, f2, f3, f4, f5, f6, f7, f8, f10);
int numNextEvents = tw.assertEvents(null); // no check of type since we don't want to test barging results here, just interleaving behavior
assertEquals(173500, numNextEvents);
// System.out.println("Number of events executed: " + numNextEvents);
} catch (Throwable e) {
fail("Concurrency test failed: " + e.getMessage());
e.printStackTrace();
} finally {
tp.shutdown();
try {
tp.awaitTermination(25000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Test that a notification does not get delayed in the queue waiting for the next event to push it through.
*
* @throws InterruptedException if the await is interrupted
*/
@Ignore("this is non-deterministic ... haven't figured out what's wrong with the test yet (benjchristensen: July 2014)")
@Test
public void notificationDelay() throws InterruptedException {
ExecutorService tp1 = Executors.newFixedThreadPool(1);
ExecutorService tp2 = Executors.newFixedThreadPool(1);
try {
int n = 10;
for (int i = 0; i < n; i++) {
final CountDownLatch firstOnNext = new CountDownLatch(1);
final CountDownLatch onNextCount = new CountDownLatch(2);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch running = new CountDownLatch(2);
TestObserverEx<String> to = new TestObserverEx<>(new DefaultObserver<String>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String t) {
firstOnNext.countDown();
// force it to take time when delivering so the second one is enqueued
try {
latch.await();
} catch (InterruptedException e) {
}
}
});
Observer<String> o = serializedObserver(to);
Future<?> f1 = tp1.submit(new OnNextThread(o, 1, onNextCount, running));
Future<?> f2 = tp2.submit(new OnNextThread(o, 1, onNextCount, running));
running.await(); // let one of the OnNextThread actually run before proceeding
firstOnNext.await();
Thread t1 = to.lastThread();
System.out.println("first onNext on thread: " + t1);
latch.countDown();
waitOnThreads(f1, f2);
// not completed yet
assertEquals(2, to.values().size());
Thread t2 = to.lastThread();
System.out.println("second onNext on thread: " + t2);
assertSame(t1, t2);
System.out.println(to.values());
o.onComplete();
System.out.println(to.values());
}
} finally {
tp1.shutdown();
tp2.shutdown();
}
}
/**
* Demonstrates thread starvation problem.
*
* No solution on this for now. Trade-off in this direction as per https://github.com/ReactiveX/RxJava/issues/998#issuecomment-38959474
* Probably need backpressure for this to work
*
* When using SynchronizedSubscriber we get this output:
*
* {@code p1: 18 p2: 68 =>} should be close to each other unless we have thread starvation
*
* When using SerializedObserver we get:
*
* {@code p1: 1 p2: 2445261 =>} should be close to each other unless we have thread starvation
*
* This demonstrates how SynchronizedSubscriber balances back and forth better, and blocks emission.
* The real issue in this example is the async buffer-bloat, so we need backpressure.
*
*
* @throws InterruptedException if the await is interrupted
*/
@Ignore("Demonstrates thread starvation problem. Read JavaDoc")
@Test
public void threadStarvation() throws InterruptedException {
TestObserver<String> to = new TestObserver<>(new DefaultObserver<String>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String t) {
// force it to take time when delivering
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
});
final Observer<String> o = serializedObserver(to);
AtomicInteger p1 = new AtomicInteger();
AtomicInteger p2 = new AtomicInteger();
o.onSubscribe(Disposable.empty());
DisposableObserver<String> as1 = new DisposableObserver<String>() {
@Override
public void onNext(String t) {
o.onNext(t);
}
@Override
public void onError(Throwable t) {
RxJavaPlugins.onError(t);
}
@Override
public void onComplete() {
}
};
DisposableObserver<String> as2 = new DisposableObserver<String>() {
@Override
public void onNext(String t) {
o.onNext(t);
}
@Override
public void onError(Throwable t) {
RxJavaPlugins.onError(t);
}
@Override
public void onComplete() {
}
};
infinite(p1).subscribe(as1);
infinite(p2).subscribe(as2);
Thread.sleep(100);
System.out.println("p1: " + p1.get() + " p2: " + p2.get() + " => should be close to each other unless we have thread starvation");
assertEquals(p1.get(), p2.get(), 10000); // fairly distributed within 10000 of each other
as1.dispose();
as2.dispose();
}
private static void waitOnThreads(Future<?>... futures) {
for (Future<?> f : futures) {
try {
f.get(20, TimeUnit.SECONDS);
} catch (Throwable e) {
System.err.println("Failed while waiting on future.");
e.printStackTrace();
}
}
}
private static Observable<String> infinite(final AtomicInteger produced) {
return Observable.unsafeCreate(new ObservableSource<String>() {
@Override
public void subscribe(Observer<? super String> observer) {
Disposable bs = Disposable.empty();
observer.onSubscribe(bs);
while (!bs.isDisposed()) {
observer.onNext("onNext");
produced.incrementAndGet();
}
}
}).subscribeOn(Schedulers.newThread());
}
/**
* A thread that will pass data to onNext.
*/
public static
|
SerializedObserverTest
|
java
|
quarkusio__quarkus
|
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/subresource/SubresourceLocatorHttpRootTest.java
|
{
"start": 305,
"end": 925
}
|
class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(PingResource.class, PingsResource.class, MyService.class, SuperPingResource.class)
.addAsResource(new StringAsset("quarkus.http.root-path=/foo"), "application.properties"));
@Test
public void testSubresourceLocator() {
RestAssured.when().get("/pings/do").then().body(Matchers.is("pong"));
RestAssured.when().get("/pings/super").then().body(Matchers.is("superpong"));
}
}
|
SubresourceLocatorHttpRootTest
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/MySqlObjectImpl.java
|
{
"start": 851,
"end": 1259
}
|
class ____ extends SQLObjectImpl implements MySqlObject {
@Override
protected void accept0(SQLASTVisitor v) {
if (v instanceof MySqlASTVisitor) {
accept0((MySqlASTVisitor) v);
} else {
throw new IllegalArgumentException("not support visitor type : " + v.getClass().getName());
}
}
public abstract void accept0(MySqlASTVisitor v);
}
|
MySqlObjectImpl
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/checkpointing/SavepointITCase.java
|
{
"start": 66962,
"end": 68068
}
|
class ____ extends RichFlatMapFunction<Integer, Integer> {
static final ValueStateDescriptor<Boolean> DESCRIPTOR =
new ValueStateDescriptor<>("seen", Boolean.class, false);
private static final long serialVersionUID = 1L;
private ValueState<Boolean> operatorState;
@Override
public void open(OpenContext openContext) {
operatorState = this.getRuntimeContext().getState(DESCRIPTOR);
}
@Override
public void flatMap(Integer value, Collector<Integer> out) throws Exception {
if (!operatorState.value()) {
out.collect(value);
operatorState.update(true);
}
if (30 == value) {
iterTestSnapshotWait[getRuntimeContext().getTaskInfo().getIndexOfThisSubtask()]
.trigger();
}
}
}
// ------------------------------------------------------------------------
// Utilities
// ------------------------------------------------------------------------
private static
|
DuplicateFilter
|
java
|
elastic__elasticsearch
|
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/Database.java
|
{
"start": 8890,
"end": 11658
}
|
enum ____ {
IP,
COUNTRY_CONFIDENCE,
COUNTRY_IN_EUROPEAN_UNION,
COUNTRY_ISO_CODE,
COUNTRY_NAME,
CONTINENT_CODE,
CONTINENT_NAME,
REGION_ISO_CODE,
REGION_NAME,
CITY_CONFIDENCE,
CITY_NAME,
TIMEZONE,
LOCATION,
ASN,
ORGANIZATION_NAME,
NETWORK,
HOSTING_PROVIDER,
TOR_EXIT_NODE,
ANONYMOUS_VPN,
ANONYMOUS,
PUBLIC_PROXY,
RESIDENTIAL_PROXY,
DOMAIN,
ISP,
ISP_ORGANIZATION_NAME,
MOBILE_COUNTRY_CODE,
MOBILE_NETWORK_CODE,
CONNECTION_TYPE,
USER_TYPE,
TYPE,
POSTAL_CODE,
POSTAL_CONFIDENCE,
ACCURACY_RADIUS,
HOSTING,
TOR,
PROXY,
RELAY,
VPN,
SERVICE,
REGISTERED_COUNTRY_IN_EUROPEAN_UNION,
REGISTERED_COUNTRY_ISO_CODE,
REGISTERED_COUNTRY_NAME;
/**
* Parses a string representation of a property into an actual Property instance. Not all properties that exist are
* valid for all kinds of databases, so this method validates the parsed value against the provided set of valid properties.
* <p>
* See {@link Database#parseProperties(List)} where this is used.
*
* @param validProperties the valid properties against which to validate the parsed property value
* @param value the string representation to parse
* @return a parsed, validated Property
* @throws IllegalArgumentException if the value does not parse as a Property or if the parsed Property is not
* in the passed-in validProperties set
*/
private static Property parseProperty(final Set<Property> validProperties, final String value) {
try {
Property property = valueOf(value.toUpperCase(Locale.ROOT));
if (validProperties.contains(property) == false) {
throw new IllegalArgumentException("invalid");
}
return property;
} catch (IllegalArgumentException e) {
// put the properties in natural order before throwing so that we have reliable error messages -- this is a little
// bit inefficient, but we only do this validation at processor construction time so the cost is practically immaterial
Property[] properties = validProperties.toArray(new Property[0]);
Arrays.sort(properties);
throw new IllegalArgumentException(
"illegal property value [" + value + "]. valid values are " + Arrays.toString(properties)
);
}
}
}
}
|
Property
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/internal/AbstractManagedType.java
|
{
"start": 2305,
"end": 23123
}
|
class ____<J>
extends AbstractDomainType<J>
implements SqmManagedDomainType<J>, AttributeContainer<J>, Serializable {
private final String hibernateTypeName;
private final @Nullable SqmManagedDomainType<? super J> supertype;
private final RepresentationMode representationMode;
private final JpaMetamodelImplementor metamodel;
private final Map<String, SqmSingularPersistentAttribute<J, ?>> declaredSingularAttributes = new LinkedHashMap<>();
private volatile Map<String, SqmPluralPersistentAttribute<J, ?, ?>> declaredPluralAttributes ;
private volatile Map<String, SqmPersistentAttribute<J, ?>> declaredConcreteGenericAttributes;
private final List<SqmManagedDomainType<? extends J>> subtypes = new ArrayList<>();
protected AbstractManagedType(
String hibernateTypeName,
JavaType<J> javaType,
ManagedDomainType<? super J> supertype,
JpaMetamodelImplementor metamodel) {
super( javaType );
this.hibernateTypeName = hibernateTypeName;
// TODO: fix callers and remove this typecast
this.supertype = (SqmManagedDomainType<? super J>) supertype;
this.metamodel = metamodel;
if ( supertype != null ) {
supertype.addSubType( this );
}
representationMode = representationMode( javaType );
inFlightAccess = createInFlightAccess();
}
private static <J> RepresentationMode representationMode(JavaType<J> javaType) {
return javaType instanceof DynamicModelJavaType
? RepresentationMode.MAP
: RepresentationMode.POJO;
}
protected InFlightAccess<J> createInFlightAccess() {
return new InFlightAccessImpl();
}
public JpaMetamodelImplementor getMetamodel() {
return metamodel;
}
@Override
public Class<J> getJavaType() {
return super.getJavaType();
}
@Override
public @Nullable SqmManagedDomainType<? super J> getSuperType() {
return supertype;
}
@Override
public Collection<? extends SqmManagedDomainType<? extends J>> getSubTypes() {
return subtypes;
}
@Override
public void addSubType(ManagedDomainType<? extends J> subType){
subtypes.add( (SqmManagedDomainType<? extends J>) subType );
}
@Override
public RepresentationMode getRepresentationMode() {
return representationMode;
}
@Override
public void visitAttributes(Consumer<? super PersistentAttribute<? super J, ?>> action) {
visitDeclaredAttributes( action );
if ( getSuperType() != null ) {
getSuperType().visitAttributes( action );
}
}
@Override
public void visitDeclaredAttributes(Consumer<? super PersistentAttribute<J, ?>> action) {
declaredSingularAttributes.values().forEach( action );
if ( declaredPluralAttributes != null ) {
declaredPluralAttributes.values().forEach( action );
}
}
@Override
public Set<Attribute<? super J, ?>> getAttributes() {
final Set<Attribute<? super J, ?>> attributes = new LinkedHashSet<>( getDeclaredAttributes() );
if ( getSuperType() != null ) {
attributes.addAll( getSuperType().getAttributes() );
}
return attributes;
}
@Override
public Set<Attribute<J, ?>> getDeclaredAttributes() {
final boolean isDeclaredSingularAttributesEmpty = isEmpty( declaredSingularAttributes );
final boolean isDeclaredPluralAttributes = isEmpty( declaredPluralAttributes );
if ( isDeclaredSingularAttributesEmpty && isDeclaredPluralAttributes ) {
return emptySet();
}
else if ( !isDeclaredSingularAttributesEmpty ) {
final Set<Attribute<J, ?>> attributes =
new LinkedHashSet<>( declaredSingularAttributes.values() );
if ( !isDeclaredPluralAttributes ) {
attributes.addAll( declaredPluralAttributes.values() );
}
return attributes;
}
else {
return new LinkedHashSet<>( declaredPluralAttributes.values() );
}
}
@Override
public SqmPersistentAttribute<? super J,?> getAttribute(String name) {
final var attribute = findAttribute( name );
checkNotNull( "Attribute", attribute, name );
return attribute;
}
@Override
public @Nullable SqmPersistentAttribute<? super J,?> findAttribute(String name) {
final var attribute = findDeclaredAttribute( name );
if ( attribute != null ) {
return attribute;
}
else {
return supertype != null ? supertype.findAttribute( name ) : null;
}
}
@Override
public final @Nullable SqmPersistentAttribute<? super J, ?> findAttributeInSuperTypes(String name) {
final var attribute = findDeclaredAttribute( name );
if ( attribute != null ) {
return attribute;
}
else {
return supertype != null ? supertype.findAttributeInSuperTypes( name ) : null;
}
}
@Override
public @Nullable SqmPersistentAttribute<?, ?> findSubTypesAttribute(String name) {
final var attribute = findDeclaredAttribute( name );
if ( attribute != null ) {
return attribute;
}
else {
for ( var subtype : subtypes ) {
final var subTypeAttribute = subtype.findSubTypesAttribute( name );
if ( subTypeAttribute != null ) {
return subTypeAttribute;
}
}
return null;
}
}
@Override
public @Nullable SqmPersistentAttribute<J,?> findDeclaredAttribute(String name) {
// try singular attribute
final var attribute = declaredSingularAttributes.get( name );
if ( attribute != null ) {
return attribute;
}
// next plural
else if ( declaredPluralAttributes != null ) {
return declaredPluralAttributes.get( name );
}
else {
return null;
}
}
@Override
public PersistentAttribute<J,?> getDeclaredAttribute(String name) {
final var attribute = findDeclaredAttribute( name );
checkNotNull( "Attribute", attribute, name );
return attribute;
}
private void checkNotNull(String attributeType, Attribute<?,?> attribute, String name) {
if ( attribute == null ) {
throw new IllegalArgumentException(
String.format(
"Unable to locate %s with the given name [%s] on this ManagedType [%s]",
attributeType,
name,
getTypeName()
)
);
}
}
@Override
public String getTypeName() {
return hibernateTypeName;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Singular attributes
@Override
public Set<SingularAttribute<? super J, ?>> getSingularAttributes() {
final Set<SingularAttribute<? super J, ?>> attributes =
new HashSet<>( declaredSingularAttributes.values() );
if ( getSuperType() != null ) {
attributes.addAll( getSuperType().getSingularAttributes() );
}
return attributes;
}
@Override
public Set<SingularAttribute<J, ?>> getDeclaredSingularAttributes() {
return new HashSet<>( declaredSingularAttributes.values() );
}
@Override
public SingularPersistentAttribute<? super J, ?> getSingularAttribute(String name) {
final var attribute = findSingularAttribute( name );
checkNotNull( "SingularAttribute", attribute, name );
return attribute;
}
@Override
public @Nullable SqmSingularPersistentAttribute<? super J, ?> findSingularAttribute(String name) {
final var attribute = findDeclaredSingularAttribute( name );
return attribute == null && getSuperType() != null
? getSuperType().findSingularAttribute( name )
: attribute;
}
@Override
public <Y> SqmSingularPersistentAttribute<? super J, Y> getSingularAttribute(String name, Class<Y> type) {
return checkTypeForSingleAttribute( findSingularAttribute( name ), name, type );
}
@Override
public SingularAttribute<J, ?> getDeclaredSingularAttribute(String name) {
final var attribute = findDeclaredSingularAttribute( name );
checkNotNull( "SingularAttribute", attribute, name );
return attribute;
}
@Override
public @Nullable SqmSingularPersistentAttribute<J, ?> findDeclaredSingularAttribute(String name) {
return declaredSingularAttributes.get( name );
}
@Override
public <Y> SingularPersistentAttribute<J, Y> getDeclaredSingularAttribute(String name, Class<Y> javaType) {
return checkTypeForSingleAttribute( findDeclaredSingularAttribute( name ), name, javaType );
}
private <K,Y> SqmSingularPersistentAttribute<K,Y> checkTypeForSingleAttribute(
SqmSingularPersistentAttribute<K,?> attribute,
String name,
Class<Y> javaType) {
if ( attribute == null || !hasMatchingReturnType( attribute, javaType ) ) {
throw new IllegalArgumentException(
"SingularAttribute named " + name
+ ( javaType != null ? " and of type " + javaType.getName() : "" )
+ " is not present"
);
}
else {
@SuppressWarnings("unchecked")
final SqmSingularPersistentAttribute<K, Y> narrowed =
(SqmSingularPersistentAttribute<K, Y>) attribute;
return narrowed;
}
}
private <T, Y> boolean hasMatchingReturnType(SingularAttribute<T, ?> attribute, Class<Y> javaType) {
return javaType == null
|| attribute.getJavaType().equals( javaType )
|| isPrimitiveVariant( attribute, javaType );
}
protected <Y> boolean isPrimitiveVariant(SingularAttribute<?,?> attribute, Class<Y> javaType) {
if ( attribute != null ) {
final Class<?> declaredType = attribute.getJavaType();
if ( declaredType.isPrimitive() ) {
return ( Boolean.class.equals( javaType ) && Boolean.TYPE.equals( declaredType ) )
|| ( Character.class.equals( javaType ) && Character.TYPE.equals( declaredType ) )
|| ( Byte.class.equals( javaType ) && Byte.TYPE.equals( declaredType ) )
|| ( Short.class.equals( javaType ) && Short.TYPE.equals( declaredType ) )
|| ( Integer.class.equals( javaType ) && Integer.TYPE.equals( declaredType ) )
|| ( Long.class.equals( javaType ) && Long.TYPE.equals( declaredType ) )
|| ( Float.class.equals( javaType ) && Float.TYPE.equals( declaredType ) )
|| ( Double.class.equals( javaType ) && Double.TYPE.equals( declaredType ) );
}
if ( javaType.isPrimitive() ) {
return ( Boolean.class.equals( declaredType ) && Boolean.TYPE.equals( javaType ) )
|| ( Character.class.equals( declaredType ) && Character.TYPE.equals( javaType ) )
|| ( Byte.class.equals( declaredType ) && Byte.TYPE.equals( javaType ) )
|| ( Short.class.equals( declaredType ) && Short.TYPE.equals( javaType ) )
|| ( Integer.class.equals( declaredType ) && Integer.TYPE.equals( javaType ) )
|| ( Long.class.equals( declaredType ) && Long.TYPE.equals( javaType ) )
|| ( Float.class.equals( declaredType ) && Float.TYPE.equals( javaType ) )
|| ( Double.class.equals( declaredType ) && Double.TYPE.equals( javaType ) );
}
}
return false;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Plural attributes
@Override
public Set<PluralAttribute<? super J, ?, ?>> getPluralAttributes() {
final Set<PluralAttribute<? super J, ?, ?>> attributes =
declaredPluralAttributes == null
? new HashSet<>()
: new HashSet<>( declaredPluralAttributes.values() );
if ( getSuperType() != null ) {
attributes.addAll( getSuperType().getPluralAttributes() );
}
return attributes;
}
@Override
public Set<PluralAttribute<J, ?, ?>> getDeclaredPluralAttributes() {
return declaredPluralAttributes == null
? emptySet()
: new HashSet<>( declaredPluralAttributes.values() );
}
@Override
public @Nullable SqmPluralPersistentAttribute<? super J, ?, ?> findPluralAttribute(String name) {
var attribute = findDeclaredPluralAttribute( name );
if ( attribute != null ) {
return attribute;
}
else if ( getSuperType() != null ) {
return getSuperType().findPluralAttribute( name );
}
else {
return null;
}
}
@Override
public @Nullable SqmPluralPersistentAttribute<J, ?, ?> findDeclaredPluralAttribute(String name) {
return declaredPluralAttributes == null ? null : declaredPluralAttributes.get( name );
}
private <E> void checkTypeForPluralAttributes(
String attributeType,
PluralAttribute<?,?,?> attribute,
String name,
Class<E> elementType,
PluralAttribute.CollectionType collectionType) {
if ( attribute == null
|| elementType != null && !attribute.getBindableJavaType().equals( elementType )
|| attribute.getCollectionType() != collectionType ) {
throw new IllegalArgumentException(
attributeType + " named " + name
+ ( elementType != null ? " and of element type " + elementType : "" )
+ " is not present"
);
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Generic attributes
@Override
public @Nullable SqmPersistentAttribute<? super J, ?> findConcreteGenericAttribute(String name) {
final var attribute = findDeclaredConcreteGenericAttribute( name );
return attribute == null && getSuperType() != null
? getSuperType().findDeclaredConcreteGenericAttribute( name )
: attribute;
}
@Override
public @Nullable SqmPersistentAttribute<J, ?> findDeclaredConcreteGenericAttribute(String name) {
return declaredConcreteGenericAttributes == null ? null : declaredConcreteGenericAttributes.get( name );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Bags
@Override
@SuppressWarnings("unchecked")
public BagPersistentAttribute<? super J, ?> getCollection(String name) {
var attribute = findPluralAttribute( name );
if ( attribute == null && getSuperType() != null ) {
attribute = getSuperType().findPluralAttribute( name );
}
basicCollectionCheck( attribute, name );
return (BagPersistentAttribute<J, ?>) attribute;
}
private void basicCollectionCheck(PluralAttribute<? super J, ?, ?> attribute, String name) {
checkNotNull( "CollectionAttribute", attribute, name );
if ( ! BagPersistentAttribute.class.isAssignableFrom( attribute.getClass() ) ) {
throw new IllegalArgumentException( name + " is not a CollectionAttribute: " + attribute.getClass() );
}
}
@Override
@SuppressWarnings( "unchecked")
public CollectionAttribute<J, ?> getDeclaredCollection(String name) {
final var attribute = findDeclaredPluralAttribute( name );
basicCollectionCheck( attribute, name );
return ( CollectionAttribute<J, ?> ) attribute;
}
@Override
@SuppressWarnings("unchecked")
public <E> BagPersistentAttribute<? super J, E> getCollection(String name, Class<E> elementType) {
final var attribute = findPluralAttribute( name );
checkCollectionElementType( attribute, name, elementType );
return (BagPersistentAttribute<? super J, E>) attribute;
}
private <E> void checkCollectionElementType(PluralAttribute<?,?,?> attribute, String name, Class<E> elementType) {
checkTypeForPluralAttributes( "CollectionAttribute", attribute, name, elementType,
PluralAttribute.CollectionType.COLLECTION );
}
@Override
@SuppressWarnings("unchecked")
public <E> CollectionAttribute<J, E> getDeclaredCollection(String name, Class<E> elementType) {
final var attribute = findDeclaredPluralAttribute( name );
checkCollectionElementType( attribute, name, elementType );
return (CollectionAttribute<J, E>) attribute;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Set attributes
@Override
@SuppressWarnings("unchecked")
public SetPersistentAttribute<? super J, ?> getSet(String name) {
final var attribute = findPluralAttribute( name );
basicSetCheck( attribute, name );
return (SetPersistentAttribute<? super J, ?>) attribute;
}
private void basicSetCheck(PluralAttribute<? super J, ?, ?> attribute, String name) {
checkNotNull( "SetAttribute", attribute, name );
if ( ! SetPersistentAttribute.class.isAssignableFrom( attribute.getClass() ) ) {
throw new IllegalArgumentException( name + " is not a SetAttribute: " + attribute.getClass() );
}
}
@Override
@SuppressWarnings( "unchecked")
public SetPersistentAttribute<J, ?> getDeclaredSet(String name) {
final var attribute = findDeclaredPluralAttribute( name );
basicSetCheck( attribute, name );
return (SetPersistentAttribute<J, ?>) attribute;
}
@Override
@SuppressWarnings("unchecked")
public <E> SetAttribute<? super J, E> getSet(String name, Class<E> elementType) {
final var attribute = findPluralAttribute( name );
checkSetElementType( attribute, name, elementType );
return (SetAttribute<? super J, E>) attribute;
}
private <E> void checkSetElementType(PluralAttribute<? super J, ?, ?> attribute, String name, Class<E> elementType) {
checkTypeForPluralAttributes( "SetAttribute", attribute, name, elementType,
PluralAttribute.CollectionType.SET );
}
@Override
@SuppressWarnings("unchecked")
public <E> SetAttribute<J, E> getDeclaredSet(String name, Class<E> elementType) {
final var attribute = findDeclaredPluralAttribute( name );
checkSetElementType( attribute, name, elementType );
return (SetAttribute<J, E>) attribute;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// List attributes
@Override
@SuppressWarnings("unchecked")
public ListPersistentAttribute<? super J, ?> getList(String name) {
final var attribute = findPluralAttribute( name );
basicListCheck( attribute, name );
return (ListPersistentAttribute<? super J, ?>) attribute;
}
private void basicListCheck(PluralAttribute<? super J, ?, ?> attribute, String name) {
checkNotNull( "ListAttribute", attribute, name );
if ( ! ListPersistentAttribute.class.isAssignableFrom( attribute.getClass() ) ) {
throw new IllegalArgumentException( name + " is not a ListAttribute: " + attribute.getClass() );
}
}
@Override
@SuppressWarnings("unchecked")
public ListPersistentAttribute<J, ?> getDeclaredList(String name) {
final var attribute = findDeclaredPluralAttribute( name );
basicListCheck( attribute, name );
return (ListPersistentAttribute<J, ?>) attribute;
}
@Override
@SuppressWarnings("unchecked")
public <E> ListAttribute<? super J, E> getList(String name, Class<E> elementType) {
final var attribute = findPluralAttribute( name );
checkListElementType( attribute, name, elementType );
return ( ListAttribute<? super J, E> ) attribute;
}
private <E> void checkListElementType(PluralAttribute<? super J, ?, ?> attribute, String name, Class<E> elementType) {
checkTypeForPluralAttributes( "ListAttribute", attribute, name, elementType, PluralAttribute.CollectionType.LIST );
}
@Override
@SuppressWarnings("unchecked")
public <E> ListAttribute<J, E> getDeclaredList(String name, Class<E> elementType) {
final var attribute = findDeclaredPluralAttribute( name );
checkListElementType( attribute, name, elementType );
return ( ListAttribute<J, E> ) attribute;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Map attributes
@Override
@SuppressWarnings("unchecked")
public MapPersistentAttribute<? super J, ?, ?> getMap(String name) {
final var attribute = findPluralAttribute( name );
basicMapCheck( attribute, name );
return (MapPersistentAttribute<? super J, ?, ?>) attribute;
}
private void basicMapCheck(PluralAttribute<? super J, ?, ?> attribute, String name) {
checkNotNull( "MapAttribute", attribute, name );
if ( ! MapAttribute.class.isAssignableFrom( attribute.getClass() ) ) {
throw new IllegalArgumentException( name + " is not a MapAttribute: " + attribute.getClass() );
}
}
@Override
@SuppressWarnings("unchecked")
public MapPersistentAttribute<J, ?, ?> getDeclaredMap(String name) {
final var attribute = findDeclaredPluralAttribute( name );
basicMapCheck( attribute, name );
return (MapPersistentAttribute<J, ?, ?>) attribute;
}
@Override
@SuppressWarnings("unchecked")
public <K, V> MapAttribute<? super J, K, V> getMap(String name, Class<K> keyType, Class<V> valueType) {
final var attribute = findPluralAttribute( name );
checkMapValueType( attribute, name, valueType );
final var mapAttribute = (MapAttribute<? super J, K, V>) attribute;
checkMapKeyType( mapAttribute, name, keyType );
return mapAttribute;
}
private <V> void checkMapValueType(PluralAttribute<? super J, ?, ?> attribute, String name, Class<V> valueType) {
checkTypeForPluralAttributes( "MapAttribute", attribute, name, valueType, PluralAttribute.CollectionType.MAP);
}
private <K,V> void checkMapKeyType(MapAttribute<? super J, K, V> mapAttribute, String name, Class<K> keyType) {
if ( mapAttribute.getKeyJavaType() != keyType ) {
throw new IllegalArgumentException( "MapAttribute named " + name + " does not support a key of type " + keyType );
}
}
@Override
@SuppressWarnings("unchecked")
public <K, V> MapAttribute<J, K, V> getDeclaredMap(String name, Class<K> keyType, Class<V> valueType) {
final var attribute = findDeclaredPluralAttribute( name );
checkMapValueType( attribute, name, valueType );
final var mapAttribute = (MapAttribute<J, K, V>) attribute;
checkMapKeyType( mapAttribute, name, keyType );
return mapAttribute;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Serialization
@Serial
protected Object writeReplace() throws ObjectStreamException {
return new SerialForm( metamodel, getJavaType() );
}
private static
|
AbstractManagedType
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TempDirectoryPreconditionTests.java
|
{
"start": 4243,
"end": 4475
}
|
class ____ {
@Test
void validTempDirType(@TempDir File file, @TempDir Path path) {
}
@Test
void invalidTempDirType(@TempDir String text) {
}
}
@SuppressWarnings("JUnitMalformedDeclaration")
static
|
ParameterTypeTestCase
|
java
|
quarkusio__quarkus
|
test-framework/common/src/main/java/io/quarkus/test/common/NativeImageLauncher.java
|
{
"start": 40,
"end": 146
}
|
interface ____ extends ArtifactLauncher<NativeImageLauncher.NativeImageInitContext> {
|
NativeImageLauncher
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultExecutionDeployer.java
|
{
"start": 14775,
"end": 15975
}
|
class ____ {
private final Execution execution;
private final ExecutionSlotAssignment executionSlotAssignment;
private final ExecutionVertexVersion requiredVertexVersion;
ExecutionDeploymentHandle(
final Execution execution,
final ExecutionSlotAssignment executionSlotAssignment,
final ExecutionVertexVersion requiredVertexVersion) {
this.execution = checkNotNull(execution);
this.executionSlotAssignment = checkNotNull(executionSlotAssignment);
this.requiredVertexVersion = checkNotNull(requiredVertexVersion);
}
Execution getExecution() {
return execution;
}
ExecutionAttemptID getExecutionAttemptId() {
return execution.getAttemptId();
}
CompletableFuture<LogicalSlot> getLogicalSlotFuture() {
return executionSlotAssignment.getLogicalSlotFuture();
}
ExecutionVertexVersion getRequiredVertexVersion() {
return requiredVertexVersion;
}
}
/** Factory to instantiate the {@link DefaultExecutionDeployer}. */
public static
|
ExecutionDeploymentHandle
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/ParcelableCreatorNegativeCases.java
|
{
"start": 3407,
"end": 4028
}
|
class ____ implements Parcelable {
public static final Parcelable.Creator CREATOR =
new Parcelable.Creator() {
public PublicParcelableWithRawCreatorClass createFromParcel(Parcel in) {
return new PublicParcelableWithRawCreatorClass();
}
public PublicParcelableWithRawCreatorClass[] newArray(int size) {
return new PublicParcelableWithRawCreatorClass[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
// no op
}
}
}
|
PublicParcelableWithRawCreatorClass
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/health/node/action/HealthNodeNotDiscoveredException.java
|
{
"start": 841,
"end": 1226
}
|
class ____ extends ElasticsearchException {
public HealthNodeNotDiscoveredException() {
super("No health node was discovered");
}
public HealthNodeNotDiscoveredException(StreamInput in) throws IOException {
super(in);
}
@Override
public RestStatus status() {
return RestStatus.SERVICE_UNAVAILABLE;
}
}
|
HealthNodeNotDiscoveredException
|
java
|
google__dagger
|
javatests/dagger/hilt/android/MultiTestRoot1Test.java
|
{
"start": 4857,
"end": 4929
}
|
class ____ {}
@Module
@InstallIn(SingletonComponent.class)
public
|
Qux
|
java
|
mapstruct__mapstruct
|
processor/src/main/java/org/mapstruct/ap/internal/model/assignment/StreamAdderWrapper.java
|
{
"start": 645,
"end": 2376
}
|
class ____ extends AssignmentWrapper {
private final List<Type> thrownTypesToExclude;
private final Type adderType;
public StreamAdderWrapper(Assignment rhs,
List<Type> thrownTypesToExclude,
boolean fieldAssignment,
String targetPropertyName ) {
super( rhs, fieldAssignment );
this.thrownTypesToExclude = thrownTypesToExclude;
String desiredName = Nouns.singularize( targetPropertyName );
rhs.setSourceLocalVarName( rhs.createUniqueVarName( desiredName ) );
adderType = first( getSourceType().determineTypeArguments( Stream.class ) );
}
@Override
public List<Type> getThrownTypes() {
List<Type> parentThrownTypes = super.getThrownTypes();
List<Type> result = new ArrayList<>( parentThrownTypes );
for ( Type thrownTypeToExclude : thrownTypesToExclude ) {
for ( Type parentExceptionType : parentThrownTypes ) {
if ( parentExceptionType.isAssignableTo( thrownTypeToExclude ) ) {
result.remove( parentExceptionType );
}
}
}
return result;
}
public Type getAdderType() {
return adderType;
}
public boolean isIncludeSourceNullCheck() {
return true;
}
public boolean isSetExplicitlyToNull() {
return false;
}
public boolean isSetExplicitlyToDefault() {
return false;
}
@Override
public Set<Type> getImportTypes() {
Set<Type> imported = new HashSet<>( super.getImportTypes() );
imported.add( adderType.getTypeBound() );
return imported;
}
}
|
StreamAdderWrapper
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/throwable/ThrowableAssert_hasRootCauseExactlyInstanceOf_Test.java
|
{
"start": 839,
"end": 1263
}
|
class ____ extends ThrowableAssertBaseTest {
@Override
protected ThrowableAssert<Throwable> invoke_api_method() {
return assertions.hasRootCauseExactlyInstanceOf(Exception.class);
}
@Override
protected void verify_internal_effects() {
verify(throwables).assertHasRootCauseExactlyInstanceOf(getInfo(assertions), getActual(assertions), Exception.class);
}
}
|
ThrowableAssert_hasRootCauseExactlyInstanceOf_Test
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/validation/DataBinderTests.java
|
{
"start": 89253,
"end": 90165
}
|
class ____ implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return TestBean.class.isAssignableFrom(clazz);
}
@Override
public void validate(@Nullable Object obj, Errors errors) {
TestBean tb = (TestBean) obj;
if (tb.getAge() < 32) {
errors.rejectValue("age", "TOO_YOUNG", "simply too young");
}
if (tb.getAge() % 2 == 0) {
errors.rejectValue("age", "AGE_NOT_ODD", "your age isn't odd");
}
if (tb.getName() == null || !tb.getName().equals("Rod")) {
errors.rejectValue("name", "NOT_ROD", "are you sure you're not Rod?");
}
if (tb.getTouchy() == null || !tb.getTouchy().equals(tb.getName())) {
errors.reject("NAME_TOUCHY_MISMATCH", "name and touchy do not match");
}
if (tb.getAge() == 0) {
errors.reject("GENERAL_ERROR", new String[] {"arg"}, "msg");
}
}
}
@SuppressWarnings("unused")
private static
|
TestBeanValidator
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/operators/SourceOperatorLatencyMetricsTest.java
|
{
"start": 1880,
"end": 6485
}
|
class ____ {
private static final long MAX_PROCESSING_TIME = 100L;
private static final long LATENCY_MARK_INTERVAL = 10L;
/** Verifies that by default no latency metrics are emitted. */
@Test
void testLatencyMarkEmissionDisabled() throws Exception {
testLatencyMarkEmission(false, new Configuration(), new ExecutionConfig());
}
/** Verifies that latency metrics can be enabled via the {@link ExecutionConfig}. */
@Test
void testLatencyMarkEmissionEnabledViaExecutionConfig() throws Exception {
Configuration taskConfiguration = new Configuration();
ExecutionConfig executionConfig = new ExecutionConfig();
executionConfig.setLatencyTrackingInterval(LATENCY_MARK_INTERVAL);
testLatencyMarkEmission(true, taskConfiguration, executionConfig);
}
/** Verifies that latency metrics can be enabled via the configuration. */
@Test
void testLatencyMarkEmissionEnabledViaFlinkConfig() throws Exception {
Configuration taskConfiguration = new Configuration();
taskConfiguration.set(
MetricOptions.LATENCY_INTERVAL, Duration.ofMillis(LATENCY_MARK_INTERVAL));
ExecutionConfig executionConfig = new ExecutionConfig();
testLatencyMarkEmission(true, taskConfiguration, executionConfig);
}
/**
* Verifies that latency metrics can be enabled via the {@link ExecutionConfig} even if they are
* disabled via the configuration.
*/
@Test
void testLatencyMarkEmissionEnabledOverrideViaExecutionConfig() throws Exception {
Configuration taskConfiguration = new Configuration();
taskConfiguration.set(MetricOptions.LATENCY_INTERVAL, Duration.ofMillis(0L));
ExecutionConfig executionConfig = new ExecutionConfig();
executionConfig.setLatencyTrackingInterval(LATENCY_MARK_INTERVAL);
testLatencyMarkEmission(true, taskConfiguration, executionConfig);
}
/**
* Verifies that latency metrics can be disabled via the {@link ExecutionConfig} even if they
* are enabled via the configuration.
*/
@Test
void testLatencyMarkEmissionDisabledOverrideViaExecutionConfig() throws Exception {
Configuration taskConfiguration = new Configuration();
taskConfiguration.set(
MetricOptions.LATENCY_INTERVAL, Duration.ofMillis(LATENCY_MARK_INTERVAL));
ExecutionConfig executionConfig = new ExecutionConfig();
executionConfig.setLatencyTrackingInterval(0);
testLatencyMarkEmission(false, taskConfiguration, executionConfig);
}
private void testLatencyMarkEmission(
boolean shouldExpectLatencyMarkers,
Configuration taskManagerConfig,
ExecutionConfig executionConfig)
throws Exception {
try (SourceOperatorTestHarness testHarness =
new SourceOperatorTestHarness(
new SourceOperatorFactory(
new MockSource(Boundedness.CONTINUOUS_UNBOUNDED, 1),
WatermarkStrategy.noWatermarks()),
new MockEnvironmentBuilder()
.setTaskManagerRuntimeInfo(
new TestingTaskManagerRuntimeInfo(taskManagerConfig))
.setExecutionConfig(executionConfig)
.build())) {
testHarness.open();
testHarness.setup();
for (long processingTime = 0; processingTime <= MAX_PROCESSING_TIME; processingTime++) {
testHarness.getProcessingTimeService().setCurrentTime(processingTime);
testHarness.emitNext();
}
List<LatencyMarker> expectedOutput = new ArrayList<>();
if (!shouldExpectLatencyMarkers) {
assertThat(testHarness.getOutput()).isEmpty();
} else {
expectedOutput.add(
new LatencyMarker(1, testHarness.getOperator().getOperatorID(), 0));
for (long markedTime = LATENCY_MARK_INTERVAL;
markedTime <= MAX_PROCESSING_TIME;
markedTime += LATENCY_MARK_INTERVAL) {
expectedOutput.add(
new LatencyMarker(
markedTime, testHarness.getOperator().getOperatorID(), 0));
}
assertThat(testHarness.getOutput()).containsExactlyElementsOf(expectedOutput);
}
}
}
}
|
SourceOperatorLatencyMetricsTest
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/java/typeutils/TypeExtractorInputFormatsTest.java
|
{
"start": 5372,
"end": 5759
}
|
class ____ extends GenericInputFormat<Short> {
@Override
public boolean reachedEnd() {
return false;
}
@Override
public Short nextRecord(Short reuse) {
return null;
}
}
// --------------------------------------------------------------------------------------------
public static final
|
DerivedInputFormat
|
java
|
hibernate__hibernate-orm
|
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/accesstype/Building.java
|
{
"start": 251,
"end": 435
}
|
class ____ extends Area {
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
|
Building
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/IncompatibleArgumentTypeTest.java
|
{
"start": 1548,
"end": 1791
}
|
class ____<B> {
<C> C remove(@CompatibleWith("B") Object b, @CompatibleWith("C") Object c) {
return null;
}
<C> C varargs(@CompatibleWith("B") Object b, @CompatibleWith("C") Object... cs) {
return (C) cs[0];
}
}
|
A
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/TestPropertySourceTestClassScopedExtensionContextNestedTests.java
|
{
"start": 2408,
"end": 2756
}
|
class ____ {
@Autowired
Environment env2;
@Test
void propertiesInEnvironment() {
assertThat(env1.getProperty("p1")).isEqualTo("v1");
assertThat(env2.getProperty("p1")).isEqualTo("v1");
assertThat(env1).isSameAs(env2);
}
}
@Nested
@SpringJUnitConfig(Config.class)
@TestPropertySource(properties = "p2 = v2")
|
InheritedCfgTests
|
java
|
netty__netty
|
codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java
|
{
"start": 26918,
"end": 30829
}
|
class ____ extends WritabilityMonitor implements Http2StreamVisitor {
private final Listener listener;
ListenerWritabilityMonitor(Listener listener) {
this.listener = listener;
}
@Override
public boolean visit(Http2Stream stream) throws Http2Exception {
FlowState state = state(stream);
if (isWritable(state) != state.markedWritability()) {
notifyWritabilityChanged(state);
}
return true;
}
@Override
void windowSize(FlowState state, int initialWindowSize) {
super.windowSize(state, initialWindowSize);
try {
checkStateWritability(state);
} catch (Http2Exception e) {
throw new RuntimeException("Caught unexpected exception from window", e);
}
}
@Override
void incrementWindowSize(FlowState state, int delta) throws Http2Exception {
super.incrementWindowSize(state, delta);
checkStateWritability(state);
}
@Override
void initialWindowSize(int newWindowSize) throws Http2Exception {
super.initialWindowSize(newWindowSize);
if (isWritableConnection()) {
// If the write operation does not occur we still need to check all streams because they
// may have transitioned from writable to not writable.
checkAllWritabilityChanged();
}
}
@Override
void enqueueFrame(FlowState state, FlowControlled frame) throws Http2Exception {
super.enqueueFrame(state, frame);
checkConnectionThenStreamWritabilityChanged(state);
}
@Override
void stateCancelled(FlowState state) {
try {
checkConnectionThenStreamWritabilityChanged(state);
} catch (Http2Exception e) {
throw new RuntimeException("Caught unexpected exception from checkAllWritabilityChanged", e);
}
}
@Override
void channelWritabilityChange() throws Http2Exception {
if (connectionState.markedWritability() != isChannelWritable()) {
checkAllWritabilityChanged();
}
}
private void checkStateWritability(FlowState state) throws Http2Exception {
if (isWritable(state) != state.markedWritability()) {
if (state == connectionState) {
checkAllWritabilityChanged();
} else {
notifyWritabilityChanged(state);
}
}
}
private void notifyWritabilityChanged(FlowState state) {
state.markedWritability(!state.markedWritability());
try {
listener.writabilityChanged(state.stream);
} catch (Throwable cause) {
logger.error("{} Caught Throwable from listener.writabilityChanged for {}",
ctx.channel(), state.stream, cause);
}
}
private void checkConnectionThenStreamWritabilityChanged(FlowState state) throws Http2Exception {
// It is possible that the connection window and/or the individual stream writability could change.
if (isWritableConnection() != connectionState.markedWritability()) {
checkAllWritabilityChanged();
} else if (isWritable(state) != state.markedWritability()) {
notifyWritabilityChanged(state);
}
}
private void checkAllWritabilityChanged() throws Http2Exception {
// Make sure we mark that we have notified as a result of this change.
connectionState.markedWritability(isWritableConnection());
connection.forEachActiveStream(this);
}
}
}
|
ListenerWritabilityMonitor
|
java
|
redisson__redisson
|
redisson-micronaut/redisson-micronaut-40/src/test/java/org/redisson/micronaut/RedissonSessionTest.java
|
{
"start": 2065,
"end": 8008
}
|
class ____ implements ApplicationEventListener<AbstractSessionEvent> {
List<AbstractSessionEvent> events = new ArrayList<>();
@Override
public void onApplicationEvent(AbstractSessionEvent event) {
events.add(event);
}
public List<AbstractSessionEvent> getEvents() {
return events;
}
}
@Test
public void testWriteBehind() throws ExecutionException, InterruptedException {
Map<String, Object> map = new HashMap<>();
map.put("redisson.threads", "10");
map.put("micronaut.session.http.redisson.enabled", "true");
map.put("micronaut.session.http.redisson.updateMode", "WRITE_BEHIND");
map.put("redisson.singleServerConfig.address", "redis://127.0.0.1:" + REDIS.getFirstMappedPort());
ApplicationContext ac = ApplicationContext.run(map);
RedissonClient rc = ac.getBean(RedissonClient.class);
rc.getKeys().flushall();
RedissonSessionStore sessionStore = ac.getBean(RedissonSessionStore.class);
RedissonSession session = sessionStore.newSession();
session.put("key1", "oleg");
session.put("key2", new MyObject("myname"));
session.setMaxInactiveInterval(Duration.ofSeconds(30));
RedissonSession saved = sessionStore.save(session).get();
saved.remove("key2");
saved.put("key1", "alba");
Thread.sleep(50);
RedissonSession s = sessionStore.findSession(saved.getId()).get().get();
assertThat(s.get("key1").get()).isEqualTo("alba");
assertThat(s.contains("key2")).isFalse();
ac.stop();
}
@Test
public void testSessionExpiration() throws ExecutionException, InterruptedException {
Map<String, Object> map = new HashMap<>();
map.put("redisson.threads", "10");
map.put("micronaut.session.http.redisson.enabled", "true");
map.put("redisson.singleServerConfig.address", "redis://127.0.0.1:" + REDIS.getFirstMappedPort());
ApplicationContext ac = ApplicationContext.run(map);
RedissonClient rc = ac.getBean(RedissonClient.class);
rc.getKeys().flushall();
RedissonSessionStore sessionStore = ac.getBean(RedissonSessionStore.class);
RedissonSession session = sessionStore.newSession();
session.put("username", "oleg");
session.put("foo", new MyObject("myname"));
session.setMaxInactiveInterval(Duration.ofSeconds(30));
RedissonSession saved = sessionStore.save(session).get();
testData(saved);
Thread.sleep(30500);
Optional<RedissonSession> noSession = sessionStore.findSession(saved.getId()).get();
assertThat(noSession).isEmpty();
Thread.sleep(10000);
assertThat(rc.getKeys().count()).isZero();
ac.stop();
}
@Test
public void testSessionCreate() throws ExecutionException, InterruptedException {
Map<String, Object> map = new HashMap<>();
map.put("redisson.threads", "10");
map.put("micronaut.session.http.redisson.enabled", "true");
map.put("redisson.singleServerConfig.address", "redis://127.0.0.1:" + REDIS.getFirstMappedPort());
ApplicationContext ac = ApplicationContext.run(map);
RedissonClient rc = ac.getBean(RedissonClient.class);
AppListener listener = ac.getBean(AppListener.class);
rc.getKeys().flushall();
RedissonSessionStore sessionStore = ac.getBean(RedissonSessionStore.class);
RedissonSession session = sessionStore.newSession();
session.put("username", "oleg");
session.put("foo", new MyObject("myname"));
RedissonSession saved = sessionStore.save(session).get();
testData(saved);
assertThat(listener.getEvents()).hasSize(1);
assertThat(listener.getEvents().get(0)).isInstanceOf(SessionCreatedEvent.class);
listener.getEvents().clear();
RedissonSession loaded = sessionStore.findSession(saved.getId()).get().get();
testData(loaded);
loaded.put("key", "value");
loaded.remove("username");
loaded.setLastAccessedTime(Instant.now());
loaded.setMaxInactiveInterval(Duration.ofMinutes(1));
sessionStore.save(loaded).get();
assertThat(listener.getEvents()).isEmpty();
loaded = sessionStore.findSession(saved.getId()).get().get();
assertThat(listener.getEvents()).isEmpty();
assertThat(loaded.contains("username")).isFalse();
assertThat(((MyObject) loaded.get("foo").get()).getName()).isEqualTo("myname");
assertThat(loaded.get("key").get()).isEqualTo("value");
assertThat(loaded.isExpired()).isFalse();
assertThat(loaded.getCreationTime().getEpochSecond()).isEqualTo(saved.getCreationTime().getEpochSecond());
assertThat(loaded.getMaxInactiveInterval()).isEqualTo(Duration.ofMinutes(1));
assertThat(loaded.getId()).isEqualTo(saved.getId());
Boolean deleted = sessionStore.deleteSession(saved.getId()).get();
assertThat(deleted).isTrue();
Thread.sleep(1500);
assertThat(listener.getEvents()).hasSize(1);
assertThat(listener.getEvents().get(0)).isInstanceOf(SessionDeletedEvent.class);
Optional<RedissonSession> noSession = sessionStore.findSession(saved.getId()).get();
assertThat(noSession).isEmpty();
Thread.sleep(15000);
assertThat(rc.getKeys().count()).isZero();
ac.stop();
}
private void testData(RedissonSession saved) {
assertThat(saved.get("username").get()).isEqualTo("oleg");
assertThat(((MyObject) saved.get("foo").get()).getName()).isEqualTo("myname");
assertThat(saved.isExpired()).isFalse();
assertThat(saved.getCreationTime()).isNotNull();
assertThat(saved.getMaxInactiveInterval()).isNotNull();
assertThat(saved.getId()).isNotNull();
}
}
|
AppListener
|
java
|
apache__dubbo
|
dubbo-common/src/test/java/org/apache/dubbo/common/utils/LockUtilsTest.java
|
{
"start": 1160,
"end": 5815
}
|
class ____ {
@RepeatedTest(5)
void testLockFailed() {
ReentrantLock reentrantLock = new ReentrantLock();
AtomicBoolean releaseLock = new AtomicBoolean(false);
new Thread(() -> {
reentrantLock.lock();
while (!releaseLock.get()) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
reentrantLock.unlock();
})
.start();
await().until(reentrantLock::isLocked);
AtomicLong lockTime = new AtomicLong(0);
long startTime = System.currentTimeMillis();
LockUtils.safeLock(reentrantLock, 1000, () -> {
lockTime.set(System.currentTimeMillis());
});
Assertions.assertTrue(lockTime.get() - startTime >= 1000);
releaseLock.set(true);
while (reentrantLock.isLocked()) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
lockTime.set(0);
startTime = System.currentTimeMillis();
LockUtils.safeLock(reentrantLock, 1000, () -> {
lockTime.set(System.currentTimeMillis());
});
Assertions.assertTrue(lockTime.get() - startTime < 1000);
}
@RepeatedTest(5)
void testReentrant() {
ReentrantLock reentrantLock = new ReentrantLock();
reentrantLock.lock();
AtomicLong lockTime = new AtomicLong(0);
long startTime = System.currentTimeMillis();
LockUtils.safeLock(reentrantLock, 1000, () -> {
lockTime.set(System.currentTimeMillis());
});
Assertions.assertTrue(lockTime.get() - startTime < 1000);
reentrantLock.lock();
lockTime.set(0);
startTime = System.currentTimeMillis();
LockUtils.safeLock(reentrantLock, 1000, () -> {
lockTime.set(System.currentTimeMillis());
});
Assertions.assertTrue(lockTime.get() - startTime < 1000);
Assertions.assertTrue(reentrantLock.isLocked());
reentrantLock.unlock();
Assertions.assertTrue(reentrantLock.isLocked());
reentrantLock.unlock();
Assertions.assertFalse(reentrantLock.isLocked());
}
@RepeatedTest(5)
void testInterrupt() {
ReentrantLock reentrantLock = new ReentrantLock();
reentrantLock.lock();
AtomicBoolean locked = new AtomicBoolean(false);
Thread thread = new Thread(() -> {
LockUtils.safeLock(reentrantLock, 10000, () -> {
locked.set(true);
});
});
thread.start();
await().until(() -> thread.getState() == State.TIMED_WAITING);
thread.interrupt();
await().until(() -> thread.getState() == State.TERMINATED);
Assertions.assertTrue(locked.get());
reentrantLock.unlock();
}
@RepeatedTest(5)
void testHoldLock() throws InterruptedException {
ReentrantLock reentrantLock = new ReentrantLock();
reentrantLock.lock();
AtomicLong lockTime = new AtomicLong(0);
long startTime = System.currentTimeMillis();
Thread thread = new Thread(() -> {
LockUtils.safeLock(reentrantLock, 10000, () -> {
lockTime.set(System.currentTimeMillis());
});
});
thread.start();
await().until(() -> thread.getState() == State.TIMED_WAITING);
Thread.sleep(1000);
reentrantLock.unlock();
await().until(() -> thread.getState() == State.TERMINATED);
Assertions.assertTrue(lockTime.get() - startTime > 1000);
Assertions.assertTrue(lockTime.get() - startTime < 10000);
}
@RepeatedTest(5)
void testInterrupted() throws InterruptedException {
ReentrantLock reentrantLock = new ReentrantLock();
reentrantLock.lock();
AtomicLong lockTime = new AtomicLong(0);
long startTime = System.currentTimeMillis();
Thread thread = new Thread(() -> {
Thread.currentThread().interrupt();
LockUtils.safeLock(reentrantLock, 10000, () -> {
lockTime.set(System.currentTimeMillis());
});
});
thread.start();
await().until(() -> thread.getState() == State.TERMINATED);
Assertions.assertTrue(lockTime.get() >= startTime);
Assertions.assertTrue(lockTime.get() - startTime < 10000);
}
}
|
LockUtilsTest
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfigurationTests.java
|
{
"start": 33124,
"end": 33321
}
|
class ____ {
@GetMapping("/public")
String permitAll() {
return "public";
}
}
}
@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
@EnableWebMvc
static
|
PublicController
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/streaming/runtime/StreamTaskSelectiveReadingITCase.java
|
{
"start": 5498,
"end": 5857
}
|
class ____ extends TestSource<String> {
public TestStringSource(String name, String[] elements) {
super(name, elements);
}
@Override
protected String outValue(String inValue, int subTaskIndex) {
return "[" + name + "-" + subTaskIndex + "]: " + inValue;
}
}
private static
|
TestStringSource
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/chararrays/CharArrays_assertContainsExactly_Test.java
|
{
"start": 1852,
"end": 9251
}
|
class ____ extends CharArraysBaseTest {
@Test
void should_pass_if_actual_contains_given_values_exactly() {
arrays.assertContainsExactly(someInfo(), actual, arrayOf('a', 'b', 'c'));
}
@Test
void should_pass_if_actual_and_given_values_are_empty() {
arrays.assertContainsExactly(someInfo(), emptyArray(), emptyArray());
}
@Test
void should_fail_if_actual_contains_given_values_exactly_but_in_different_order() {
AssertionInfo info = someInfo();
char[] expected = arrayOf('a', 'c', 'b');
Throwable error = catchThrowable(() -> arrays.assertContainsExactly(info, actual, expected));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, elementsDifferAtIndex('b', 'c', 1), asList(actual), asList(expected));
}
@Test
void should_fail_if_arrays_have_different_sizes() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContainsExactly(someInfo(), actual,
arrayOf('a', 'b')));
}
@Test
void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContainsExactly(someInfo(), actual,
emptyArray()));
}
@Test
void should_throw_error_if_array_of_values_to_look_for_is_null() {
assertThatNullPointerException().isThrownBy(() -> arrays.assertContainsExactly(someInfo(), actual, null))
.withMessage(valuesToLookForIsNull());
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContainsExactly(someInfo(), null, arrayOf('b')))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_does_not_contain_given_values_exactly() {
AssertionInfo info = someInfo();
char[] expected = { 'a', 'b', 'e' };
Throwable error = catchThrowable(() -> arrays.assertContainsExactly(info, actual, expected));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldContainExactly(actual, asList(expected),
newArrayList('e'), newArrayList('c')),
asList(actual), asList(expected));
}
@Test
void should_fail_if_actual_contains_all_given_values_but_size_differ() {
AssertionInfo info = someInfo();
char[] expected = { 'a', 'b', 'c', 'c' };
Throwable error = catchThrowable(() -> arrays.assertContainsExactly(info, actual, expected));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldContainExactly(actual, asList(expected),
newArrayList('c'), newArrayList()),
asList(actual), asList(expected));
}
// ------------------------------------------------------------------------------------------------------------------
// tests using a custom comparison strategy
// ------------------------------------------------------------------------------------------------------------------
@Test
void should_pass_if_actual_contains_given_values_exactly_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertContainsExactly(someInfo(), actual, arrayOf('a', 'B', 'c'));
}
@Test
void should_pass_if_actual_contains_given_values_exactly_in_different_order_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
char[] expected = { 'A', 'c', 'b' };
Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertContainsExactly(someInfo(), actual,
expected));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, elementsDifferAtIndex('b', 'c', 1, caseInsensitiveComparisonStrategy), asList(actual),
asList(expected));
}
@Test
void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContainsExactly(someInfo(),
actual,
emptyArray()));
}
@Test
void should_throw_error_if_array_of_values_to_look_for_is_null_whatever_custom_comparison_strategy_is() {
assertThatNullPointerException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContainsExactly(someInfo(),
actual,
null))
.withMessage(valuesToLookForIsNull());
}
@Test
void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContainsExactly(someInfo(),
null,
arrayOf('b')))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_does_not_contain_given_values_exactly_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
char[] expected = { 'a', 'B', 'e' };
Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertContainsExactly(info, actual, expected));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info,
shouldContainExactly(actual, asList(expected), newArrayList('e'), newArrayList('c'),
caseInsensitiveComparisonStrategy),
asList(actual), asList(expected));
}
@Test
void should_fail_if_actual_contains_all_given_values_but_size_differ_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
char[] expected = { 'a', 'b', 'C', 'c' };
Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertContainsExactly(info, actual, expected));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldContainExactly(actual, asList(expected),
newArrayList('c'), newArrayList(),
caseInsensitiveComparisonStrategy),
asList(actual), asList(expected));
}
}
|
CharArrays_assertContainsExactly_Test
|
java
|
google__auto
|
value/src/it/functional/src/test/java/com/google/auto/value/gwt/SerialSignatureTest.java
|
{
"start": 1046,
"end": 1245
}
|
class ____ a dummy field to
* influence the signature, and that different classes have different signatures.
*
* @author emcmanus@google.com (Éamonn McManus)
*/
@RunWith(JUnit4.class)
public
|
contains
|
java
|
apache__commons-lang
|
src/main/java/org/apache/commons/lang3/concurrent/ConcurrentInitializer.java
|
{
"start": 1310,
"end": 2167
}
|
interface ____ use different strategies for the creation of the managed object, e.g. lazy initialization or initialization
* in a background thread. This is completely transparent to client code, so it is possible to change the initialization strategy without affecting clients.
* </p>
* <p>
* An implementation of {@link #get()} returns the fully initialized object produced by this {@code
* ConcurrentInitializer}. A concrete implementation here returns the results of the initialization process. This method may block until results are available.
* Typically, once created the result object is always the same.
* </p>
* <p>
* An implementation throws {@link ConcurrentException} if an error occurred during initialization of the object.
* </p>
*
* @param <T> the type of the object managed by this initializer class.
* @since 3.0
*/
public
|
will
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/placement/csmappingrule/TestCSMappingPlacementRule.java
|
{
"start": 39642,
"end": 40351
}
|
class ____ implements GroupMappingServiceProvider {
public MockUnixGroupsMapping() {
GROUP.clear();
GROUP.add("testGroup1");
GROUP.add("testGroup2");
GROUP.add("testGroup3");
}
private static final List<String> GROUP = new ArrayList<>();
@Override
public List<String> getGroups(String user) throws IOException {
return GROUP;
}
@Override
public void cacheGroupsRefresh() {
GROUP.add(0, "testGroup0");
}
@Override
public void cacheGroupsAdd(List<String> groups) {
// Do nothing
}
@Override
public Set<String> getGroupsSet(String user) {
return ImmutableSet.copyOf(GROUP);
}
}
}
|
MockUnixGroupsMapping
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/EmbeddedColumnNamingAnnotation.java
|
{
"start": 385,
"end": 1316
}
|
class ____ implements EmbeddedColumnNaming {
private String value;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public EmbeddedColumnNamingAnnotation(ModelsContext modelContext) {
}
/**
* Used in creating annotation instances from JDK variant
*/
public EmbeddedColumnNamingAnnotation(
EmbeddedColumnNaming annotation,
ModelsContext modelContext) {
this.value = annotation.value();
}
/**
* Used in creating annotation instances from Jandex variant
*/
public EmbeddedColumnNamingAnnotation(
Map<String, Object> attributeValues,
ModelsContext modelContext) {
this.value = (String) attributeValues.get( "value" );
}
@Override
public Class<? extends Annotation> annotationType() {
return EmbeddedColumnNaming.class;
}
@Override
public String value() {
return value;
}
public void value(String value) {
this.value = value;
}
}
|
EmbeddedColumnNamingAnnotation
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_3.java
|
{
"start": 3018,
"end": 4115
}
|
class ____ {
private int v1;
private String v2;
private boolean v3;
private BigDecimal v4;
private Long v5;
private B o1;
public A(){
}
public Long getV5() {
return v5;
}
public void setV5(Long v5) {
this.v5 = v5;
}
public B getO1() {
return o1;
}
public void setO1(B o1) {
this.o1 = o1;
}
public int getV1() {
return v1;
}
public void setV1(int v1) {
this.v1 = v1;
}
public String getV2() {
return v2;
}
public void setV2(String v2) {
this.v2 = v2;
}
public boolean isV3() {
return v3;
}
public void setV3(boolean v3) {
this.v3 = v3;
}
public BigDecimal getV4() {
return v4;
}
public void setV4(BigDecimal v4) {
this.v4 = v4;
}
}
public static
|
A
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/cache/spi/support/DirectAccessRegionTemplate.java
|
{
"start": 408,
"end": 1486
}
|
class ____ extends AbstractRegion implements DirectAccessRegion {
private final StorageAccess storageAccess;
/**
* Constructs a {@link DirectAccessRegionTemplate}.
*
* @param name - the unqualified region name
* @param regionFactory - the region factory
* @param storageAccess - the cache storage access strategy
*/
public DirectAccessRegionTemplate(String name, RegionFactory regionFactory, StorageAccess storageAccess) {
super( name, regionFactory );
this.storageAccess = storageAccess;
}
public StorageAccess getStorageAccess() {
return storageAccess;
}
@Override
public Object getFromCache(Object key, SharedSessionContractImplementor session) {
return getStorageAccess().getFromCache( key, session );
}
@Override
public void putIntoCache(Object key, Object value, SharedSessionContractImplementor session) {
getStorageAccess().putIntoCache( key, value, session );
}
@Override
public void clear() {
getStorageAccess().evictData();
}
@Override
public void destroy() {
getStorageAccess().release();
}
}
|
DirectAccessRegionTemplate
|
java
|
apache__camel
|
core/camel-api/src/main/java/org/apache/camel/spi/PackageScanFilter.java
|
{
"start": 1031,
"end": 1192
}
|
class ____
*
* @param type the class
* @return true to include this class, false to skip it.
*/
boolean matches(Class<?> type);
}
|
match
|
java
|
elastic__elasticsearch
|
modules/data-streams/src/main/java/org/elasticsearch/datastreams/options/action/TransportPutDataStreamOptionsAction.java
|
{
"start": 1819,
"end": 4181
}
|
class ____ extends AcknowledgedTransportMasterNodeProjectAction<PutDataStreamOptionsAction.Request> {
private final IndexNameExpressionResolver indexNameExpressionResolver;
private final MetadataDataStreamsService metadataDataStreamsService;
private final SystemIndices systemIndices;
@Inject
public TransportPutDataStreamOptionsAction(
TransportService transportService,
ClusterService clusterService,
ThreadPool threadPool,
ActionFilters actionFilters,
ProjectResolver projectResolver,
IndexNameExpressionResolver indexNameExpressionResolver,
MetadataDataStreamsService metadataDataStreamsService,
SystemIndices systemIndices
) {
super(
PutDataStreamOptionsAction.INSTANCE.name(),
transportService,
clusterService,
threadPool,
actionFilters,
PutDataStreamOptionsAction.Request::new,
projectResolver,
EsExecutors.DIRECT_EXECUTOR_SERVICE
);
this.indexNameExpressionResolver = indexNameExpressionResolver;
this.metadataDataStreamsService = metadataDataStreamsService;
this.systemIndices = systemIndices;
}
@Override
protected void masterOperation(
Task task,
PutDataStreamOptionsAction.Request request,
ProjectState state,
ActionListener<AcknowledgedResponse> listener
) {
List<String> dataStreamNames = DataStreamsActionUtil.getDataStreamNames(
indexNameExpressionResolver,
state.metadata(),
request.getNames(),
request.indicesOptions()
);
for (String name : dataStreamNames) {
systemIndices.validateDataStreamAccess(name, threadPool.getThreadContext());
}
metadataDataStreamsService.setDataStreamOptions(
state.projectId(),
dataStreamNames,
request.getOptions(),
request.ackTimeout(),
request.masterNodeTimeout(),
listener
);
}
@Override
protected ClusterBlockException checkBlock(PutDataStreamOptionsAction.Request request, ProjectState state) {
return state.blocks().globalBlockedException(state.projectId(), ClusterBlockLevel.METADATA_WRITE);
}
}
|
TransportPutDataStreamOptionsAction
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-ws/src/test/java/org/apache/camel/component/spring/ws/ConsumerEndpointMappingByBeanNameRouteTest.java
|
{
"start": 1450,
"end": 2798
}
|
class ____ extends CamelSpringTestSupport {
private final String xmlRequestForGoogleStockQuote
= "<GetQuote xmlns=\"http://www.stockquotes.edu/\"><symbol>GOOG</symbol></GetQuote>";
private String expectedResponse;
private WebServiceTemplate webServiceTemplate;
@Override
public void doPostSetup() {
webServiceTemplate = applicationContext.getBean("webServiceTemplate", WebServiceTemplate.class);
expectedResponse = context.getTypeConverter().convertTo(String.class,
getClass().getResourceAsStream("/stockquote-response.txt"));
}
@Test
public void testBeanName() throws Exception {
StreamSource source = new StreamSource(new StringReader(xmlRequestForGoogleStockQuote));
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
webServiceTemplate.sendSourceAndReceiveToResult(source, result);
assertNotNull(result);
TestUtil.assertEqualsIgnoreNewLinesSymbol(expectedResponse, sw.toString());
}
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext(
"org/apache/camel/component/spring/ws/ConsumerEndpointMappingByBeanNameRouteTest-context.xml");
}
}
|
ConsumerEndpointMappingByBeanNameRouteTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/HairColor.java
|
{
"start": 189,
"end": 231
}
|
enum ____ {
BLONDE, BROWN, BLACK;
}
|
HairColor
|
java
|
apache__maven
|
its/core-it-support/core-it-plugins/maven-it-plugin-core-stubs/maven-resources-plugin/src/main/java/org/apache/maven/plugin/coreit/ResourcesMojo.java
|
{
"start": 1511,
"end": 3656
}
|
class ____ extends AbstractMojo {
/**
* The current Maven project.
*/
@Parameter(defaultValue = "${project}", required = true, readonly = true)
private MavenProject project;
/**
* The path to the output file, relative to the project base directory.
*
*/
@Parameter
private String pathname = "target/resources-resources.txt";
/**
* An optional message line to write to the output file (using UTF-8 encoding). If given, the output file will be
* opened in append mode.
*
*/
@Parameter
private String message;
/**
* Runs this mojo.
*
* @throws MojoExecutionException If the output file could not be created.
* @throws MojoFailureException If the output file has not been set.
*/
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info("[MAVEN-CORE-IT-LOG] Using output file path: " + pathname);
if (pathname == null || pathname.length() <= 0) {
throw new MojoFailureException("Path name for output file has not been specified");
}
File outputFile = new File(pathname);
if (!outputFile.isAbsolute()) {
outputFile = new File(project.getBasedir(), pathname).getAbsoluteFile();
}
getLog().info("[MAVEN-CORE-IT-LOG] Creating output file: " + outputFile);
try {
outputFile.getParentFile().mkdirs();
if (message != null && message.length() > 0) {
getLog().info("[MAVEN-CORE-IT-LOG] " + message);
try (OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream(outputFile, true), "UTF-8")) {
writer.write(message);
writer.write("\n");
}
} else {
outputFile.createNewFile();
}
} catch (IOException e) {
throw new MojoExecutionException("Output file could not be created: " + pathname, e);
}
getLog().info("[MAVEN-CORE-IT-LOG] Created output file: " + outputFile);
}
}
|
ResourcesMojo
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/sql/ast/statement/SQLUpdateStatementTest.java
|
{
"start": 316,
"end": 1043
}
|
class ____ {
@Test
public void testGetTableName() {
SQLUpdateBuilderImpl updateBuilder = (SQLUpdateBuilderImpl) SQLBuilderFactory.createUpdateBuilder("UPDATE a\n" +
"LEFT JOIN b ON b.id = a.id\n" +
"LEFT JOIN c ON c.id = a.id\n" +
"set a.id=11,b.id=11,c.id=11", DbType.mysql);
SQLUpdateStatement sqlUpdateStatement = updateBuilder.getSQLUpdateStatement();
SQLName tableName = sqlUpdateStatement.getTableName();
String simpleName = sqlUpdateStatement.getTableName(true).getSimpleName();
// 原有逻辑返回null
assertTrue(tableName == null);
// 新增逻辑 返回表名a
assertTrue(simpleName.equals("a"));
}
}
|
SQLUpdateStatementTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/termsenum/action/TransportTermsEnumAction.java
|
{
"start": 4450,
"end": 19702
}
|
class ____ extends HandledTransportAction<TermsEnumRequest, TermsEnumResponse> {
private static final Logger logger = LogManager.getLogger(TransportTermsEnumAction.class);
private final ClusterService clusterService;
private final TransportService transportService;
private final RemoteClusterService remoteClusterService;
private final SearchService searchService;
private final IndicesService indicesService;
private final ScriptService scriptService;
private final ProjectResolver projectResolver;
private final IndexNameExpressionResolver indexNameExpressionResolver;
final String transportShardAction;
private final Executor coordinationExecutor;
private final Executor shardExecutor;
private final XPackLicenseState licenseState;
private final Settings settings;
private final boolean ccsCheckCompatibility;
@Inject
public TransportTermsEnumAction(
ClusterService clusterService,
SearchService searchService,
TransportService transportService,
IndicesService indicesService,
ScriptService scriptService,
ActionFilters actionFilters,
XPackLicenseState licenseState,
Settings settings,
ProjectResolver projectResolver,
IndexNameExpressionResolver indexNameExpressionResolver
) {
super(
TermsEnumAction.NAME,
transportService,
actionFilters,
TermsEnumRequest::new,
clusterService.threadPool().executor(ThreadPool.Names.SEARCH_COORDINATION)
);
this.clusterService = clusterService;
this.searchService = searchService;
this.transportService = transportService;
this.projectResolver = projectResolver;
this.indexNameExpressionResolver = indexNameExpressionResolver;
this.transportShardAction = actionName + "[s]";
this.coordinationExecutor = clusterService.threadPool().executor(ThreadPool.Names.SEARCH_COORDINATION);
this.shardExecutor = clusterService.threadPool().executor(ThreadPool.Names.AUTO_COMPLETE);
this.indicesService = indicesService;
this.scriptService = scriptService;
this.licenseState = licenseState;
this.settings = settings;
this.remoteClusterService = transportService.getRemoteClusterService();
this.ccsCheckCompatibility = SearchService.CCS_VERSION_CHECK_SETTING.get(clusterService.getSettings());
transportService.registerRequestHandler(
transportShardAction,
coordinationExecutor,
NodeTermsEnumRequest::new,
new NodeTransportHandler()
);
}
@Override
protected void doExecute(Task task, TermsEnumRequest request, ActionListener<TermsEnumResponse> listener) {
// workaround for https://github.com/elastic/elasticsearch/issues/97916 - TODO remove this when we can
coordinationExecutor.execute(ActionRunnable.wrap(listener, l -> doExecuteForked(task, request, l)));
}
private void doExecuteForked(Task task, TermsEnumRequest request, ActionListener<TermsEnumResponse> listener) {
if (ccsCheckCompatibility) {
checkCCSVersionCompatibility(request);
}
// log any errors that occur in a successful partial results scenario
ActionListener<TermsEnumResponse> loggingListener = listener.delegateFailureAndWrap((l, termsEnumResponse) -> {
// Deduplicate failures by exception message and index
ShardOperationFailedException[] deduplicated = ExceptionsHelper.groupBy(termsEnumResponse.getShardFailures());
for (ShardOperationFailedException e : deduplicated) {
boolean causeHas500Status = false;
if (e.getCause() != null) {
causeHas500Status = ExceptionsHelper.status(e.getCause()).getStatus() >= 500;
}
if ((e.status().getStatus() >= 500 || causeHas500Status)
&& ExceptionsHelper.isNodeOrShardUnavailableTypeException(e.getCause()) == false) {
logger.warn("TransportTermsEnumAction shard failure (partial results response)", e);
}
}
l.onResponse(termsEnumResponse);
});
new AsyncBroadcastAction(task, request, loggingListener).start();
}
protected static NodeTermsEnumRequest newNodeRequest(
final OriginalIndices originalIndices,
final String nodeId,
final Set<ShardId> shardIds,
TermsEnumRequest request,
long taskStartMillis
) {
// Given we look terms up in the terms dictionary alias filters is another aspect of search (like DLS) that we
// currently do not support.
// final ClusterState clusterState = clusterService.state();
// final Set<String> indicesAndAliases = indexNameExpressionResolver.resolveExpressions(clusterState, request.indices());
// final AliasFilter aliasFilter = searchService.buildAliasFilter(clusterState, shard.getIndexName(), indicesAndAliases);
return new NodeTermsEnumRequest(originalIndices, nodeId, shardIds, request, taskStartMillis);
}
private static NodeTermsEnumResponse readShardResponse(StreamInput in) throws IOException {
return new NodeTermsEnumResponse(in);
}
protected Map<String, Set<ShardId>> getNodeBundles(ProjectState project, String[] concreteIndices) {
assert Transports.assertNotTransportThread("O(#shards) work is too much for transport threads");
// Group targeted shards by nodeId
Map<String, Set<ShardId>> fastNodeBundles = new HashMap<>();
for (String indexName : concreteIndices) {
String[] singleIndex = { indexName };
List<SearchShardRouting> shards = clusterService.operationRouting().searchShards(project, singleIndex, null, null);
for (ShardIterator copiesOfShard : shards) {
ShardRouting selectedCopyOfShard = null;
for (ShardRouting copy : copiesOfShard) {
// Pick the first active node with a copy of the shard
if (copy.active() && copy.assignedToNode()) {
selectedCopyOfShard = copy;
break;
}
}
if (selectedCopyOfShard == null) {
break;
}
String nodeId = selectedCopyOfShard.currentNodeId();
final Set<ShardId> bundle;
if (fastNodeBundles.containsKey(nodeId)) {
bundle = fastNodeBundles.get(nodeId);
} else {
bundle = new HashSet<>();
fastNodeBundles.put(nodeId, bundle);
}
if (bundle != null) {
bundle.add(selectedCopyOfShard.shardId());
}
}
}
return fastNodeBundles;
}
private static TermsEnumResponse mergeResponses(
TermsEnumRequest request,
AtomicReferenceArray<?> atomicResponses,
boolean complete,
Map<String, Set<ShardId>> nodeBundles
) {
assert Transports.assertNotTransportThread("O(#shards) work is too much for transport threads");
int successfulShards = 0;
int failedShards = 0;
List<DefaultShardOperationFailedException> shardFailures = null;
List<List<String>> termsList = new ArrayList<>();
for (int i = 0; i < atomicResponses.length(); i++) {
Object atomicResponse = atomicResponses.get(i);
if (atomicResponse instanceof NodeTermsEnumResponse str) {
// Only one node response has to be incomplete for the entire result to be labelled incomplete.
if (str.isComplete() == false) {
complete = false;
}
Set<ShardId> shards = nodeBundles.get(str.getNodeId());
if (str.getError() != null) {
complete = false;
// A single reported error is assumed to be for all shards queried on that node.
// When reading we read from multiple Lucene indices in one unified view so any error is
// assumed to be all shards on that node.
failedShards += shards.size();
if (shardFailures == null) {
shardFailures = new ArrayList<>();
}
for (ShardId failedShard : shards) {
shardFailures.add(
new DefaultShardOperationFailedException(
new BroadcastShardOperationFailedException(failedShard, str.getError())
)
);
}
} else {
successfulShards += shards.size();
}
termsList.add(str.terms());
} else if (atomicResponse instanceof RemoteClusterTermsEnumResponse rc) {
// Only one node response has to be incomplete for the entire result to be labelled incomplete.
if (rc.resp.isComplete() == false || rc.resp.getFailedShards() > 0) {
complete = false;
}
successfulShards += rc.resp.getSuccessfulShards();
failedShards += rc.resp.getFailedShards();
for (DefaultShardOperationFailedException exc : rc.resp.getShardFailures()) {
if (shardFailures == null) {
shardFailures = new ArrayList<>();
}
shardFailures.add(
new DefaultShardOperationFailedException(rc.clusterAlias + ":" + exc.index(), exc.shardId(), exc.getCause())
);
}
termsList.add(rc.resp.getTerms());
} else {
// ignore non-active responses
if (atomicResponse != null) {
throw new AssertionError("Unknown atomic response type: " + atomicResponse.getClass().getName());
}
}
}
List<String> ans = termsList.size() == 1 ? termsList.get(0) : mergeResponses(termsList, request.size());
return new TermsEnumResponse(ans, (failedShards + successfulShards), successfulShards, failedShards, shardFailures, complete);
}
private static List<String> mergeResponses(List<List<String>> termsList, int size) {
final PriorityQueue<TermIterator> pq = new PriorityQueue<>(termsList.size()) {
@Override
protected boolean lessThan(TermIterator a, TermIterator b) {
return a.compareTo(b) < 0;
}
};
for (List<String> terms : termsList) {
Iterator<String> it = terms.iterator();
if (it.hasNext()) {
pq.add(new TermIterator(it));
}
}
String lastTerm = null;
final List<String> ans = new ArrayList<>();
while (pq.size() != 0) {
TermIterator it = pq.top();
String term = it.term();
if (lastTerm != null && lastTerm.compareTo(term) != 0) {
ans.add(lastTerm);
if (ans.size() == size) {
break;
}
lastTerm = null;
}
if (lastTerm == null) {
lastTerm = term;
}
if (it.hasNext()) {
String itTerm = it.term();
it.next();
assert itTerm.compareTo(it.term()) <= 0;
pq.updateTop();
} else {
pq.pop();
}
}
if (lastTerm != null && ans.size() < size) {
ans.add(lastTerm);
}
return ans;
}
private NodeTermsEnumResponse dataNodeOperation(NodeTermsEnumRequest request) throws IOException {
List<String> termsList = new ArrayList<>();
long timeout_millis = request.timeout();
long scheduledEnd = request.nodeStartedTimeMillis() + timeout_millis;
ArrayList<Closeable> openedResources = new ArrayList<>();
try {
MultiShardTermsEnum.Builder teBuilder = new MultiShardTermsEnum.Builder();
for (ShardId shardId : request.shardIds()) {
// Check we haven't just arrived on a node and time is up already.
if (System.currentTimeMillis() > scheduledEnd) {
return NodeTermsEnumResponse.partial(request.nodeId(), termsList);
}
final IndexService indexService = indicesService.indexServiceSafe(shardId.getIndex());
final IndexShard indexShard = indexService.getShard(shardId.getId());
Engine.Searcher searcher = indexShard.acquireSearcher(Engine.SEARCH_SOURCE);
openedResources.add(searcher);
final MappedFieldType mappedFieldType = indexShard.mapperService().fieldType(request.field());
if (mappedFieldType != null) {
TermsEnum terms = mappedFieldType.getTerms(
searcher.getIndexReader(),
request.string() == null ? "" : request.string(),
request.caseInsensitive(),
request.searchAfter()
);
if (terms != null) {
teBuilder.add(terms, mappedFieldType::valueForDisplay);
}
}
}
if (teBuilder.size() == 0) {
// No term enums available
return NodeTermsEnumResponse.empty(request.nodeId());
}
MultiShardTermsEnum te = teBuilder.build();
int shard_size = request.size();
// All the above prep might take a while - do a timer check now before we continue further.
if (System.currentTimeMillis() > scheduledEnd) {
return NodeTermsEnumResponse.partial(request.nodeId(), termsList);
}
int numTermsBetweenClockChecks = 100;
int termCount = 0;
// Collect in alphabetical order
while (te.next() != null) {
termCount++;
if (termCount > numTermsBetweenClockChecks) {
if (System.currentTimeMillis() > scheduledEnd) {
return NodeTermsEnumResponse.partial(request.nodeId(), termsList);
}
termCount = 0;
}
termsList.add(te.decodedTerm());
if (termsList.size() >= shard_size) {
break;
}
}
return NodeTermsEnumResponse.complete(request.nodeId(), termsList);
} catch (Exception e) {
return NodeTermsEnumResponse.error(request.nodeId(), termsList, e);
} finally {
IOUtils.close(openedResources);
}
}
// TODO remove this so we can shift code to server module - write a separate Interceptor
|
TransportTermsEnumAction
|
java
|
google__dagger
|
javatests/dagger/functional/modules/ModuleIncludesCollectedFromModuleSuperclasses.java
|
{
"start": 1554,
"end": 1674
}
|
class ____ {
@Provides String inheritedProvision() {
return "inherited";
}
}
}
|
IncludedFromModuleInheritance
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitEnumConvertersTest.java
|
{
"start": 1513,
"end": 1943
}
|
class ____ implements AttributeConverter<MediaType,String> {
@Override
public String convertToDatabaseColumn(MediaType attribute) {
convertToDatabaseColumnCalled = true;
return attribute.name();
}
@Override
public MediaType convertToEntityAttribute(String dbData) {
convertToEntityAttributeCalled = true;
return MediaType.valueOf( dbData );
}
}
@Entity( name = "Entity1" )
public static
|
MediaTypeConverter
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/double_/DoubleAssert_usingComparator_Test.java
|
{
"start": 1037,
"end": 1609
}
|
class ____ extends DoubleAssertBaseTest {
private Comparator<Double> comparator = alwaysEqual();
@Override
protected DoubleAssert invoke_api_method() {
// in that, we don't care of the comparator, the point to check is that we switch correctly of comparator
return assertions.usingComparator(comparator);
}
@Override
protected void verify_internal_effects() {
assertThat(getObjects(assertions).getComparator()).isSameAs(comparator);
assertThat(getDoubles(assertions).getComparator()).isSameAs(comparator);
}
}
|
DoubleAssert_usingComparator_Test
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/CompileTimeConstantCheckerTest.java
|
{
"start": 27280,
"end": 27598
}
|
class ____ {
@CompileTimeConstant
final String s =
switch (1) {
case 1 -> "a";
case 2 -> "b";
default -> throw new RuntimeException();
};
}
""")
.doTest();
}
}
|
Test
|
java
|
netty__netty
|
handler/src/test/java/io/netty/handler/pcap/PcapWriteHandlerTest.java
|
{
"start": 64878,
"end": 65292
}
|
class ____ extends ChannelOutboundHandlerAdapter {
@Override
public void flush(ChannelHandlerContext ctx) {
//Discard
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
//Discard
ReferenceCountUtil.release(msg);
promise.setSuccess();
}
}
}
|
DiscardingWritesAndFlushesHandler
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest11.java
|
{
"start": 978,
"end": 4346
}
|
class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = "SELECT ID, GMT_CREATE, GMT_MODIFIED, COMPANY_ID, MEMBER_ID" +
" , MEMBER_SEQ, FILE_NAME, DISPLAY_NAME, DISPLAY_NAME_UTF8, FILE_SIZE" +
" , STATUS, WIDTH, HEIGHT, REFERENCE_COUNT, HASH_CODE" +
" , GROUP_ID" +
" FROM (SELECT *" +
" FROM (SELECT row_.*, rownum AS rownum_" +
" FROM (SELECT rowid AS rid" +
" FROM IMAGE_REPOSITORY" +
" WHERE COMPANY_ID = :1 AND STATUS = 'enable' " +
" AND MEMBER_SEQ = :2 AND GMT_MODIFIED >= to_date(:3, 'yyyy-mm-dd hh24:mi:ss') " +
" AND GMT_MODIFIED < to_date(:4, 'yyyy-mm-dd hh24:mi:ss')" +
" ORDER BY \"FILE_SIZE\" DESC, \"ID\" DESC" + // //
" ) row_" +
" WHERE rownum <= :5" +
" )" +
" WHERE rownum_ >= :6" +
" ) a, IMAGE_REPOSITORY b " +
" WHERE a.rid = b.rowid;";
// sql = "select ID, GMT_CREATE, GMT_MODIFIED, COMPANY_ID, MEMBER_ID, MEMBER_SEQ, FILE_NAME, DISPLAY_NAME, DISPLAY_NAME_UTF8, FILE_SIZE, STATUS, WIDTH, HEIGHT, REFERENCE_COUNT, HASH_CODE, GROUP_ID from ( select * from (select row_.*, rownum rownum_ from ( select rowid rid from IMAGE_REPOSITORY where COMPANY_ID = :1 and STATUS = 'enable' and MEMBER_SEQ = :2 and GMT_MODIFIED >= to_date(:3 , 'yyyy-mm-dd hh24:mi:ss') and GMT_MODIFIED < to_date(:4 , 'yyyy-mm-dd hh24:mi:ss') order by \"FILE_SIZE\" desc , \"ID\" desc )row_ where rownum <= :5 ) where rownum_ >= :6 ) a , IMAGE_REPOSITORY b where a.rid = b.rowid ";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement statemen = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
statemen.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertTrue(visitor.getTables().containsKey(new TableStat.Name("IMAGE_REPOSITORY")));
assertEquals(17, visitor.getColumns().size());
assertTrue(visitor.getColumns().contains(new TableStat.Column("IMAGE_REPOSITORY", "rowid")));
assertTrue(visitor.getColumns().contains(new TableStat.Column("IMAGE_REPOSITORY", "COMPANY_ID")));
assertTrue(visitor.getColumns().contains(new TableStat.Column("IMAGE_REPOSITORY", "STATUS")));
}
}
|
OracleSelectTest11
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/api/recursive/assertion/DefaultRecursiveAssertionIntrospectionStrategy.java
|
{
"start": 1018,
"end": 2911
}
|
class ____ implements RecursiveAssertionIntrospectionStrategy {
@Override
public List<RecursiveAssertionNode> getChildNodesOf(Object node) {
return getDeclaredFieldsIncludingInherited(node.getClass()).stream()
.map(field -> toNode(field, node))
.collect(toList());
}
@Override
public String getDescription() {
return "DefaultRecursiveAssertionIntrospectionStrategy which introspects all fields (including inherited ones)";
}
private static RecursiveAssertionNode toNode(Field field, Object node) {
String fieldName = field.getName();
Object fieldValue = EXTRACTION.getSimpleValue(fieldName, node);
Class<?> fieldType = getFieldType(fieldValue, fieldName, node);
return new RecursiveAssertionNode(fieldValue, fieldName, fieldType);
}
private static Class<?> getFieldType(Object fieldValue, String fieldName, Object targetObject) {
return fieldValue != null ? fieldValue.getClass() : getFieldType(fieldName, targetObject.getClass());
}
private static Class<?> getFieldType(String fieldName, Class<?> objectClass) {
try {
Optional<Field> potentialField = stream(objectClass.getDeclaredFields()).filter(field -> fieldName.equals(field.getName()))
.findAny();
if (potentialField.isPresent()) return potentialField.get().getType();
Class<?> superclass = objectClass.getSuperclass();
if (superclass != null) return getFieldType(fieldName, superclass);
throw new NoSuchFieldException();
} catch (NoSuchFieldException | SecurityException e) {
throw new IllegalStateException("Could not find field %s on class %s, even though its name was retrieved from the
|
DefaultRecursiveAssertionIntrospectionStrategy
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java
|
{
"start": 1699,
"end": 3633
}
|
class ____ {
protected static final AtomicInteger invocationCount = new AtomicInteger();
private final Class<?> testClass;
private final int expectedFailureCount;
private final int expectedStartedCount;
private final int expectedFinishedCount;
private final int expectedInvocationCount;
@Parameters(name = "{0}")
public static Object[][] repetitionData() {
return new Object[][] {//
{ NonAnnotatedRepeatedTestCase.class.getSimpleName(), 0, 1, 1, 1 },//
{ DefaultRepeatValueRepeatedTestCase.class.getSimpleName(), 0, 1, 1, 1 },//
{ NegativeRepeatValueRepeatedTestCase.class.getSimpleName(), 0, 1, 1, 1 },//
{ RepeatedFiveTimesRepeatedTestCase.class.getSimpleName(), 0, 1, 1, 5 },//
{ RepeatedFiveTimesViaMetaAnnotationRepeatedTestCase.class.getSimpleName(), 0, 1, 1, 5 },//
{ TimedRepeatedTestCase.class.getSimpleName(), 3, 4, 4, (5 + 1 + 4 + 10) } //
};
}
public RepeatedSpringRunnerTests(String testClassName, int expectedFailureCount,
int expectedTestStartedCount, int expectedTestFinishedCount, int expectedInvocationCount) throws Exception {
this.testClass = ClassUtils.forName(getClass().getName() + "." + testClassName, getClass().getClassLoader());
this.expectedFailureCount = expectedFailureCount;
this.expectedStartedCount = expectedTestStartedCount;
this.expectedFinishedCount = expectedTestFinishedCount;
this.expectedInvocationCount = expectedInvocationCount;
}
protected Class<? extends Runner> getRunnerClass() {
return SpringRunner.class;
}
@Test
public void assertRepetitions() throws Exception {
invocationCount.set(0);
runTestsAndAssertCounters(getRunnerClass(), this.testClass, expectedStartedCount, expectedFailureCount,
expectedFinishedCount, 0, 0);
assertThat(invocationCount.get()).as("invocations for [" + testClass + "]:").isEqualTo(expectedInvocationCount);
}
@TestExecutionListeners({})
public abstract static
|
RepeatedSpringRunnerTests
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/InfinispanEmbeddedEndpointBuilderFactory.java
|
{
"start": 43976,
"end": 53398
}
|
class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final InfinispanEmbeddedHeaderNameBuilder INSTANCE = new InfinispanEmbeddedHeaderNameBuilder();
/**
* The type of the received event.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code InfinispanEventType}.
*/
public String infinispanEventType() {
return "CamelInfinispanEventType";
}
/**
* true if the notification is before the event has occurred, false if
* after the event has occurred.
*
* The option is a: {@code boolean} type.
*
* Group: consumer
*
* @return the name of the header {@code InfinispanIsPre}.
*/
public String infinispanIsPre() {
return "CamelInfinispanIsPre";
}
/**
* The cache participating in the operation or event.
*
* The option is a: {@code String} type.
*
* Group: common
*
* @return the name of the header {@code InfinispanCacheName}.
*/
public String infinispanCacheName() {
return "CamelInfinispanCacheName";
}
/**
* The key to perform the operation to or the key generating the event.
*
* The option is a: {@code Object} type.
*
* Group: common
*
* @return the name of the header {@code InfinispanKey}.
*/
public String infinispanKey() {
return "CamelInfinispanKey";
}
/**
* The value to use for the operation.
*
* The option is a: {@code Object} type.
*
* Group: producer
*
* @return the name of the header {@code InfinispanValue}.
*/
public String infinispanValue() {
return "CamelInfinispanValue";
}
/**
* The default value to use for a getOrDefault.
*
* The option is a: {@code Object} type.
*
* Group: producer
*
* @return the name of the header {@code InfinispanDefaultValue}.
*/
public String infinispanDefaultValue() {
return "CamelInfinispanDefaultValue";
}
/**
* The old value to use for a replace.
*
* The option is a: {@code Object} type.
*
* Group: producer
*
* @return the name of the header {@code InfinispanOldValue}.
*/
public String infinispanOldValue() {
return "CamelInfinispanOldValue";
}
/**
* A Map to use in case of CamelInfinispanOperationPutAll operation.
*
* The option is a: {@code Map} type.
*
* Group: producer
*
* @return the name of the header {@code InfinispanMap}.
*/
public String infinispanMap() {
return "CamelInfinispanMap";
}
/**
* The operation to perform.
*
* The option is a: {@code
* org.apache.camel.component.infinispan.InfinispanOperation} type.
*
* Group: producer
*
* @return the name of the header {@code InfinispanOperation}.
*/
public String infinispanOperation() {
return "CamelInfinispanOperation";
}
/**
* The name of the header whose value is the result.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code InfinispanOperationResult}.
*/
public String infinispanOperationResult() {
return "CamelInfinispanOperationResult";
}
/**
* Store the operation result in a header instead of the message body.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code
* InfinispanOperationResultHeader}.
*/
public String infinispanOperationResultHeader() {
return "CamelInfinispanOperationResultHeader";
}
/**
* The Lifespan time of a value inside the cache. Negative values are
* interpreted as infinity.
*
* The option is a: {@code long} type.
*
* Group: producer
*
* @return the name of the header {@code InfinispanLifespanTime}.
*/
public String infinispanLifespanTime() {
return "CamelInfinispanLifespanTime";
}
/**
* The Time Unit of an entry Lifespan Time.
*
* The option is a: {@code java.util.concurrent.TimeUnit} type.
*
* Group: producer
*
* @return the name of the header {@code InfinispanTimeUnit}.
*/
public String infinispanTimeUnit() {
return "CamelInfinispanTimeUnit";
}
/**
* The maximum amount of time an entry is allowed to be idle for before
* it is considered as expired.
*
* The option is a: {@code long} type.
*
* Group: producer
*
* @return the name of the header {@code InfinispanMaxIdleTime}.
*/
public String infinispanMaxIdleTime() {
return "CamelInfinispanMaxIdleTime";
}
/**
* The Time Unit of an entry Max Idle Time.
*
* The option is a: {@code java.util.concurrent.TimeUnit} type.
*
* Group: producer
*
* @return the name of the header {@code InfinispanMaxIdleTimeUnit}.
*/
public String infinispanMaxIdleTimeUnit() {
return "CamelInfinispanMaxIdleTimeUnit";
}
/**
* Signals that a write operation's return value will be ignored, so
* reading the existing value from a store or from a remote node is not
* necessary.
*
* The option is a: {@code boolean} type.
*
* Default: false
* Group: consumer
*
* @return the name of the header {@code InfinispanIgnoreReturnValues}.
*/
public String infinispanIgnoreReturnValues() {
return "CamelInfinispanIgnoreReturnValues";
}
/**
* The event data.
*
* The option is a: {@code Object} type.
*
* Group: consumer
*
* @return the name of the header {@code InfinispanEventData}.
*/
public String infinispanEventData() {
return "CamelInfinispanEventData";
}
/**
* The QueryBuilder to use for QUERY command, if not present the command
* defaults to InifinispanConfiguration's one.
*
* The option is a: {@code
* org.apache.camel.component.infinispan.InfinispanQueryBuilder} type.
*
* Group: producer
*
* @return the name of the header {@code InfinispanQueryBuilder}.
*/
public String infinispanQueryBuilder() {
return "CamelInfinispanQueryBuilder";
}
/**
* This will be true if the write command that caused this had to be
* retried again due to a topology change.
*
* The option is a: {@code boolean} type.
*
* Group: consumer
*
* @return the name of the header {@code InfinispanCommandRetried}.
*/
public String infinispanCommandRetried() {
return "CamelInfinispanCommandRetried";
}
/**
* Indicates whether the cache entry modification event is the result of
* the cache entry being created.
*
* The option is a: {@code boolean} type.
*
* Group: consumer
*
* @return the name of the header {@code InfinispanEntryCreated}.
*/
public String infinispanEntryCreated() {
return "CamelInfinispanEntryCreated";
}
/**
* true if the call originated on the local cache instance; false if
* originated from a remote one.
*
* The option is a: {@code boolean} type.
*
* Group: consumer
*
* @return the name of the header {@code InfinispanOriginLocal}.
*/
public String infinispanOriginLocal() {
return "CamelInfinispanOriginLocal";
}
/**
* True if this event is generated from an existing entry as the
* listener has Listener.
*
* The option is a: {@code boolean} type.
*
* Group: consumer
*
* @return the name of the header {@code InfinispanCurrentState}.
*/
public String infinispanCurrentState() {
return "CamelInfinispanCurrentState";
}
}
static InfinispanEmbeddedEndpointBuilder endpointBuilder(String componentName, String path) {
|
InfinispanEmbeddedHeaderNameBuilder
|
java
|
apache__logging-log4j2
|
log4j-1.2-api/src/main/java/org/apache/log4j/xml/DOMConfigurator.java
|
{
"start": 2734,
"end": 7683
}
|
class ____ {
private static boolean isFullCompatibilityEnabled() {
return PropertiesUtil.getProperties().getBooleanProperty(ConfigurationFactory.LOG4J1_EXPERIMENTAL);
}
private static void warnFullCompatibilityDisabled() {
LogLog.warn(
"Ignoring `DOMConfigurator` call, since `log4j1.compatibility` is not enabled.\n"
+ "See https://logging.staged.apache.org/log4j/2.x/migrate-from-log4j1.html#log4j1.compatibility for details.");
}
public static void configure(final Element element) {}
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "The filename comes from a system property.")
public static void configure(final String fileName) throws FactoryConfigurationError {
if (isFullCompatibilityEnabled()) {
final Path path = Paths.get(fileName);
try (final InputStream inputStream = Files.newInputStream(path)) {
final ConfigurationSource source = new ConfigurationSource(inputStream, path);
final LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
Configuration configuration;
configuration = new XmlConfigurationFactory().getConfiguration(context, source);
LogManager.getRootLogger().removeAllAppenders();
Configurator.reconfigure(configuration);
} catch (final IOException e) {
throw new FactoryConfigurationError(e);
}
} else {
warnFullCompatibilityDisabled();
}
}
public static void configure(final URL url) throws FactoryConfigurationError {
new DOMConfigurator().doConfigure(url, LogManager.getLoggerRepository());
}
public static void configureAndWatch(final String fileName) {
// TODO Watch
configure(fileName);
}
public static void configureAndWatch(final String fileName, final long delay) {
if (isFullCompatibilityEnabled()) {
final XMLWatchdog xdog = new XMLWatchdog(fileName);
xdog.setDelay(delay);
xdog.start();
} else {
warnFullCompatibilityDisabled();
}
}
public static Object parseElement(
final Element element, final Properties props, @SuppressWarnings("rawtypes") final Class expectedClass) {
return null;
}
public static void setParameter(final Element elem, final PropertySetter propSetter, final Properties props) {}
public static String subst(final String value, final Properties props) {
return OptionConverter.substVars(value, props);
}
private void doConfigure(final ConfigurationSource source) {
final LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
final Configuration configuration = new XmlConfigurationFactory().getConfiguration(context, source);
Configurator.reconfigure(configuration);
}
public void doConfigure(final Element element, final LoggerRepository repository) {}
public void doConfigure(final InputStream inputStream, final LoggerRepository repository)
throws FactoryConfigurationError {
if (isFullCompatibilityEnabled()) {
try {
doConfigure(new ConfigurationSource(inputStream));
} catch (final IOException e) {
throw new FactoryConfigurationError(e);
}
} else {
warnFullCompatibilityDisabled();
}
}
public void doConfigure(final Reader reader, final LoggerRepository repository) throws FactoryConfigurationError {
if (isFullCompatibilityEnabled()) {
try {
final StringWriter sw = new StringWriter();
IOUtils.copy(reader, sw);
doConfigure(new ConfigurationSource(
new ByteArrayInputStream(sw.toString().getBytes(StandardCharsets.UTF_8))));
} catch (final IOException e) {
throw new FactoryConfigurationError(e);
}
} else {
warnFullCompatibilityDisabled();
}
}
public void doConfigure(final String fileName, final LoggerRepository repository) {
configure(fileName);
}
public void doConfigure(final URL url, final LoggerRepository repository) {
if (isFullCompatibilityEnabled()) {
try {
final URLConnection connection = UrlConnectionFactory.createConnection(url);
try (final InputStream inputStream = connection.getInputStream()) {
doConfigure(new ConfigurationSource(inputStream, url));
}
} catch (final IOException e) {
throw new FactoryConfigurationError(e);
}
} else {
warnFullCompatibilityDisabled();
}
}
}
|
DOMConfigurator
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/android/FragmentNotInstantiableTest.java
|
{
"start": 2209,
"end": 2382
}
|
class ____ extends Fragment {
public PrivateFragment() {}
}
// BUG: Diagnostic contains: public
static
|
PrivateFragment
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/hql/MappedSuperclassAttributeQueryTest.java
|
{
"start": 2405,
"end": 2496
}
|
class ____ extends AbstractSuperclass {
}
@Entity( name = "EntityB" )
public static
|
EntityA
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_2001/Form.java
|
{
"start": 232,
"end": 432
}
|
class ____ {
private FormExtra[] extras;
public FormExtra[] getExtras() {
return extras;
}
public void setExtras(FormExtra[] extras) {
this.extras = extras;
}
}
|
Form
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.