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 | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java | {
"start": 73373,
"end": 73500
} | interface ____ {
String getFoo();
}
@ConfigurationProperties("test")
@Validated
static | InterfaceForValidatedImplementation |
java | eclipse-vertx__vert.x | vertx-core/src/test/java/io/vertx/tests/shareddata/SharedCounterTest.java | {
"start": 682,
"end": 5337
} | class ____ extends VertxTestBase {
protected Vertx getVertx() {
return vertx;
}
@Test
public void testIllegalArguments() throws Exception {
assertNullPointerException(() -> getVertx().sharedData().getCounter(null));
}
@Test
public void testGet() {
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter -> {
counter.get().onComplete(onSuccess(res -> {
assertEquals(0L, res.longValue());
testComplete();
}));
}));
await();
}
@Test
public void testIncrementAndGet() {
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter -> {
counter.incrementAndGet().onComplete(onSuccess(res1 -> {
assertEquals(1L, res1.longValue());
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter2 -> {
counter2.incrementAndGet().onComplete(onSuccess(res2 -> {
assertEquals(2L, res2.longValue());
testComplete();
}));
}));
}));
}));
await();
}
@Test
public void testGetAndIncrement() {
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter -> {
counter.getAndIncrement().onComplete(onSuccess(res -> {
assertEquals(0L, res.longValue());
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter2 -> {
counter2.getAndIncrement().onComplete(onSuccess(res2 -> {
assertEquals(1L, res2.longValue());
counter2.get().onComplete(onSuccess(res3 -> {
assertEquals(2L, res3.longValue());
testComplete();
}));
}));
}));
}));
}));
await();
}
@Test
public void testDecrementAndGet() {
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter -> {
counter.decrementAndGet().onComplete(onSuccess(res -> {
assertEquals(-1L, res.longValue());
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter2 -> {
counter2.decrementAndGet().onComplete(onSuccess(res2 -> {
assertEquals(-2L, res2.longValue());
testComplete();
}));
}));
}));
}));
await();
}
@Test
public void testAddAndGet() {
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter -> {
counter.addAndGet(2).onComplete(onSuccess(res -> {
assertEquals(2L, res.longValue());
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter2 -> {
counter2.addAndGet(2L).onComplete(onSuccess(res2 -> {
assertEquals(4L, res2.longValue());
testComplete();
}));
}));
}));
}));
await();
}
@Test
public void getAndAdd() {
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter -> {
counter.getAndAdd(2).onComplete(onSuccess(res -> {
assertEquals(0L, res.longValue());
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter2 -> {
counter2.getAndAdd(2L).onComplete(onSuccess(res2 -> {
assertEquals(2L, res2.longValue());
counter2.get().onComplete(onSuccess(res3 -> {
assertEquals(4L, res3.longValue());
testComplete();
}));
}));
}));
}));
}));
await();
}
@Test
public void testCompareAndSet() {
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter -> {
counter.compareAndSet(0L, 2L).onComplete(onSuccess(result -> {
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter2 -> {
counter2.compareAndSet(2L, 4L).onComplete(onSuccess(result2 -> {
assertTrue(result2);
counter2.compareAndSet(3L, 5L).onComplete(onSuccess(result3 -> {
assertFalse(result3);
testComplete();
}));
}));
}));
}));
}));
await();
}
@Test
public void testDifferentCounters() {
getVertx().sharedData().getCounter("foo").onComplete(onSuccess(counter -> {
counter.incrementAndGet().onComplete(onSuccess(res -> {
assertEquals(1L, res.longValue());
getVertx().sharedData().getCounter("bar").onComplete(onSuccess(counter2 -> {
counter2.incrementAndGet().onComplete(onSuccess(res2 -> {
assertEquals(1L, res2.longValue());
counter.incrementAndGet().onComplete(onSuccess(res3 -> {
assertEquals(2L, res3.longValue());
testComplete();
}));
}));
}));
}));
}));
await();
}
}
| SharedCounterTest |
java | redisson__redisson | redisson/src/main/java/org/redisson/client/protocol/pubsub/PubSubMessageDecoder.java | {
"start": 955,
"end": 1527
} | class ____ implements MultiDecoder<Object> {
private final Decoder<Object> decoder;
public PubSubMessageDecoder(Decoder<Object> decoder) {
super();
this.decoder = decoder;
}
@Override
public Decoder<Object> getDecoder(Codec codec, int paramNum, State state, long size) {
return decoder;
}
@Override
public PubSubMessage decode(List<Object> parts, State state) {
ChannelName name = new ChannelName((byte[]) parts.get(1));
return new PubSubMessage(name, parts.get(2));
}
}
| PubSubMessageDecoder |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/vector/VectorSimilarParams.java | {
"start": 744,
"end": 3164
} | class ____ implements VectorSimilarArgs {
private final String element;
private final byte[] vectorBytes;
private final Double[] vectorDoubles;
private Integer count;
private Double epsilon;
private Integer effort;
private String filter;
private Integer filterEffort;
private boolean useLinearScan;
private boolean useMainThread;
VectorSimilarParams(String element) {
this.element = element;
this.vectorBytes = null;
this.vectorDoubles = null;
}
VectorSimilarParams(byte[] vector) {
this.element = null;
this.vectorBytes = vector;
this.vectorDoubles = null;
}
VectorSimilarParams(Double... vector) {
this.element = null;
this.vectorBytes = null;
this.vectorDoubles = vector;
}
@Override
public VectorSimilarArgs count(int count) {
this.count = count;
return this;
}
@Override
public VectorSimilarArgs epsilon(double value) {
this.epsilon = value;
return this;
}
@Override
public VectorSimilarArgs explorationFactor(int effort) {
this.effort = effort;
return this;
}
@Override
public VectorSimilarArgs filter(String filter) {
this.filter = filter;
return this;
}
@Override
public VectorSimilarArgs filterEffort(int filterEffort) {
this.filterEffort = filterEffort;
return this;
}
@Override
public VectorSimilarArgs useLinearScan() {
this.useLinearScan = true;
return this;
}
@Override
public VectorSimilarArgs useMainThread() {
this.useMainThread = true;
return this;
}
public String getElement() {
return element;
}
public byte[] getVectorBytes() {
return vectorBytes;
}
public Double[] getVectorDoubles() {
return vectorDoubles;
}
public Integer getCount() {
return count;
}
public Double getEpsilon() {
return epsilon;
}
public Integer getEffort() {
return effort;
}
public String getFilter() {
return filter;
}
public Integer getFilterEffort() {
return filterEffort;
}
public boolean isUseLinearScan() {
return useLinearScan;
}
public boolean isUseMainThread() {
return useMainThread;
}
}
| VectorSimilarParams |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java | {
"start": 28797,
"end": 29069
} | class ____ implements FactoryBean<String> {
@Override
public String getObject() {
return "";
}
@Override
public Class<?> getObjectType() {
return String.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
static | TypedFactoryBean |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/admin/cluster/node/shutdown/PrevalidateNodeRemovalRequestSerializationTests.java | {
"start": 682,
"end": 3281
} | class ____ extends AbstractWireSerializingTestCase<PrevalidateNodeRemovalRequest> {
@Override
protected Writeable.Reader<PrevalidateNodeRemovalRequest> instanceReader() {
return PrevalidateNodeRemovalRequest::new;
}
@Override
protected PrevalidateNodeRemovalRequest createTestInstance() {
return randomRequest();
}
@Override
protected PrevalidateNodeRemovalRequest mutateInstance(PrevalidateNodeRemovalRequest request) {
int i = randomIntBetween(0, 2);
return switch (i) {
case 0 -> PrevalidateNodeRemovalRequest.builder()
.setNames(
randomValueOtherThanMany(
input -> Arrays.equals(input, request.getNames()),
PrevalidateNodeRemovalRequestSerializationTests::randomStringArray
)
)
.setIds(request.getIds())
.setExternalIds(request.getExternalIds())
.build(TEST_REQUEST_TIMEOUT);
case 1 -> PrevalidateNodeRemovalRequest.builder()
.setNames(request.getNames())
.setIds(
randomValueOtherThanMany(
input -> Arrays.equals(input, request.getIds()),
PrevalidateNodeRemovalRequestSerializationTests::randomStringArray
)
)
.setExternalIds(request.getExternalIds())
.build(TEST_REQUEST_TIMEOUT);
case 2 -> PrevalidateNodeRemovalRequest.builder()
.setNames(request.getNames())
.setIds(request.getIds())
.setExternalIds(
randomValueOtherThanMany(
input -> Arrays.equals(input, request.getExternalIds()),
PrevalidateNodeRemovalRequestSerializationTests::randomStringArray
)
)
.build(TEST_REQUEST_TIMEOUT);
default -> throw new IllegalStateException("unexpected value: " + i);
};
}
private static String[] randomStringArray() {
return randomArray(0, 20, String[]::new, () -> randomAlphaOfLengthBetween(5, 20));
}
private static PrevalidateNodeRemovalRequest randomRequest() {
return PrevalidateNodeRemovalRequest.builder()
.setNames(randomStringArray())
.setIds(randomStringArray())
.setExternalIds(randomStringArray())
.build(TEST_REQUEST_TIMEOUT);
}
}
| PrevalidateNodeRemovalRequestSerializationTests |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToOptionalConverterTest.java | {
"start": 1223,
"end": 1777
} | class ____ {
private StringToOptionalConverter converter;
@BeforeEach
public void init() {
converter =
(StringToOptionalConverter) getExtensionLoader(Converter.class).getExtension("string-to-optional");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, Optional.class));
}
@Test
void testConvert() {
assertEquals(Optional.of("1"), converter.convert("1"));
assertEquals(Optional.empty(), converter.convert(null));
}
}
| StringToOptionalConverterTest |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/constants/QosConstants.java | {
"start": 853,
"end": 1732
} | interface ____ {
String QOS_ENABLE = "qos.enable";
String QOS_CHECK = "qos.check";
String QOS_HOST = "qos.host";
String QOS_PORT = "qos.port";
String ACCEPT_FOREIGN_IP = "qos.accept.foreign.ip";
String ACCEPT_FOREIGN_IP_WHITELIST = "qos.accept.foreign.ip.whitelist";
String ANONYMOUS_ACCESS_PERMISSION_LEVEL = "qos.anonymous.access.permission.level";
String ANONYMOUS_ACCESS_ALLOW_COMMANDS = "qos.anonymous.access.allow.commands";
String QOS_ENABLE_COMPATIBLE = "qos-enable";
String QOS_HOST_COMPATIBLE = "qos-host";
String QOS_PORT_COMPATIBLE = "qos-port";
String ACCEPT_FOREIGN_IP_COMPATIBLE = "qos-accept-foreign-ip";
String ACCEPT_FOREIGN_IP_WHITELIST_COMPATIBLE = "qos-accept-foreign-ip-whitelist";
String ANONYMOUS_ACCESS_PERMISSION_LEVEL_COMPATIBLE = "qos-anonymous-access-permission-level";
}
| QosConstants |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/selection/methodgenerics/objectfactory/ObjectFactoryMapper.java | {
"start": 456,
"end": 872
} | interface ____ {
ObjectFactoryMapper INSTANCE = Mappers.getMapper( ObjectFactoryMapper.class );
TargetA toTarget(SourceA source);
@ObjectFactory
default <T extends Target, S extends Source> T createTarget(S source, @TargetType Class<T> targetType) {
if ( source.isA() ) {
return (T) new TargetA();
}
return (T) new TargetB();
}
abstract | ObjectFactoryMapper |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/Simple.java | {
"start": 731,
"end": 1779
} | class ____ {
private Integer id1;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) {
scope.inTransaction( em -> {
IntTestEntity ite = new IntTestEntity( 10 );
em.persist( ite );
id1 = ite.getId();
} );
scope.inTransaction( em -> {
IntTestEntity ite = em.find( IntTestEntity.class, id1 );
ite.setNumber( 20 );
} );
}
@Test
public void testRevisionsCounts(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
assertEquals(
Arrays.asList( 1, 2 ),
AuditReaderFactory.get( em ).getRevisions( IntTestEntity.class, id1 )
);
} );
}
@Test
public void testHistoryOfId1(EntityManagerFactoryScope scope) {
IntTestEntity ver1 = new IntTestEntity( 10, id1 );
IntTestEntity ver2 = new IntTestEntity( 20, id1 );
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
assertEquals( ver1, auditReader.find( IntTestEntity.class, id1, 1 ) );
assertEquals( ver2, auditReader.find( IntTestEntity.class, id1, 2 ) );
} );
}
}
| Simple |
java | jhy__jsoup | src/main/java/org/jsoup/helper/RequestExecutor.java | {
"start": 364,
"end": 749
} | class ____ {
final Request req;
final @Nullable Response prevRes;
RequestExecutor(Request request, @Nullable Response previousResponse) {
this.req = request;
this.prevRes = previousResponse;
}
abstract Response execute() throws IOException;
abstract InputStream responseBody() throws IOException;
abstract void safeClose();
}
| RequestExecutor |
java | spring-projects__spring-boot | smoke-test/spring-boot-smoke-test-data-jpa/src/main/java/smoketest/data/jpa/service/HotelServiceImpl.java | {
"start": 2620,
"end": 3119
} | class ____ implements ReviewsSummary {
private final Map<Rating, Long> ratingCount;
ReviewsSummaryImpl(List<RatingCount> ratingCounts) {
this.ratingCount = new HashMap<>();
for (RatingCount ratingCount : ratingCounts) {
this.ratingCount.put(ratingCount.getRating(), ratingCount.getCount());
}
}
@Override
public long getNumberOfReviewsWithRating(Rating rating) {
Long count = this.ratingCount.get(rating);
return (count != null) ? count : 0;
}
}
}
| ReviewsSummaryImpl |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvtVO/PushMsg.java | {
"start": 7144,
"end": 15680
} | enum ____ {
INDEX_POS, INDEX_OPEN_URL, INDEX_DIMISS, INDEX_CANCEL_BTN, INDEX_TEXT_EFFECTS, INDEX_SHARE, INDEX_ATTACH_IMAGE, INDEX_LIMIT_SHOW_MAX_ONCE
}
private final int COUNT = INDEX_TYPE.values().length;
public static final int CTR_UNKNOWN = 0;
private String text;
/**
* <p>
* 展示位置(暂时只有顶部,居中)
* </p>
* <p>
* A:顶部(default)<br/>
* B:居中 <br/>
* </p>
*/
private char ctrlPos;
/**
* <p>
* URL打开方式
* </p>
* <p>
* A:内嵌打开(default)<br/>
* B:外部浏览器打开 <br/>
* </p>
*/
private char ctrlOpenUrl;
/**
* <p>
* 消失方式
* </p>
* <p>
* A:不消失(直至过期失效)(default)<br/>
* B:点击消失<br/>
* C:解锁消失 <br/>
* D:浏览消失<br/>
* E:解锁+点击消失 <br/>
* F:解锁+浏览消失 <br/>
* G:解锁+点击+浏览消失 <br/>
* </p>
*/
private char ctrlDimiss;
/**
* <p>
* 删除按钮
* </p>
* <p>
* A:显示(default)<br/>
* B:不显示 <br/>
* </p>
*/
private char ctrlCancelBtn;
/**
* <p>
* 是否支持分享
* </p>
* <p>
* A:开启(default)<br/>
* B:关闭<br/>
* </p>
*/
private char ctrlShare;
/**
* <p>
* 附加图片来源
* </p>
* <p>
* A:无图片(default)<br/>
* B:使用屏幕截图<br/>
* C:使用服务器指定的URL网络图片
* </p>
*/
private char ctrlAttachImage;
/**
* <p>
* 文案展示效果
* </p>
* <p>
* A:静止显示(default)<br/>
* B:滚动 <br/>
* </p>
*/
private char ctrlTextEffects;
/**
* <p>
* <b>同一gid通知</b>,限制最多展示一次
* </p>
* <p>
* A:否(default)
* </p>
* <p>
* B:是
* </p>
*/
private char ctrlLimitShowMaxOnce;
public ControlFlags(String param) {
this.text = param;
ctrlPos = text.charAt(INDEX_TYPE.INDEX_POS.ordinal());
ctrlOpenUrl = text.charAt(INDEX_TYPE.INDEX_OPEN_URL.ordinal());
ctrlDimiss = text.charAt(INDEX_TYPE.INDEX_DIMISS.ordinal());
ctrlCancelBtn = text.charAt(INDEX_TYPE.INDEX_CANCEL_BTN.ordinal());
ctrlShare = text.charAt(INDEX_TYPE.INDEX_SHARE.ordinal());
ctrlAttachImage = text.charAt(INDEX_TYPE.INDEX_ATTACH_IMAGE.ordinal());
ctrlTextEffects = text.charAt(INDEX_TYPE.INDEX_TEXT_EFFECTS.ordinal());
ctrlLimitShowMaxOnce = text.charAt(INDEX_TYPE.INDEX_LIMIT_SHOW_MAX_ONCE.ordinal());
}
/* control of position */
public boolean posTop() {
// default
return 'A' == ctrlPos || ctrlPos > 'B' || ctrlPos < 'A';
}
public boolean posCenter() {
return 'B' == ctrlPos;
}
/* control of open URL mode */
public boolean openUrlByInner() {
// default
return 'A' == ctrlOpenUrl || ctrlOpenUrl > 'B' || ctrlPos < 'A';
}
public boolean openUrlByOutside() {
return 'B' == ctrlOpenUrl;
}
/* control of dismiss */
public boolean nerverDismiss() {
// default
return 'A' == ctrlDimiss || ctrlDimiss > 'G' || ctrlPos < 'A';
}
public boolean dismissByUnlock() {
return 'C' == ctrlDimiss || 'D' == ctrlDimiss;
}
public boolean dismissByClick() {
return 'B' == ctrlDimiss || 'D' == ctrlDimiss;
}
/* control of show cancel btn */
public boolean showCancelBtn() {
// default
return 'A' == ctrlCancelBtn || ctrlCancelBtn > 'B' || ctrlPos < 'A';
}
/**
* 是否首页 或 Web页,开启分享按钮
*
* @return true if Not 'B'(B:首页 和 Web页均关闭分享按钮显示)
*/
public boolean enableShare() {
return 'B' != ctrlShare;
}
/* control of share */
/**
* 首页是否支持通知显示分享按钮
*
* @return true if equal 'A', 'C' or [*,A] || [D,*]
*/
public boolean enableShareInHomePage() {
// default
return 'A' == ctrlShare || 'C' == ctrlShare || ctrlShare > 'D' || ctrlPos < 'A';
}
/**
* Web页是否支持通知显示分享按钮
*
* @return true if equal 'A' Or 'D'
*/
public boolean enableShareInWebPage() {
// default
return 'A' == ctrlShare || 'D' == ctrlShare || ctrlShare > 'D' || ctrlPos < 'A';
}
/* control of use screen shot image */
public boolean attachNoImage() {
// default
return 'A' == ctrlAttachImage || ctrlAttachImage > 'C' || ctrlPos < 'A';
}
public boolean attachScreenShot() {
return 'B' == ctrlAttachImage;
}
public boolean attachWebUrlImage() {
return 'C' == ctrlAttachImage;
}
/* control of text effects */
public boolean isStaicTextEffects() {
return 'A' == ctrlTextEffects || ctrlTextEffects > 'C' || ctrlPos < 'A';
}
public boolean isScrollTextEffects() {
return 'B' == ctrlTextEffects;
}
public boolean isBlingTextEffects() {
return 'C' == ctrlTextEffects;
}
public boolean isLimitShowMaxOnce() {
return 'B' == ctrlLimitShowMaxOnce;
}
/**
*
* 控制字不能为空<br/>
* 控制字长度不少于所需长度
*
* @return true if valid, otherwise return false.
*/
public boolean isValid() {
return true;
}
/**
* 打印调试信息
*
* @return
*/
public String debug() {
StringBuilder sb = new StringBuilder();
sb.append("\n>>>>>>>>>>>");
sb.append("\nflag:" + text);
sb.append("\n(" + INDEX_TYPE.INDEX_POS.ordinal() + ")ctrlPos=" + ctrlPos);
sb.append("\n(" + INDEX_TYPE.INDEX_OPEN_URL.ordinal() + ")ctrlOpenUrl=" + ctrlOpenUrl);
sb.append("\n(" + INDEX_TYPE.INDEX_DIMISS.ordinal() + ")ctrlDismiss=" + ctrlDimiss);
sb.append("\n(" + INDEX_TYPE.INDEX_CANCEL_BTN.ordinal() + ")ctrlCancelBtn=" + ctrlCancelBtn);
sb.append("\n(" + INDEX_TYPE.INDEX_TEXT_EFFECTS.ordinal() + ")ctrlTextEffects=" + ctrlTextEffects);
sb.append("\n(" + INDEX_TYPE.INDEX_SHARE.ordinal() + ")ctrlShare=" + ctrlShare);
sb.append("\n(" + INDEX_TYPE.INDEX_ATTACH_IMAGE.ordinal() + ")ctrlAttachImage=" + ctrlAttachImage);
sb.append("\n(" + INDEX_TYPE.INDEX_LIMIT_SHOW_MAX_ONCE.ordinal() + ")ctrlLimitShowMaxOnce="
+ ctrlLimitShowMaxOnce);
sb.append("\n>>>>>>>>>>>");
return sb.toString();
}
}
}
/**
* 打印debug信息
*
* @return
*/
public String debug() {
StringBuilder sb = new StringBuilder();
sb.append("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
sb.append("\nid=" + id);
sb.append("\nst=" + st);
sb.append("\net=" + et);
sb.append("\ndr=" + dr);
sb.append("\nmsg=\n" + msg.debug());
sb.append("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
return sb.toString();
}
public long getDr() {
return dr;
}
public void setDr(long dr) {
this.dr = dr;
}
}
| INDEX_TYPE |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/bulk/TransportAbstractBulkAction.java | {
"start": 2770,
"end": 3010
} | class ____ bulk actions. It traverses all indices that the request gets routed to, executes all applicable
* pipelines, and then delegates to the concrete implementation of #doInternalExecute to actually index the data.
*/
public abstract | for |
java | spring-projects__spring-security | oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationTests.java | {
"start": 1771,
"end": 7375
} | class ____ {
private final OAuth2AccessToken token = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token",
Instant.now(), Instant.now().plusSeconds(3600));
private final String name = "sub";
private Map<String, Object> attributesMap = new HashMap<>();
private DefaultOAuth2AuthenticatedPrincipal principal;
private final Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("USER");
@BeforeEach
public void setUp() {
this.attributesMap.put(OAuth2TokenIntrospectionClaimNames.SUB, this.name);
this.attributesMap.put(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "client_id");
this.attributesMap.put(OAuth2TokenIntrospectionClaimNames.USERNAME, "username");
this.principal = new DefaultOAuth2AuthenticatedPrincipal(this.attributesMap, null);
}
@Test
public void getNameWhenConfiguredInConstructorThenReturnsName() {
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(this.name, this.attributesMap,
this.authorities);
BearerTokenAuthentication authenticated = new BearerTokenAuthentication(principal, this.token,
this.authorities);
assertThat(authenticated.getName()).isEqualTo(this.name);
}
@Test
public void getNameWhenHasNoSubjectThenReturnsNull() {
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(
Collections.singletonMap("claim", "value"), null);
BearerTokenAuthentication authenticated = new BearerTokenAuthentication(principal, this.token, null);
assertThat(authenticated.getName()).isNull();
}
@Test
public void getNameWhenTokenHasUsernameThenReturnsUsernameAttribute() {
BearerTokenAuthentication authenticated = new BearerTokenAuthentication(this.principal, this.token, null);
// @formatter:off
assertThat(authenticated.getName())
.isEqualTo(this.principal.getAttribute(OAuth2TokenIntrospectionClaimNames.SUB));
// @formatter:on
}
@Test
public void constructorWhenTokenIsNullThenThrowsException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenAuthentication(this.principal, null, null))
.withMessageContaining("token cannot be null");
// @formatter:on
}
@Test
public void constructorWhenCredentialIsNullThenThrowsException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenAuthentication(null, this.token, null))
.withMessageContaining("principal cannot be null");
// @formatter:on
}
@Test
public void constructorWhenPassingAllAttributesThenTokenIsAuthenticated() {
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal("harris",
Collections.singletonMap("claim", "value"), null);
BearerTokenAuthentication authenticated = new BearerTokenAuthentication(principal, this.token, null);
assertThat(authenticated.isAuthenticated()).isTrue();
}
@Test
public void getTokenAttributesWhenHasTokenThenReturnsThem() {
BearerTokenAuthentication authenticated = new BearerTokenAuthentication(this.principal, this.token,
Collections.emptyList());
assertThat(authenticated.getTokenAttributes()).isEqualTo(this.principal.getAttributes());
}
@Test
public void getAuthoritiesWhenHasAuthoritiesThenReturnsThem() {
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("USER");
BearerTokenAuthentication authenticated = new BearerTokenAuthentication(this.principal, this.token,
authorities);
assertThat(authenticated.getAuthorities()).isEqualTo(authorities);
}
// gh-6843
@Test
public void constructorWhenDefaultParametersThenSetsPrincipalToAttributesCopy() {
JSONObject attributes = new JSONObject();
attributes.put("active", true);
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(attributes, null);
BearerTokenAuthentication token = new BearerTokenAuthentication(principal, this.token, null);
assertThat(token.getPrincipal()).isNotSameAs(attributes);
assertThat(token.getTokenAttributes()).isNotSameAs(attributes);
}
// gh-6843
@Test
public void toStringWhenAttributesContainsURLThenDoesNotFail() throws Exception {
JSONObject attributes = new JSONObject(Collections.singletonMap("iss", new URL("https://idp.example.com")));
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(attributes, null);
BearerTokenAuthentication token = new BearerTokenAuthentication(principal, this.token, null);
token.toString();
}
@Test
public void toBuilderWhenApplyThenCopies() {
BearerTokenAuthentication factorOne = new BearerTokenAuthentication(TestOAuth2AuthenticatedPrincipals.active(),
this.token, AuthorityUtils.createAuthorityList("FACTOR_ONE"));
BearerTokenAuthentication factorTwo = new BearerTokenAuthentication(
TestOAuth2AuthenticatedPrincipals.active((m) -> m.put("k", "v")),
new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "nekot", Instant.now(),
Instant.now().plusSeconds(3600)),
AuthorityUtils.createAuthorityList("FACTOR_TWO"));
BearerTokenAuthentication authentication = factorOne.toBuilder()
.authorities((a) -> a.addAll(factorTwo.getAuthorities()))
.principal(factorTwo.getPrincipal())
.token(factorTwo.getToken())
.build();
Set<String> authorities = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
assertThat(authentication.getPrincipal()).isSameAs(factorTwo.getPrincipal());
assertThat(authentication.getToken()).isSameAs(factorTwo.getToken());
assertThat(authorities).containsExactlyInAnyOrder("FACTOR_ONE", "FACTOR_TWO");
}
}
| BearerTokenAuthenticationTests |
java | apache__camel | components/camel-ibm/camel-ibm-secrets-manager/src/generated/java/org/apache/camel/component/ibm/secrets/manager/IBMSecretsManagerEndpointConfigurer.java | {
"start": 746,
"end": 2997
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
IBMSecretsManagerEndpoint target = (IBMSecretsManagerEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "operation": target.getConfiguration().setOperation(property(camelContext, org.apache.camel.component.ibm.secrets.manager.IBMSecretsManagerOperation.class, value)); return true;
case "serviceurl":
case "serviceUrl": target.getConfiguration().setServiceUrl(property(camelContext, java.lang.String.class, value)); return true;
case "token": target.getConfiguration().setToken(property(camelContext, java.lang.String.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.ibm.secrets.manager.IBMSecretsManagerOperation.class;
case "serviceurl":
case "serviceUrl": return java.lang.String.class;
case "token": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
IBMSecretsManagerEndpoint target = (IBMSecretsManagerEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "operation": return target.getConfiguration().getOperation();
case "serviceurl":
case "serviceUrl": return target.getConfiguration().getServiceUrl();
case "token": return target.getConfiguration().getToken();
default: return null;
}
}
}
| IBMSecretsManagerEndpointConfigurer |
java | google__guice | extensions/testlib/test/com/google/inject/testing/fieldbinder/BoundFieldModuleTest.java | {
"start": 24380,
"end": 24859
} | class ____ {
@Bind(to = String.class)
Integer anInt;
}
public void testIncompatibleBindingTypeStackTraceHasUserFrame() {
Object instance = new InvalidBindableClass();
BoundFieldModule module = BoundFieldModule.of(instance);
try {
Guice.createInjector(module);
fail();
} catch (CreationException e) {
assertContains(e.getMessage(), "at BoundFieldModuleTest$InvalidBindableClass.anInt");
}
}
private static | InvalidBindableClass |
java | elastic__elasticsearch | x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/action/MoveToStepRequestTests.java | {
"start": 612,
"end": 3380
} | class ____ extends AbstractXContentSerializingTestCase<TransportMoveToStepAction.Request> {
private String index;
private static final StepKeyTests stepKeyTests = new StepKeyTests();
@Before
public void setup() {
index = randomAlphaOfLength(5);
}
@Override
protected TransportMoveToStepAction.Request createTestInstance() {
return new TransportMoveToStepAction.Request(
TEST_REQUEST_TIMEOUT,
TEST_REQUEST_TIMEOUT,
index,
stepKeyTests.createTestInstance(),
randomStepSpecification()
);
}
@Override
protected Writeable.Reader<TransportMoveToStepAction.Request> instanceReader() {
return TransportMoveToStepAction.Request::new;
}
@Override
protected TransportMoveToStepAction.Request doParseInstance(XContentParser parser) {
return TransportMoveToStepAction.Request.parseRequest(
(currentStepKey, nextStepKey) -> new TransportMoveToStepAction.Request(
TEST_REQUEST_TIMEOUT,
TEST_REQUEST_TIMEOUT,
index,
currentStepKey,
nextStepKey
),
parser
);
}
@Override
protected TransportMoveToStepAction.Request mutateInstance(TransportMoveToStepAction.Request request) {
String indexName = request.getIndex();
StepKey currentStepKey = request.getCurrentStepKey();
TransportMoveToStepAction.Request.PartialStepKey nextStepKey = request.getNextStepKey();
switch (between(0, 2)) {
case 0 -> indexName += randomAlphaOfLength(5);
case 1 -> currentStepKey = stepKeyTests.mutateInstance(currentStepKey);
case 2 -> nextStepKey = randomValueOtherThan(nextStepKey, MoveToStepRequestTests::randomStepSpecification);
default -> throw new AssertionError("Illegal randomisation branch");
}
return new TransportMoveToStepAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, indexName, currentStepKey, nextStepKey);
}
private static TransportMoveToStepAction.Request.PartialStepKey randomStepSpecification() {
if (randomBoolean()) {
StepKey key = stepKeyTests.createTestInstance();
return new TransportMoveToStepAction.Request.PartialStepKey(key.phase(), key.action(), key.name());
} else {
String phase = randomAlphaOfLength(10);
String action = randomBoolean() ? null : randomAlphaOfLength(6);
String name = action == null ? null : (randomBoolean() ? null : randomAlphaOfLength(6));
return new TransportMoveToStepAction.Request.PartialStepKey(phase, action, name);
}
}
}
| MoveToStepRequestTests |
java | apache__kafka | coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/Deserializer.java | {
"start": 1521,
"end": 2377
} | class ____ extends RuntimeException {
private final short type;
private final short unknownVersion;
public UnknownRecordVersionException(short type, short unknownVersion) {
super(String.format("Found an unknown record version %d for %d type", unknownVersion, type));
this.type = type;
this.unknownVersion = unknownVersion;
}
public short type() {
return type;
}
public short unknownVersion() {
return unknownVersion;
}
}
/**
* Deserializes the key and the value.
*
* @param key The key or null if not present.
* @param value The value or null if not present.
* @return The record.
*/
T deserialize(ByteBuffer key, ByteBuffer value) throws RuntimeException;
}
| UnknownRecordVersionException |
java | google__guava | android/guava-tests/test/com/google/common/collect/ListsImplTest.java | {
"start": 2003,
"end": 9054
} | class ____ {
private final String name;
private final Modifiability modifiability;
protected ListExample(String name, Modifiability modifiability) {
this.name = name;
this.modifiability = modifiability;
}
/** Gets the name of the example */
public String getName() {
return name;
}
/** Creates a new list with the given contents. */
public abstract <T> List<T> createList(Class<T> listType, Collection<? extends T> contents);
/** The modifiability of this list example. */
public Modifiability modifiability() {
return modifiability;
}
}
@J2ktIncompatible
@GwtIncompatible // suite
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(createExampleSuite(new ArrayListExample("ArrayList")));
suite.addTest(createExampleSuite(new LinkedListExample("LinkedList")));
suite.addTest(createExampleSuite(new ArraysAsListExample("Arrays.asList")));
suite.addTest(createExampleSuite(new ImmutableListExample("ImmutableList")));
suite.addTest(createExampleSuite(new CopyOnWriteListExample("CopyOnWriteArrayList")));
suite.addTestSuite(ListsImplTest.class);
return suite;
}
@J2ktIncompatible
@GwtIncompatible // suite sub call
private static TestSuite createExampleSuite(ListExample example) {
TestSuite resultSuite = new TestSuite(ListsImplTest.class);
for (Enumeration<Test> testEnum = resultSuite.tests(); testEnum.hasMoreElements(); ) {
ListsImplTest test = (ListsImplTest) testEnum.nextElement();
test.example = example;
}
return resultSuite;
}
private @Nullable ListExample example;
private ListExample getExample() {
// because sometimes one version with a null example is created.
return example == null ? new ImmutableListExample("test") : example;
}
@J2ktIncompatible
@GwtIncompatible // not used under GWT, and super.getName() is not available under J2CL
@Override
public String getName() {
return example == null ? super.getName() : buildTestName();
}
@J2ktIncompatible
@GwtIncompatible // not used under GWT, and super.getName() is not available under J2CL
private String buildTestName() {
return super.getName() + ":" + example.getName();
}
public void testHashCodeImpl() {
List<Integer> base = createList(Integer.class, 1, 2, 2);
List<Integer> copy = createList(Integer.class, 1, 2, 2);
List<Integer> outOfOrder = createList(Integer.class, 2, 2, 1);
List<Integer> diffValue = createList(Integer.class, 1, 2, 4);
List<Integer> diffLength = createList(Integer.class, 1, 2);
List<Integer> empty = createList(Integer.class);
assertThat(Lists.hashCodeImpl(base)).isEqualTo(Lists.hashCodeImpl(copy));
assertThat(Lists.hashCodeImpl(base)).isNotEqualTo(Lists.hashCodeImpl(outOfOrder));
assertThat(Lists.hashCodeImpl(base)).isNotEqualTo(Lists.hashCodeImpl(diffValue));
assertThat(Lists.hashCodeImpl(base)).isNotEqualTo(Lists.hashCodeImpl(diffLength));
assertThat(Lists.hashCodeImpl(base)).isNotEqualTo(Lists.hashCodeImpl(empty));
}
public void testEqualsImpl() {
List<Integer> base = createList(Integer.class, 1, 2, 2);
List<Integer> copy = createList(Integer.class, 1, 2, 2);
ImmutableList<Integer> otherType = ImmutableList.of(1, 2, 2);
List<Integer> outOfOrder = createList(Integer.class, 2, 2, 1);
List<Integer> diffValue = createList(Integer.class, 1, 2, 3);
List<Integer> diffLength = createList(Integer.class, 1, 2);
List<Integer> empty = createList(Integer.class);
assertThat(Lists.equalsImpl(base, copy)).isTrue();
assertThat(Lists.equalsImpl(base, otherType)).isTrue();
List<@Nullable Object> unEqualItems =
asList(outOfOrder, diffValue, diffLength, empty, null, new Object());
for (Object other : unEqualItems) {
assertWithMessage("%s", other).that(Lists.equalsImpl(base, other)).isFalse();
}
}
public void testAddAllImpl() {
if (getExample().modifiability() != Modifiability.ALL) {
return;
}
List<String> toTest = createList(String.class);
List<Iterable<String>> toAdd =
ImmutableList.of(
singleton("A"),
emptyList(),
ImmutableList.of("A", "B", "C"),
ImmutableList.of("D", "E"));
List<Integer> indexes = ImmutableList.of(0, 0, 1, 3);
List<List<String>> expected =
ImmutableList.of(
ImmutableList.of("A"),
ImmutableList.of("A"),
ImmutableList.of("A", "A", "B", "C"),
ImmutableList.of("A", "A", "D", "E", "B", "C"));
String format = "Adding %s at %s";
for (int i = 0; i < toAdd.size(); i++) {
int index = indexes.get(i);
Iterable<String> iterableToAdd = toAdd.get(i);
boolean expectedChanged = iterableToAdd.iterator().hasNext();
assertWithMessage(format, iterableToAdd, index)
.that(Lists.addAllImpl(toTest, index, iterableToAdd))
.isEqualTo(expectedChanged);
assertWithMessage(format, iterableToAdd, index)
.that(toTest)
.containsExactlyElementsIn(expected.get(i));
}
}
public void testIndexOfImpl_nonNull() {
List<Integer> toTest = createList(Integer.class, 5, 2, -1, 2, 1, 10, 5);
int[] expected = {0, 1, 2, 1, 4, 5, 0};
checkIndexOf(toTest, expected);
}
public void testIndexOfImpl_null() {
List<String> toTest;
try {
toTest = createList(String.class, null, "A", "B", null, "C", null);
} catch (NullPointerException e) {
// example cannot handle nulls, test invalid
return;
}
int[] expected = {0, 1, 2, 0, 4, 0};
checkIndexOf(toTest, expected);
}
public void testLastIndexOfImpl_nonNull() {
List<Integer> toTest = createList(Integer.class, 1, 5, 6, 10, 1, 3, 2, 1, 6);
int[] expected = {7, 1, 8, 3, 7, 5, 6, 7, 8};
checkLastIndexOf(toTest, expected);
}
public void testLastIndexOfImpl_null() {
List<String> toTest;
try {
toTest = createList(String.class, null, "A", "B", null, "C", "B");
} catch (NullPointerException e) {
// example cannot handle nulls, test invalid
return;
}
int[] expected = {3, 1, 5, 3, 4, 5};
checkLastIndexOf(toTest, expected);
}
private void checkIndexOf(List<?> toTest, int[] expected) {
int index = 0;
for (Object obj : toTest) {
String name = "toTest[" + index + "] (" + obj + ")";
assertWithMessage(name).that(Lists.indexOfImpl(toTest, obj)).isEqualTo(expected[index]);
index++;
}
}
private void checkLastIndexOf(List<?> toTest, int[] expected) {
int index = 0;
for (Object obj : toTest) {
String name = "toTest[" + index + "] (" + obj + ")";
assertWithMessage(name).that(Lists.lastIndexOfImpl(toTest, obj)).isEqualTo(expected[index]);
index++;
}
}
@SafeVarargs
private final <T> List<T> createList(Class<T> listType, T... contents) {
return getExample().createList(listType, asList(contents));
}
private static final | ListExample |
java | apache__kafka | connect/json/src/main/java/org/apache/kafka/connect/json/JsonConverter.java | {
"start": 35891,
"end": 36032
} | interface ____ {
Object convert(Schema schema, JsonNode value, JsonConverterConfig config);
}
private | JsonToConnectTypeConverter |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/client/api/AppAdminClient.java | {
"start": 1494,
"end": 2853
} | class ____ extends CompositeService {
public static final String YARN_APP_ADMIN_CLIENT_PREFIX = "yarn" +
".application.admin.client.class.";
public static final String DEFAULT_TYPE = "yarn-service";
public static final String DEFAULT_CLASS_NAME = "org.apache.hadoop.yarn" +
".service.client.ApiServiceClient";
public static final String UNIT_TEST_TYPE = "unit-test";
public static final String UNIT_TEST_CLASS_NAME = "org.apache.hadoop.yarn" +
".service.client.ServiceClient";
@Private
protected AppAdminClient() {
super(AppAdminClient.class.getName());
}
/**
* <p>
* Create a new instance of AppAdminClient.
* </p>
*
* @param appType application type
* @param conf configuration
* @return app admin client
*/
@Public
@Unstable
public static AppAdminClient createAppAdminClient(String appType,
Configuration conf) {
Map<String, String> clientClassMap =
conf.getPropsWithPrefix(YARN_APP_ADMIN_CLIENT_PREFIX);
if (!clientClassMap.containsKey(DEFAULT_TYPE)) {
clientClassMap.put(DEFAULT_TYPE, DEFAULT_CLASS_NAME);
}
if (!clientClassMap.containsKey(UNIT_TEST_TYPE)) {
clientClassMap.put(UNIT_TEST_TYPE, UNIT_TEST_CLASS_NAME);
}
if (!clientClassMap.containsKey(appType)) {
throw new IllegalArgumentException("App admin client | AppAdminClient |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/convert/PolymorphicUpdateValueTest.java | {
"start": 379,
"end": 623
} | class ____
{
@JsonTypeInfo(include=JsonTypeInfo.As.WRAPPER_ARRAY //PROPERTY
,use=JsonTypeInfo.Id.NAME, property="type")
@JsonSubTypes(value={ @JsonSubTypes.Type(value=Child.class)})
abstract static | PolymorphicUpdateValueTest |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/runtime/operators/sink/CommitterOperator.java | {
"start": 3430,
"end": 10604
} | class ____<CommT> extends AbstractStreamOperator<CommittableMessage<CommT>>
implements OneInputStreamOperator<CommittableMessage<CommT>, CommittableMessage<CommT>>,
BoundedOneInput {
private final SimpleVersionedSerializer<CommT> committableSerializer;
private final FunctionWithException<CommitterInitContext, Committer<CommT>, IOException>
committerSupplier;
private final boolean emitDownstream;
private final boolean isBatchMode;
private final boolean isCheckpointingEnabled;
private SinkCommitterMetricGroup metricGroup;
private Committer<CommT> committer;
private CommittableCollector<CommT> committableCollector;
private long lastCompletedCheckpointId = CheckpointIDCounter.INITIAL_CHECKPOINT_ID - 1;
private int maxRetries;
/** The operator's state descriptor. */
private static final ListStateDescriptor<byte[]> STREAMING_COMMITTER_RAW_STATES_DESC =
new ListStateDescriptor<>(
"streaming_committer_raw_states", BytePrimitiveArraySerializer.INSTANCE);
/** The operator's state. */
private ListState<CommittableCollector<CommT>> committableCollectorState;
public CommitterOperator(
StreamOperatorParameters<CommittableMessage<CommT>> parameters,
ProcessingTimeService processingTimeService,
SimpleVersionedSerializer<CommT> committableSerializer,
FunctionWithException<CommitterInitContext, Committer<CommT>, IOException>
committerSupplier,
boolean emitDownstream,
boolean isBatchMode,
boolean isCheckpointingEnabled) {
super(parameters);
this.emitDownstream = emitDownstream;
this.isBatchMode = isBatchMode;
this.isCheckpointingEnabled = isCheckpointingEnabled;
this.processingTimeService = checkNotNull(processingTimeService);
this.committableSerializer = checkNotNull(committableSerializer);
this.committerSupplier = checkNotNull(committerSupplier);
}
@Override
protected void setup(
StreamTask<?, ?> containingTask,
StreamConfig config,
Output<StreamRecord<CommittableMessage<CommT>>> output) {
super.setup(containingTask, config, output);
metricGroup = InternalSinkCommitterMetricGroup.wrap(getMetricGroup());
committableCollector = CommittableCollector.of(metricGroup);
maxRetries = config.getConfiguration().get(SinkOptions.COMMITTER_RETRIES);
}
@Override
public void initializeState(StateInitializationContext context) throws Exception {
super.initializeState(context);
OptionalLong checkpointId = context.getRestoredCheckpointId();
CommitterInitContext initContext =
new CommitterInitContextImpl(getRuntimeContext(), metricGroup, checkpointId);
committer = committerSupplier.apply(initContext);
committableCollectorState =
new SimpleVersionedListState<>(
context.getOperatorStateStore()
.getListState(STREAMING_COMMITTER_RAW_STATES_DESC),
new CommittableCollectorSerializer<>(
committableSerializer,
getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(),
getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks(),
metricGroup));
if (checkpointId.isPresent()) {
committableCollectorState.get().forEach(cc -> committableCollector.merge(cc));
lastCompletedCheckpointId = checkpointId.getAsLong();
// try to re-commit recovered transactions as quickly as possible
commitAndEmitCheckpoints(lastCompletedCheckpointId);
}
}
@Override
public void snapshotState(StateSnapshotContext context) throws Exception {
super.snapshotState(context);
// It is important to copy the collector to not mutate the state.
committableCollectorState.update(Collections.singletonList(committableCollector.copy()));
}
@Override
public void endInput() throws Exception {
if (!isCheckpointingEnabled || isBatchMode) {
// There will be no final checkpoint, all committables should be committed here
commitAndEmitCheckpoints(Long.MAX_VALUE);
}
}
@Override
public void notifyCheckpointComplete(long checkpointId) throws Exception {
super.notifyCheckpointComplete(checkpointId);
commitAndEmitCheckpoints(Math.max(lastCompletedCheckpointId, checkpointId));
}
private void commitAndEmitCheckpoints(long checkpointId)
throws IOException, InterruptedException {
lastCompletedCheckpointId = checkpointId;
for (CheckpointCommittableManager<CommT> checkpointManager :
committableCollector.getCheckpointCommittablesUpTo(checkpointId)) {
// ensure that all committables of the first checkpoint are fully committed before
// attempting the next committable
commitAndEmit(checkpointManager);
committableCollector.remove(checkpointManager);
}
}
private void commitAndEmit(CheckpointCommittableManager<CommT> committableManager)
throws IOException, InterruptedException {
committableManager.commit(committer, maxRetries);
if (emitDownstream) {
emit(committableManager);
}
}
private void emit(CheckpointCommittableManager<CommT> committableManager) {
int subtaskId = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask();
// Ensure that numberOfSubtasks is in sync with the number of actually emitted
// CommittableSummaries during upscaling recovery (see FLINK-37747).
int numberOfSubtasks =
Math.min(
getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks(),
committableManager.getNumberOfSubtasks());
long checkpointId = committableManager.getCheckpointId();
Collection<CommT> committables = committableManager.getSuccessfulCommittables();
output.collect(
new StreamRecord<>(
new CommittableSummary<>(
subtaskId,
numberOfSubtasks,
checkpointId,
committables.size(),
committableManager.getNumFailed())));
for (CommT committable : committables) {
output.collect(
new StreamRecord<>(
new CommittableWithLineage<>(committable, checkpointId, subtaskId)));
}
}
@Override
public void processElement(StreamRecord<CommittableMessage<CommT>> element) throws Exception {
committableCollector.addMessage(element.getValue());
}
@Override
public void close() throws Exception {
closeAll(committer, super::close);
}
}
| CommitterOperator |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/privilege/TransportDeletePrivilegesAction.java | {
"start": 1222,
"end": 2713
} | class ____ extends HandledTransportAction<DeletePrivilegesRequest, DeletePrivilegesResponse> {
private final NativePrivilegeStore privilegeStore;
@Inject
public TransportDeletePrivilegesAction(
ActionFilters actionFilters,
NativePrivilegeStore privilegeStore,
TransportService transportService
) {
super(
DeletePrivilegesAction.NAME,
transportService,
actionFilters,
DeletePrivilegesRequest::new,
EsExecutors.DIRECT_EXECUTOR_SERVICE
);
this.privilegeStore = privilegeStore;
}
@Override
protected void doExecute(Task task, final DeletePrivilegesRequest request, final ActionListener<DeletePrivilegesResponse> listener) {
if (request.privileges() == null || request.privileges().length == 0) {
listener.onResponse(new DeletePrivilegesResponse(Collections.emptyList()));
return;
}
final Set<String> names = Sets.newHashSet(request.privileges());
this.privilegeStore.deletePrivileges(
request.application(),
names,
request.getRefreshPolicy(),
ActionListener.wrap(
privileges -> listener.onResponse(
new DeletePrivilegesResponse(privileges.getOrDefault(request.application(), Collections.emptyList()))
),
listener::onFailure
)
);
}
}
| TransportDeletePrivilegesAction |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/chararrays/CharArrays_assertEndsWith_Test.java | {
"start": 1723,
"end": 7292
} | class ____ extends CharArraysBaseTest {
@Override
protected void initActualArray() {
actual = arrayOf('a', 'b', 'c', 'd');
}
@Test
void should_throw_error_if_sequence_is_null() {
assertThatNullPointerException().isThrownBy(() -> arrays.assertEndsWith(someInfo(), actual, null))
.withMessage(valuesToLookForIsNull());
}
@Test
void should_pass_if_actual_and_given_values_are_empty() {
actual = emptyArray();
arrays.assertEndsWith(someInfo(), actual, emptyArray());
}
@Test
void should_pass_if_array_of_values_to_look_for_is_empty_and_actual_is_not() {
arrays.assertEndsWith(someInfo(), actual, emptyArray());
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertEndsWith(someInfo(), null, arrayOf('a')))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_sequence_is_bigger_than_actual() {
AssertionInfo info = someInfo();
char[] sequence = { 'a', 'b', 'c', 'd', 'e', 'f' };
Throwable error = catchThrowable(() -> arrays.assertEndsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldEndWith(actual, sequence));
}
@Test
void should_fail_if_actual_does_not_end_with_sequence() {
AssertionInfo info = someInfo();
char[] sequence = { 'x', 'y', 'z' };
Throwable error = catchThrowable(() -> arrays.assertEndsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldEndWith(actual, sequence));
}
@Test
void should_fail_if_actual_ends_with_first_elements_of_sequence_only() {
AssertionInfo info = someInfo();
char[] sequence = { 'b', 'y', 'z' };
Throwable error = catchThrowable(() -> arrays.assertEndsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldEndWith(actual, sequence));
}
@Test
void should_pass_if_actual_ends_with_sequence() {
arrays.assertEndsWith(someInfo(), actual, arrayOf('b', 'c', 'd'));
}
@Test
void should_pass_if_actual_and_sequence_are_equal() {
arrays.assertEndsWith(someInfo(), actual, arrayOf('a', 'b', 'c', 'd'));
}
@Test
void should_throw_error_if_sequence_is_null_whatever_custom_comparison_strategy_is() {
assertThatNullPointerException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertEndsWith(someInfo(),
actual,
null))
.withMessage(valuesToLookForIsNull());
}
@Test
void should_pass_if_array_of_values_to_look_for_is_empty_and_actual_is_not_whatever_custom_comparison_strategy_is() {
arraysWithCustomComparisonStrategy.assertEndsWith(someInfo(), actual, emptyArray());
}
@Test
void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertEndsWith(someInfo(),
null,
arrayOf('A')))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_sequence_is_bigger_than_actual_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
char[] sequence = { 'A', 'b', 'c', 'd', 'e', 'f' };
Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertEndsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldEndWith(actual, sequence, caseInsensitiveComparisonStrategy));
}
@Test
void should_fail_if_actual_does_not_end_with_sequence_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
char[] sequence = { 'x', 'y', 'z' };
Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertEndsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldEndWith(actual, sequence, caseInsensitiveComparisonStrategy));
}
@Test
void should_fail_if_actual_ends_with_first_elements_of_sequence_only_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
char[] sequence = { 'b', 'y', 'z' };
Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertEndsWith(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldEndWith(actual, sequence, caseInsensitiveComparisonStrategy));
}
@Test
void should_pass_if_actual_ends_with_sequence_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertEndsWith(someInfo(), actual, arrayOf('b', 'c', 'd'));
}
@Test
void should_pass_if_actual_and_sequence_are_equal_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertEndsWith(someInfo(), actual, arrayOf('A', 'b', 'c', 'd'));
}
}
| CharArrays_assertEndsWith_Test |
java | google__guava | android/guava/src/com/google/common/graph/ValueGraphBuilder.java | {
"start": 1159,
"end": 1417
} | class ____ the following default properties:
*
* <ul>
* <li>does not allow self-loops
* <li>orders {@link ValueGraph#nodes()} in the order in which the elements were added (insertion
* order)
* </ul>
*
* <p>{@code ValueGraph}s built by this | has |
java | alibaba__nacos | console/src/main/java/com/alibaba/nacos/console/handler/impl/noop/naming/ServiceNoopHandler.java | {
"start": 1703,
"end": 4384
} | class ____ implements ServiceHandler {
private static final String MCP_NOT_ENABLED_MESSAGE = "Current functionMode is `config`, naming module is disabled.";
@Override
public void createService(ServiceForm serviceForm, ServiceMetadata serviceMetadata) throws Exception {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public void deleteService(String namespaceId, String serviceName, String groupName) throws Exception {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public void updateService(ServiceForm serviceForm, ServiceMetadata serviceMetadata) throws Exception {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public List<String> getSelectorTypeList() throws NacosException {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public Page<SubscriberInfo> getSubscribers(int pageNo, int pageSize, String namespaceId, String serviceName,
String groupName, boolean aggregation) throws Exception {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public Object getServiceList(boolean withInstances, String namespaceId, int pageNo, int pageSize,
String serviceName, String groupName, boolean ignoreEmptyService) throws NacosException {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public ServiceDetailInfo getServiceDetail(String namespaceId, String serviceName, String groupName)
throws NacosException {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public void updateClusterMetadata(String namespaceId, String groupName, String serviceName, String clusterName,
ClusterMetadata clusterMetadata) throws Exception {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
}
| ServiceNoopHandler |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/errors/LogAndFailProcessingExceptionHandler.java | {
"start": 1303,
"end": 2562
} | class ____ implements ProcessingExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(LogAndFailProcessingExceptionHandler.class);
private String deadLetterQueueTopic = null;
@Override
public Response handleError(final ErrorHandlerContext context,
final Record<?, ?> record,
final Exception exception) {
log.error(
"Exception caught during message processing, processor node: {}, taskId: {}, source topic: {}, source partition: {}, source offset: {}",
context.processorNodeId(),
context.taskId(),
context.topic(),
context.partition(),
context.offset(),
exception
);
return Response.fail(maybeBuildDeadLetterQueueRecords(deadLetterQueueTopic, context.sourceRawKey(), context.sourceRawValue(), context, exception));
}
@Override
public void configure(final Map<String, ?> configs) {
if (configs.get(StreamsConfig.ERRORS_DEAD_LETTER_QUEUE_TOPIC_NAME_CONFIG) != null)
deadLetterQueueTopic = String.valueOf(configs.get(StreamsConfig.ERRORS_DEAD_LETTER_QUEUE_TOPIC_NAME_CONFIG));
}
}
| LogAndFailProcessingExceptionHandler |
java | greenrobot__EventBus | EventBusTestJava/src/main/java/org/greenrobot/eventbus/EventBusBasicTest.java | {
"start": 7784,
"end": 7989
} | class ____ {
public String lastStringEvent;
@Subscribe
public void onEvent(String event) {
lastStringEvent = event;
}
}
public static | StringEventSubscriber |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/text/FormattableUtilsTest.java | {
"start": 1197,
"end": 8686
} | class ____ extends AbstractLangTest {
@Test
void testAlternatePadCharacter() {
final char pad = '_';
assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, pad).toString());
assertEquals("fo", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, pad).toString());
assertEquals("_foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, pad).toString());
assertEquals("___foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1, pad).toString());
assertEquals("_fo", FormattableUtils.append("foo", new Formatter(), 0, 3, 2, pad).toString());
assertEquals("___fo", FormattableUtils.append("foo", new Formatter(), 0, 5, 2, pad).toString());
assertEquals("foo_", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 4, -1, pad).toString());
assertEquals("foo___", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 6, -1, pad).toString());
assertEquals("fo_", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 3, 2, pad).toString());
assertEquals("fo___", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 5, 2, pad).toString());
}
@Test
void testAlternatePadCharAndEllipsis() {
assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, '_', "*").toString());
assertEquals("f*", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, '_', "*").toString());
assertEquals("_foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, '_', "*").toString());
assertEquals("___foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1, '_', "*").toString());
assertEquals("_f*", FormattableUtils.append("foo", new Formatter(), 0, 3, 2, '_', "*").toString());
assertEquals("___f*", FormattableUtils.append("foo", new Formatter(), 0, 5, 2, '_', "*").toString());
assertEquals("foo_", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 4, -1, '_', "*").toString());
assertEquals("foo___", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 6, -1, '_', "*").toString());
assertEquals("f*_", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 3, 2, '_', "*").toString());
assertEquals("f*___", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 5, 2, '_', "*").toString());
assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, '_', "+*").toString());
assertEquals("+*", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, '_', "+*").toString());
assertEquals("_foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, '_', "+*").toString());
assertEquals("___foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1, '_', "+*").toString());
assertEquals("_+*", FormattableUtils.append("foo", new Formatter(), 0, 3, 2, '_', "+*").toString());
assertEquals("___+*", FormattableUtils.append("foo", new Formatter(), 0, 5, 2, '_', "+*").toString());
assertEquals("foo_", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 4, -1, '_', "+*").toString());
assertEquals("foo___", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 6, -1, '_', "+*").toString());
assertEquals("+*_", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 3, 2, '_', "+*").toString());
assertEquals("+*___", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 5, 2, '_', "+*").toString());
}
@Test
void testDefaultAppend() {
assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1).toString());
assertEquals("fo", FormattableUtils.append("foo", new Formatter(), 0, -1, 2).toString());
assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1).toString());
assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1).toString());
assertEquals(" fo", FormattableUtils.append("foo", new Formatter(), 0, 3, 2).toString());
assertEquals(" fo", FormattableUtils.append("foo", new Formatter(), 0, 5, 2).toString());
assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 4, -1).toString());
assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 6, -1).toString());
assertEquals("fo ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 3, 2).toString());
assertEquals("fo ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 5, 2).toString());
}
@Test
void testEllipsis() {
assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, "*").toString());
assertEquals("f*", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, "*").toString());
assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, "*").toString());
assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1, "*").toString());
assertEquals(" f*", FormattableUtils.append("foo", new Formatter(), 0, 3, 2, "*").toString());
assertEquals(" f*", FormattableUtils.append("foo", new Formatter(), 0, 5, 2, "*").toString());
assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 4, -1, "*").toString());
assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 6, -1, "*").toString());
assertEquals("f* ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 3, 2, "*").toString());
assertEquals("f* ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 5, 2, "*").toString());
assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, "+*").toString());
assertEquals("+*", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, "+*").toString());
assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, "+*").toString());
assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1, "+*").toString());
assertEquals(" +*", FormattableUtils.append("foo", new Formatter(), 0, 3, 2, "+*").toString());
assertEquals(" +*", FormattableUtils.append("foo", new Formatter(), 0, 5, 2, "+*").toString());
assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 4, -1, "+*").toString());
assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 6, -1, "+*").toString());
assertEquals("+* ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 3, 2, "+*").toString());
assertEquals("+* ", FormattableUtils.append("foo", new Formatter(), FormattableFlags.LEFT_JUSTIFY, 5, 2, "+*").toString());
}
@Test
void testIllegalEllipsis() {
assertIllegalArgumentException(() -> FormattableUtils.append("foo", new Formatter(), 0, -1, 1, "xx"));
}
}
| FormattableUtilsTest |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/support/logging/SLF4JImpl.java | {
"start": 767,
"end": 3651
} | class ____ implements Log {
private static final String callerFQCN = SLF4JImpl.class.getName();
private static final Logger testLogger = LoggerFactory.getLogger(SLF4JImpl.class);
static {
// if the logger is not a LocationAwareLogger instance, it can not get correct stack StackTraceElement
// so ignore this implementation.
if (!(testLogger instanceof LocationAwareLogger)) {
throw new UnsupportedOperationException(testLogger.getClass() + " is not a suitable logger");
}
}
private int errorCount;
private int warnCount;
private int infoCount;
private int debugCount;
private LocationAwareLogger log;
public SLF4JImpl(LocationAwareLogger log) {
this.log = log;
}
public SLF4JImpl(String loggerName) {
this.log = (LocationAwareLogger) LoggerFactory.getLogger(loggerName);
}
@Override
public boolean isDebugEnabled() {
return log.isDebugEnabled();
}
@Override
public void error(String msg, Throwable e) {
log.log(null, callerFQCN, LocationAwareLogger.ERROR_INT, msg, null, e);
errorCount++;
}
@Override
public void error(String msg) {
log.log(null, callerFQCN, LocationAwareLogger.ERROR_INT, msg, null, null);
errorCount++;
}
@Override
public boolean isInfoEnabled() {
return log.isInfoEnabled();
}
@Override
public void info(String msg) {
infoCount++;
log.log(null, callerFQCN, LocationAwareLogger.INFO_INT, msg, null, null);
}
@Override
public void debug(String msg) {
debugCount++;
log.log(null, callerFQCN, LocationAwareLogger.DEBUG_INT, msg, null, null);
}
@Override
public void debug(String msg, Throwable e) {
debugCount++;
log.log(null, callerFQCN, LocationAwareLogger.DEBUG_INT, msg, null, e);
}
@Override
public boolean isWarnEnabled() {
return log.isWarnEnabled();
}
@Override
public boolean isErrorEnabled() {
return log.isErrorEnabled();
}
@Override
public void warn(String msg) {
log.log(null, callerFQCN, LocationAwareLogger.WARN_INT, msg, null, null);
warnCount++;
}
@Override
public void warn(String msg, Throwable e) {
log.log(null, callerFQCN, LocationAwareLogger.WARN_INT, msg, null, e);
warnCount++;
}
@Override
public int getErrorCount() {
return errorCount;
}
@Override
public int getWarnCount() {
return warnCount;
}
@Override
public int getInfoCount() {
return infoCount;
}
public int getDebugCount() {
return debugCount;
}
@Override
public void resetStat() {
errorCount = 0;
warnCount = 0;
infoCount = 0;
debugCount = 0;
}
}
| SLF4JImpl |
java | FasterXML__jackson-core | src/main/java/tools/jackson/core/exc/UnexpectedEndOfInputException.java | {
"start": 389,
"end": 1161
} | class ____
extends StreamReadException
{
private static final long serialVersionUID = 3L;
/**
* Type of token that was being decoded, if parser had enough information
* to recognize type (such as starting double-quote for Strings)
*/
protected final JsonToken _token;
public UnexpectedEndOfInputException(JsonParser p, JsonToken token, String msg) {
super(p, msg);
_token = token;
}
/**
* Accessor for possibly available information about token that was being
* decoded while encountering end of input.
*
* @return JsonToken that was being decoded while encountering end-of-input
*/
public JsonToken getTokenBeingDecoded() {
return _token;
}
}
| UnexpectedEndOfInputException |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/config/AbstractInterceptorDrivenBeanDefinitionDecorator.java | {
"start": 2574,
"end": 5879
} | class ____ implements BeanDefinitionDecorator {
@Override
public final BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definitionHolder, ParserContext parserContext) {
BeanDefinitionRegistry registry = parserContext.getRegistry();
// get the root bean name - will be the name of the generated proxy factory bean
String existingBeanName = definitionHolder.getBeanName();
BeanDefinition targetDefinition = definitionHolder.getBeanDefinition();
BeanDefinitionHolder targetHolder = new BeanDefinitionHolder(targetDefinition, existingBeanName + ".TARGET");
// delegate to subclass for interceptor definition
BeanDefinition interceptorDefinition = createInterceptorDefinition(node);
// generate name and register the interceptor
String interceptorName = existingBeanName + '.' + getInterceptorNameSuffix(interceptorDefinition);
BeanDefinitionReaderUtils.registerBeanDefinition(
new BeanDefinitionHolder(interceptorDefinition, interceptorName), registry);
BeanDefinitionHolder result = definitionHolder;
if (!isProxyFactoryBeanDefinition(targetDefinition)) {
// create the proxy definition
RootBeanDefinition proxyDefinition = new RootBeanDefinition();
// create proxy factory bean definition
proxyDefinition.setBeanClass(ProxyFactoryBean.class);
proxyDefinition.setScope(targetDefinition.getScope());
proxyDefinition.setLazyInit(targetDefinition.isLazyInit());
// set the target
proxyDefinition.setDecoratedDefinition(targetHolder);
proxyDefinition.getPropertyValues().add("target", targetHolder);
// create the interceptor names list
proxyDefinition.getPropertyValues().add("interceptorNames", new ManagedList<>());
// copy autowire settings from original bean definition.
proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
proxyDefinition.setPrimary(targetDefinition.isPrimary());
if (targetDefinition instanceof AbstractBeanDefinition abd) {
proxyDefinition.copyQualifiersFrom(abd);
}
// wrap it in a BeanDefinitionHolder with bean name
result = new BeanDefinitionHolder(proxyDefinition, existingBeanName);
}
addInterceptorNameToList(interceptorName, result.getBeanDefinition());
return result;
}
@SuppressWarnings("unchecked")
private void addInterceptorNameToList(String interceptorName, BeanDefinition beanDefinition) {
List<String> list = (List<String>) beanDefinition.getPropertyValues().get("interceptorNames");
Assert.state(list != null, "Missing 'interceptorNames' property");
list.add(interceptorName);
}
private boolean isProxyFactoryBeanDefinition(BeanDefinition existingDefinition) {
return ProxyFactoryBean.class.getName().equals(existingDefinition.getBeanClassName());
}
protected String getInterceptorNameSuffix(BeanDefinition interceptorDefinition) {
String beanClassName = interceptorDefinition.getBeanClassName();
return (StringUtils.hasLength(beanClassName) ?
StringUtils.uncapitalize(ClassUtils.getShortName(beanClassName)) : "");
}
/**
* Subclasses should implement this method to return the {@code BeanDefinition}
* for the interceptor they wish to apply to the bean being decorated.
*/
protected abstract BeanDefinition createInterceptorDefinition(Node node);
}
| AbstractInterceptorDrivenBeanDefinitionDecorator |
java | apache__camel | core/camel-core-languages/src/main/java/org/apache/camel/language/constant/ConstantLanguage.java | {
"start": 1307,
"end": 2849
} | class ____ extends LanguageSupport {
public static Expression constant(Object value) {
return ExpressionBuilder.constantExpression(value);
}
@Override
public Predicate createPredicate(String expression) {
return ExpressionToPredicateAdapter.toPredicate(createExpression(expression));
}
@Override
public Expression createExpression(String expression) {
if (expression != null && isStaticResource(expression)) {
expression = loadResource(expression);
}
return ConstantLanguage.constant(expression);
}
@Override
public Predicate createPredicate(String expression, Object[] properties) {
Expression exp = createExpression(expression, properties);
return ExpressionToPredicateAdapter.toPredicate(exp);
}
@Override
public Expression createExpression(String expression, Object[] properties) {
Class<?> resultType = property(Class.class, properties, 0, null);
if (resultType != null) {
try {
// convert constant to result type eager as its a constant
Object value = getCamelContext().getTypeConverter().mandatoryConvertTo(resultType, expression);
return ExpressionBuilder.constantExpression(value);
} catch (NoTypeConversionAvailableException e) {
throw RuntimeCamelException.wrapRuntimeException(e);
}
} else {
return ConstantLanguage.constant(expression);
}
}
}
| ConstantLanguage |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ServerRequest.java | {
"start": 6532,
"end": 16538
} | class ____ bind this request to
* @param dataBinderCustomizer used to customize the data binder, for example, set
* (dis)allowed fields
* @param <T> the type to bind to
* @return a mono containing either a constructed and bound instance of
* {@code bindType}, or a {@link BindException} in case of binding errors
* @since 6.1
*/
<T> Mono<T> bind(Class<T> bindType, Consumer<WebDataBinder> dataBinderCustomizer);
/**
* Get the request attribute value if present.
* @param name the attribute name
* @return the attribute value
*/
default Optional<Object> attribute(String name) {
return Optional.ofNullable(attributes().get(name));
}
/**
* Get a mutable map of request attributes.
* @return the request attributes
*/
Map<String, Object> attributes();
/**
* Get the first query parameter with the given name, if present.
* @param name the parameter name
* @return the parameter value
*/
default Optional<String> queryParam(String name) {
List<String> queryParamValues = queryParams().get(name);
if (CollectionUtils.isEmpty(queryParamValues)) {
return Optional.empty();
}
else {
String value = queryParamValues.get(0);
if (value == null) {
value = "";
}
return Optional.of(value);
}
}
/**
* Get all query parameters for this request.
*/
MultiValueMap<String, String> queryParams();
/**
* Get the path variable with the given name, if present.
* @param name the variable name
* @return the variable value
* @throws IllegalArgumentException if there is no path variable with the given name
*/
default String pathVariable(String name) {
Map<String, String> pathVariables = pathVariables();
if (pathVariables.containsKey(name)) {
return pathVariables.get(name);
}
else {
throw new IllegalArgumentException("No path variable with name \"" + name + "\" available");
}
}
/**
* Get all path variables for this request.
*/
Map<String, String> pathVariables();
/**
* Get the web session for this request.
* <p>Always guaranteed to return an instance either matching the session id
* requested by the client, or with a new session id either because the client
* did not specify one or because the underlying session had expired.
* <p>Use of this method does not automatically create a session.
*/
Mono<WebSession> session();
/**
* Get the authenticated user for the request, if any.
*/
Mono<? extends Principal> principal();
/**
* Get the form data from the body of the request if the Content-Type is
* {@code "application/x-www-form-urlencoded"} or an empty map otherwise.
* <p><strong>Note:</strong> calling this method causes the request body to
* be read and parsed in full, and the resulting {@code MultiValueMap} is
* cached so that this method is safe to call more than once.
*/
Mono<MultiValueMap<String, String>> formData();
/**
* Get the parts of a multipart request if the Content-Type is
* {@code "multipart/form-data"} or an empty map otherwise.
* <p><strong>Note:</strong> calling this method causes the request body to
* be read and parsed in full, and the resulting {@code MultiValueMap} is
* cached so that this method is safe to call more than once.
*/
Mono<MultiValueMap<String, Part>> multipartData();
/**
* Get the web exchange that this request is based on.
* <p>Note: Manipulating the exchange directly (instead of using the methods provided on
* {@code ServerRequest} and {@code ServerResponse}) can lead to irregular results.
* @since 5.1
*/
ServerWebExchange exchange();
/**
* Check whether the requested resource has been modified given the
* supplied last-modified timestamp (as determined by the application).
* <p>If not modified, this method returns a response with corresponding
* status code and headers, otherwise an empty result.
* <p>Typical usage:
* <pre class="code">
* public Mono<ServerResponse> myHandleMethod(ServerRequest request) {
* Instant lastModified = // application-specific calculation
* return request.checkNotModified(lastModified)
* .switchIfEmpty(Mono.defer(() -> {
* // further request processing, actually building content
* return ServerResponse.ok().body(...);
* }));
* }</pre>
* <p>This method works with conditional GET/HEAD requests, but
* also with conditional POST/PUT/DELETE requests.
* <p><strong>Note:</strong> you can use either
* this {@code #checkNotModified(Instant)} method; or
* {@link #checkNotModified(String)}. If you want to enforce both
* a strong entity tag and a Last-Modified value,
* as recommended by the HTTP specification,
* then you should use {@link #checkNotModified(Instant, String)}.
* @param lastModified the last-modified timestamp that the
* application determined for the underlying resource
* @return a corresponding response if the request qualifies as not
* modified, or an empty result otherwise
* @since 5.2.5
*/
default Mono<ServerResponse> checkNotModified(Instant lastModified) {
Assert.notNull(lastModified, "LastModified must not be null");
return DefaultServerRequest.checkNotModified(exchange(), lastModified, null);
}
/**
* Check whether the requested resource has been modified given the
* supplied {@code ETag} (entity tag), as determined by the application.
* <p>If not modified, this method returns a response with corresponding
* status code and headers, otherwise an empty result.
* <p>Typical usage:
* <pre class="code">
* public Mono<ServerResponse> myHandleMethod(ServerRequest request) {
* String eTag = // application-specific calculation
* return request.checkNotModified(eTag)
* .switchIfEmpty(Mono.defer(() -> {
* // further request processing, actually building content
* return ServerResponse.ok().body(...);
* }));
* }</pre>
* <p>This method works with conditional GET/HEAD requests, but
* also with conditional POST/PUT/DELETE requests.
* <p><strong>Note:</strong> you can use either
* this {@link #checkNotModified(Instant)} method; or
* {@code #checkNotModified(String)}. If you want to enforce both
* a strong entity tag and a Last-Modified value,
* as recommended by the HTTP specification,
* then you should use {@link #checkNotModified(Instant, String)}.
* @param etag the entity tag that the application determined
* for the underlying resource. This parameter will be padded
* with quotes (") if necessary. Use an empty string {@code ""}
* for no value.
* @return a corresponding response if the request qualifies as not
* modified, or an empty result otherwise
* @since 5.2.5
*/
default Mono<ServerResponse> checkNotModified(String etag) {
Assert.notNull(etag, "Etag must not be null");
return DefaultServerRequest.checkNotModified(exchange(), null, etag);
}
/**
* Check whether the requested resource has been modified given the
* supplied {@code ETag} (entity tag) and last-modified timestamp,
* as determined by the application.
* <p>If not modified, this method returns a response with corresponding
* status code and headers, otherwise an empty result.
* <p>Typical usage:
* <pre class="code">
* public Mono<ServerResponse> myHandleMethod(ServerRequest request) {
* Instant lastModified = // application-specific calculation
* String eTag = // application-specific calculation
* return request.checkNotModified(lastModified, eTag)
* .switchIfEmpty(Mono.defer(() -> {
* // further request processing, actually building content
* return ServerResponse.ok().body(...);
* }));
* }</pre>
* <p>This method works with conditional GET/HEAD requests, but
* also with conditional POST/PUT/DELETE requests.
* @param lastModified the last-modified timestamp that the
* application determined for the underlying resource
* @param etag the entity tag that the application determined
* for the underlying resource. This parameter will be padded
* with quotes (") if necessary. Use an empty string {@code ""}
* for no value.
* @return a corresponding response if the request qualifies as not
* modified, or an empty result otherwise.
* @since 5.2.5
*/
default Mono<ServerResponse> checkNotModified(Instant lastModified, String etag) {
Assert.notNull(lastModified, "LastModified must not be null");
Assert.notNull(etag, "Etag must not be null");
return DefaultServerRequest.checkNotModified(exchange(), lastModified, etag);
}
// Static builder methods
/**
* Create a new {@code ServerRequest} based on the given {@code ServerWebExchange} and
* message readers.
* @param exchange the exchange
* @param messageReaders the message readers
* @return the created {@code ServerRequest}
*/
static ServerRequest create(ServerWebExchange exchange, List<HttpMessageReader<?>> messageReaders) {
return new DefaultServerRequest(exchange, messageReaders);
}
/**
* Create a new {@code ServerRequest} based on the given {@code ServerWebExchange} and
* message readers.
* @param exchange the exchange
* @param messageReaders the message readers
* @param versionStrategy a strategy to use to parse version
* @return the created {@code ServerRequest}
* @since 7.0
*/
static ServerRequest create(
ServerWebExchange exchange, List<HttpMessageReader<?>> messageReaders,
@Nullable ApiVersionStrategy versionStrategy) {
return new DefaultServerRequest(exchange, messageReaders, versionStrategy);
}
/**
* Create a builder with the {@linkplain HttpMessageReader message readers},
* method name, URI, headers, cookies, and attributes of the given request.
* @param other the request to copy the message readers, method name, URI,
* headers, and attributes from
* @return the created builder
* @since 5.1
*/
static Builder from(ServerRequest other) {
return new DefaultServerRequestBuilder(other);
}
/**
* Represents the headers of the HTTP request.
* @see ServerRequest#headers()
*/
| to |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/codec/vectors/es818/ES818BinaryQuantizedVectorsWriter.java | {
"start": 3407,
"end": 31140
} | class ____ extends FlatVectorsWriter {
private static final long SHALLOW_RAM_BYTES_USED = shallowSizeOfInstance(ES818BinaryQuantizedVectorsWriter.class);
private final SegmentWriteState segmentWriteState;
private final List<FieldWriter> fields = new ArrayList<>();
private final IndexOutput meta, binarizedVectorData;
private final FlatVectorsWriter rawVectorDelegate;
private final ES818BinaryFlatVectorsScorer vectorsScorer;
private boolean finished;
/**
* Sole constructor
*
* @param vectorsScorer the scorer to use for scoring vectors
*/
@SuppressWarnings("this-escape")
public ES818BinaryQuantizedVectorsWriter(
ES818BinaryFlatVectorsScorer vectorsScorer,
FlatVectorsWriter rawVectorDelegate,
SegmentWriteState state
) throws IOException {
super(vectorsScorer);
this.vectorsScorer = vectorsScorer;
this.segmentWriteState = state;
String metaFileName = IndexFileNames.segmentFileName(
state.segmentInfo.name,
state.segmentSuffix,
ES818BinaryQuantizedVectorsFormat.META_EXTENSION
);
String binarizedVectorDataFileName = IndexFileNames.segmentFileName(
state.segmentInfo.name,
state.segmentSuffix,
ES818BinaryQuantizedVectorsFormat.VECTOR_DATA_EXTENSION
);
this.rawVectorDelegate = rawVectorDelegate;
boolean success = false;
try {
meta = state.directory.createOutput(metaFileName, state.context);
binarizedVectorData = state.directory.createOutput(binarizedVectorDataFileName, state.context);
CodecUtil.writeIndexHeader(
meta,
ES818BinaryQuantizedVectorsFormat.META_CODEC_NAME,
ES818BinaryQuantizedVectorsFormat.VERSION_CURRENT,
state.segmentInfo.getId(),
state.segmentSuffix
);
CodecUtil.writeIndexHeader(
binarizedVectorData,
ES818BinaryQuantizedVectorsFormat.VECTOR_DATA_CODEC_NAME,
ES818BinaryQuantizedVectorsFormat.VERSION_CURRENT,
state.segmentInfo.getId(),
state.segmentSuffix
);
success = true;
} finally {
if (success == false) {
IOUtils.closeWhileHandlingException(this);
}
}
}
@Override
public FlatFieldVectorsWriter<?> addField(FieldInfo fieldInfo) throws IOException {
FlatFieldVectorsWriter<?> rawVectorDelegate = this.rawVectorDelegate.addField(fieldInfo);
if (fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32)) {
@SuppressWarnings("unchecked")
FieldWriter fieldWriter = new FieldWriter(fieldInfo, (FlatFieldVectorsWriter<float[]>) rawVectorDelegate);
fields.add(fieldWriter);
return fieldWriter;
}
return rawVectorDelegate;
}
@Override
public void flush(int maxDoc, Sorter.DocMap sortMap) throws IOException {
rawVectorDelegate.flush(maxDoc, sortMap);
for (FieldWriter field : fields) {
// after raw vectors are written, normalize vectors for clustering and quantization
if (VectorSimilarityFunction.COSINE == field.fieldInfo.getVectorSimilarityFunction()) {
field.normalizeVectors();
}
final float[] clusterCenter;
int vectorCount = field.flatFieldVectorsWriter.getVectors().size();
clusterCenter = new float[field.dimensionSums.length];
if (vectorCount > 0) {
for (int i = 0; i < field.dimensionSums.length; i++) {
clusterCenter[i] = field.dimensionSums[i] / vectorCount;
}
if (VectorSimilarityFunction.COSINE == field.fieldInfo.getVectorSimilarityFunction()) {
VectorUtil.l2normalize(clusterCenter);
}
}
if (segmentWriteState.infoStream.isEnabled(BINARIZED_VECTOR_COMPONENT)) {
segmentWriteState.infoStream.message(BINARIZED_VECTOR_COMPONENT, "Vectors' count:" + vectorCount);
}
OptimizedScalarQuantizer quantizer = new OptimizedScalarQuantizer(field.fieldInfo.getVectorSimilarityFunction());
if (sortMap == null) {
writeField(field, clusterCenter, maxDoc, quantizer);
} else {
writeSortingField(field, clusterCenter, maxDoc, sortMap, quantizer);
}
field.finish();
}
}
private void writeField(FieldWriter fieldData, float[] clusterCenter, int maxDoc, OptimizedScalarQuantizer quantizer)
throws IOException {
// write vector values
long vectorDataOffset = binarizedVectorData.alignFilePointer(Float.BYTES);
writeBinarizedVectors(fieldData, clusterCenter, quantizer);
long vectorDataLength = binarizedVectorData.getFilePointer() - vectorDataOffset;
float centroidDp = fieldData.getVectors().size() > 0 ? VectorUtil.dotProduct(clusterCenter, clusterCenter) : 0;
writeMeta(
fieldData.fieldInfo,
maxDoc,
vectorDataOffset,
vectorDataLength,
clusterCenter,
centroidDp,
fieldData.getDocsWithFieldSet()
);
}
private void writeBinarizedVectors(FieldWriter fieldData, float[] clusterCenter, OptimizedScalarQuantizer scalarQuantizer)
throws IOException {
int discreteDims = BQVectorUtils.discretize(fieldData.fieldInfo.getVectorDimension(), 64);
int[] quantizationScratch = new int[discreteDims];
byte[] vector = new byte[discreteDims / 8];
float[] scratch = new float[fieldData.fieldInfo.getVectorDimension()];
for (int i = 0; i < fieldData.getVectors().size(); i++) {
float[] v = fieldData.getVectors().get(i);
OptimizedScalarQuantizer.QuantizationResult corrections = scalarQuantizer.scalarQuantize(
v,
scratch,
quantizationScratch,
(byte) 1,
clusterCenter
);
ESVectorUtil.packAsBinary(quantizationScratch, vector);
binarizedVectorData.writeBytes(vector, vector.length);
binarizedVectorData.writeInt(Float.floatToIntBits(corrections.lowerInterval()));
binarizedVectorData.writeInt(Float.floatToIntBits(corrections.upperInterval()));
binarizedVectorData.writeInt(Float.floatToIntBits(corrections.additionalCorrection()));
assert corrections.quantizedComponentSum() >= 0 && corrections.quantizedComponentSum() <= 0xffff;
binarizedVectorData.writeShort((short) corrections.quantizedComponentSum());
}
}
private void writeSortingField(
FieldWriter fieldData,
float[] clusterCenter,
int maxDoc,
Sorter.DocMap sortMap,
OptimizedScalarQuantizer scalarQuantizer
) throws IOException {
final int[] ordMap = new int[fieldData.getDocsWithFieldSet().cardinality()]; // new ord to old ord
DocsWithFieldSet newDocsWithField = new DocsWithFieldSet();
mapOldOrdToNewOrd(fieldData.getDocsWithFieldSet(), sortMap, null, ordMap, newDocsWithField);
// write vector values
long vectorDataOffset = binarizedVectorData.alignFilePointer(Float.BYTES);
writeSortedBinarizedVectors(fieldData, clusterCenter, ordMap, scalarQuantizer);
long quantizedVectorLength = binarizedVectorData.getFilePointer() - vectorDataOffset;
float centroidDp = VectorUtil.dotProduct(clusterCenter, clusterCenter);
writeMeta(fieldData.fieldInfo, maxDoc, vectorDataOffset, quantizedVectorLength, clusterCenter, centroidDp, newDocsWithField);
}
private void writeSortedBinarizedVectors(
FieldWriter fieldData,
float[] clusterCenter,
int[] ordMap,
OptimizedScalarQuantizer scalarQuantizer
) throws IOException {
int discreteDims = BQVectorUtils.discretize(fieldData.fieldInfo.getVectorDimension(), 64);
int[] quantizationScratch = new int[discreteDims];
byte[] vector = new byte[discreteDims / 8];
float[] scratch = new float[fieldData.fieldInfo.getVectorDimension()];
for (int ordinal : ordMap) {
float[] v = fieldData.getVectors().get(ordinal);
OptimizedScalarQuantizer.QuantizationResult corrections = scalarQuantizer.scalarQuantize(
v,
scratch,
quantizationScratch,
(byte) 1,
clusterCenter
);
ESVectorUtil.packAsBinary(quantizationScratch, vector);
binarizedVectorData.writeBytes(vector, vector.length);
binarizedVectorData.writeInt(Float.floatToIntBits(corrections.lowerInterval()));
binarizedVectorData.writeInt(Float.floatToIntBits(corrections.upperInterval()));
binarizedVectorData.writeInt(Float.floatToIntBits(corrections.additionalCorrection()));
assert corrections.quantizedComponentSum() >= 0 && corrections.quantizedComponentSum() <= 0xffff;
binarizedVectorData.writeShort((short) corrections.quantizedComponentSum());
}
}
private void writeMeta(
FieldInfo field,
int maxDoc,
long vectorDataOffset,
long vectorDataLength,
float[] clusterCenter,
float centroidDp,
DocsWithFieldSet docsWithField
) throws IOException {
meta.writeInt(field.number);
meta.writeInt(field.getVectorEncoding().ordinal());
meta.writeInt(field.getVectorSimilarityFunction().ordinal());
meta.writeVInt(field.getVectorDimension());
meta.writeVLong(vectorDataOffset);
meta.writeVLong(vectorDataLength);
int count = docsWithField.cardinality();
meta.writeVInt(count);
if (count > 0) {
final ByteBuffer buffer = ByteBuffer.allocate(field.getVectorDimension() * Float.BYTES).order(ByteOrder.LITTLE_ENDIAN);
buffer.asFloatBuffer().put(clusterCenter);
meta.writeBytes(buffer.array(), buffer.array().length);
meta.writeInt(Float.floatToIntBits(centroidDp));
}
OrdToDocDISIReaderConfiguration.writeStoredMeta(
DIRECT_MONOTONIC_BLOCK_SHIFT,
meta,
binarizedVectorData,
count,
maxDoc,
docsWithField
);
}
@Override
public void finish() throws IOException {
if (finished) {
throw new IllegalStateException("already finished");
}
finished = true;
rawVectorDelegate.finish();
if (meta != null) {
// write end of fields marker
meta.writeInt(-1);
CodecUtil.writeFooter(meta);
}
if (binarizedVectorData != null) {
CodecUtil.writeFooter(binarizedVectorData);
}
}
@Override
public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
if (fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32)) {
final float[] centroid;
final float[] mergedCentroid = new float[fieldInfo.getVectorDimension()];
int vectorCount = mergeAndRecalculateCentroids(mergeState, fieldInfo, mergedCentroid);
// Don't need access to the random vectors, we can just use the merged
rawVectorDelegate.mergeOneField(fieldInfo, mergeState);
centroid = mergedCentroid;
if (segmentWriteState.infoStream.isEnabled(BINARIZED_VECTOR_COMPONENT)) {
segmentWriteState.infoStream.message(BINARIZED_VECTOR_COMPONENT, "Vectors' count:" + vectorCount);
}
FloatVectorValues floatVectorValues = KnnVectorsWriter.MergedVectorValues.mergeFloatVectorValues(fieldInfo, mergeState);
if (fieldInfo.getVectorSimilarityFunction() == COSINE) {
floatVectorValues = new NormalizedFloatVectorValues(floatVectorValues);
}
BinarizedFloatVectorValues binarizedVectorValues = new BinarizedFloatVectorValues(
floatVectorValues,
new OptimizedScalarQuantizer(fieldInfo.getVectorSimilarityFunction()),
centroid
);
long vectorDataOffset = binarizedVectorData.alignFilePointer(Float.BYTES);
DocsWithFieldSet docsWithField = writeBinarizedVectorData(binarizedVectorData, binarizedVectorValues);
long vectorDataLength = binarizedVectorData.getFilePointer() - vectorDataOffset;
float centroidDp = docsWithField.cardinality() > 0 ? VectorUtil.dotProduct(centroid, centroid) : 0;
writeMeta(
fieldInfo,
segmentWriteState.segmentInfo.maxDoc(),
vectorDataOffset,
vectorDataLength,
centroid,
centroidDp,
docsWithField
);
} else {
rawVectorDelegate.mergeOneField(fieldInfo, mergeState);
}
}
static DocsWithFieldSet writeBinarizedVectorAndQueryData(
IndexOutput binarizedVectorData,
IndexOutput binarizedQueryData,
FloatVectorValues floatVectorValues,
float[] centroid,
OptimizedScalarQuantizer binaryQuantizer
) throws IOException {
int discretizedDimension = BQVectorUtils.discretize(floatVectorValues.dimension(), 64);
DocsWithFieldSet docsWithField = new DocsWithFieldSet();
int[][] quantizationScratch = new int[2][floatVectorValues.dimension()];
byte[] toIndex = new byte[discretizedDimension / 8];
byte[] toQuery = new byte[(discretizedDimension / 8) * BinaryQuantizer.B_QUERY];
KnnVectorValues.DocIndexIterator iterator = floatVectorValues.iterator();
float[] scratch = new float[floatVectorValues.dimension()];
for (int docV = iterator.nextDoc(); docV != NO_MORE_DOCS; docV = iterator.nextDoc()) {
// write index vector
OptimizedScalarQuantizer.QuantizationResult[] r = binaryQuantizer.multiScalarQuantize(
floatVectorValues.vectorValue(iterator.index()),
scratch,
quantizationScratch,
new byte[] { 1, 4 },
centroid
);
// pack and store document bit vector
ESVectorUtil.packAsBinary(quantizationScratch[0], toIndex);
binarizedVectorData.writeBytes(toIndex, toIndex.length);
binarizedVectorData.writeInt(Float.floatToIntBits(r[0].lowerInterval()));
binarizedVectorData.writeInt(Float.floatToIntBits(r[0].upperInterval()));
binarizedVectorData.writeInt(Float.floatToIntBits(r[0].additionalCorrection()));
assert r[0].quantizedComponentSum() >= 0 && r[0].quantizedComponentSum() <= 0xffff;
binarizedVectorData.writeShort((short) r[0].quantizedComponentSum());
docsWithField.add(docV);
// pack and store the 4bit query vector
ESVectorUtil.transposeHalfByte(quantizationScratch[1], toQuery);
binarizedQueryData.writeBytes(toQuery, toQuery.length);
binarizedQueryData.writeInt(Float.floatToIntBits(r[1].lowerInterval()));
binarizedQueryData.writeInt(Float.floatToIntBits(r[1].upperInterval()));
binarizedQueryData.writeInt(Float.floatToIntBits(r[1].additionalCorrection()));
assert r[1].quantizedComponentSum() >= 0 && r[1].quantizedComponentSum() <= 0xffff;
binarizedQueryData.writeShort((short) r[1].quantizedComponentSum());
}
return docsWithField;
}
static DocsWithFieldSet writeBinarizedVectorData(IndexOutput output, BinarizedByteVectorValues binarizedByteVectorValues)
throws IOException {
DocsWithFieldSet docsWithField = new DocsWithFieldSet();
KnnVectorValues.DocIndexIterator iterator = binarizedByteVectorValues.iterator();
for (int docV = iterator.nextDoc(); docV != NO_MORE_DOCS; docV = iterator.nextDoc()) {
// write vector
byte[] binaryValue = binarizedByteVectorValues.vectorValue(iterator.index());
output.writeBytes(binaryValue, binaryValue.length);
OptimizedScalarQuantizer.QuantizationResult corrections = binarizedByteVectorValues.getCorrectiveTerms(iterator.index());
output.writeInt(Float.floatToIntBits(corrections.lowerInterval()));
output.writeInt(Float.floatToIntBits(corrections.upperInterval()));
output.writeInt(Float.floatToIntBits(corrections.additionalCorrection()));
assert corrections.quantizedComponentSum() >= 0 && corrections.quantizedComponentSum() <= 0xffff;
output.writeShort((short) corrections.quantizedComponentSum());
docsWithField.add(docV);
}
return docsWithField;
}
@Override
public CloseableRandomVectorScorerSupplier mergeOneFieldToIndex(FieldInfo fieldInfo, MergeState mergeState) throws IOException {
if (fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32)) {
final float[] centroid;
final float cDotC;
final float[] mergedCentroid = new float[fieldInfo.getVectorDimension()];
int vectorCount = mergeAndRecalculateCentroids(mergeState, fieldInfo, mergedCentroid);
// Don't need access to the random vectors, we can just use the merged
rawVectorDelegate.mergeOneField(fieldInfo, mergeState);
centroid = mergedCentroid;
cDotC = vectorCount > 0 ? VectorUtil.dotProduct(centroid, centroid) : 0;
if (segmentWriteState.infoStream.isEnabled(BINARIZED_VECTOR_COMPONENT)) {
segmentWriteState.infoStream.message(BINARIZED_VECTOR_COMPONENT, "Vectors' count:" + vectorCount);
}
return mergeOneFieldToIndex(segmentWriteState, fieldInfo, mergeState, centroid, cDotC);
}
return rawVectorDelegate.mergeOneFieldToIndex(fieldInfo, mergeState);
}
private CloseableRandomVectorScorerSupplier mergeOneFieldToIndex(
SegmentWriteState segmentWriteState,
FieldInfo fieldInfo,
MergeState mergeState,
float[] centroid,
float cDotC
) throws IOException {
long vectorDataOffset = binarizedVectorData.alignFilePointer(Float.BYTES);
IndexInput binarizedDataInput = null;
IndexInput binarizedScoreDataInput = null;
IndexOutput tempQuantizedVectorData = null;
IndexOutput tempScoreQuantizedVectorData = null;
boolean success = false;
OptimizedScalarQuantizer quantizer = new OptimizedScalarQuantizer(fieldInfo.getVectorSimilarityFunction());
try {
// Since we are opening two files, it's possible that one or the other fails to open
// we open them within the try to ensure they are cleaned
tempQuantizedVectorData = segmentWriteState.directory.createTempOutput(
binarizedVectorData.getName(),
"temp",
segmentWriteState.context
);
tempScoreQuantizedVectorData = segmentWriteState.directory.createTempOutput(
binarizedVectorData.getName(),
"score_temp",
segmentWriteState.context
);
final String tempQuantizedVectorDataName = tempQuantizedVectorData.getName();
final String tempScoreQuantizedVectorDataName = tempScoreQuantizedVectorData.getName();
FloatVectorValues floatVectorValues = KnnVectorsWriter.MergedVectorValues.mergeFloatVectorValues(fieldInfo, mergeState);
if (fieldInfo.getVectorSimilarityFunction() == COSINE) {
floatVectorValues = new NormalizedFloatVectorValues(floatVectorValues);
}
DocsWithFieldSet docsWithField = writeBinarizedVectorAndQueryData(
tempQuantizedVectorData,
tempScoreQuantizedVectorData,
floatVectorValues,
centroid,
quantizer
);
CodecUtil.writeFooter(tempQuantizedVectorData);
IOUtils.close(tempQuantizedVectorData);
binarizedDataInput = segmentWriteState.directory.openInput(tempQuantizedVectorData.getName(), segmentWriteState.context);
binarizedVectorData.copyBytes(binarizedDataInput, binarizedDataInput.length() - CodecUtil.footerLength());
long vectorDataLength = binarizedVectorData.getFilePointer() - vectorDataOffset;
CodecUtil.retrieveChecksum(binarizedDataInput);
CodecUtil.writeFooter(tempScoreQuantizedVectorData);
IOUtils.close(tempScoreQuantizedVectorData);
binarizedScoreDataInput = segmentWriteState.directory.openInput(
tempScoreQuantizedVectorData.getName(),
segmentWriteState.context
);
writeMeta(
fieldInfo,
segmentWriteState.segmentInfo.maxDoc(),
vectorDataOffset,
vectorDataLength,
centroid,
cDotC,
docsWithField
);
success = true;
final IndexInput finalBinarizedDataInput = binarizedDataInput;
final IndexInput finalBinarizedScoreDataInput = binarizedScoreDataInput;
OffHeapBinarizedVectorValues vectorValues = new OffHeapBinarizedVectorValues.DenseOffHeapVectorValues(
fieldInfo.getVectorDimension(),
docsWithField.cardinality(),
centroid,
cDotC,
quantizer,
fieldInfo.getVectorSimilarityFunction(),
vectorsScorer,
finalBinarizedDataInput
);
RandomVectorScorerSupplier scorerSupplier = vectorsScorer.getRandomVectorScorerSupplier(
fieldInfo.getVectorSimilarityFunction(),
new OffHeapBinarizedQueryVectorValues(
finalBinarizedScoreDataInput,
fieldInfo.getVectorDimension(),
docsWithField.cardinality()
),
vectorValues
);
return new BinarizedCloseableRandomVectorScorerSupplier(scorerSupplier, vectorValues, () -> {
IOUtils.close(finalBinarizedDataInput, finalBinarizedScoreDataInput);
IOUtils.deleteFilesIgnoringExceptions(
segmentWriteState.directory,
tempQuantizedVectorDataName,
tempScoreQuantizedVectorDataName
);
});
} finally {
if (success == false) {
IOUtils.closeWhileHandlingException(
tempQuantizedVectorData,
tempScoreQuantizedVectorData,
binarizedDataInput,
binarizedScoreDataInput
);
if (tempQuantizedVectorData != null) {
IOUtils.deleteFilesIgnoringExceptions(segmentWriteState.directory, tempQuantizedVectorData.getName());
}
if (tempScoreQuantizedVectorData != null) {
IOUtils.deleteFilesIgnoringExceptions(segmentWriteState.directory, tempScoreQuantizedVectorData.getName());
}
}
}
}
@Override
public void close() throws IOException {
IOUtils.close(meta, binarizedVectorData, rawVectorDelegate);
}
static float[] getCentroid(KnnVectorsReader vectorsReader, String fieldName) {
if (vectorsReader instanceof PerFieldKnnVectorsFormat.FieldsReader candidateReader) {
vectorsReader = candidateReader.getFieldReader(fieldName);
}
if (vectorsReader instanceof ES818BinaryQuantizedVectorsReader reader) {
return reader.getCentroid(fieldName);
}
return null;
}
static int mergeAndRecalculateCentroids(MergeState mergeState, FieldInfo fieldInfo, float[] mergedCentroid) throws IOException {
boolean recalculate = false;
int totalVectorCount = 0;
for (int i = 0; i < mergeState.knnVectorsReaders.length; i++) {
KnnVectorsReader knnVectorsReader = mergeState.knnVectorsReaders[i];
if (knnVectorsReader == null || knnVectorsReader.getFloatVectorValues(fieldInfo.name) == null) {
continue;
}
float[] centroid = getCentroid(knnVectorsReader, fieldInfo.name);
int vectorCount = knnVectorsReader.getFloatVectorValues(fieldInfo.name).size();
if (vectorCount == 0) {
continue;
}
totalVectorCount += vectorCount;
// If there aren't centroids, or previously clustered with more than one cluster
// or if there are deleted docs, we must recalculate the centroid
if (centroid == null || mergeState.liveDocs[i] != null) {
recalculate = true;
break;
}
for (int j = 0; j < centroid.length; j++) {
mergedCentroid[j] += centroid[j] * vectorCount;
}
}
if (recalculate) {
return calculateCentroid(mergeState, fieldInfo, mergedCentroid);
} else {
for (int j = 0; j < mergedCentroid.length; j++) {
mergedCentroid[j] = mergedCentroid[j] / totalVectorCount;
}
if (fieldInfo.getVectorSimilarityFunction() == COSINE) {
VectorUtil.l2normalize(mergedCentroid);
}
return totalVectorCount;
}
}
static int calculateCentroid(MergeState mergeState, FieldInfo fieldInfo, float[] centroid) throws IOException {
assert fieldInfo.getVectorEncoding().equals(VectorEncoding.FLOAT32);
// clear out the centroid
Arrays.fill(centroid, 0);
int count = 0;
for (int i = 0; i < mergeState.knnVectorsReaders.length; i++) {
KnnVectorsReader knnVectorsReader = mergeState.knnVectorsReaders[i];
if (knnVectorsReader == null) continue;
FloatVectorValues vectorValues = mergeState.knnVectorsReaders[i].getFloatVectorValues(fieldInfo.name);
if (vectorValues == null) {
continue;
}
KnnVectorValues.DocIndexIterator iterator = vectorValues.iterator();
for (int doc = iterator.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = iterator.nextDoc()) {
++count;
float[] vector = vectorValues.vectorValue(iterator.index());
// TODO Panama sum
for (int j = 0; j < vector.length; j++) {
centroid[j] += vector[j];
}
}
}
if (count == 0) {
return count;
}
// TODO Panama div
for (int i = 0; i < centroid.length; i++) {
centroid[i] /= count;
}
if (fieldInfo.getVectorSimilarityFunction() == COSINE) {
VectorUtil.l2normalize(centroid);
}
return count;
}
@Override
public long ramBytesUsed() {
long total = SHALLOW_RAM_BYTES_USED;
for (FieldWriter field : fields) {
// the field tracks the delegate field usage
total += field.ramBytesUsed();
}
return total;
}
static | ES818BinaryQuantizedVectorsWriter |
java | spring-projects__spring-framework | integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java | {
"start": 4395,
"end": 5112
} | class ____").isFalse();
assertThat(sessionScopedAlias).isSameAs(sessionScoped);
assertThat(AopUtils.isAopProxy(testBean)).as("Should be AOP proxy").isTrue();
boolean condition = testBean instanceof TestBean;
assertThat(condition).as("Regular bean should be JDK proxy").isFalse();
String rob = "Rob Harrop";
String bram = "Bram Smeets";
assertThat(sessionScoped.getName()).isEqualTo(rob);
sessionScoped.setName(bram);
request.setSession(newSession);
assertThat(sessionScoped.getName()).isEqualTo(rob);
request.setSession(oldSession);
assertThat(sessionScoped.getName()).isEqualTo(bram);
assertThat(((Advised) sessionScoped).getAdvisors()).as("Should have advisors").isNotEmpty();
}
}
| proxy |
java | apache__flink | flink-rpc/flink-rpc-core/src/main/java/org/apache/flink/runtime/rpc/messages/CallAsync.java | {
"start": 1006,
"end": 1271
} | class ____ implements Message {
private final Callable<?> callable;
public CallAsync(Callable<?> callable) {
this.callable = Preconditions.checkNotNull(callable);
}
public Callable<?> getCallable() {
return callable;
}
}
| CallAsync |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/EsqlBaseParser.java | {
"start": 269600,
"end": 274526
} | class ____ extends ConstantContext {
public BooleanValueContext booleanValue() {
return getRuleContext(BooleanValueContext.class,0);
}
@SuppressWarnings("this-escape")
public BooleanLiteralContext(ConstantContext ctx) { copyFrom(ctx); }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).enterBooleanLiteral(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).exitBooleanLiteral(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof EsqlBaseParserVisitor ) return ((EsqlBaseParserVisitor<? extends T>)visitor).visitBooleanLiteral(this);
else return visitor.visitChildren(this);
}
}
public final ConstantContext constant() throws RecognitionException {
ConstantContext _localctx = new ConstantContext(_ctx, getState());
enterRule(_localctx, 168, RULE_constant);
int _la;
try {
setState(910);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,85,_ctx) ) {
case 1:
_localctx = new NullLiteralContext(_localctx);
enterOuterAlt(_localctx, 1);
{
setState(868);
match(NULL);
}
break;
case 2:
_localctx = new QualifiedIntegerLiteralContext(_localctx);
enterOuterAlt(_localctx, 2);
{
setState(869);
integerValue();
setState(870);
match(UNQUOTED_IDENTIFIER);
}
break;
case 3:
_localctx = new DecimalLiteralContext(_localctx);
enterOuterAlt(_localctx, 3);
{
setState(872);
decimalValue();
}
break;
case 4:
_localctx = new IntegerLiteralContext(_localctx);
enterOuterAlt(_localctx, 4);
{
setState(873);
integerValue();
}
break;
case 5:
_localctx = new BooleanLiteralContext(_localctx);
enterOuterAlt(_localctx, 5);
{
setState(874);
booleanValue();
}
break;
case 6:
_localctx = new InputParameterContext(_localctx);
enterOuterAlt(_localctx, 6);
{
setState(875);
parameter();
}
break;
case 7:
_localctx = new StringLiteralContext(_localctx);
enterOuterAlt(_localctx, 7);
{
setState(876);
string();
}
break;
case 8:
_localctx = new NumericArrayLiteralContext(_localctx);
enterOuterAlt(_localctx, 8);
{
setState(877);
match(OPENING_BRACKET);
setState(878);
numericValue();
setState(883);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==COMMA) {
{
{
setState(879);
match(COMMA);
setState(880);
numericValue();
}
}
setState(885);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(886);
match(CLOSING_BRACKET);
}
break;
case 9:
_localctx = new BooleanArrayLiteralContext(_localctx);
enterOuterAlt(_localctx, 9);
{
setState(888);
match(OPENING_BRACKET);
setState(889);
booleanValue();
setState(894);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==COMMA) {
{
{
setState(890);
match(COMMA);
setState(891);
booleanValue();
}
}
setState(896);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(897);
match(CLOSING_BRACKET);
}
break;
case 10:
_localctx = new StringArrayLiteralContext(_localctx);
enterOuterAlt(_localctx, 10);
{
setState(899);
match(OPENING_BRACKET);
setState(900);
string();
setState(905);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==COMMA) {
{
{
setState(901);
match(COMMA);
setState(902);
string();
}
}
setState(907);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(908);
match(CLOSING_BRACKET);
}
break;
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
@SuppressWarnings("CheckReturnValue")
public static | BooleanLiteralContext |
java | spring-projects__spring-boot | core/spring-boot-testcontainers/src/test/java/org/springframework/boot/testcontainers/service/connection/ServiceConnectionContextCustomizerTests.java | {
"start": 7072,
"end": 7208
} | class ____ implements DatabaseConnectionDetails {
@Override
public String getJdbcUrl() {
return "";
}
}
}
| TestConnectionDetails |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/ZeroShotClassificationConfigUpdate.java | {
"start": 1330,
"end": 6362
} | class ____ extends NlpConfigUpdate implements NamedXContentObject {
public static final String NAME = "zero_shot_classification";
public static ZeroShotClassificationConfigUpdate fromXContentStrict(XContentParser parser) {
return STRICT_PARSER.apply(parser, null).build();
}
@SuppressWarnings({ "unchecked" })
public static ZeroShotClassificationConfigUpdate fromMap(Map<String, Object> map) {
Map<String, Object> options = new HashMap<>(map);
Boolean isMultiLabel = (Boolean) options.remove(MULTI_LABEL.getPreferredName());
List<String> labels = (List<String>) options.remove(LABELS.getPreferredName());
String resultsField = (String) options.remove(RESULTS_FIELD.getPreferredName());
TokenizationUpdate tokenizationUpdate = NlpConfigUpdate.tokenizationFromMap(options);
if (options.isEmpty() == false) {
throw ExceptionsHelper.badRequestException("Unrecognized fields {}.", map.keySet());
}
return new ZeroShotClassificationConfigUpdate(labels, isMultiLabel, resultsField, tokenizationUpdate);
}
@SuppressWarnings({ "unchecked" })
private static final ObjectParser<ZeroShotClassificationConfigUpdate.Builder, Void> STRICT_PARSER = new ObjectParser<>(
NAME,
ZeroShotClassificationConfigUpdate.Builder::new
);
static {
STRICT_PARSER.declareStringArray(Builder::setLabels, LABELS);
STRICT_PARSER.declareBoolean(Builder::setMultiLabel, MULTI_LABEL);
STRICT_PARSER.declareString(Builder::setResultsField, RESULTS_FIELD);
STRICT_PARSER.declareNamedObject(
Builder::setTokenizationUpdate,
(p, c, n) -> p.namedObject(TokenizationUpdate.class, n, false),
TOKENIZATION
);
}
private final List<String> labels;
private final Boolean isMultiLabel;
private final String resultsField;
public ZeroShotClassificationConfigUpdate(
@Nullable List<String> labels,
@Nullable Boolean isMultiLabel,
@Nullable String resultsField,
@Nullable TokenizationUpdate tokenizationUpdate
) {
super(tokenizationUpdate);
this.labels = labels;
if (labels != null && labels.isEmpty()) {
throw ExceptionsHelper.badRequestException("[{}] must not be empty", LABELS.getPreferredName());
}
this.isMultiLabel = isMultiLabel;
this.resultsField = resultsField;
}
public ZeroShotClassificationConfigUpdate(StreamInput in) throws IOException {
super(in);
labels = in.readOptionalStringCollectionAsList();
isMultiLabel = in.readOptionalBoolean();
resultsField = in.readOptionalString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalStringCollection(labels);
out.writeOptionalBoolean(isMultiLabel);
out.writeOptionalString(resultsField);
}
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
if (labels != null) {
builder.field(LABELS.getPreferredName(), labels);
}
if (isMultiLabel != null) {
builder.field(MULTI_LABEL.getPreferredName(), isMultiLabel);
}
if (resultsField != null) {
builder.field(RESULTS_FIELD.getPreferredName(), resultsField);
}
return builder;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public boolean isSupported(InferenceConfig config) {
return config instanceof ZeroShotClassificationConfig;
}
@Override
public String getResultsField() {
return resultsField;
}
@Override
public InferenceConfigUpdate.Builder<? extends InferenceConfigUpdate.Builder<?, ?>, ? extends InferenceConfigUpdate> newBuilder() {
return new Builder().setLabels(labels)
.setMultiLabel(isMultiLabel)
.setResultsField(resultsField)
.setTokenizationUpdate(tokenizationUpdate);
}
@Override
public String getName() {
return NAME;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || getClass() != o.getClass()) return false;
ZeroShotClassificationConfigUpdate that = (ZeroShotClassificationConfigUpdate) o;
return Objects.equals(isMultiLabel, that.isMultiLabel)
&& Objects.equals(labels, that.labels)
&& Objects.equals(resultsField, that.resultsField)
&& Objects.equals(tokenizationUpdate, that.tokenizationUpdate);
}
@Override
public int hashCode() {
return Objects.hash(labels, isMultiLabel, resultsField, tokenizationUpdate);
}
public List<String> getLabels() {
return labels;
}
public Boolean getMultiLabel() {
return isMultiLabel;
}
public static | ZeroShotClassificationConfigUpdate |
java | apache__camel | tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/UpdateMimeTypeHelper.java | {
"start": 1603,
"end": 2264
} | class ____ extends AbstractGeneratorMojo {
private static final String TYPES_START_TOKEN = "// MIME-TYPES: START";
private static final String TYPES_END_TOKEN = "// MIME-TYPES: END";
@Parameter(defaultValue = "${project.basedir}/src/main/resources/mime-types.txt")
protected File mimeFile;
@Parameter(defaultValue = "${project.basedir}/")
protected File baseDir;
@Inject
public UpdateMimeTypeHelper(MavenProjectHelper projectHelper, BuildContext buildContext) {
super(projectHelper, buildContext);
}
/**
* Execute goal.
*
* @throws MojoExecutionException execution of the main | UpdateMimeTypeHelper |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/transaction/manager/PrimaryTransactionManagerTests.java | {
"start": 3246,
"end": 3867
} | class ____ {
@Primary
@Bean
PlatformTransactionManager primaryTransactionManager() {
return new DataSourceTransactionManager(dataSource1());
}
@Bean
PlatformTransactionManager additionalTransactionManager() {
return new DataSourceTransactionManager(dataSource2());
}
@Bean
DataSource dataSource1() {
return new EmbeddedDatabaseBuilder()
.generateUniqueName(true)
.addScript("classpath:/org/springframework/test/context/jdbc/schema.sql")
.build();
}
@Bean
DataSource dataSource2() {
return new EmbeddedDatabaseBuilder().generateUniqueName(true).build();
}
}
}
| Config |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/http/StreamPriority.java | {
"start": 597,
"end": 691
} | class ____ HTTP/2 stream priority defined in RFC 7540 clause 5.3
*/
@DataObject
public | represents |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/aot/generate/AccessControl.java | {
"start": 4223,
"end": 8757
} | enum ____ {
/**
* Public visibility. The member or type is visible to all classes.
*/
PUBLIC,
/**
* Protected visibility. The member or type is only visible to classes
* in the same package or subclasses.
*/
PROTECTED,
/**
* Package-private visibility. The member or type is only visible to classes
* in the same package.
*/
PACKAGE_PRIVATE,
/**
* Private visibility. The member or type is not visible to other classes.
*/
PRIVATE;
private static Visibility forMember(Member member) {
Assert.notNull(member, "'member' must not be null");
Visibility visibility = forModifiers(member.getModifiers());
Visibility declaringClassVisibility = forClass(member.getDeclaringClass());
visibility = lowest(visibility, declaringClassVisibility);
if (visibility != PRIVATE) {
if (member instanceof Field field) {
Visibility fieldVisibility = forResolvableType(
ResolvableType.forField(field));
return lowest(visibility, fieldVisibility);
}
if (member instanceof Constructor<?> constructor) {
Visibility parameterVisibility = forParameterTypes(constructor,
i -> ResolvableType.forConstructorParameter(constructor, i));
return lowest(visibility, parameterVisibility);
}
if (member instanceof Method method) {
Visibility parameterVisibility = forParameterTypes(method,
i -> ResolvableType.forMethodParameter(method, i));
Visibility returnTypeVisibility = forResolvableType(
ResolvableType.forMethodReturnType(method));
return lowest(visibility, parameterVisibility, returnTypeVisibility);
}
}
return PRIVATE;
}
private static Visibility forResolvableType(ResolvableType resolvableType) {
return forResolvableType(resolvableType, new HashSet<>());
}
private static Visibility forResolvableType(ResolvableType resolvableType,
Set<ResolvableType> seen) {
if (!seen.add(resolvableType)) {
return Visibility.PUBLIC;
}
Class<?> userClass = ClassUtils.getUserClass(resolvableType.toClass());
ResolvableType userType = resolvableType.as(userClass);
Visibility visibility = forClass(userType.toClass());
for (ResolvableType generic : userType.getGenerics()) {
visibility = lowest(visibility, forResolvableType(generic, seen));
}
return visibility;
}
private static Visibility forParameterTypes(Executable executable,
IntFunction<ResolvableType> resolvableTypeFactory) {
Visibility visibility = Visibility.PUBLIC;
Class<?>[] parameterTypes = executable.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
ResolvableType type = resolvableTypeFactory.apply(i);
visibility = lowest(visibility, forResolvableType(type));
}
return visibility;
}
private static Visibility forClass(Class<?> clazz) {
clazz = ClassUtils.getUserClass(clazz);
Visibility visibility = forModifiers(clazz.getModifiers());
if (clazz.isArray()) {
visibility = lowest(visibility, forClass(clazz.componentType()));
}
Class<?> enclosingClass = clazz.getEnclosingClass();
if (enclosingClass != null) {
visibility = lowest(visibility, forClass(clazz.getEnclosingClass()));
}
return visibility;
}
private static Visibility forModifiers(int modifiers) {
if (Modifier.isPublic(modifiers)) {
return PUBLIC;
}
if (Modifier.isProtected(modifiers)) {
return PROTECTED;
}
if (Modifier.isPrivate(modifiers)) {
return PRIVATE;
}
return PACKAGE_PRIVATE;
}
/**
* Returns the lowest {@link Visibility} from the given candidates.
* @param candidates the candidates to check
* @return the lowest {@link Visibility} from the candidates
*/
static Visibility lowest(Visibility... candidates) {
Visibility visibility = PUBLIC;
for (Visibility candidate : candidates) {
if (candidate.ordinal() > visibility.ordinal()) {
visibility = candidate;
}
}
return visibility;
}
/**
* Returns the index of the lowest {@link Visibility} from the given
* candidates.
* @param candidates the candidates to check
* @return the index of the lowest {@link Visibility} from the candidates
*/
static int lowestIndex(Visibility... candidates) {
Visibility visibility = PUBLIC;
int index = 0;
for (int i = 0; i < candidates.length; i++) {
Visibility candidate = candidates[i];
if (candidate.ordinal() > visibility.ordinal()) {
visibility = candidate;
index = i;
}
}
return index;
}
}
}
| Visibility |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java | {
"start": 28058,
"end": 28240
} | class ____ implements WebMvcConfigurer {
@Bean
public PersonsAddressesController controller() {
return new PersonsAddressesController();
}
}
@EnableWebMvc
static | WebConfig |
java | grpc__grpc-java | xds/src/main/java/io/grpc/xds/internal/security/certprovider/CertProviderSslContextProvider.java | {
"start": 1487,
"end": 9171
} | class ____ extends DynamicSslContextProvider implements
CertificateProvider.Watcher {
@Nullable private final NoExceptionCloseable certHandle;
@Nullable private final NoExceptionCloseable rootCertHandle;
@Nullable private final CertificateProviderInstance certInstance;
@Nullable protected final CertificateProviderInstance rootCertInstance;
@Nullable protected PrivateKey savedKey;
@Nullable protected List<X509Certificate> savedCertChain;
@Nullable protected List<X509Certificate> savedTrustedRoots;
@Nullable protected Map<String, List<X509Certificate>> savedSpiffeTrustMap;
private final boolean isUsingSystemRootCerts;
protected CertProviderSslContextProvider(
Node node,
@Nullable Map<String, CertificateProviderInfo> certProviders,
CertificateProviderInstance certInstance,
CertificateProviderInstance rootCertInstance,
CertificateValidationContext staticCertValidationContext,
BaseTlsContext tlsContext,
CertificateProviderStore certificateProviderStore) {
super(tlsContext, staticCertValidationContext);
this.certInstance = certInstance;
this.rootCertInstance = rootCertInstance;
this.isUsingSystemRootCerts = rootCertInstance == null
&& CommonTlsContextUtil.isUsingSystemRootCerts(tlsContext.getCommonTlsContext());
boolean createCertInstance = certInstance != null && certInstance.isInitialized();
boolean createRootCertInstance = rootCertInstance != null && rootCertInstance.isInitialized();
boolean sharedCertInstance = createCertInstance && createRootCertInstance
&& rootCertInstance.getInstanceName().equals(certInstance.getInstanceName());
if (createCertInstance) {
CertificateProviderInfo certProviderInstanceConfig =
getCertProviderConfig(certProviders, certInstance.getInstanceName());
CertificateProvider.Watcher watcher = this;
if (!sharedCertInstance && !isUsingSystemRootCerts) {
watcher = new IgnoreUpdatesWatcher(watcher, /* ignoreRootCertUpdates= */ true);
}
// TODO: Previously we'd hang if certProviderInstanceConfig were null or
// certInstance.isInitialized() == false. Now we'll proceed. Those should be errors, or are
// they impossible and should be assertions?
certHandle = certProviderInstanceConfig == null ? null
: certificateProviderStore.createOrGetProvider(
certInstance.getCertificateName(),
certProviderInstanceConfig.pluginName(),
certProviderInstanceConfig.config(),
watcher,
true)::close;
} else {
certHandle = null;
}
if (createRootCertInstance && !sharedCertInstance) {
CertificateProviderInfo certProviderInstanceConfig =
getCertProviderConfig(certProviders, rootCertInstance.getInstanceName());
rootCertHandle = certProviderInstanceConfig == null ? null
: certificateProviderStore.createOrGetProvider(
rootCertInstance.getCertificateName(),
certProviderInstanceConfig.pluginName(),
certProviderInstanceConfig.config(),
new IgnoreUpdatesWatcher(this, /* ignoreRootCertUpdates= */ false),
false)::close;
} else if (rootCertInstance == null
&& CommonTlsContextUtil.isUsingSystemRootCerts(tlsContext.getCommonTlsContext())) {
SystemRootCertificateProvider systemRootProvider = new SystemRootCertificateProvider(this);
systemRootProvider.start();
rootCertHandle = systemRootProvider::close;
} else {
rootCertHandle = null;
}
}
private static CertificateProviderInfo getCertProviderConfig(
@Nullable Map<String, CertificateProviderInfo> certProviders, String pluginInstanceName) {
return certProviders != null ? certProviders.get(pluginInstanceName) : null;
}
@Nullable
protected static CertificateProviderInstance getCertProviderInstance(
CommonTlsContext commonTlsContext) {
if (commonTlsContext.hasTlsCertificateProviderInstance()) {
return CommonTlsContextUtil.convert(commonTlsContext.getTlsCertificateProviderInstance());
}
// Fall back to deprecated field for backward compatibility with Istio
@SuppressWarnings("deprecation")
CertificateProviderInstance deprecatedInstance =
commonTlsContext.hasTlsCertificateCertificateProviderInstance()
? commonTlsContext.getTlsCertificateCertificateProviderInstance()
: null;
return deprecatedInstance;
}
@Nullable
protected static CertificateValidationContext getStaticValidationContext(
CommonTlsContext commonTlsContext) {
if (commonTlsContext.hasValidationContext()) {
return commonTlsContext.getValidationContext();
} else if (commonTlsContext.hasCombinedValidationContext()) {
CommonTlsContext.CombinedCertificateValidationContext combinedValidationContext =
commonTlsContext.getCombinedValidationContext();
if (combinedValidationContext.hasDefaultValidationContext()) {
return combinedValidationContext.getDefaultValidationContext();
}
}
return null;
}
@Nullable
protected static CommonTlsContext.CertificateProviderInstance getRootCertProviderInstance(
CommonTlsContext commonTlsContext) {
CertificateValidationContext certValidationContext = getStaticValidationContext(
commonTlsContext);
if (certValidationContext != null && certValidationContext.hasCaCertificateProviderInstance()) {
return CommonTlsContextUtil.convert(certValidationContext.getCaCertificateProviderInstance());
}
return null;
}
@Override
public final void updateCertificate(PrivateKey key, List<X509Certificate> certChain) {
savedKey = key;
savedCertChain = certChain;
updateSslContextWhenReady();
}
@Override
public final void updateTrustedRoots(List<X509Certificate> trustedRoots) {
savedTrustedRoots = trustedRoots;
updateSslContextWhenReady();
}
@Override
public final void updateSpiffeTrustMap(Map<String, List<X509Certificate>> spiffeTrustMap) {
savedSpiffeTrustMap = spiffeTrustMap;
updateSslContextWhenReady();
}
private void updateSslContextWhenReady() {
if (isMtls()) {
if (savedKey != null && (savedTrustedRoots != null || savedSpiffeTrustMap != null)) {
updateSslContext();
clearKeysAndCerts();
}
} else if (isRegularTlsAndClientSide()) {
if (savedTrustedRoots != null || savedSpiffeTrustMap != null) {
updateSslContext();
clearKeysAndCerts();
}
} else if (isRegularTlsAndServerSide()) {
if (savedKey != null) {
updateSslContext();
clearKeysAndCerts();
}
}
}
private void clearKeysAndCerts() {
savedKey = null;
if (!isUsingSystemRootCerts) {
savedTrustedRoots = null;
savedSpiffeTrustMap = null;
}
savedCertChain = null;
}
protected final boolean isMtls() {
return certInstance != null && (rootCertInstance != null || isUsingSystemRootCerts);
}
protected final boolean isRegularTlsAndClientSide() {
return (rootCertInstance != null || isUsingSystemRootCerts) && certInstance == null;
}
protected final boolean isRegularTlsAndServerSide() {
return certInstance != null && rootCertInstance == null;
}
@Override
protected final CertificateValidationContext generateCertificateValidationContext() {
return staticCertificateValidationContext;
}
@Override
public final void close() {
if (certHandle != null) {
certHandle.close();
}
if (rootCertHandle != null) {
rootCertHandle.close();
}
}
| CertProviderSslContextProvider |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java | {
"start": 73498,
"end": 75240
} | class ____ extends
BaseTransition {
@Override
public void transition(RMAppAttemptImpl appAttempt,
RMAppAttemptEvent event) {
RMAppAttemptStatusupdateEvent statusUpdateEvent
= (RMAppAttemptStatusupdateEvent) event;
// Update progress
appAttempt.progress = statusUpdateEvent.getProgress();
// Update tracking url if changed and save it to state store
String newTrackingUrl = statusUpdateEvent.getTrackingUrl();
if (newTrackingUrl != null &&
!newTrackingUrl.equals(appAttempt.originalTrackingUrl)) {
appAttempt.originalTrackingUrl = newTrackingUrl;
ApplicationAttemptStateData attemptState = ApplicationAttemptStateData
.newInstance(appAttempt.applicationAttemptId,
appAttempt.getMasterContainer(),
appAttempt.rmContext.getStateStore()
.getCredentialsFromAppAttempt(appAttempt),
appAttempt.startTime, appAttempt.recoveredFinalState,
newTrackingUrl, appAttempt.getDiagnostics(), null,
ContainerExitStatus.INVALID, appAttempt.getFinishTime(),
appAttempt.attemptMetrics.getAggregateAppResourceUsage()
.getResourceUsageSecondsMap(),
appAttempt.attemptMetrics.getPreemptedResourceSecondsMap(),
appAttempt.attemptMetrics.getTotalAllocatedContainers());
appAttempt.rmContext.getStateStore()
.updateApplicationAttemptState(attemptState);
}
// Ping to AMLivelinessMonitor
appAttempt.rmContext.getAMLivelinessMonitor().receivedPing(
statusUpdateEvent.getApplicationAttemptId());
}
}
private static final | StatusUpdateTransition |
java | quarkusio__quarkus | extensions/spring-data-jpa/deployment/src/test/java/io/quarkus/spring/data/devmode/BookResource.java | {
"start": 209,
"end": 548
} | class ____ {
private final BookRepository bookRepository;
public BookResource(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Book> findAll() {
return bookRepository.findAll();
}
// <placeholder>
}
| BookResource |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/creators/TestCreators2.java | {
"start": 4275,
"end": 4499
} | class ____
{
protected Issue700Set item;
@JsonCreator
public Issue700Bean(@JsonProperty("item") String item) { }
public String getItem() { return null; }
}
static final | Issue700Bean |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/jaxb/mapping/spi/db/JaxbColumnUniqueable.java | {
"start": 184,
"end": 259
} | interface ____ extends JaxbColumn {
Boolean isUnique();
}
| JaxbColumnUniqueable |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorAotContributionTests.java | {
"start": 18823,
"end": 18905
} | class ____ {
}
}
@Nested
| PropertySourceWithWildcardLocationPatternConfiguration |
java | netty__netty | codec-base/src/main/java/io/netty/handler/codec/Headers.java | {
"start": 1108,
"end": 39916
} | interface ____<K, V, T extends Headers<K, V, T>> extends Iterable<Entry<K, V>> {
/**
* Returns the value of a header with the specified name. If there is more than one value for the specified name,
* the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @return the first header value if the header is found. {@code null} if there's no such header
*/
V get(K name);
/**
* Returns the value of a header with the specified name. If there is more than one value for the specified name,
* the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the first header value or {@code defaultValue} if there is no such header
*/
V get(K name, V defaultValue);
/**
* Returns the value of a header with the specified name and removes it from this object. If there is more than
* one value for the specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @return the first header value or {@code null} if there is no such header
*/
V getAndRemove(K name);
/**
* Returns the value of a header with the specified name and removes it from this object. If there is more than
* one value for the specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the first header value or {@code defaultValue} if there is no such header
*/
V getAndRemove(K name, V defaultValue);
/**
* Returns all values for the header with the specified name. The returned {@link List} can't be modified.
*
* @param name the name of the header to retrieve
* @return a {@link List} of header values or an empty {@link List} if no values are found.
*/
List<V> getAll(K name);
/**
* Returns all values for the header with the specified name and removes them from this object.
* The returned {@link List} can't be modified.
*
* @param name the name of the header to retrieve
* @return a {@link List} of header values or an empty {@link List} if no values are found.
*/
List<V> getAllAndRemove(K name);
/**
* Returns the {@code boolean} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @return the {@code boolean} value of the first value in insertion order or {@code null} if there is no such
* value or it can't be converted to {@code boolean}.
*/
Boolean getBoolean(K name);
/**
* Returns the {@code boolean} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the {@code boolean} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code boolean}.
*/
boolean getBoolean(K name, boolean defaultValue);
/**
* Returns the {@code byte} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @return the {@code byte} value of the first value in insertion order or {@code null} if there is no such
* value or it can't be converted to {@code byte}.
*/
Byte getByte(K name);
/**
* Returns the {@code byte} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the {@code byte} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code byte}.
*/
byte getByte(K name, byte defaultValue);
/**
* Returns the {@code char} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @return the {@code char} value of the first value in insertion order or {@code null} if there is no such
* value or it can't be converted to {@code char}.
*/
Character getChar(K name);
/**
* Returns the {@code char} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the {@code char} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code char}.
*/
char getChar(K name, char defaultValue);
/**
* Returns the {@code short} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @return the {@code short} value of the first value in insertion order or {@code null} if there is no such
* value or it can't be converted to {@code short}.
*/
Short getShort(K name);
/**
* Returns the {@code short} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the {@code short} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code short}.
*/
short getShort(K name, short defaultValue);
/**
* Returns the {@code int} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @return the {@code int} value of the first value in insertion order or {@code null} if there is no such
* value or it can't be converted to {@code int}.
*/
Integer getInt(K name);
/**
* Returns the {@code int} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the {@code int} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code int}.
*/
int getInt(K name, int defaultValue);
/**
* Returns the {@code long} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @return the {@code long} value of the first value in insertion order or {@code null} if there is no such
* value or it can't be converted to {@code long}.
*/
Long getLong(K name);
/**
* Returns the {@code long} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the {@code long} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code long}.
*/
long getLong(K name, long defaultValue);
/**
* Returns the {@code float} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @return the {@code float} value of the first value in insertion order or {@code null} if there is no such
* value or it can't be converted to {@code float}.
*/
Float getFloat(K name);
/**
* Returns the {@code float} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the {@code float} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code float}.
*/
float getFloat(K name, float defaultValue);
/**
* Returns the {@code double} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @return the {@code double} value of the first value in insertion order or {@code null} if there is no such
* value or it can't be converted to {@code double}.
*/
Double getDouble(K name);
/**
* Returns the {@code double} value of a header with the specified name. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the {@code double} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code double}.
*/
double getDouble(K name, double defaultValue);
/**
* Returns the value of a header with the specified name in milliseconds. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @return the milliseconds value of the first value in insertion order or {@code null} if there is no such
* value or it can't be converted to milliseconds.
*/
Long getTimeMillis(K name);
/**
* Returns the value of a header with the specified name in milliseconds. If there is more than one value for the
* specified name, the first value in insertion order is returned.
*
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the milliseconds value of the first value in insertion order or {@code defaultValue} if there is no such
* value or it can't be converted to milliseconds.
*/
long getTimeMillis(K name, long defaultValue);
/**
* Returns the {@code boolean} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to retrieve
* @return the {@code boolean} value of the first value in insertion order or {@code null} if there is no
* such value or it can't be converted to {@code boolean}.
*/
Boolean getBooleanAndRemove(K name);
/**
* Returns the {@code boolean} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @param defaultValue the default value
* @return the {@code boolean} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code boolean}.
*/
boolean getBooleanAndRemove(K name, boolean defaultValue);
/**
* Returns the {@code byte} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @return the {@code byte} value of the first value in insertion order or {@code null} if there is no
* such value or it can't be converted to {@code byte}.
*/
Byte getByteAndRemove(K name);
/**
* Returns the {@code byte} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @param defaultValue the default value
* @return the {@code byte} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code byte}.
*/
byte getByteAndRemove(K name, byte defaultValue);
/**
* Returns the {@code char} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @return the {@code char} value of the first value in insertion order or {@code null} if there is no
* such value or it can't be converted to {@code char}.
*/
Character getCharAndRemove(K name);
/**
* Returns the {@code char} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @param defaultValue the default value
* @return the {@code char} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code char}.
*/
char getCharAndRemove(K name, char defaultValue);
/**
* Returns the {@code short} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @return the {@code short} value of the first value in insertion order or {@code null} if there is no
* such value or it can't be converted to {@code short}.
*/
Short getShortAndRemove(K name);
/**
* Returns the {@code short} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @param defaultValue the default value
* @return the {@code short} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code short}.
*/
short getShortAndRemove(K name, short defaultValue);
/**
* Returns the {@code int} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @return the {@code int} value of the first value in insertion order or {@code null} if there is no
* such value or it can't be converted to {@code int}.
*/
Integer getIntAndRemove(K name);
/**
* Returns the {@code int} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @param defaultValue the default value
* @return the {@code int} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code int}.
*/
int getIntAndRemove(K name, int defaultValue);
/**
* Returns the {@code long} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @return the {@code long} value of the first value in insertion order or {@code null} if there is no
* such value or it can't be converted to {@code long}.
*/
Long getLongAndRemove(K name);
/**
* Returns the {@code long} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @param defaultValue the default value
* @return the {@code long} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code long}.
*/
long getLongAndRemove(K name, long defaultValue);
/**
* Returns the {@code float} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @return the {@code float} value of the first value in insertion order or {@code null} if there is no
* such value or it can't be converted to {@code float}.
*/
Float getFloatAndRemove(K name);
/**
* Returns the {@code float} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @param defaultValue the default value
* @return the {@code float} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code float}.
*/
float getFloatAndRemove(K name, float defaultValue);
/**
* Returns the {@code double} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @return the {@code double} value of the first value in insertion order or {@code null} if there is no
* such value or it can't be converted to {@code double}.
*/
Double getDoubleAndRemove(K name);
/**
* Returns the {@code double} value of a header with the specified {@code name} and removes the header from this
* object. If there is more than one value for the specified name, the first value in insertion order is returned.
* In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to search
* @param defaultValue the default value
* @return the {@code double} value of the first value in insertion order or {@code defaultValue} if there is no
* such value or it can't be converted to {@code double}.
*/
double getDoubleAndRemove(K name, double defaultValue);
/**
* Returns the value of a header with the specified {@code name} in milliseconds and removes the header from this
* object. If there is more than one value for the specified {@code name}, the first value in insertion order is
* returned. In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to retrieve
* @return the milliseconds value of the first value in insertion order or {@code null} if there is no such
* value or it can't be converted to milliseconds.
*/
Long getTimeMillisAndRemove(K name);
/**
* Returns the value of a header with the specified {@code name} in milliseconds and removes the header from this
* object. If there is more than one value for the specified {@code name}, the first value in insertion order is
* returned. In any case all values for {@code name} are removed.
* <p>
* If an exception occurs during the translation from type {@code T} all entries with {@code name} may still
* be removed.
* @param name the name of the header to retrieve
* @param defaultValue the default value
* @return the milliseconds value of the first value in insertion order or {@code defaultValue} if there is no such
* value or it can't be converted to milliseconds.
*/
long getTimeMillisAndRemove(K name, long defaultValue);
/**
* Returns {@code true} if a header with the {@code name} exists, {@code false} otherwise.
*
* @param name the header name
*/
boolean contains(K name);
/**
* Returns {@code true} if a header with the {@code name} and {@code value} exists, {@code false} otherwise.
* <p>
* The {@link Object#equals(Object)} method is used to test for equality of {@code value}.
* </p>
* @param name the header name
* @param value the header value of the header to find
*/
boolean contains(K name, V value);
/**
* Returns {@code true} if a header with the name and value exists.
*
* @param name the header name
* @param value the header value
* @return {@code true} if it contains it {@code false} otherwise
*/
boolean containsObject(K name, Object value);
/**
* Returns {@code true} if a header with the name and value exists.
*
* @param name the header name
* @param value the header value
* @return {@code true} if it contains it {@code false} otherwise
*/
boolean containsBoolean(K name, boolean value);
/**
* Returns {@code true} if a header with the name and value exists.
*
* @param name the header name
* @param value the header value
* @return {@code true} if it contains it {@code false} otherwise
*/
boolean containsByte(K name, byte value);
/**
* Returns {@code true} if a header with the name and value exists.
*
* @param name the header name
* @param value the header value
* @return {@code true} if it contains it {@code false} otherwise
*/
boolean containsChar(K name, char value);
/**
* Returns {@code true} if a header with the name and value exists.
*
* @param name the header name
* @param value the header value
* @return {@code true} if it contains it {@code false} otherwise
*/
boolean containsShort(K name, short value);
/**
* Returns {@code true} if a header with the name and value exists.
*
* @param name the header name
* @param value the header value
* @return {@code true} if it contains it {@code false} otherwise
*/
boolean containsInt(K name, int value);
/**
* Returns {@code true} if a header with the name and value exists.
*
* @param name the header name
* @param value the header value
* @return {@code true} if it contains it {@code false} otherwise
*/
boolean containsLong(K name, long value);
/**
* Returns {@code true} if a header with the name and value exists.
*
* @param name the header name
* @param value the header value
* @return {@code true} if it contains it {@code false} otherwise
*/
boolean containsFloat(K name, float value);
/**
* Returns {@code true} if a header with the name and value exists.
*
* @param name the header name
* @param value the header value
* @return {@code true} if it contains it {@code false} otherwise
*/
boolean containsDouble(K name, double value);
/**
* Returns {@code true} if a header with the name and value exists.
*
* @param name the header name
* @param value the header value
* @return {@code true} if it contains it {@code false} otherwise
*/
boolean containsTimeMillis(K name, long value);
/**
* Returns the number of headers in this object.
*/
int size();
/**
* Returns {@code true} if {@link #size()} equals {@code 0}.
*/
boolean isEmpty();
/**
* Returns a {@link Set} of all header names in this object. The returned {@link Set} cannot be modified.
*/
Set<K> names();
/**
* Adds a new header with the specified {@code name} and {@code value}.
*
* @param name the name of the header
* @param value the value of the header
* @return {@code this}
*/
T add(K name, V value);
/**
* Adds new headers with the specified {@code name} and {@code values}. This method is semantically equivalent to
*
* <pre>
* for (T value : values) {
* headers.add(name, value);
* }
* </pre>
*
* @param name the header name
* @param values the values of the header
* @return {@code this}
*/
T add(K name, Iterable<? extends V> values);
/**
* Adds new headers with the specified {@code name} and {@code values}. This method is semantically equivalent to
*
* <pre>
* for (T value : values) {
* headers.add(name, value);
* }
* </pre>
*
* @param name the header name
* @param values the values of the header
* @return {@code this}
*/
T add(K name, V... values);
/**
* Adds a new header. Before the {@code value} is added, it's converted to type {@code T}.
*
* @param name the header name
* @param value the value of the header
* @return {@code this}
*/
T addObject(K name, Object value);
/**
* Adds a new header with the specified name and values. This method is equivalent to
*
* <pre>
* for (Object v : values) {
* headers.addObject(name, v);
* }
* </pre>
*
* @param name the header name
* @param values the value of the header
* @return {@code this}
*/
T addObject(K name, Iterable<?> values);
/**
* Adds a new header with the specified name and values. This method is equivalent to
*
* <pre>
* for (Object v : values) {
* headers.addObject(name, v);
* }
* </pre>
*
* @param name the header name
* @param values the value of the header
* @return {@code this}
*/
T addObject(K name, Object... values);
/**
* Adds a new header.
*
* @param name the header name
* @param value the value of the header
* @return {@code this}
*/
T addBoolean(K name, boolean value);
/**
* Adds a new header.
*
* @param name the header name
* @param value the value of the header
* @return {@code this}
*/
T addByte(K name, byte value);
/**
* Adds a new header.
*
* @param name the header name
* @param value the value of the header
* @return {@code this}
*/
T addChar(K name, char value);
/**
* Adds a new header.
*
* @param name the header name
* @param value the value of the header
* @return {@code this}
*/
T addShort(K name, short value);
/**
* Adds a new header.
*
* @param name the header name
* @param value the value of the header
* @return {@code this}
*/
T addInt(K name, int value);
/**
* Adds a new header.
*
* @param name the header name
* @param value the value of the header
* @return {@code this}
*/
T addLong(K name, long value);
/**
* Adds a new header.
*
* @param name the header name
* @param value the value of the header
* @return {@code this}
*/
T addFloat(K name, float value);
/**
* Adds a new header.
*
* @param name the header name
* @param value the value of the header
* @return {@code this}
*/
T addDouble(K name, double value);
/**
* Adds a new header.
*
* @param name the header name
* @param value the value of the header
* @return {@code this}
*/
T addTimeMillis(K name, long value);
/**
* Adds all header names and values of {@code headers} to this object.
*
* @throws IllegalArgumentException if {@code headers == this}.
* @return {@code this}
*/
T add(Headers<? extends K, ? extends V, ?> headers);
/**
* Sets a header with the specified name and value. Any existing headers with the same name are overwritten.
*
* @param name the header name
* @param value the value of the header
* @return {@code this}
*/
T set(K name, V value);
/**
* Sets a new header with the specified name and values. This method is equivalent to
*
* <pre>
* for (T v : values) {
* headers.addObject(name, v);
* }
* </pre>
*
* @param name the header name
* @param values the value of the header
* @return {@code this}
*/
T set(K name, Iterable<? extends V> values);
/**
* Sets a header with the specified name and values. Any existing headers with this name are removed. This method
* is equivalent to:
*
* <pre>
* headers.remove(name);
* for (T v : values) {
* headers.add(name, v);
* }
* </pre>
*
* @param name the header name
* @param values the value of the header
* @return {@code this}
*/
T set(K name, V... values);
/**
* Sets a new header. Any existing headers with this name are removed. Before the {@code value} is add, it's
* converted to type {@code T}.
*
* @param name the header name
* @param value the value of the header
* @throws NullPointerException if either {@code name} or {@code value} before or after its conversion is
* {@code null}.
* @return {@code this}
*/
T setObject(K name, Object value);
/**
* Sets a header with the specified name and values. Any existing headers with this name are removed. This method
* is equivalent to:
*
* <pre>
* headers.remove(name);
* for (Object v : values) {
* headers.addObject(name, v);
* }
* </pre>
*
* @param name the header name
* @param values the values of the header
* @return {@code this}
*/
T setObject(K name, Iterable<?> values);
/**
* Sets a header with the specified name and values. Any existing headers with this name are removed. This method
* is equivalent to:
*
* <pre>
* headers.remove(name);
* for (Object v : values) {
* headers.addObject(name, v);
* }
* </pre>
*
* @param name the header name
* @param values the values of the header
* @return {@code this}
*/
T setObject(K name, Object... values);
/**
* Set the {@code name} to {@code value}. This will remove all previous values associated with {@code name}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
T setBoolean(K name, boolean value);
/**
* Set the {@code name} to {@code value}. This will remove all previous values associated with {@code name}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
T setByte(K name, byte value);
/**
* Set the {@code name} to {@code value}. This will remove all previous values associated with {@code name}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
T setChar(K name, char value);
/**
* Set the {@code name} to {@code value}. This will remove all previous values associated with {@code name}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
T setShort(K name, short value);
/**
* Set the {@code name} to {@code value}. This will remove all previous values associated with {@code name}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
T setInt(K name, int value);
/**
* Set the {@code name} to {@code value}. This will remove all previous values associated with {@code name}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
T setLong(K name, long value);
/**
* Set the {@code name} to {@code value}. This will remove all previous values associated with {@code name}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
T setFloat(K name, float value);
/**
* Set the {@code name} to {@code value}. This will remove all previous values associated with {@code name}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
T setDouble(K name, double value);
/**
* Set the {@code name} to {@code value}. This will remove all previous values associated with {@code name}.
* @param name The name to modify
* @param value The value
* @return {@code this}
*/
T setTimeMillis(K name, long value);
/**
* Clears the current header entries and copies all header entries of the specified {@code headers}.
*
* @return {@code this}
*/
T set(Headers<? extends K, ? extends V, ?> headers);
/**
* Retains all current headers but calls {@link #set(K, V)} for each entry in {@code headers}.
*
* @param headers The headers used to {@link #set(K, V)} values in this instance
* @return {@code this}
*/
T setAll(Headers<? extends K, ? extends V, ?> headers);
/**
* Removes all headers with the specified {@code name}.
*
* @param name the header name
* @return {@code true} if at least one entry has been removed.
*/
boolean remove(K name);
/**
* Removes all headers. After a call to this method {@link #size()} equals {@code 0}.
*
* @return {@code this}
*/
T clear();
@Override
Iterator<Entry<K, V>> iterator();
}
| Headers |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/io/UrlResource.java | {
"start": 1524,
"end": 12005
} | class ____ extends AbstractFileResolvingResource {
private static final String AUTHORIZATION = "Authorization";
/**
* Original URI, if available; used for URI and File access.
*/
private final @Nullable URI uri;
/**
* Original URL, used for actual access.
*/
private final URL url;
/**
* Cleaned URL String (with normalized path), used for comparisons.
*/
private volatile @Nullable String cleanedUrl;
/**
* Whether to use URLConnection caches ({@code null} means default).
*/
volatile @Nullable Boolean useCaches;
/**
* Create a new {@code UrlResource} based on the given URL object.
* @param url a URL
* @see #UrlResource(URI)
* @see #UrlResource(String)
*/
public UrlResource(URL url) {
Assert.notNull(url, "URL must not be null");
this.uri = null;
this.url = url;
}
/**
* Create a new {@code UrlResource} based on the given URI object.
* @param uri a URI
* @throws MalformedURLException if the given URL path is not valid
* @since 2.5
*/
public UrlResource(URI uri) throws MalformedURLException {
Assert.notNull(uri, "URI must not be null");
this.uri = uri;
this.url = uri.toURL();
}
/**
* Create a new {@code UrlResource} based on a URI path.
* <p>Note: The given path needs to be pre-encoded if necessary.
* @param path a URI path
* @throws MalformedURLException if the given URI path is not valid
* @see ResourceUtils#toURI(String)
*/
public UrlResource(String path) throws MalformedURLException {
Assert.notNull(path, "Path must not be null");
String cleanedPath = StringUtils.cleanPath(path);
URI uri;
URL url;
try {
// Prefer URI construction with toURL conversion (as of 6.1)
uri = ResourceUtils.toURI(cleanedPath);
url = uri.toURL();
}
catch (URISyntaxException | IllegalArgumentException ex) {
uri = null;
url = ResourceUtils.toURL(path);
}
this.uri = uri;
this.url = url;
this.cleanedUrl = cleanedPath;
}
/**
* Create a new {@code UrlResource} based on a URI specification.
* <p>The given parts will automatically get encoded if necessary.
* @param protocol the URL protocol to use (for example, "jar" or "file" - without colon);
* also known as "scheme"
* @param location the location (for example, the file path within that protocol);
* also known as "scheme-specific part"
* @throws MalformedURLException if the given URL specification is not valid
* @see java.net.URI#URI(String, String, String)
*/
public UrlResource(String protocol, String location) throws MalformedURLException {
this(protocol, location, null);
}
/**
* Create a new {@code UrlResource} based on a URI specification.
* <p>The given parts will automatically get encoded if necessary.
* @param protocol the URL protocol to use (for example, "jar" or "file" - without colon);
* also known as "scheme"
* @param location the location (for example, the file path within that protocol);
* also known as "scheme-specific part"
* @param fragment the fragment within that location (for example, anchor on an HTML page,
* as following after a "#" separator)
* @throws MalformedURLException if the given URL specification is not valid
* @see java.net.URI#URI(String, String, String)
*/
public UrlResource(String protocol, String location, @Nullable String fragment) throws MalformedURLException {
try {
this.uri = new URI(protocol, location, fragment);
this.url = this.uri.toURL();
}
catch (URISyntaxException ex) {
MalformedURLException exToThrow = new MalformedURLException(ex.getMessage());
exToThrow.initCause(ex);
throw exToThrow;
}
}
/**
* Create a new {@code UrlResource} from the given {@link URI}.
* <p>This factory method is a convenience for {@link #UrlResource(URI)} that
* catches any {@link MalformedURLException} and rethrows it wrapped in an
* {@link UncheckedIOException}; suitable for use in {@link java.util.stream.Stream}
* and {@link java.util.Optional} APIs or other scenarios when a checked
* {@link IOException} is undesirable.
* @param uri a URI
* @throws UncheckedIOException if the given URL path is not valid
* @since 6.0
* @see #UrlResource(URI)
*/
public static UrlResource from(URI uri) throws UncheckedIOException {
try {
return new UrlResource(uri);
}
catch (MalformedURLException ex) {
throw new UncheckedIOException(ex);
}
}
/**
* Create a new {@code UrlResource} from the given URL path.
* <p>This factory method is a convenience for {@link #UrlResource(String)}
* that catches any {@link MalformedURLException} and rethrows it wrapped in an
* {@link UncheckedIOException}; suitable for use in {@link java.util.stream.Stream}
* and {@link java.util.Optional} APIs or other scenarios when a checked
* {@link IOException} is undesirable.
* @param path a URL path
* @throws UncheckedIOException if the given URL path is not valid
* @since 6.0
* @see #UrlResource(String)
*/
public static UrlResource from(String path) throws UncheckedIOException {
try {
return new UrlResource(path);
}
catch (MalformedURLException ex) {
throw new UncheckedIOException(ex);
}
}
/**
* Lazily determine a cleaned URL for the given original URL.
*/
private String getCleanedUrl() {
String cleanedUrl = this.cleanedUrl;
if (cleanedUrl != null) {
return cleanedUrl;
}
String originalPath = (this.uri != null ? this.uri : this.url).toString();
cleanedUrl = StringUtils.cleanPath(originalPath);
this.cleanedUrl = cleanedUrl;
return cleanedUrl;
}
/**
* Set an explicit flag for {@link URLConnection#setUseCaches},
* to be applied for any {@link URLConnection} operation in this resource.
* <p>By default, caching will be applied only to jar resources.
* An explicit {@code true} flag applies caching to all resources, whereas an
* explicit {@code false} flag turns off caching for jar resources as well.
* @since 6.2.10
* @see ResourceUtils#useCachesIfNecessary
*/
public void setUseCaches(boolean useCaches) {
this.useCaches = useCaches;
}
/**
* This implementation opens an InputStream for the given URL.
* @see java.net.URL#openConnection()
* @see java.net.URLConnection#setUseCaches(boolean)
* @see java.net.URLConnection#getInputStream()
*/
@Override
public InputStream getInputStream() throws IOException {
URLConnection con = this.url.openConnection();
customizeConnection(con);
try {
return con.getInputStream();
}
catch (IOException ex) {
// Close the HTTP connection (if applicable).
if (con instanceof HttpURLConnection httpCon) {
httpCon.disconnect();
}
throw ex;
}
}
@Override
protected void customizeConnection(URLConnection con) throws IOException {
super.customizeConnection(con);
String userInfo = this.url.getUserInfo();
if (userInfo != null) {
String encodedCredentials = Base64.getUrlEncoder().encodeToString(userInfo.getBytes());
con.setRequestProperty(AUTHORIZATION, "Basic " + encodedCredentials);
}
}
@Override
void useCachesIfNecessary(URLConnection con) {
Boolean useCaches = this.useCaches;
if (useCaches != null) {
con.setUseCaches(useCaches);
}
else {
super.useCachesIfNecessary(con);
}
}
/**
* This implementation returns the underlying URL reference.
*/
@Override
public URL getURL() {
return this.url;
}
/**
* This implementation returns the underlying URI directly,
* if possible.
*/
@Override
public URI getURI() throws IOException {
if (this.uri != null) {
return this.uri;
}
else {
return super.getURI();
}
}
@Override
public boolean isFile() {
if (this.uri != null) {
return super.isFile(this.uri);
}
else {
return super.isFile();
}
}
/**
* This implementation returns a File reference for the underlying URL/URI,
* provided that it refers to a file in the file system.
* @see org.springframework.util.ResourceUtils#getFile(java.net.URL, String)
*/
@Override
public File getFile() throws IOException {
if (this.uri != null) {
return super.getFile(this.uri);
}
else {
return super.getFile();
}
}
/**
* This implementation creates a {@code UrlResource}, delegating to
* {@link #createRelativeURL(String)} for adapting the relative path.
* @see #createRelativeURL(String)
*/
@Override
public Resource createRelative(String relativePath) throws MalformedURLException {
UrlResource resource = new UrlResource(createRelativeURL(relativePath));
resource.useCaches = this.useCaches;
return resource;
}
/**
* This delegate creates a {@code java.net.URL}, applying the given path
* relative to the path of the underlying URL of this resource descriptor.
* <p>A leading slash will get dropped; a "#" symbol will get encoded.
* Note that this method effectively cleans the combined path as of 6.1.
* @since 5.2
* @see #createRelative(String)
* @see ResourceUtils#toRelativeURL(URL, String)
*/
protected URL createRelativeURL(String relativePath) throws MalformedURLException {
if (relativePath.startsWith("/")) {
relativePath = relativePath.substring(1);
}
return ResourceUtils.toRelativeURL(this.url, relativePath);
}
/**
* This implementation returns the URL-decoded name of the file that this URL
* refers to.
* @see java.net.URL#getPath()
* @see java.net.URLDecoder#decode(String, java.nio.charset.Charset)
*/
@Override
public @Nullable String getFilename() {
if (this.uri != null) {
String path = this.uri.getPath();
if (path != null) {
// Prefer URI path: decoded and has standard separators
return StringUtils.getFilename(this.uri.getPath());
}
}
// Otherwise, process URL path
String filename = StringUtils.getFilename(StringUtils.cleanPath(this.url.getPath()));
return (filename != null ? URLDecoder.decode(filename, StandardCharsets.UTF_8) : null);
}
/**
* This implementation returns a description that includes the URL.
*/
@Override
public String getDescription() {
return "URL [" + (this.uri != null ? this.uri : this.url) + "]";
}
/**
* This implementation compares the underlying URL references.
*/
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof UrlResource that &&
getCleanedUrl().equals(that.getCleanedUrl())));
}
/**
* This implementation returns the hash code of the underlying URL reference.
*/
@Override
public int hashCode() {
return getCleanedUrl().hashCode();
}
}
| UrlResource |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/api/AbstractListAssert.java | {
"start": 1769,
"end": 4970
} | class ____<SELF extends AbstractListAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT>,
ACTUAL extends List<? extends ELEMENT>,
ELEMENT,
ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>>
extends AbstractCollectionAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT>
implements IndexedObjectEnumerableAssert<SELF, ELEMENT> {
// @format:on
// TODO reduce the visibility of the fields annotated with @VisibleForTesting
Lists lists = Lists.instance();
protected AbstractListAssert(ACTUAL actual, Class<?> selfType) {
super(actual, selfType);
}
/** {@inheritDoc} */
@Override
public SELF contains(ELEMENT value, Index index) {
lists.assertContains(info, actual, value, index);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF doesNotContain(ELEMENT value, Index index) {
lists.assertDoesNotContain(info, actual, value, index);
return myself;
}
/**
* Verifies that the actual object at the given index in the actual group satisfies the given condition.
*
* @param condition the given condition.
* @param index the index where the object should be stored in the actual group.
* @return this assertion object.
* @throws AssertionError if the given {@code List} is {@code null} or empty.
* @throws NullPointerException if the given {@code Index} is {@code null}.
* @throws IndexOutOfBoundsException if the value of the given {@code Index} is equal to or greater than the size of
* the given {@code List}.
* @throws NullPointerException if the given {@code Condition} is {@code null}.
* @throws AssertionError if the value in the given {@code List} at the given index does not satisfy the given
* {@code Condition} .
*/
public SELF has(Condition<? super ELEMENT> condition, Index index) {
lists.assertHas(info, actual, condition, index);
return myself;
}
/**
* Verifies that the actual object at the given index in the actual group satisfies the given condition.
*
* @param condition the given condition.
* @param index the index where the object should be stored in the actual group.
* @return this assertion object.
* @throws AssertionError if the given {@code List} is {@code null} or empty.
* @throws NullPointerException if the given {@code Index} is {@code null}.
* @throws IndexOutOfBoundsException if the value of the given {@code Index} is equal to or greater than the size of
* the given {@code List}.
* @throws NullPointerException if the given {@code Condition} is {@code null}.
* @throws AssertionError if the value in the given {@code List} at the given index does not satisfy the given
* {@code Condition} .
*/
public SELF is(Condition<? super ELEMENT> condition, Index index) {
lists.assertIs(info, actual, condition, index);
return myself;
}
/**
* Verifies that the actual list is sorted in ascending order according to the natural ordering of its elements.
* <p>
* All list elements must implement the {@link Comparable} | AbstractListAssert |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/Lens.java | {
"start": 429,
"end": 1077
} | class ____ {
@Id
@GeneratedValue
private Long id;
private float focal;
@Formula("(1/focal)")
private float length;
@ManyToOne()
@JoinColumn(name="`frame_fk`", referencedColumnName = "name")
private Frame frame;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public float getFocal() {
return focal;
}
public void setFocal(float focal) {
this.focal = focal;
}
public float getLength() {
return length;
}
public void setLength(float length) {
this.length = length;
}
public Frame getFrame() {
return frame;
}
public void setFrame(Frame frame) {
this.frame = frame;
}
}
| Lens |
java | spring-projects__spring-framework | spring-jms/src/main/java/org/springframework/jms/listener/endpoint/JmsMessageEndpointManager.java | {
"start": 2182,
"end": 4378
} | class ____ extends GenericMessageEndpointManager
implements BeanNameAware, MessageListenerContainer {
private final JmsMessageEndpointFactory endpointFactory = new JmsMessageEndpointFactory();
private boolean messageListenerSet = false;
private JmsActivationSpecFactory activationSpecFactory = new DefaultJmsActivationSpecFactory();
private @Nullable JmsActivationSpecConfig activationSpecConfig;
/**
* Set the JMS MessageListener for this endpoint.
* <p>This is a shortcut for configuring a dedicated JmsMessageEndpointFactory.
* @see JmsMessageEndpointFactory#setMessageListener
*/
public void setMessageListener(MessageListener messageListener) {
this.endpointFactory.setMessageListener(messageListener);
this.messageListenerSet = true;
}
/**
* Return the JMS MessageListener for this endpoint.
*/
public MessageListener getMessageListener() {
return this.endpointFactory.getMessageListener();
}
/**
* Set the XA transaction manager to use for wrapping endpoint
* invocations, enlisting the endpoint resource in each such transaction.
* <p>The passed-in object may be a transaction manager which implements
* Spring's {@link org.springframework.transaction.jta.TransactionFactory}
* interface, or a plain {@link jakarta.transaction.TransactionManager}.
* <p>If no transaction manager is specified, the endpoint invocation
* will simply not be wrapped in an XA transaction. Consult your
* resource provider's ActivationSpec documentation for the local
* transaction options of your particular provider.
* <p>This is a shortcut for configuring a dedicated JmsMessageEndpointFactory.
* @see JmsMessageEndpointFactory#setTransactionManager
*/
public void setTransactionManager(Object transactionManager) {
this.endpointFactory.setTransactionManager(transactionManager);
}
/**
* Set the factory for concrete JCA 1.5 ActivationSpec objects,
* creating JCA ActivationSpecs based on
* {@link #setActivationSpecConfig JmsActivationSpecConfig} objects.
* <p>This factory is dependent on the concrete JMS provider, for example, on ActiveMQ.
* The default implementation simply guesses the ActivationSpec | JmsMessageEndpointManager |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ObjectOfTypeStrategy.java | {
"start": 1790,
"end": 2494
} | class ____ from the first argument (must be a non-null string literal)
* <li>Processes key-value pairs starting from the second argument
* <li>Extracts field names (keys) from odd-positioned arguments (indices 1, 3, 5, ...)
* </ul>
*
* <p><b>Examples:</b>
*
* <ul>
* <li>{@code OBJECT_OF('com.example.User', 'name', 'Alice', 'age', 30)} → {@code
* STRUCTURED<com.example.User>(name CHAR(5), age INT)}
* <li>{@code OBJECT_OF('com.example.Point', 'x', 1.5, 'y', 2.0)} → {@code
* STRUCTURED<com.example.Point>(x DOUBLE, y DOUBLE)}
* </ul>
*
* @see org.apache.flink.table.functions.BuiltInFunctionDefinitions#OBJECT_OF
* @see ObjectOfInputTypeStrategy
*/
@Internal
public | name |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryQualifierTest.java | {
"start": 5607,
"end": 6837
} | interface ____ {
@Qual
Object frobnicator();
}
""")
.doTest();
}
@Test
public void recordWithExplicitlyAnnotatedConstructor_noFinding() {
helper
.addSourceLines(
"Test.java",
"""
import javax.inject.Inject;
record Test(@Qual int x) {
@Inject
Test {}
}
""")
.doTest();
}
@Test
public void recordWithoutExplicitlyAnnotatedConstructor_finding() {
helper
.addSourceLines(
"Test.java",
"""
import javax.inject.Inject;
// BUG: Diagnostic contains:
record Test(@Qual int x) {
Test {}
}
""")
.doTest();
}
@Test
public void jukitoTestRunner_noFinding() {
helper
.addSourceLines(
"org/jukito/All.java",
"""
package org.jukito;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Qualifier;
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @ | Test |
java | apache__flink | flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/FileSystemTableSource.java | {
"start": 3928,
"end": 22137
} | class ____ extends AbstractFileSystemTable
implements ScanTableSource,
SupportsProjectionPushDown,
SupportsLimitPushDown,
SupportsPartitionPushDown,
SupportsFilterPushDown,
SupportsReadingMetadata,
SupportsStatisticReport {
private static final Logger LOG = LoggerFactory.getLogger(FileSystemTableSource.class);
@Nullable private final DecodingFormat<BulkFormat<RowData, FileSourceSplit>> bulkReaderFormat;
@Nullable private final DecodingFormat<DeserializationSchema<RowData>> deserializationFormat;
// These mutable fields
private List<Map<String, String>> remainingPartitions;
private List<ResolvedExpression> filters;
private Long limit;
private int[][] projectFields;
private List<String> metadataKeys;
private DataType producedDataType;
public FileSystemTableSource(
ObjectIdentifier tableIdentifier,
DataType physicalRowDataType,
List<String> partitionKeys,
ReadableConfig tableOptions,
@Nullable DecodingFormat<BulkFormat<RowData, FileSourceSplit>> bulkReaderFormat,
@Nullable DecodingFormat<DeserializationSchema<RowData>> deserializationFormat) {
super(tableIdentifier, physicalRowDataType, partitionKeys, tableOptions);
if (Stream.of(bulkReaderFormat, deserializationFormat).allMatch(Objects::isNull)) {
String identifier = tableOptions.get(FactoryUtil.FORMAT);
throw new ValidationException(
String.format(
"Could not find any format factory for identifier '%s' in the classpath.",
identifier));
}
this.bulkReaderFormat = bulkReaderFormat;
this.deserializationFormat = deserializationFormat;
this.producedDataType = physicalRowDataType;
}
@Override
public ScanRuntimeProvider getScanRuntimeProvider(ScanContext scanContext) {
// When this table has no partition, just return an empty source.
if (!partitionKeys.isEmpty() && getOrFetchPartitions().isEmpty()) {
return InputFormatProvider.of(new CollectionInputFormat<>(new ArrayList<>(), null));
}
// Resolve metadata and make sure to filter out metadata not in the producedDataType
final List<String> metadataKeys =
this.metadataKeys == null ? Collections.emptyList() : this.metadataKeys;
final List<ReadableFileInfo> metadataToExtract =
metadataKeys.stream().map(ReadableFileInfo::resolve).collect(Collectors.toList());
// Filter out partition columns not in producedDataType
final List<String> partitionKeysToExtract =
DataType.getFieldNames(producedDataType).stream()
.filter(this.partitionKeys::contains)
.collect(Collectors.toList());
// Compute the physical projection and the physical data type, that is
// the type without partition columns and metadata in the same order of the schema
DataType physicalDataType = physicalRowDataType;
final Projection partitionKeysProjections =
Projection.fromFieldNames(physicalDataType, partitionKeys);
final Projection physicalProjections =
(projectFields != null
? Projection.of(projectFields)
: Projection.all(physicalDataType))
.difference(partitionKeysProjections);
physicalDataType =
partitionKeysProjections.complement(physicalDataType).project(physicalDataType);
if (bulkReaderFormat != null) {
if (bulkReaderFormat instanceof BulkDecodingFormat
&& filters != null
&& filters.size() > 0) {
((BulkDecodingFormat<RowData>) bulkReaderFormat).applyFilters(filters);
}
BulkFormat<RowData, FileSourceSplit> format;
if (bulkReaderFormat instanceof ProjectableDecodingFormat) {
format =
((ProjectableDecodingFormat<BulkFormat<RowData, FileSourceSplit>>)
bulkReaderFormat)
.createRuntimeDecoder(
scanContext,
physicalDataType,
physicalProjections.toNestedIndexes());
} else {
format =
new ProjectingBulkFormat(
bulkReaderFormat.createRuntimeDecoder(
scanContext, physicalDataType),
physicalProjections.toTopLevelIndexes(),
scanContext.createTypeInformation(
physicalProjections.project(physicalDataType)));
}
format =
wrapBulkFormat(
scanContext,
format,
producedDataType,
metadataToExtract,
partitionKeysToExtract);
return createSourceProvider(format);
} else if (deserializationFormat != null) {
BulkFormat<RowData, FileSourceSplit> format;
if (deserializationFormat instanceof ProjectableDecodingFormat) {
format =
new DeserializationSchemaAdapter(
((ProjectableDecodingFormat<DeserializationSchema<RowData>>)
deserializationFormat)
.createRuntimeDecoder(
scanContext,
physicalDataType,
physicalProjections.toNestedIndexes()));
} else {
format =
new ProjectingBulkFormat(
new DeserializationSchemaAdapter(
deserializationFormat.createRuntimeDecoder(
scanContext, physicalDataType)),
physicalProjections.toTopLevelIndexes(),
scanContext.createTypeInformation(
physicalProjections.project(physicalDataType)));
}
format =
wrapBulkFormat(
scanContext,
format,
producedDataType,
metadataToExtract,
partitionKeysToExtract);
return createSourceProvider(format);
} else {
throw new TableException("Can not find format factory.");
}
}
/**
* Wraps bulk format in a {@link FileInfoExtractorBulkFormat} and {@link LimitableBulkFormat},
* if needed.
*/
private BulkFormat<RowData, FileSourceSplit> wrapBulkFormat(
ScanContext context,
BulkFormat<RowData, FileSourceSplit> bulkFormat,
DataType producedDataType,
List<ReadableFileInfo> metadata,
List<String> partitionKeys) {
if (!metadata.isEmpty() || !partitionKeys.isEmpty()) {
final List<String> producedFieldNames = DataType.getFieldNames(producedDataType);
final Map<String, FileInfoAccessor> metadataColumns =
IntStream.range(0, metadata.size())
.mapToObj(
i -> {
// Access metadata columns from the back because the
// names are decided by the planner
final int columnPos =
producedFieldNames.size() - metadata.size() + i;
return entry(
producedFieldNames.get(columnPos),
metadata.get(i).getAccessor());
})
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
bulkFormat =
new FileInfoExtractorBulkFormat(
bulkFormat,
producedDataType,
context.createTypeInformation(producedDataType),
metadataColumns,
partitionKeys,
defaultPartName);
}
bulkFormat = LimitableBulkFormat.create(bulkFormat, limit);
return bulkFormat;
}
private SourceProvider createSourceProvider(BulkFormat<RowData, FileSourceSplit> bulkFormat) {
final FileSource.FileSourceBuilder<RowData> fileSourceBuilder =
FileSource.forBulkFileFormat(bulkFormat, paths());
tableOptions
.getOptional(FileSystemConnectorOptions.SOURCE_MONITOR_INTERVAL)
.ifPresent(fileSourceBuilder::monitorContinuously);
tableOptions
.getOptional(FileSystemConnectorOptions.SOURCE_PATH_REGEX_PATTERN)
.ifPresent(
regex ->
fileSourceBuilder.setFileEnumerator(
bulkFormat.isSplittable()
? () ->
new BlockSplittingRecursiveAllDirEnumerator(
regex)
: () ->
new NonSplittingRecursiveAllDirEnumerator(
regex)));
return SourceProvider.of(fileSourceBuilder.build());
}
private Path[] paths() {
if (partitionKeys.isEmpty()) {
return new Path[] {path};
} else {
return getOrFetchPartitions().stream()
.map(FileSystemTableSource.this::toFullLinkedPartSpec)
.map(PartitionPathUtils::generatePartitionPath)
.map(n -> new Path(path, n))
.toArray(Path[]::new);
}
}
@Override
public ChangelogMode getChangelogMode() {
if (bulkReaderFormat != null) {
return bulkReaderFormat.getChangelogMode();
} else if (deserializationFormat != null) {
return deserializationFormat.getChangelogMode();
} else {
throw new TableException("Can not find format factory.");
}
}
@Override
public Result applyFilters(List<ResolvedExpression> filters) {
this.filters = new ArrayList<>(filters);
return Result.of(new ArrayList<>(filters), new ArrayList<>(filters));
}
@Override
public void applyLimit(long limit) {
this.limit = limit;
}
@Override
public Optional<List<Map<String, String>>> listPartitions() {
try {
return Optional.of(
PartitionPathUtils.searchPartSpecAndPaths(
path.getFileSystem(), path, partitionKeys.size())
.stream()
.map(tuple2 -> tuple2.f0)
.map(
spec -> {
LinkedHashMap<String, String> ret = new LinkedHashMap<>();
spec.forEach(
(k, v) ->
ret.put(
k,
defaultPartName.equals(v)
? null
: v));
return ret;
})
.collect(Collectors.toList()));
} catch (Exception e) {
throw new TableException("Fetch partitions fail.", e);
}
}
@Override
public void applyPartitions(List<Map<String, String>> remainingPartitions) {
this.remainingPartitions = remainingPartitions;
}
@Override
public boolean supportsNestedProjection() {
return false;
}
@Override
public TableStats reportStatistics() {
try {
// only support BOUNDED source
Optional<Duration> monitorIntervalOpt =
tableOptions.getOptional(FileSystemConnectorOptions.SOURCE_MONITOR_INTERVAL);
if (monitorIntervalOpt.isPresent() && monitorIntervalOpt.get().toMillis() <= 0) {
return TableStats.UNKNOWN;
}
if (tableOptions.get(FileSystemConnectorOptions.SOURCE_REPORT_STATISTICS)
== FileSystemConnectorOptions.FileStatisticsType.NONE) {
return TableStats.UNKNOWN;
}
// use NonSplittingRecursiveEnumerator to get all files
NonSplittingRecursiveEnumerator enumerator = new NonSplittingRecursiveEnumerator();
Collection<FileSourceSplit> splits = enumerator.enumerateSplits(paths(), 1);
List<Path> files =
splits.stream().map(FileSourceSplit::path).collect(Collectors.toList());
if (bulkReaderFormat instanceof FileBasedStatisticsReportableInputFormat) {
TableStats tableStats =
((FileBasedStatisticsReportableInputFormat) bulkReaderFormat)
.reportStatistics(files, producedDataType);
if (tableStats.equals(TableStats.UNKNOWN)) {
return tableStats;
}
return limit == null
? tableStats
: new TableStats(Math.min(limit, tableStats.getRowCount()));
} else if (deserializationFormat instanceof FileBasedStatisticsReportableInputFormat) {
TableStats tableStats =
((FileBasedStatisticsReportableInputFormat) deserializationFormat)
.reportStatistics(files, producedDataType);
if (tableStats.equals(TableStats.UNKNOWN)) {
return tableStats;
}
return limit == null
? tableStats
: new TableStats(Math.min(limit, tableStats.getRowCount()));
} else {
return TableStats.UNKNOWN;
}
} catch (Exception e) {
LOG.warn(
"Reporting statistics failed for file system table source: {}", e.getMessage());
return TableStats.UNKNOWN;
}
}
@Override
public FileSystemTableSource copy() {
FileSystemTableSource source =
new FileSystemTableSource(
tableIdentifier,
physicalRowDataType,
partitionKeys,
tableOptions,
bulkReaderFormat,
deserializationFormat);
source.partitionKeys = partitionKeys;
source.remainingPartitions = remainingPartitions;
source.filters = filters;
source.limit = limit;
source.projectFields = projectFields;
source.metadataKeys = metadataKeys;
source.producedDataType = producedDataType;
return source;
}
@Override
public String asSummaryString() {
return "Filesystem";
}
private List<Map<String, String>> getOrFetchPartitions() {
if (remainingPartitions == null) {
remainingPartitions = listPartitions().get();
}
return remainingPartitions;
}
private LinkedHashMap<String, String> toFullLinkedPartSpec(Map<String, String> part) {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
for (String k : partitionKeys) {
if (!part.containsKey(k)) {
throw new TableException(
"Partition keys are: "
+ partitionKeys
+ ", incomplete partition spec: "
+ part);
}
map.put(k, part.get(k));
}
return map;
}
// --------------------------------------------------------------------------------------------
// Methods to apply projections and metadata,
// will influence the final output and physical type used by formats
// --------------------------------------------------------------------------------------------
@Override
public void applyProjection(int[][] projectedFields, DataType producedDataType) {
this.projectFields = projectedFields;
this.producedDataType = producedDataType;
}
@Override
public void applyReadableMetadata(List<String> metadataKeys, DataType producedDataType) {
this.metadataKeys = metadataKeys;
this.producedDataType = producedDataType;
}
// --------------------------------------------------------------------------------------------
// Metadata handling
// --------------------------------------------------------------------------------------------
@Override
public Map<String, DataType> listReadableMetadata() {
return Arrays.stream(ReadableFileInfo.values())
.collect(Collectors.toMap(ReadableFileInfo::getKey, ReadableFileInfo::getDataType));
}
| FileSystemTableSource |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/sql/model/internal/TableUpdateStandard.java | {
"start": 748,
"end": 3888
} | class ____ extends AbstractTableUpdate<JdbcMutationOperation> {
private final String whereFragment;
private final Expectation expectation;
private final List<ColumnReference> returningColumns;
public TableUpdateStandard(
MutatingTableReference mutatingTable,
MutationTarget<?> mutationTarget,
String sqlComment,
List<ColumnValueBinding> valueBindings,
List<ColumnValueBinding> keyRestrictionBindings,
List<ColumnValueBinding> optLockRestrictionBindings) {
this(
mutatingTable,
mutationTarget,
sqlComment,
valueBindings,
keyRestrictionBindings,
optLockRestrictionBindings,
null,
null,
Collections.emptyList()
);
}
public TableUpdateStandard(
MutatingTableReference mutatingTable,
MutationTarget<?> mutationTarget,
String sqlComment,
List<ColumnValueBinding> valueBindings,
List<ColumnValueBinding> keyRestrictionBindings,
List<ColumnValueBinding> optLockRestrictionBindings,
String whereFragment,
Expectation expectation,
List<ColumnReference> returningColumns) {
super( mutatingTable, mutationTarget, sqlComment, valueBindings, keyRestrictionBindings, optLockRestrictionBindings );
this.whereFragment = whereFragment;
this.expectation = expectation;
this.returningColumns = returningColumns;
}
public TableUpdateStandard(
MutatingTableReference tableReference,
MutationTarget<?> mutationTarget,
String sqlComment,
List<ColumnValueBinding> valueBindings,
List<ColumnValueBinding> keyRestrictionBindings,
List<ColumnValueBinding> optLockRestrictionBindings,
List<ColumnValueParameter> parameters) {
this(
tableReference,
mutationTarget,
sqlComment,
valueBindings,
keyRestrictionBindings,
optLockRestrictionBindings,
parameters,
null,
null
);
}
public TableUpdateStandard(
MutatingTableReference tableReference,
MutationTarget<?> mutationTarget,
String sqlComment,
List<ColumnValueBinding> valueBindings,
List<ColumnValueBinding> keyRestrictionBindings,
List<ColumnValueBinding> optLockRestrictionBindings,
List<ColumnValueParameter> parameters,
String whereFragment,
Expectation expectation) {
super( tableReference, mutationTarget, sqlComment, valueBindings, keyRestrictionBindings, optLockRestrictionBindings, parameters );
this.whereFragment = whereFragment;
this.expectation = expectation;
this.returningColumns = Collections.emptyList();
}
@Override
public boolean isCustomSql() {
return false;
}
@Override
public boolean isCallable() {
return false;
}
public String getWhereFragment() {
return whereFragment;
}
@Override
public void accept(SqlAstWalker walker) {
walker.visitStandardTableUpdate( this );
}
@Override
public Expectation getExpectation() {
if ( expectation != null ) {
return expectation;
}
return super.getExpectation();
}
@Override
public List<ColumnReference> getReturningColumns() {
return returningColumns;
}
@Override
public void forEachReturningColumn(BiConsumer<Integer,ColumnReference> consumer) {
forEachThing( returningColumns, consumer );
}
}
| TableUpdateStandard |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestConcatenatedCompressedInput.java | {
"start": 1927,
"end": 1993
} | class ____ concatenated {@link CompressionInputStream}.
*/
public | for |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/aggregate/StringValueMax.java | {
"start": 989,
"end": 1145
} | class ____ a value aggregator that maintain the biggest of
* a sequence of strings.
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public | implements |
java | resilience4j__resilience4j | resilience4j-micrometer/src/main/java/io/github/resilience4j/micrometer/tagged/TaggedTimeLimiterMetricsPublisher.java | {
"start": 875,
"end": 1679
} | class ____
extends AbstractTimeLimiterMetrics implements MetricsPublisher<TimeLimiter> {
private final MeterRegistry meterRegistry;
public TaggedTimeLimiterMetricsPublisher(MeterRegistry meterRegistry) {
super(TimeLimiterMetricNames.ofDefaults());
this.meterRegistry = requireNonNull(meterRegistry);
}
public TaggedTimeLimiterMetricsPublisher(TimeLimiterMetricNames names, MeterRegistry meterRegistry) {
super(names);
this.meterRegistry = requireNonNull(meterRegistry);
}
@Override
public void publishMetrics(TimeLimiter entry) {
addMetrics(meterRegistry, entry);
}
@Override
public void removeMetrics(TimeLimiter entry) {
removeMetrics(meterRegistry, entry.getName());
}
}
| TaggedTimeLimiterMetricsPublisher |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng3740SelfReferentialReactorProjectsTest.java | {
"start": 1334,
"end": 2020
} | class ____ extends AbstractMavenIntegrationTestCase {
@Test
public void testitMNG3740() throws Exception {
File testDir = extractResources("/mng-3740");
File v1 = new File(testDir, "projects.v1");
File v2 = new File(testDir, "projects.v2");
Verifier verifier;
verifier = newVerifier(v1.getAbsolutePath());
verifier.addCliArgument("install");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier = newVerifier(v2.getAbsolutePath());
verifier.addCliArgument("package");
verifier.execute();
verifier.verifyErrorFreeLog();
}
}
| MavenITmng3740SelfReferentialReactorProjectsTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/createTable/OracleCreateTableTest70.java | {
"start": 875,
"end": 2922
} | class ____ extends OracleTest {
public void test_types() throws Exception {
String sql = //
" create table month_part (c1 number,c3 date)\n" +
"partition by range(c3)\n" +
"interval(numtoyminterval (1,'month'))\n" +
"(partition part1 values less than (to_date('2010-01-01','YYYY-MM-DD')),\n" +
"partition part2 values less than (to_date('2010-02-01','YYYY-MM-DD'))\n" +
") ";
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE);
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
//
assertEquals("CREATE TABLE month_part (\n" +
"\tc1 number,\n" +
"\tc3 date\n" +
")\n" +
"PARTITION BY RANGE (c3) INTERVAL (numtoyminterval(1, 'month')) (\n" +
"\tPARTITION part1 VALUES LESS THAN (to_date('2010-01-01', 'YYYY-MM-DD')),\n" +
"\tPARTITION part2 VALUES LESS THAN (to_date('2010-02-01', 'YYYY-MM-DD'))\n" +
")",
SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE));
//
// SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ORACLE);
// stmt.accept(visitor);
//
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("relationships : " + visitor.getRelationships());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
//
// assertEquals(1, visitor.getTables().size());
//
// assertEquals(3, visitor.getColumns().size());
//
// assertTrue(visitor.getColumns().contains(new TableStat.Column("JWGZPT.A", "XM")));
}
}
| OracleCreateTableTest70 |
java | micronaut-projects__micronaut-core | http/src/main/java/io/micronaut/http/annotation/Head.java | {
"start": 1218,
"end": 2021
} | interface ____ {
/**
* @return The URI of the HEAD route
*/
@AliasFor(annotation = HttpMethodMapping.class, member = "value")
@AliasFor(annotation = UriMapping.class, member = "value")
String value() default UriMapping.DEFAULT_URI;
/**
* @return The URI of the HEAD route
*/
@AliasFor(annotation = HttpMethodMapping.class, member = "value")
@AliasFor(annotation = UriMapping.class, member = "value")
String uri() default UriMapping.DEFAULT_URI;
/**
* Only to be used in the context of a server.
*
* @return The URIs of the HEAD route
*/
@AliasFor(annotation = HttpMethodMapping.class, member = "uris")
@AliasFor(annotation = UriMapping.class, member = "uris")
String[] uris() default {UriMapping.DEFAULT_URI};
}
| Head |
java | apache__flink | flink-metrics/flink-metrics-core/src/main/java/org/apache/flink/metrics/CharacterFilter.java | {
"start": 1078,
"end": 1477
} | interface ____ {
CharacterFilter NO_OP_FILTER = input -> input;
/**
* Filter the given string and generate a resulting string from it.
*
* <p>For example, one implementation could filter out invalid characters from the input string.
*
* @param input Input string
* @return Filtered result string
*/
String filterCharacters(String input);
}
| CharacterFilter |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/CamelContext.java | {
"start": 49625,
"end": 49788
} | class ____ to be used for loading/lookup of classes.
*
* @return the resolver
*/
ClassResolver getClassResolver();
/**
* Sets the | resolver |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetJavaTypeContributionTests.java | {
"start": 1535,
"end": 2177
} | class ____ {
@Id
private Integer id;
private BitSet bitSet;
//Constructors, getters, and setters are omitted for brevity
//end::basic-bitset-example-java-type-contrib[]
public Product() {
}
public Product(Number id, BitSet bitSet) {
this.id = id.intValue();
this.bitSet = bitSet;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public BitSet getBitSet() {
return bitSet;
}
public void setBitSet(BitSet bitSet) {
this.bitSet = bitSet;
}
//tag::basic-bitset-example-java-type-contrib[]
}
//end::basic-bitset-example-java-type-contrib[]
}
| Product |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/buildextension/injectionPoints/RepeatingQualifiersInjectionPointTransformerTest.java | {
"start": 1783,
"end": 1987
} | interface ____ {
Location[] value();
}
@Qualifier
@Inherited
@Target({ TYPE, METHOD, FIELD, PARAMETER })
@Retention(RUNTIME)
@Repeatable(Locations.class)
public @ | Locations |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/core/security/transport/netty4/SecurityNetty4Transport.java | {
"start": 11530,
"end": 12650
} | class ____ extends ServerChannelInitializer {
private final SslProfile profile;
public SslChannelInitializer(String name, SslProfile profile) {
super(name);
this.profile = profile;
}
@Override
protected void initChannel(Channel ch) throws Exception {
SSLEngine serverEngine = profile.engine(null, -1);
serverEngine.setUseClientMode(false);
final SslHandler sslHandler = new SslHandler(serverEngine);
sslHandler.setHandshakeTimeoutMillis(profile.configuration().handshakeTimeoutMillis());
ch.pipeline().addFirst("sslhandler", sslHandler);
super.initChannel(ch);
assert ch.pipeline().first() == sslHandler : "SSL handler must be first handler in pipeline";
}
}
protected ServerChannelInitializer getSslChannelInitializer(final String name, final SslProfile profile) {
return new SslChannelInitializer(name, profile);
}
@Override
public boolean isSecure() {
return this.transportSslEnabled;
}
private | SslChannelInitializer |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/grant/MySqlGrantTest_28.java | {
"start": 969,
"end": 2378
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "GRANT REPLICATION SLAVE ON mydb.* TO 'someuser'@'somehost';";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
// print(statementList);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
String output = SQLUtils.toMySqlString(stmt);
assertEquals("GRANT REPLICATION SLAVE ON mydb.* TO 'someuser'@'somehost';", //
output);
//
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(0, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("City")));
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("t2")));
// assertTrue(visitor.getColumns().contains(new Column("t2", "id")));
}
}
| MySqlGrantTest_28 |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/tool/schema/spi/SourceDescriptor.java | {
"start": 715,
"end": 1333
} | interface ____ {
/**
* The indicated source type for this target type.
*
* @return The source type
*/
SourceType getSourceType();
/**
* If {@link #getSourceType()} indicates scripts are involved, returns
* a representation of the script file to read. Otherwise, returns {@code null}.
* <p>
* While it is ultimately up to the actual tooling provider, it is generally an error
* for {@link #getSourceType()} to indicate that scripts are involved and for this
* method to return {@code null}.
*
* @return The script file to read.
*/
ScriptSourceInput getScriptSourceInput();
}
| SourceDescriptor |
java | apache__camel | components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxProducer.java | {
"start": 1071,
"end": 1289
} | class ____ extends AbstractApiProducer<BoxApiName, BoxConfiguration> {
public BoxProducer(BoxEndpoint endpoint) {
super(endpoint, BoxPropertiesHelper.getHelper(endpoint.getCamelContext()));
}
}
| BoxProducer |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/hive/HiveCreateTableTest_14_skew.java | {
"start": 917,
"end": 2712
} | class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = //
"CREATE TABLE list_bucket_multiple (col1 STRING, col2 int, col3 STRING)\n" +
" SKEWED BY (col1, col2) ON (('s1',1), ('s3',3), ('s13',13), ('s78',78))";
List<SQLStatement> statementList = SQLUtils.toStatementList(sql, JdbcConstants.HIVE);
SQLStatement stmt = statementList.get(0);
System.out.println(stmt.toString());
assertEquals(1, statementList.size());
SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.HIVE);
stmt.accept(visitor);
{
String text = SQLUtils.toSQLString(stmt, JdbcConstants.HIVE);
assertEquals("CREATE TABLE list_bucket_multiple (\n" +
"\tcol1 STRING,\n" +
"\tcol2 int,\n" +
"\tcol3 STRING\n" +
")\n" +
"SKEWED BY (col1,col2) ON (('s1', 1),('s3', 3),('s13', 13),('s78', 78))", text);
}
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(3, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
assertEquals(0, visitor.getRelationships().size());
assertEquals(0, visitor.getOrderByColumns().size());
assertTrue(visitor.containsTable("list_bucket_multiple"));
}
}
| HiveCreateTableTest_14_skew |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/archive/internal/StandardArchiveDescriptorFactory.java | {
"start": 678,
"end": 4229
} | class ____ implements ArchiveDescriptorFactory, JarFileEntryUrlAdjuster {
/**
* Singleton access
*/
public static final StandardArchiveDescriptorFactory INSTANCE = new StandardArchiveDescriptorFactory();
@Override
public ArchiveDescriptor buildArchiveDescriptor(URL url) {
return buildArchiveDescriptor( url, "" );
}
@Override
public ArchiveDescriptor buildArchiveDescriptor(URL url, String entry) {
final String protocol = url.getProtocol();
if ( "jar".equals( protocol ) ) {
return new JarProtocolArchiveDescriptor( this, url, entry );
}
else if ( StringHelper.isEmpty( protocol )
|| "file".equals( protocol )
|| "vfszip".equals( protocol )
|| "vfsfile".equals( protocol ) ) {
final File file = new File( extractLocalFilePath( url ) );
if ( file.isDirectory() ) {
return new ExplodedArchiveDescriptor( this, url, entry );
}
else {
return new JarFileBasedArchiveDescriptor( this, url, entry );
}
}
else {
//let's assume the url can return the jar as a zip stream
return new JarInputStreamBasedArchiveDescriptor( this, url, entry );
}
}
protected String extractLocalFilePath(URL url) {
final String filePart = url.getFile();
if ( filePart != null && filePart.indexOf( ' ' ) != -1 ) {
//unescaped (from the container), keep as is
return filePart;
}
else {
try {
return url.toURI().getSchemeSpecificPart();
}
catch (URISyntaxException e) {
throw new IllegalArgumentException(
"Unable to visit JAR " + url + ". Cause: " + e.getMessage(), e
);
}
}
}
@Override
public URL getJarURLFromURLEntry(URL url, String entry) throws IllegalArgumentException {
return ArchiveHelper.getJarURLFromURLEntry( url, entry );
}
@Override
public URL adjustJarFileEntryUrl(URL url, URL rootUrl) {
final String protocol = url.getProtocol();
final boolean check = StringHelper.isEmpty( protocol )
|| "file".equals( protocol )
|| "vfszip".equals( protocol )
|| "vfsfile".equals( protocol );
if ( !check ) {
return url;
}
final String filePart = extractLocalFilePath( url );
if ( filePart.startsWith( "/" ) || new File(url.getFile()).isAbsolute() ) {
// the URL is already an absolute form
return url;
}
else {
// see if the URL exists as a File (used for tests)
final File urlAsFile = new File( url.getFile() );
if ( urlAsFile.exists() && urlAsFile.isFile() ) {
return url;
}
// prefer to resolve the relative URL relative to the root PU URL per
// JPA 2.0 clarification.
final File rootUrlFile = new File( extractLocalFilePath( rootUrl ) );
try {
if ( rootUrlFile.isDirectory() ) {
// The PU root is a directory (exploded). Here we can just build
// the relative File reference and use the Filesystem API to convert
// to URI and then a URL
final File combined = new File( rootUrlFile, filePart );
// make sure it exists..
if ( combined.exists() ) {
return combined.toURI().toURL();
}
}
else {
// The PU root is an archive. Here we have to build a JAR URL to properly
// handle the nested entry reference (the !/ part).
return new URL(
"jar:" + protocol + "://" + rootUrlFile.getAbsolutePath() + "!/" + filePart
);
}
}
catch (MalformedURLException e) {
// allow to pass through to return the original URL
BOOT_LOGGER.unableToAdjustRelativeJarFileUrl(
filePart,
rootUrlFile.getAbsolutePath(),
e
);
}
return url;
}
}
}
| StandardArchiveDescriptorFactory |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/MisleadingEscapedSpaceTest.java | {
"start": 2980,
"end": 3332
} | class ____ {
private static final String FOO =
\"""
foo \\s\\s\\s\\s
\""";
}
""")
.doTest();
}
@Test
public void withinCommentInBrokenUpString_noFinding() {
testHelper
.addSourceLines(
"Test.class",
"""
| Test |
java | grpc__grpc-java | api/src/main/java/io/grpc/ClientStreamTracer.java | {
"start": 3589,
"end": 4345
} | class ____ {
/**
* Creates a {@link ClientStreamTracer} for a new client stream. This is called inside the
* transport when it's creating the stream.
*
* @param info information about the stream
* @param headers the mutable headers of the stream. It can be safely mutated within this
* method. Changes made to it will be sent by the stream. It should not be saved
* because it is not safe for read or write after the method returns.
*
* @since 1.20.0
*/
public ClientStreamTracer newClientStreamTracer(StreamInfo info, Metadata headers) {
throw new UnsupportedOperationException("Not implemented");
}
}
/**
* Information about a stream.
*
* <p>Note this | Factory |
java | google__dagger | javatests/dagger/internal/codegen/DependencyCycleValidationTest.java | {
"start": 28091,
"end": 29347
} | interface ____ {",
" void inject(A a);",
"}");
CompilerTests.daggerCompiler(a, b, component)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
String.join(
"\n",
"Found a dependency cycle:",
" test.B is injected at",
" [CycleComponent] test.A.b",
" test.A is injected at",
" [CycleComponent] test.B.a",
" test.B is injected at",
" [CycleComponent] test.A.b",
" ...",
"",
"The cycle is requested via:",
" test.B is injected at",
" [CycleComponent] test.A.b",
" test.A is injected at",
" [CycleComponent] CycleComponent.inject(test.A)"))
.onSource(component)
.onLineContaining(" | CycleComponent |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/analysis/ReloadableCustomAnalyzer.java | {
"start": 979,
"end": 6730
} | class ____ extends Analyzer implements AnalyzerComponentsProvider {
private volatile AnalyzerComponents components;
private CloseableThreadLocal<AnalyzerComponents> storedComponents = new CloseableThreadLocal<>();
// external resources that this analyzer is based on
private final Set<String> resources;
private final int positionIncrementGap;
private final int offsetGap;
/**
* An alternative {@link ReuseStrategy} that allows swapping the stored analyzer components when they change.
* This is used to change e.g. token filters in search time analyzers.
*/
private static final ReuseStrategy UPDATE_STRATEGY = new ReuseStrategy() {
@Override
public TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName) {
ReloadableCustomAnalyzer custom = (ReloadableCustomAnalyzer) analyzer;
AnalyzerComponents components = custom.getComponents();
AnalyzerComponents storedComponents = custom.getStoredComponents();
if (storedComponents == null || components != storedComponents) {
custom.setStoredComponents(components);
return null;
}
TokenStreamComponents tokenStream = (TokenStreamComponents) getStoredValue(analyzer);
assert tokenStream != null;
return tokenStream;
}
@Override
public void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents tokenStream) {
setStoredValue(analyzer, tokenStream);
}
};
ReloadableCustomAnalyzer(AnalyzerComponents components, int positionIncrementGap, int offsetGap) {
super(UPDATE_STRATEGY);
if (components.analysisMode().equals(AnalysisMode.SEARCH_TIME) == false) {
throw new IllegalArgumentException(
"ReloadableCustomAnalyzer must only be initialized with analysis components in AnalysisMode.SEARCH_TIME mode"
);
}
this.components = components;
this.positionIncrementGap = positionIncrementGap;
this.offsetGap = offsetGap;
Set<String> resourcesTemp = new HashSet<>();
for (TokenFilterFactory tokenFilter : components.getTokenFilters()) {
if (tokenFilter.getResourceName() != null) {
resourcesTemp.add(tokenFilter.getResourceName());
}
}
resources = resourcesTemp.isEmpty() ? null : Set.copyOf(resourcesTemp);
}
@Override
public AnalyzerComponents getComponents() {
return this.components;
}
public boolean usesResource(String resourceName) {
if (resourceName == null) {
return true;
}
if (resources == null) {
return false;
}
return resources.contains(resourceName);
}
@Override
public int getPositionIncrementGap(String fieldName) {
return this.positionIncrementGap;
}
@Override
public int getOffsetGap(String field) {
if (this.offsetGap < 0) {
return super.getOffsetGap(field);
}
return this.offsetGap;
}
public AnalysisMode getAnalysisMode() {
return this.components.analysisMode();
}
@Override
protected Reader initReaderForNormalization(String fieldName, Reader reader) {
final AnalyzerComponents components = getComponents();
for (CharFilterFactory charFilter : components.getCharFilters()) {
reader = charFilter.normalize(reader);
}
return reader;
}
@Override
protected TokenStream normalize(String fieldName, TokenStream in) {
final AnalyzerComponents components = getComponents();
TokenStream result = in;
for (TokenFilterFactory filter : components.getTokenFilters()) {
result = filter.normalize(result);
}
return result;
}
public synchronized void reload(
String name,
Settings settings,
final Map<String, TokenizerFactory> tokenizers,
final Map<String, CharFilterFactory> charFilters,
final Map<String, TokenFilterFactory> tokenFilters
) {
AnalyzerComponents components = AnalyzerComponents.createComponents(
IndexCreationContext.RELOAD_ANALYZERS,
name,
settings,
tokenizers,
charFilters,
tokenFilters
);
this.components = components;
}
@Override
public void close() {
super.close();
storedComponents.close();
}
private void setStoredComponents(AnalyzerComponents components) {
storedComponents.set(components);
}
private AnalyzerComponents getStoredComponents() {
return storedComponents.get();
}
@Override
protected TokenStreamComponents createComponents(String fieldName) {
final AnalyzerComponents components = getStoredComponents();
Tokenizer tokenizer = components.getTokenizerFactory().create();
TokenStream tokenStream = tokenizer;
for (TokenFilterFactory tokenFilter : components.getTokenFilters()) {
tokenStream = tokenFilter.create(tokenStream);
}
return new TokenStreamComponents(tokenizer, tokenStream);
}
@Override
protected Reader initReader(String fieldName, Reader reader) {
final AnalyzerComponents components = getStoredComponents();
if (CollectionUtils.isEmpty(components.getCharFilters()) == false) {
for (CharFilterFactory charFilter : components.getCharFilters()) {
reader = charFilter.create(reader);
}
}
return reader;
}
}
| ReloadableCustomAnalyzer |
java | quarkusio__quarkus | extensions/micrometer/deployment/src/test/java/io/quarkus/micrometer/deployment/pathparams/HttpPathParamLimitWithJaxRs400Test.java | {
"start": 549,
"end": 2887
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withConfigurationResource("test-logging.properties")
.overrideConfigKey("quarkus.micrometer.binder-enabled-default", "false")
.overrideConfigKey("quarkus.micrometer.binder.http-client.enabled", "true")
.overrideConfigKey("quarkus.micrometer.binder.http-server.enabled", "true")
.overrideConfigKey("quarkus.micrometer.binder.vertx.enabled", "true")
.overrideConfigKey("quarkus.redis.devservices.enabled", "false")
.withApplicationRoot((jar) -> jar
.addClasses(Util.class,
Resource.class));
@Inject
MeterRegistry registry;
public static final int COUNT = 101;
@Test
void testWithResteasy400() throws InterruptedException {
registry.clear();
// Test a JAX-RS endpoint with GET /jaxrs and GET /jaxrs/{message}
// Verify OK response
for (int i = 0; i < COUNT; i++) {
RestAssured.get("/jaxrs").then().statusCode(200);
RestAssured.get("/jaxrs/foo-" + i).then().statusCode(200);
}
// Verify metrics
Util.waitForMeters(registry.find("http.server.requests").timers(), COUNT);
Assertions.assertEquals(COUNT, registry.find("http.server.requests")
.tag("uri", "/jaxrs").timers().iterator().next().count());
Assertions.assertEquals(COUNT, registry.find("http.server.requests")
.tag("uri", "/jaxrs/{message}").timers().iterator().next().count());
// Verify method producing a 400
for (int i = 0; i < COUNT; i++) {
RestAssured.get("/bad").then().statusCode(400);
RestAssured.get("/bad/foo-" + i).then().statusCode(400);
}
Util.waitForMeters(registry.find("http.server.requests").timers(), COUNT * 2);
Assertions.assertEquals(COUNT, registry.find("http.server.requests")
.tag("uri", "/bad").tag("method", "GET").timers().iterator().next().count());
Assertions.assertEquals(4, registry.find("http.server.requests")
.tag("method", "GET").timers().size()); // Pattern recognized
}
@Path("/")
@Singleton
public static | HttpPathParamLimitWithJaxRs400Test |
java | spring-projects__spring-security | config/src/main/java/org/springframework/security/config/web/server/OidcBackChannelLogoutWebFilter.java | {
"start": 2413,
"end": 5571
} | class ____ implements WebFilter {
private final Log logger = LogFactory.getLog(getClass());
private final ServerAuthenticationConverter authenticationConverter;
private final ReactiveAuthenticationManager authenticationManager;
private final ServerLogoutHandler logoutHandler;
private final HttpMessageWriter<OAuth2Error> errorHttpMessageConverter = new EncoderHttpMessageWriter<>(
new OAuth2ErrorEncoder());
/**
* Construct an {@link OidcBackChannelLogoutWebFilter}
* @param authenticationConverter the {@link AuthenticationConverter} for deriving
* Logout Token authentication
* @param authenticationManager the {@link AuthenticationManager} for authenticating
* Logout Tokens
*/
OidcBackChannelLogoutWebFilter(ServerAuthenticationConverter authenticationConverter,
ReactiveAuthenticationManager authenticationManager, ServerLogoutHandler logoutHandler) {
Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
Assert.notNull(logoutHandler, "logoutHandler cannot be null");
this.authenticationConverter = authenticationConverter;
this.authenticationManager = authenticationManager;
this.logoutHandler = logoutHandler;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return this.authenticationConverter.convert(exchange).onErrorResume(AuthenticationException.class, (ex) -> {
this.logger.debug("Failed to process OIDC Back-Channel Logout", ex);
if (ex instanceof AuthenticationServiceException) {
return Mono.error(ex);
}
return handleAuthenticationFailure(exchange, ex).then(Mono.empty());
})
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.flatMap(this.authenticationManager::authenticate)
.onErrorResume(AuthenticationException.class, (ex) -> {
this.logger.debug("Failed to process OIDC Back-Channel Logout", ex);
if (ex instanceof AuthenticationServiceException) {
return Mono.error(ex);
}
return handleAuthenticationFailure(exchange, ex).then(Mono.empty());
})
.flatMap((authentication) -> {
WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain);
return this.logoutHandler.logout(webFilterExchange, authentication);
});
}
private Mono<Void> handleAuthenticationFailure(ServerWebExchange exchange, Exception ex) {
this.logger.debug("Failed to process OIDC Back-Channel Logout", ex);
exchange.getResponse().setRawStatusCode(HttpStatus.BAD_REQUEST.value());
return this.errorHttpMessageConverter.write(Mono.just(oauth2Error(ex)), ResolvableType.forClass(Object.class),
ResolvableType.forClass(Object.class), MediaType.APPLICATION_JSON, exchange.getRequest(),
exchange.getResponse(), Collections.emptyMap());
}
private OAuth2Error oauth2Error(Exception ex) {
if (ex instanceof OAuth2AuthenticationException oauth2) {
return oauth2.getError();
}
return new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, ex.getMessage(),
"https://openid.net/specs/openid-connect-backchannel-1_0.html#Validation");
}
}
| OidcBackChannelLogoutWebFilter |
java | spring-projects__spring-boot | module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/docker/compose/SqlServerEnvironment.java | {
"start": 908,
"end": 1507
} | class ____ {
private final String username = "SA";
private final String password;
SqlServerEnvironment(Map<String, @Nullable String> env) {
this.password = extractPassword(env);
}
private String extractPassword(Map<String, @Nullable String> env) {
String password = env.get("MSSQL_SA_PASSWORD");
password = (password != null) ? password : env.get("SA_PASSWORD");
Assert.state(StringUtils.hasLength(password), "No MSSQL password found");
return password;
}
String getUsername() {
return this.username;
}
String getPassword() {
return this.password;
}
}
| SqlServerEnvironment |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/common/notifications/AbstractAuditor.java | {
"start": 1600,
"end": 9289
} | class ____<T extends AbstractAuditMessage> {
// The special ID that means the message applies to all jobs/resources.
public static final String All_RESOURCES_ID = "";
private static final Logger logger = LogManager.getLogger(AbstractAuditor.class);
static final int MAX_BUFFER_SIZE = 1000;
protected static final TimeValue MASTER_TIMEOUT = TimeValue.timeValueMinutes(1);
private final OriginSettingClient client;
private final String nodeName;
private final String auditIndexWriteAlias;
private final AbstractAuditMessageFactory<T> messageFactory;
private final ClusterService clusterService;
private final IndexNameExpressionResolver indexNameExpressionResolver;
private final AtomicBoolean indexAndAliasCreated;
private Queue<ToXContent> backlog;
private final AtomicBoolean indexAndAliasCreationInProgress;
private final ExecutorService executorService;
protected AbstractAuditor(
OriginSettingClient client,
String auditIndexWriteAlias,
String nodeName,
AbstractAuditMessageFactory<T> messageFactory,
ClusterService clusterService,
IndexNameExpressionResolver indexNameExpressionResolver,
ExecutorService executorService
) {
this.client = Objects.requireNonNull(client);
this.auditIndexWriteAlias = Objects.requireNonNull(auditIndexWriteAlias);
this.messageFactory = Objects.requireNonNull(messageFactory);
this.nodeName = Objects.requireNonNull(nodeName);
this.clusterService = Objects.requireNonNull(clusterService);
this.indexNameExpressionResolver = Objects.requireNonNull(indexNameExpressionResolver);
this.backlog = new ConcurrentLinkedQueue<>();
this.indexAndAliasCreated = new AtomicBoolean();
this.indexAndAliasCreationInProgress = new AtomicBoolean();
this.executorService = executorService;
}
public void audit(Level level, String resourceId, String message) {
indexDoc(messageFactory.newMessage(resourceId, message, level, new Date(), nodeName));
}
public void info(String resourceId, String message) {
audit(Level.INFO, resourceId, message);
}
public void warning(String resourceId, String message) {
audit(Level.WARNING, resourceId, message);
}
public void error(String resourceId, String message) {
audit(Level.ERROR, resourceId, message);
}
/**
* Calling reset will cause the auditor to check the required
* index and alias exist and recreate if necessary
*/
public void reset() {
indexAndAliasCreated.set(false);
// create a new backlog in case documents need
// to be temporarily stored when the new index/alias is created
backlog = new ConcurrentLinkedQueue<>();
}
private static void onIndexResponse(DocWriteResponse response) {
logger.trace("Successfully wrote audit message");
}
private static void onIndexFailure(Exception exception) {
logger.debug("Failed to write audit message", exception);
}
protected void indexDoc(ToXContent toXContent) {
if (indexAndAliasCreated.get()) {
writeDoc(toXContent);
return;
}
// install template & create index with alias
var createListener = ActionListener.<Boolean>wrap(success -> {
indexAndAliasCreationInProgress.set(false);
synchronized (this) {
// synchronized so nothing can be added to backlog while writing it
indexAndAliasCreated.set(true);
writeBacklog();
}
}, e -> { indexAndAliasCreationInProgress.set(false); });
synchronized (this) {
if (indexAndAliasCreated.get() == false) {
// synchronized so that hasLatestTemplate does not change value
// between the read and adding to the backlog
if (backlog != null) {
if (backlog.size() >= MAX_BUFFER_SIZE) {
backlog.remove();
}
backlog.add(toXContent);
} else {
logger.error("Audit message cannot be added to the backlog");
}
// stop multiple invocations
if (indexAndAliasCreationInProgress.compareAndSet(false, true)) {
installTemplateAndCreateIndex(createListener);
}
}
}
}
private void writeDoc(ToXContent toXContent) {
client.index(indexRequest(toXContent), ActionListener.wrap(AbstractAuditor::onIndexResponse, e -> {
if (e instanceof IndexNotFoundException) {
executorService.execute(() -> {
reset();
indexDoc(toXContent);
});
} else {
onIndexFailure(e);
}
}));
}
private IndexRequest indexRequest(ToXContent toXContent) {
IndexRequest indexRequest = new IndexRequest(auditIndexWriteAlias);
indexRequest.source(toXContentBuilder(toXContent));
indexRequest.timeout(TimeValue.timeValueSeconds(5));
indexRequest.setRequireAlias(true);
return indexRequest;
}
private static XContentBuilder toXContentBuilder(ToXContent toXContent) {
try (XContentBuilder jsonBuilder = jsonBuilder()) {
return toXContent.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
protected void clearBacklog() {
backlog = null;
}
protected void writeBacklog() {
if (backlog == null) {
logger.debug("Message back log has already been written");
return;
}
BulkRequest bulkRequest = new BulkRequest();
ToXContent doc = backlog.poll();
while (doc != null) {
bulkRequest.add(indexRequest(doc));
doc = backlog.poll();
}
client.bulk(bulkRequest, ActionListener.wrap(bulkItemResponses -> {
if (bulkItemResponses.hasFailures()) {
logger.warn("Failures bulk indexing the message back log: {}", bulkItemResponses.buildFailureMessage());
} else {
logger.trace("Successfully wrote audit message backlog");
}
backlog = null;
}, AbstractAuditor::onIndexFailure));
}
// for testing
int backLogSize() {
return backlog.size();
}
private void installTemplateAndCreateIndex(ActionListener<Boolean> listener) {
SubscribableListener.<Boolean>newForked(l -> {
MlIndexAndAlias.installIndexTemplateIfRequired(clusterService.state(), client, templateVersion(), putTemplateRequest(), l);
}).<Boolean>andThen((l, success) -> {
var indexDetails = indexDetails();
MlIndexAndAlias.createIndexAndAliasIfNecessary(
client,
clusterService.state(),
indexNameExpressionResolver,
indexDetails.indexPrefix(),
indexDetails.indexVersion(),
auditIndexWriteAlias,
MASTER_TIMEOUT,
ActiveShardCount.DEFAULT,
l
);
}).addListener(listener);
}
protected abstract TransportPutComposableIndexTemplateAction.Request putTemplateRequest();
protected abstract int templateVersion();
protected abstract IndexDetails indexDetails();
public record IndexDetails(String indexPrefix, String indexVersion) {};
}
| AbstractAuditor |
java | apache__camel | core/camel-core-reifier/src/main/java/org/apache/camel/reifier/language/SimpleExpressionReifier.java | {
"start": 1011,
"end": 1701
} | class ____ extends TypedExpressionReifier<SimpleExpression> {
public SimpleExpressionReifier(CamelContext camelContext, ExpressionDefinition definition) {
super(camelContext, definition);
}
@Override
public boolean isResolveOptionalExternalScriptEnabled() {
// simple language will handle to resolve external scripts as they can be dynamic using simple language itself
return false;
}
@Override
protected Object[] createProperties() {
Object[] properties = new Object[2];
properties[0] = asResultType();
properties[1] = parseBoolean(definition.getTrim());
return properties;
}
}
| SimpleExpressionReifier |
java | spring-projects__spring-framework | spring-aop/src/test/java/org/springframework/aop/support/ControlFlowPointcutTests.java | {
"start": 1265,
"end": 8576
} | class ____ {
@Test
void matchesExactMethodName() {
MyComponent component = new MyComponent();
TestBean target = new TestBean("Jane", 27);
ControlFlowPointcut cflow = pointcut("getAge");
NopInterceptor nop = new NopInterceptor();
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvisor(new DefaultPointcutAdvisor(cflow, nop));
ITestBean proxy = (ITestBean) pf.getProxy();
// Will not be advised: not under MyComponent
assertThat(proxy.getAge()).isEqualTo(target.getAge());
assertThat(cflow.getEvaluations()).isEqualTo(1);
assertThat(nop.getCount()).isEqualTo(0);
// Will be advised due to "getAge" pattern: the proxy is invoked under MyComponent#getAge
assertThat(component.getAge(proxy)).isEqualTo(target.getAge());
assertThat(cflow.getEvaluations()).isEqualTo(2);
assertThat(nop.getCount()).isEqualTo(1);
// Will not be advised: the proxy is invoked under MyComponent, but there is no match for "nomatch"
assertThat(component.nomatch(proxy)).isEqualTo(target.getAge());
assertThat(cflow.getEvaluations()).isEqualTo(3);
assertThat(nop.getCount()).isEqualTo(1);
}
@Test
void matchesMethodNamePatterns() {
ControlFlowPointcut cflow = pointcut("set", "getAge");
assertMatchesSetAndGetAge(cflow);
cflow = pointcut("foo", "get*", "bar", "*se*", "baz");
assertMatchesSetAndGetAge(cflow);
}
@Test
void regExControlFlowPointcut() {
ControlFlowPointcut cflow = new RegExControlFlowPointcut(MyComponent.class, "(set.*?|getAge)");
assertMatchesSetAndGetAge(cflow);
cflow = new RegExControlFlowPointcut(MyComponent.class, "set", "^getAge$");
assertMatchesSetAndGetAge(cflow);
}
@Test
void controlFlowPointcutIsExtensible() {
CustomControlFlowPointcut cflow = new CustomControlFlowPointcut(MyComponent.class, "set*", "getAge", "set*", "set*");
assertMatchesSetAndGetAge(cflow, 2);
assertThat(cflow.trackedClass()).isEqualTo(MyComponent.class);
assertThat(cflow.trackedMethodNamePatterns()).containsExactly("set*", "getAge");
}
/**
* Check that we can use a cflow pointcut in conjunction with
* a static pointcut: for example, all setter methods that are invoked under
* a particular class. This greatly reduces the number of calls
* to the cflow pointcut, meaning that it's not so prohibitively
* expensive.
*/
@Test
void controlFlowPointcutCanBeCombinedWithStaticPointcut() {
MyComponent component = new MyComponent();
TestBean target = new TestBean("Jane", 27);
ControlFlowPointcut cflow = pointcut();
Pointcut settersUnderMyComponent = Pointcuts.intersection(Pointcuts.SETTERS, cflow);
NopInterceptor nop = new NopInterceptor();
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvisor(new DefaultPointcutAdvisor(settersUnderMyComponent, nop));
ITestBean proxy = (ITestBean) pf.getProxy();
// Will not be advised: not under MyComponent
target.setAge(16);
assertThat(cflow.getEvaluations()).isEqualTo(0);
assertThat(nop.getCount()).isEqualTo(0);
// Will not be advised: under MyComponent but not a setter
assertThat(component.getAge(proxy)).isEqualTo(16);
assertThat(cflow.getEvaluations()).isEqualTo(0);
assertThat(nop.getCount()).isEqualTo(0);
// Will be advised due to Pointcuts.SETTERS: the proxy is invoked under MyComponent#set
component.set(proxy);
assertThat(proxy.getAge()).isEqualTo(5);
assertThat(nop.getCount()).isEqualTo(1);
// We saved most evaluations
assertThat(cflow.getEvaluations()).isEqualTo(1);
}
@Test
void equalsAndHashCode() {
assertThat(pointcut()).isEqualTo(pointcut());
assertThat(pointcut()).hasSameHashCodeAs(pointcut());
assertThat(pointcut("getAge")).isEqualTo(pointcut("getAge"));
assertThat(pointcut("getAge")).hasSameHashCodeAs(pointcut("getAge"));
assertThat(pointcut("getAge")).isNotEqualTo(pointcut());
assertThat(pointcut("getAge")).doesNotHaveSameHashCodeAs(pointcut());
assertThat(pointcut("get*", "set*")).isEqualTo(pointcut("get*", "set*"));
assertThat(pointcut("get*", "set*")).isEqualTo(pointcut("get*", "set*", "set*", "get*"));
assertThat(pointcut("get*", "set*")).hasSameHashCodeAs(pointcut("get*", "get*", "set*"));
assertThat(pointcut("get*", "set*")).isNotEqualTo(pointcut("set*", "get*"));
assertThat(pointcut("get*", "set*")).doesNotHaveSameHashCodeAs(pointcut("set*", "get*"));
assertThat(pointcut("get*", "set*")).isEqualTo(pointcut(List.of("get*", "set*")));
assertThat(pointcut("get*", "set*")).isEqualTo(pointcut(List.of("get*", "set*", "set*", "get*")));
assertThat(pointcut("get*", "set*")).hasSameHashCodeAs(pointcut(List.of("get*", "get*", "set*")));
}
@Test
void testToString() {
String pointcutType = ControlFlowPointcut.class.getName();
String componentType = MyComponent.class.getName();
assertThat(pointcut()).asString()
.startsWith(pointcutType)
.contains(componentType)
.endsWith("[]");
assertThat(pointcut("getAge")).asString()
.startsWith(pointcutType)
.contains(componentType)
.endsWith("[getAge]");
assertThat(pointcut("get*", "set*", "get*")).asString()
.startsWith(pointcutType)
.contains(componentType)
.endsWith("[get*, set*]");
}
private static ControlFlowPointcut pointcut() {
return new ControlFlowPointcut(MyComponent.class);
}
private static ControlFlowPointcut pointcut(String methodNamePattern) {
return new ControlFlowPointcut(MyComponent.class, methodNamePattern);
}
private static ControlFlowPointcut pointcut(String... methodNamePatterns) {
return new ControlFlowPointcut(MyComponent.class, methodNamePatterns);
}
private static ControlFlowPointcut pointcut(List<String> methodNamePatterns) {
return new ControlFlowPointcut(MyComponent.class, methodNamePatterns);
}
private static void assertMatchesSetAndGetAge(ControlFlowPointcut cflow) {
assertMatchesSetAndGetAge(cflow, 1);
}
private static void assertMatchesSetAndGetAge(ControlFlowPointcut cflow, int evaluationFactor) {
MyComponent component = new MyComponent();
TestBean target = new TestBean("Jane", 27);
NopInterceptor nop = new NopInterceptor();
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvisor(new DefaultPointcutAdvisor(cflow, nop));
ITestBean proxy = (ITestBean) pf.getProxy();
// Will not be advised: not under MyComponent
assertThat(proxy.getAge()).isEqualTo(target.getAge());
assertThat(cflow.getEvaluations()).isEqualTo(evaluationFactor);
assertThat(nop.getCount()).isEqualTo(0);
// Will be advised: the proxy is invoked under MyComponent#getAge
assertThat(component.getAge(proxy)).isEqualTo(target.getAge());
assertThat(cflow.getEvaluations()).isEqualTo(2 * evaluationFactor);
assertThat(nop.getCount()).isEqualTo(1);
// Will be advised: the proxy is invoked under MyComponent#set
component.set(proxy);
assertThat(cflow.getEvaluations()).isEqualTo(3 * evaluationFactor);
assertThat(proxy.getAge()).isEqualTo(5);
assertThat(cflow.getEvaluations()).isEqualTo(4 * evaluationFactor);
assertThat(nop.getCount()).isEqualTo(2);
// Will not be advised: the proxy is invoked under MyComponent, but there is no match for "nomatch"
assertThat(component.nomatch(proxy)).isEqualTo(target.getAge());
assertThat(nop.getCount()).isEqualTo(2);
assertThat(cflow.getEvaluations()).isEqualTo(5 * evaluationFactor);
}
private static | ControlFlowPointcutTests |
java | apache__kafka | streams/src/test/java/org/apache/kafka/streams/kstream/internals/KStreamKStreamJoinTest.java | {
"start": 4539,
"end": 19255
} | class ____ {
private final String topic1 = "topic1";
private final String topic2 = "topic2";
private final Consumed<Integer, String> consumed = Consumed.with(Serdes.Integer(), Serdes.String());
private final Properties props = StreamsTestUtils.getStreamsConfig(Serdes.String(), Serdes.String());
private final JoinWindows joinWindows = JoinWindows.ofTimeDifferenceAndGrace(ofMillis(50), Duration.ofMillis(50));
private final StreamJoined<String, Integer, Integer> streamJoined = StreamJoined.with(Serdes.String(), Serdes.Integer(), Serdes.Integer());
private final String errorMessagePrefix = "Window settings mismatch. WindowBytesStoreSupplier settings";
@Test
public void shouldLogAndMeterOnSkippedRecordsWithNullValueWithBuiltInMetricsVersionLatest() {
final StreamsBuilder builder = new StreamsBuilder();
final KStream<String, Integer> left = builder.stream("left", Consumed.with(Serdes.String(), Serdes.Integer()));
final KStream<String, Integer> right = builder.stream("right", Consumed.with(Serdes.String(), Serdes.Integer()));
left.join(
right,
Integer::sum,
JoinWindows.ofTimeDifferenceWithNoGrace(ofMillis(100)),
StreamJoined.with(Serdes.String(), Serdes.Integer(), Serdes.Integer())
);
props.setProperty(StreamsConfig.BUILT_IN_METRICS_VERSION_CONFIG, StreamsConfig.METRICS_LATEST);
try (final LogCaptureAppender appender = LogCaptureAppender.createAndRegister(KStreamKStreamJoin.class);
final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) {
final TestInputTopic<String, Integer> inputTopic =
driver.createInputTopic("left", new StringSerializer(), new IntegerSerializer());
inputTopic.pipeInput("A", null);
assertThat(
appender.getMessages(),
hasItem("Skipping record due to null key or value. topic=[left] partition=[0] offset=[0]")
);
}
}
@Test
public void shouldReuseRepartitionTopicWithGeneratedName() {
final StreamsBuilder builder = new StreamsBuilder();
final Properties props = new Properties();
props.put(StreamsConfig.TOPOLOGY_OPTIMIZATION_CONFIG, StreamsConfig.NO_OPTIMIZATION);
final KStream<String, String> stream1 = builder.stream("topic", Consumed.with(Serdes.String(), Serdes.String()));
final KStream<String, String> stream2 = builder.stream("topic2", Consumed.with(Serdes.String(), Serdes.String()));
final KStream<String, String> stream3 = builder.stream("topic3", Consumed.with(Serdes.String(), Serdes.String()));
final KStream<String, String> newStream = stream1.map((k, v) -> new KeyValue<>(v, k));
newStream.join(stream2, (value1, value2) -> value1 + value2, JoinWindows.ofTimeDifferenceWithNoGrace(ofMillis(100))).to("out-one");
newStream.join(stream3, (value1, value2) -> value1 + value2, JoinWindows.ofTimeDifferenceWithNoGrace(ofMillis(100))).to("out-to");
assertEquals(expectedTopologyWithGeneratedRepartitionTopic, builder.build(props).describe().toString());
}
@Test
public void shouldCreateRepartitionTopicsWithUserProvidedName() {
final StreamsBuilder builder = new StreamsBuilder();
final Properties props = new Properties();
props.put(StreamsConfig.TOPOLOGY_OPTIMIZATION_CONFIG, StreamsConfig.NO_OPTIMIZATION);
final KStream<String, String> stream1 = builder.stream("topic", Consumed.with(Serdes.String(), Serdes.String()));
final KStream<String, String> stream2 = builder.stream("topic2", Consumed.with(Serdes.String(), Serdes.String()));
final KStream<String, String> stream3 = builder.stream("topic3", Consumed.with(Serdes.String(), Serdes.String()));
final KStream<String, String> newStream = stream1.map((k, v) -> new KeyValue<>(v, k));
final StreamJoined<String, String, String> streamJoined = StreamJoined.with(Serdes.String(), Serdes.String(), Serdes.String());
newStream.join(stream2, (value1, value2) -> value1 + value2, JoinWindows.ofTimeDifferenceWithNoGrace(ofMillis(100)), streamJoined.withName("first-join")).to("out-one");
newStream.join(stream3, (value1, value2) -> value1 + value2, JoinWindows.ofTimeDifferenceWithNoGrace(ofMillis(100)), streamJoined.withName("second-join")).to("out-two");
final Topology topology = builder.build(props);
System.out.println(topology.describe().toString());
assertEquals(expectedTopologyWithUserNamedRepartitionTopics, topology.describe().toString());
}
@Test
public void shouldDisableLoggingOnStreamJoined() {
final JoinWindows joinWindows = JoinWindows.ofTimeDifferenceAndGrace(ofMillis(100), Duration.ofMillis(50));
final StreamJoined<String, Integer, Integer> streamJoined = StreamJoined
.with(Serdes.String(), Serdes.Integer(), Serdes.Integer())
.withStoreName("store")
.withLoggingDisabled();
final StreamsBuilder builder = new StreamsBuilder();
final KStream<String, Integer> left = builder.stream("left", Consumed.with(Serdes.String(), Serdes.Integer()));
final KStream<String, Integer> right = builder.stream("right", Consumed.with(Serdes.String(), Serdes.Integer()));
left.join(
right,
Integer::sum,
joinWindows,
streamJoined
);
final Topology topology = builder.build();
final InternalTopologyBuilder internalTopologyBuilder = TopologyWrapper.getInternalTopologyBuilder(topology);
assertThat(internalTopologyBuilder.stateStores().get("store-this-join-store").loggingEnabled(), equalTo(false));
assertThat(internalTopologyBuilder.stateStores().get("store-other-join-store").loggingEnabled(), equalTo(false));
}
@Test
public void shouldEnableLoggingWithCustomConfigOnStreamJoined() {
final JoinWindows joinWindows = JoinWindows.ofTimeDifferenceAndGrace(ofMillis(100), Duration.ofMillis(50));
final StreamJoined<String, Integer, Integer> streamJoined = StreamJoined
.with(Serdes.String(), Serdes.Integer(), Serdes.Integer())
.withStoreName("store")
.withLoggingEnabled(Collections.singletonMap("test", "property"));
final StreamsBuilder builder = new StreamsBuilder();
final KStream<String, Integer> left = builder.stream("left", Consumed.with(Serdes.String(), Serdes.Integer()));
final KStream<String, Integer> right = builder.stream("right", Consumed.with(Serdes.String(), Serdes.Integer()));
left.join(
right,
Integer::sum,
joinWindows,
streamJoined
);
final Topology topology = builder.build();
final InternalTopologyBuilder internalTopologyBuilder = TopologyWrapper.getInternalTopologyBuilder(topology);
internalTopologyBuilder.buildSubtopology(0);
assertThat(internalTopologyBuilder.stateStores().get("store-this-join-store").loggingEnabled(), equalTo(true));
assertThat(internalTopologyBuilder.stateStores().get("store-other-join-store").loggingEnabled(), equalTo(true));
assertThat(internalTopologyBuilder.subtopologyToTopicsInfo().get(SUBTOPOLOGY_0).stateChangelogTopics.size(), equalTo(2));
for (final InternalTopicConfig config : internalTopologyBuilder.subtopologyToTopicsInfo().get(SUBTOPOLOGY_0).stateChangelogTopics.values()) {
assertThat(
config.properties(Collections.emptyMap(), 0).get("test"),
equalTo("property")
);
}
}
@Test
public void shouldThrowExceptionThisStoreSupplierRetentionDoNotMatchWindowsSizeAndGrace() {
// Case where retention of thisJoinStore doesn't match JoinWindows
final WindowBytesStoreSupplier thisStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store", 500L, 100L, true);
final WindowBytesStoreSupplier otherStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store-other", 150L, 100L, true);
buildStreamsJoinThatShouldThrow(
streamJoined.withThisStoreSupplier(thisStoreSupplier).withOtherStoreSupplier(otherStoreSupplier),
joinWindows,
errorMessagePrefix
);
}
@Test
public void shouldThrowExceptionThisStoreSupplierWindowSizeDoesNotMatchJoinWindowsWindowSize() {
//Case where window size of thisJoinStore doesn't match JoinWindows
final WindowBytesStoreSupplier thisStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store", 150L, 150L, true);
final WindowBytesStoreSupplier otherStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store-other", 150L, 100L, true);
buildStreamsJoinThatShouldThrow(
streamJoined.withThisStoreSupplier(thisStoreSupplier).withOtherStoreSupplier(otherStoreSupplier),
joinWindows,
errorMessagePrefix
);
}
@Test
public void shouldThrowExceptionWhenThisJoinStoreSetsRetainDuplicatesFalse() {
//Case where thisJoinStore retain duplicates false
final WindowBytesStoreSupplier thisStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store", 150L, 100L, false);
final WindowBytesStoreSupplier otherStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store-other", 150L, 100L, true);
buildStreamsJoinThatShouldThrow(
streamJoined.withThisStoreSupplier(thisStoreSupplier).withOtherStoreSupplier(otherStoreSupplier),
joinWindows,
"The StoreSupplier must set retainDuplicates=true, found retainDuplicates=false"
);
}
@Test
public void shouldThrowExceptionOtherStoreSupplierRetentionDoNotMatchWindowsSizeAndGrace() {
//Case where retention size of otherJoinStore doesn't match JoinWindows
final WindowBytesStoreSupplier thisStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store", 150L, 100L, true);
final WindowBytesStoreSupplier otherStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store-other", 500L, 100L, true);
buildStreamsJoinThatShouldThrow(
streamJoined.withThisStoreSupplier(thisStoreSupplier).withOtherStoreSupplier(otherStoreSupplier),
joinWindows,
errorMessagePrefix
);
}
@Test
public void shouldThrowExceptionOtherStoreSupplierWindowSizeDoesNotMatchJoinWindowsWindowSize() {
//Case where window size of otherJoinStore doesn't match JoinWindows
final WindowBytesStoreSupplier thisStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store", 150L, 100L, true);
final WindowBytesStoreSupplier otherStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store-other", 150L, 150L, true);
buildStreamsJoinThatShouldThrow(
streamJoined.withThisStoreSupplier(thisStoreSupplier).withOtherStoreSupplier(otherStoreSupplier),
joinWindows,
errorMessagePrefix
);
}
@Test
public void shouldThrowExceptionWhenOtherJoinStoreSetsRetainDuplicatesFalse() {
//Case where otherJoinStore retain duplicates false
final WindowBytesStoreSupplier thisStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store", 150L, 100L, true);
final WindowBytesStoreSupplier otherStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store-other", 150L, 100L, false);
buildStreamsJoinThatShouldThrow(
streamJoined.withThisStoreSupplier(thisStoreSupplier).withOtherStoreSupplier(otherStoreSupplier),
joinWindows,
"The StoreSupplier must set retainDuplicates=true, found retainDuplicates=false"
);
}
@Test
public void shouldBuildJoinWithCustomStoresAndCorrectWindowSettings() {
//Case where everything matches up
final StreamsBuilder builder = new StreamsBuilder();
final KStream<String, Integer> left = builder.stream("left", Consumed.with(Serdes.String(), Serdes.Integer()));
final KStream<String, Integer> right = builder.stream("right", Consumed.with(Serdes.String(), Serdes.Integer()));
left.join(right,
Integer::sum,
joinWindows,
streamJoined
);
builder.build();
}
@Test
public void shouldExceptionWhenJoinStoresDoNotHaveUniqueNames() {
final JoinWindows joinWindows = JoinWindows.ofTimeDifferenceAndGrace(ofMillis(100L), Duration.ofMillis(50L));
final StreamJoined<String, Integer, Integer> streamJoined = StreamJoined.with(Serdes.String(), Serdes.Integer(), Serdes.Integer());
final WindowBytesStoreSupplier thisStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store", 150L, 100L, true);
final WindowBytesStoreSupplier otherStoreSupplier = buildWindowBytesStoreSupplier("in-memory-join-store", 150L, 100L, true);
buildStreamsJoinThatShouldThrow(
streamJoined.withThisStoreSupplier(thisStoreSupplier).withOtherStoreSupplier(otherStoreSupplier),
joinWindows,
"Both StoreSuppliers have the same name. StoreSuppliers must provide unique names"
);
}
@Test
public void shouldJoinWithCustomStoreSuppliers() {
final JoinWindows joinWindows = JoinWindows.ofTimeDifferenceWithNoGrace(ofMillis(100L));
final WindowBytesStoreSupplier thisStoreSupplier = Stores.inMemoryWindowStore(
"in-memory-join-store",
Duration.ofMillis(joinWindows.size() + joinWindows.gracePeriodMs()),
Duration.ofMillis(joinWindows.size()),
true
);
final WindowBytesStoreSupplier otherStoreSupplier = Stores.inMemoryWindowStore(
"in-memory-join-store-other",
Duration.ofMillis(joinWindows.size() + joinWindows.gracePeriodMs()),
Duration.ofMillis(joinWindows.size()),
true
);
final StreamJoined<String, Integer, Integer> streamJoined = StreamJoined.with(Serdes.String(), Serdes.Integer(), Serdes.Integer());
//Case with 2 custom store suppliers
runJoin(streamJoined.withThisStoreSupplier(thisStoreSupplier).withOtherStoreSupplier(otherStoreSupplier), joinWindows);
//Case with this stream store supplier
runJoin(streamJoined.withThisStoreSupplier(thisStoreSupplier), joinWindows);
//Case with other stream store supplier
runJoin(streamJoined.withOtherStoreSupplier(otherStoreSupplier), joinWindows);
}
public static | KStreamKStreamJoinTest |
java | apache__camel | components/camel-paho-mqtt5/src/generated/java/org/apache/camel/component/paho/mqtt5/PahoMqtt5EndpointConfigurer.java | {
"start": 737,
"end": 14095
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
PahoMqtt5Endpoint target = (PahoMqtt5Endpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "automaticreconnect":
case "automaticReconnect": target.getConfiguration().setAutomaticReconnect(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "brokerurl":
case "brokerUrl": target.getConfiguration().setBrokerUrl(property(camelContext, java.lang.String.class, value)); return true;
case "cleanstart":
case "cleanStart": target.getConfiguration().setCleanStart(property(camelContext, boolean.class, value)); return true;
case "client": target.setClient(property(camelContext, org.eclipse.paho.mqttv5.client.MqttClient.class, value)); return true;
case "clientid":
case "clientId": target.getConfiguration().setClientId(property(camelContext, java.lang.String.class, value)); return true;
case "connectiontimeout":
case "connectionTimeout": target.getConfiguration().setConnectionTimeout(property(camelContext, int.class, value)); return true;
case "customwebsocketheaders":
case "customWebSocketHeaders": target.getConfiguration().setCustomWebSocketHeaders(property(camelContext, java.util.Map.class, value)); return true;
case "exceptionhandler":
case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
case "exchangepattern":
case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
case "executorservicetimeout":
case "executorServiceTimeout": target.getConfiguration().setExecutorServiceTimeout(property(camelContext, int.class, value)); return true;
case "filepersistencedirectory":
case "filePersistenceDirectory": target.getConfiguration().setFilePersistenceDirectory(property(camelContext, java.lang.String.class, value)); return true;
case "httpshostnameverificationenabled":
case "httpsHostnameVerificationEnabled": target.getConfiguration().setHttpsHostnameVerificationEnabled(property(camelContext, boolean.class, value)); return true;
case "keepaliveinterval":
case "keepAliveInterval": target.getConfiguration().setKeepAliveInterval(property(camelContext, int.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "manualacksenabled":
case "manualAcksEnabled": target.getConfiguration().setManualAcksEnabled(property(camelContext, boolean.class, value)); return true;
case "maxreconnectdelay":
case "maxReconnectDelay": target.getConfiguration().setMaxReconnectDelay(property(camelContext, int.class, value)); return true;
case "password": target.getConfiguration().setPassword(property(camelContext, java.lang.String.class, value)); return true;
case "persistence": target.getConfiguration().setPersistence(property(camelContext, org.apache.camel.component.paho.mqtt5.PahoMqtt5Persistence.class, value)); return true;
case "qos": target.getConfiguration().setQos(property(camelContext, int.class, value)); return true;
case "receivemaximum":
case "receiveMaximum": target.getConfiguration().setReceiveMaximum(property(camelContext, int.class, value)); return true;
case "retained": target.getConfiguration().setRetained(property(camelContext, boolean.class, value)); return true;
case "serveruris":
case "serverURIs": target.getConfiguration().setServerURIs(property(camelContext, java.lang.String.class, value)); return true;
case "sessionexpiryinterval":
case "sessionExpiryInterval": target.getConfiguration().setSessionExpiryInterval(property(camelContext, long.class, value)); return true;
case "socketfactory":
case "socketFactory": target.getConfiguration().setSocketFactory(property(camelContext, javax.net.SocketFactory.class, value)); return true;
case "sslclientprops":
case "sslClientProps": target.getConfiguration().setSslClientProps(property(camelContext, java.util.Properties.class, value)); return true;
case "sslhostnameverifier":
case "sslHostnameVerifier": target.getConfiguration().setSslHostnameVerifier(property(camelContext, javax.net.ssl.HostnameVerifier.class, value)); return true;
case "username":
case "userName": target.getConfiguration().setUserName(property(camelContext, java.lang.String.class, value)); return true;
case "willmqttproperties":
case "willMqttProperties": target.getConfiguration().setWillMqttProperties(property(camelContext, org.eclipse.paho.mqttv5.common.packet.MqttProperties.class, value)); return true;
case "willpayload":
case "willPayload": target.getConfiguration().setWillPayload(property(camelContext, java.lang.String.class, value)); return true;
case "willqos":
case "willQos": target.getConfiguration().setWillQos(property(camelContext, int.class, value)); return true;
case "willretained":
case "willRetained": target.getConfiguration().setWillRetained(property(camelContext, boolean.class, value)); return true;
case "willtopic":
case "willTopic": target.getConfiguration().setWillTopic(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "automaticreconnect":
case "automaticReconnect": return boolean.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "brokerurl":
case "brokerUrl": return java.lang.String.class;
case "cleanstart":
case "cleanStart": return boolean.class;
case "client": return org.eclipse.paho.mqttv5.client.MqttClient.class;
case "clientid":
case "clientId": return java.lang.String.class;
case "connectiontimeout":
case "connectionTimeout": return int.class;
case "customwebsocketheaders":
case "customWebSocketHeaders": return java.util.Map.class;
case "exceptionhandler":
case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class;
case "exchangepattern":
case "exchangePattern": return org.apache.camel.ExchangePattern.class;
case "executorservicetimeout":
case "executorServiceTimeout": return int.class;
case "filepersistencedirectory":
case "filePersistenceDirectory": return java.lang.String.class;
case "httpshostnameverificationenabled":
case "httpsHostnameVerificationEnabled": return boolean.class;
case "keepaliveinterval":
case "keepAliveInterval": return int.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "manualacksenabled":
case "manualAcksEnabled": return boolean.class;
case "maxreconnectdelay":
case "maxReconnectDelay": return int.class;
case "password": return java.lang.String.class;
case "persistence": return org.apache.camel.component.paho.mqtt5.PahoMqtt5Persistence.class;
case "qos": return int.class;
case "receivemaximum":
case "receiveMaximum": return int.class;
case "retained": return boolean.class;
case "serveruris":
case "serverURIs": return java.lang.String.class;
case "sessionexpiryinterval":
case "sessionExpiryInterval": return long.class;
case "socketfactory":
case "socketFactory": return javax.net.SocketFactory.class;
case "sslclientprops":
case "sslClientProps": return java.util.Properties.class;
case "sslhostnameverifier":
case "sslHostnameVerifier": return javax.net.ssl.HostnameVerifier.class;
case "username":
case "userName": return java.lang.String.class;
case "willmqttproperties":
case "willMqttProperties": return org.eclipse.paho.mqttv5.common.packet.MqttProperties.class;
case "willpayload":
case "willPayload": return java.lang.String.class;
case "willqos":
case "willQos": return int.class;
case "willretained":
case "willRetained": return boolean.class;
case "willtopic":
case "willTopic": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
PahoMqtt5Endpoint target = (PahoMqtt5Endpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "automaticreconnect":
case "automaticReconnect": return target.getConfiguration().isAutomaticReconnect();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "brokerurl":
case "brokerUrl": return target.getConfiguration().getBrokerUrl();
case "cleanstart":
case "cleanStart": return target.getConfiguration().isCleanStart();
case "client": return target.getClient();
case "clientid":
case "clientId": return target.getConfiguration().getClientId();
case "connectiontimeout":
case "connectionTimeout": return target.getConfiguration().getConnectionTimeout();
case "customwebsocketheaders":
case "customWebSocketHeaders": return target.getConfiguration().getCustomWebSocketHeaders();
case "exceptionhandler":
case "exceptionHandler": return target.getExceptionHandler();
case "exchangepattern":
case "exchangePattern": return target.getExchangePattern();
case "executorservicetimeout":
case "executorServiceTimeout": return target.getConfiguration().getExecutorServiceTimeout();
case "filepersistencedirectory":
case "filePersistenceDirectory": return target.getConfiguration().getFilePersistenceDirectory();
case "httpshostnameverificationenabled":
case "httpsHostnameVerificationEnabled": return target.getConfiguration().isHttpsHostnameVerificationEnabled();
case "keepaliveinterval":
case "keepAliveInterval": return target.getConfiguration().getKeepAliveInterval();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "manualacksenabled":
case "manualAcksEnabled": return target.getConfiguration().isManualAcksEnabled();
case "maxreconnectdelay":
case "maxReconnectDelay": return target.getConfiguration().getMaxReconnectDelay();
case "password": return target.getConfiguration().getPassword();
case "persistence": return target.getConfiguration().getPersistence();
case "qos": return target.getConfiguration().getQos();
case "receivemaximum":
case "receiveMaximum": return target.getConfiguration().getReceiveMaximum();
case "retained": return target.getConfiguration().isRetained();
case "serveruris":
case "serverURIs": return target.getConfiguration().getServerURIs();
case "sessionexpiryinterval":
case "sessionExpiryInterval": return target.getConfiguration().getSessionExpiryInterval();
case "socketfactory":
case "socketFactory": return target.getConfiguration().getSocketFactory();
case "sslclientprops":
case "sslClientProps": return target.getConfiguration().getSslClientProps();
case "sslhostnameverifier":
case "sslHostnameVerifier": return target.getConfiguration().getSslHostnameVerifier();
case "username":
case "userName": return target.getConfiguration().getUserName();
case "willmqttproperties":
case "willMqttProperties": return target.getConfiguration().getWillMqttProperties();
case "willpayload":
case "willPayload": return target.getConfiguration().getWillPayload();
case "willqos":
case "willQos": return target.getConfiguration().getWillQos();
case "willretained":
case "willRetained": return target.getConfiguration().isWillRetained();
case "willtopic":
case "willTopic": return target.getConfiguration().getWillTopic();
default: return null;
}
}
@Override
public Object getCollectionValueType(Object target, String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "customwebsocketheaders":
case "customWebSocketHeaders": return java.lang.String.class;
default: return null;
}
}
}
| PahoMqtt5EndpointConfigurer |
java | google__dagger | javatests/dagger/internal/codegen/XExecutableTypesTest.java | {
"start": 8727,
"end": 9652
} | class ____ {",
" void m(Collection<String> i) { throw new RuntimeException(); }",
"}");
CompilerTests.invocationCompiler(foo, bar)
.compile(
invocation -> {
XTypeElement fooType = invocation.getProcessingEnv().requireTypeElement("test.Foo");
XMethodElement m1 = fooType.getDeclaredMethods().get(0);
XTypeElement barType = invocation.getProcessingEnv().requireTypeElement("test.Bar");
XMethodElement m2 = barType.getDeclaredMethods().get(0);
assertThat(XExecutableTypes.isSubsignature(m2, m1)).isFalse();
assertThat(XExecutableTypes.isSubsignature(m1, m2)).isTrue();
});
}
@Test
public void subsignatureSameSignature() {
Source foo =
CompilerTests.javaSource(
"test.Foo",
"package test;",
"import java.util.*;",
" | Bar |
java | spring-projects__spring-security | core/src/test/java/org/springframework/security/concurrent/CurrentDelegatingSecurityContextExecutorTests.java | {
"start": 940,
"end": 1282
} | class ____ extends AbstractDelegatingSecurityContextExecutorTests {
@BeforeEach
public void setUp() throws Exception {
super.currentSecurityContextSetup();
}
@Override
protected DelegatingSecurityContextExecutor create() {
return new DelegatingSecurityContextExecutor(getExecutor());
}
}
| CurrentDelegatingSecurityContextExecutorTests |
java | apache__flink | flink-streaming-java/src/test/java/org/apache/flink/streaming/graph/WithMasterCheckpointHookConfigTest.java | {
"start": 6270,
"end": 6617
} | class ____ implements SourceFunction<String> {
@Override
public void run(SourceContext<String> ctx) {
throw new UnsupportedOperationException();
}
@Override
public void cancel() {}
}
// -----------------------------------------------------------------------
private static | TestSource |
java | spring-projects__spring-boot | loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/AbstractJarModeTests.java | {
"start": 1481,
"end": 1552
} | class ____ jar mode tests.
*
* @author Moritz Halbritter
*/
abstract | for |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/ITestAbfsStatistics.java | {
"start": 1413,
"end": 10200
} | class ____ extends AbstractAbfsIntegrationTest {
private static final int NUMBER_OF_OPS = 10;
public ITestAbfsStatistics() throws Exception {
}
@BeforeEach
public void setUp() throws Exception {
super.setup();
// Setting IOStats to INFO level, to see the IOStats after close().
getFileSystem().getConf().set(IOSTATISTICS_LOGGING_LEVEL,
IOSTATISTICS_LOGGING_LEVEL_INFO);
}
/**
* Testing the initial value of statistics.
*/
@Test
public void testInitialStatsValues() throws IOException {
describe("Testing the initial values of Abfs counters");
AbfsCounters abfsCounters =
new AbfsCountersImpl(getFileSystem().getUri());
IOStatistics ioStatistics = abfsCounters.getIOStatistics();
//Initial value verification for counters
for (Map.Entry<String, Long> entry : ioStatistics.counters().entrySet()) {
checkInitialValue(entry.getKey(), entry.getValue(), 0);
}
//Initial value verification for gauges
for (Map.Entry<String, Long> entry : ioStatistics.gauges().entrySet()) {
checkInitialValue(entry.getKey(), entry.getValue(), 0);
}
//Initial value verifications for DurationTrackers
for (Map.Entry<String, Long> entry : ioStatistics.maximums().entrySet()) {
checkInitialValue(entry.getKey(), entry.getValue(), -1);
}
}
/**
* Testing statistics by creating files and directories.
*/
@Test
public void testCreateStatistics() throws IOException {
describe("Testing counter values got by creating directories and files in"
+ " Abfs");
AzureBlobFileSystem fs = getFileSystem();
Path createFilePath = path(getMethodName());
Path createDirectoryPath = path(getMethodName() + "Dir");
fs.mkdirs(createDirectoryPath);
fs.createNonRecursive(createFilePath, FsPermission
.getDefault(), false, 1024, (short) 1, 1024, null).close();
Map<String, Long> metricMap = fs.getInstrumentationMap();
/*
Test of statistic values after creating a directory and a file ;
getFileStatus is called 1 time after creating file and 1 time at time of
initialising.
*/
assertAbfsStatistics(AbfsStatistic.CALL_CREATE_NON_RECURSIVE, 1, metricMap);
assertAbfsStatistics(AbfsStatistic.FILES_CREATED, 1, metricMap);
assertAbfsStatistics(AbfsStatistic.DIRECTORIES_CREATED, 1, metricMap);
assertAbfsStatistics(AbfsStatistic.CALL_MKDIRS, 1, metricMap);
assertAbfsStatistics(AbfsStatistic.CALL_GET_FILE_STATUS, 2, metricMap);
//re-initialising Abfs to reset statistic values.
fs.initialize(fs.getUri(), fs.getConf());
/*
Creating 10 directories and files; Directories and files can't be created
with same name, hence <Name> + i to give unique names.
*/
for (int i = 0; i < NUMBER_OF_OPS; i++) {
fs.mkdirs(path(getMethodName() + "Dir" + i));
fs.createNonRecursive(path(getMethodName() + i),
FsPermission.getDefault(), false, 1024, (short) 1,
1024, null).close();
}
metricMap = fs.getInstrumentationMap();
/*
Test of statistics values after creating 10 directories and files;
getFileStatus is called 1 time at initialise() plus number of times file
is created.
*/
assertAbfsStatistics(AbfsStatistic.CALL_CREATE_NON_RECURSIVE, NUMBER_OF_OPS,
metricMap);
assertAbfsStatistics(AbfsStatistic.FILES_CREATED, NUMBER_OF_OPS, metricMap);
assertAbfsStatistics(AbfsStatistic.DIRECTORIES_CREATED, NUMBER_OF_OPS,
metricMap);
assertAbfsStatistics(AbfsStatistic.CALL_MKDIRS, NUMBER_OF_OPS, metricMap);
assertAbfsStatistics(AbfsStatistic.CALL_GET_FILE_STATUS,
1 + NUMBER_OF_OPS, metricMap);
}
/**
* Testing statistics by deleting files and directories.
*/
@Test
public void testDeleteStatistics() throws IOException {
describe("Testing counter values got by deleting directory and files "
+ "in Abfs");
AzureBlobFileSystem fs = getFileSystem();
/*
This directory path needs to be root for triggering the
directories_deleted counter.
*/
Path createDirectoryPath = path("/");
Path createFilePath = path(getMethodName());
/*
creating a directory and a file inside that directory.
The directory is root. Hence, no parent. This allows us to invoke
deleteRoot() method to see the population of directories_deleted and
files_deleted counters.
*/
fs.mkdirs(createDirectoryPath);
fs.create(path(createDirectoryPath + getMethodName())).close();
fs.delete(createDirectoryPath, true);
Map<String, Long> metricMap = fs.getInstrumentationMap();
/*
Test for op_delete, files_deleted, op_list_status.
since directory is delete recursively op_delete is called 2 times.
1 file is deleted, 1 listStatus() call is made.
*/
assertAbfsStatistics(AbfsStatistic.CALL_DELETE, 2, metricMap);
assertAbfsStatistics(AbfsStatistic.FILES_DELETED, 1, metricMap);
assertAbfsStatistics(AbfsStatistic.CALL_LIST_STATUS, 1, metricMap);
/*
creating a root directory and deleting it recursively to see if
directories_deleted is called or not.
*/
fs.mkdirs(createDirectoryPath);
fs.create(createFilePath).close();
fs.delete(createDirectoryPath, true);
metricMap = fs.getInstrumentationMap();
//Test for directories_deleted.
assertAbfsStatistics(AbfsStatistic.DIRECTORIES_DELETED, 1, metricMap);
}
/**
* Testing statistics of open, append, rename and exists method calls.
*/
@Test
public void testOpenAppendRenameExists() throws IOException {
describe("Testing counter values on calling open, append and rename and "
+ "exists methods on Abfs");
AzureBlobFileSystem fs = getFileSystem();
Path createFilePath = path(getMethodName());
Path destCreateFilePath = path(getMethodName() + "New");
fs.create(createFilePath).close();
fs.open(createFilePath).close();
fs.append(createFilePath).close();
assertTrue(fs.rename(createFilePath, destCreateFilePath));
Map<String, Long> metricMap = fs.getInstrumentationMap();
//Testing single method calls to open, append and rename.
assertAbfsStatistics(AbfsStatistic.CALL_OPEN, 1, metricMap);
assertAbfsStatistics(AbfsStatistic.CALL_APPEND, 1, metricMap);
assertAbfsStatistics(AbfsStatistic.CALL_RENAME, 1, metricMap);
//Testing if file exists at path.
assertTrue(
fs.exists(destCreateFilePath), String.format("File with name %s should exist",
destCreateFilePath));
assertFalse(
fs.exists(createFilePath), String.format("File with name %s should not exist",
createFilePath));
metricMap = fs.getInstrumentationMap();
//Testing exists() calls.
assertAbfsStatistics(AbfsStatistic.CALL_EXIST, 2, metricMap);
//re-initialising Abfs to reset statistic values.
fs.initialize(fs.getUri(), fs.getConf());
fs.create(destCreateFilePath).close();
for (int i = 0; i < NUMBER_OF_OPS; i++) {
fs.open(destCreateFilePath);
fs.append(destCreateFilePath).close();
}
metricMap = fs.getInstrumentationMap();
//Testing large number of method calls to open, append.
assertAbfsStatistics(AbfsStatistic.CALL_OPEN, NUMBER_OF_OPS, metricMap);
assertAbfsStatistics(AbfsStatistic.CALL_APPEND, NUMBER_OF_OPS, metricMap);
for (int i = 0; i < NUMBER_OF_OPS; i++) {
// rename and then back to earlier name for no error while looping.
assertTrue(fs.rename(destCreateFilePath, createFilePath));
assertTrue(fs.rename(createFilePath, destCreateFilePath));
//check if first name is existing and 2nd is not existing.
assertTrue(
fs.exists(destCreateFilePath), String.format("File with name %s should exist",
destCreateFilePath));
assertFalse(
fs.exists(createFilePath), String.format("File with name %s should not exist",
createFilePath));
}
metricMap = fs.getInstrumentationMap();
/*
Testing exists() calls and rename calls. Since both were called 2
times in 1 loop. 2*numberOfOps is expectedValue.
*/
assertAbfsStatistics(AbfsStatistic.CALL_RENAME, 2 * NUMBER_OF_OPS,
metricMap);
assertAbfsStatistics(AbfsStatistic.CALL_EXIST, 2 * NUMBER_OF_OPS,
metricMap);
}
/**
* Method to check initial value of the statistics which should be 0.
*
* @param statName name of the statistic to be checked.
* @param statValue value of the statistic.
* @param expectedInitialValue initial value expected from this statistic.
*/
private void checkInitialValue(String statName, long statValue,
long expectedInitialValue) {
assertEquals(expectedInitialValue, statValue, "Mismatch in " + statName);
}
}
| ITestAbfsStatistics |
java | apache__camel | components/camel-huawei/camel-huaweicloud-smn/src/main/java/org/apache/camel/component/huaweicloud/smn/constants/SmnConstants.java | {
"start": 879,
"end": 1009
} | class ____ {
public static final String TOPIC_URN_FORMAT = "urn:smn:%s:%s:%s";
private SmnConstants() {
}
}
| SmnConstants |
java | bumptech__glide | library/test/src/test/java/com/bumptech/glide/load/model/GlideUrlTest.java | {
"start": 581,
"end": 4455
} | class ____ {
@Test(expected = NullPointerException.class)
public void testThrowsIfGivenURLIsNull() {
new GlideUrl((URL) null);
}
@Test(expected = IllegalArgumentException.class)
public void testThrowsIfGivenStringUrlIsNull() {
new GlideUrl((String) null);
}
@Test(expected = IllegalArgumentException.class)
public void testThrowsIfGivenStringURLIsEmpty() {
new GlideUrl("");
}
@Test
public void testCanCompareGlideUrlsCreatedWithDifferentTypes() throws MalformedURLException {
String stringUrl = "http://www.google.com";
URL url = new URL(stringUrl);
assertEquals(new GlideUrl(stringUrl), new GlideUrl(url));
}
@Test
public void testCanCompareHashcodeOfGlideUrlsCreatedWithDifferentTypes()
throws MalformedURLException {
String stringUrl = "http://nytimes.com";
URL url = new URL(stringUrl);
assertEquals(new GlideUrl(stringUrl).hashCode(), new GlideUrl(url).hashCode());
}
@Test
public void testProducesEquivalentUrlFromString() throws MalformedURLException {
String stringUrl = "http://www.google.com";
GlideUrl glideUrl = new GlideUrl(stringUrl);
URL url = glideUrl.toURL();
assertEquals(stringUrl, url.toString());
}
@Test
public void testProducesEquivalentStringFromURL() throws MalformedURLException {
String expected = "http://www.washingtonpost.com";
URL url = new URL(expected);
GlideUrl glideUrl = new GlideUrl(url);
assertEquals(expected, glideUrl.toStringUrl());
}
@Test
public void testIssue133() throws MalformedURLException {
// u00e0=à
final String original =
"http://www.commitstrip.com/wp-content/uploads/2014/07/"
+ "Excel-\u00E0-toutes-les-sauces-650-finalenglish.jpg";
final String escaped =
"http://www.commitstrip.com/wp-content/uploads/2014/07/"
+ "Excel-%C3%A0-toutes-les-sauces-650-finalenglish.jpg";
GlideUrl glideUrlFromString = new GlideUrl(original);
assertEquals(escaped, glideUrlFromString.toURL().toString());
GlideUrl glideUrlFromEscapedString = new GlideUrl(escaped);
assertEquals(escaped, glideUrlFromEscapedString.toURL().toString());
GlideUrl glideUrlFromUrl = new GlideUrl(new URL(original));
assertEquals(escaped, glideUrlFromUrl.toURL().toString());
GlideUrl glideUrlFromEscapedUrl = new GlideUrl(new URL(escaped));
assertEquals(escaped, glideUrlFromEscapedUrl.toURL().toString());
}
@Test
public void issue_2583() throws MalformedURLException {
String original =
"http://api.met.no/weatherapi/weathericon/1.1/?symbol=9;content_type=image/png";
GlideUrl glideUrl = new GlideUrl(original);
assertThat(glideUrl.toURL().toString()).isEqualTo(original);
assertThat(glideUrl.toStringUrl()).isEqualTo(original);
}
@Test
public void testEquals() throws MalformedURLException {
Headers headers = mock(Headers.class);
Headers otherHeaders = mock(Headers.class);
String url = "http://www.google.com";
String otherUrl = "http://mail.google.com";
new EqualsTester()
.addEqualityGroup(
new GlideUrl(url),
new GlideUrl(url),
new GlideUrl(new URL(url)),
new GlideUrl(new URL(url)))
.addEqualityGroup(new GlideUrl(otherUrl), new GlideUrl(new URL(otherUrl)))
.addEqualityGroup(new GlideUrl(url, headers), new GlideUrl(new URL(url), headers))
.addEqualityGroup(new GlideUrl(url, otherHeaders), new GlideUrl(new URL(url), otherHeaders))
.testEquals();
}
@Test
public void issue_5444() throws MalformedURLException {
String original = "http://[2600:1f13:37c:1400:ba21:7165:5fc7:736e]/";
GlideUrl glideUrl = new GlideUrl(original);
assertThat(glideUrl.toURL().toString()).isEqualTo(original);
assertThat(glideUrl.toStringUrl()).isEqualTo(original);
}
}
| GlideUrlTest |
java | spring-projects__spring-boot | smoke-test/spring-boot-smoke-test-graphql/src/main/java/smoketest/graphql/SampleGraphQlApplication.java | {
"start": 805,
"end": 950
} | class ____ {
public static void main(String[] args) {
SpringApplication.run(SampleGraphQlApplication.class, args);
}
}
| SampleGraphQlApplication |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/jobcontrol/ControlledJob.java | {
"start": 1439,
"end": 2116
} | class ____ a MapReduce job and its dependency. It monitors
* the states of the depending jobs and updates the state of this job.
* A job starts in the WAITING state. If it does not have any depending jobs,
* or all of the depending jobs are in SUCCESS state, then the job state
* will become READY. If any depending jobs fail, the job will fail too.
* When in READY state, the job can be submitted to Hadoop for execution, with
* the state changing into RUNNING state. From RUNNING state, the job
* can get into SUCCESS or FAILED state, depending
* the status of the job execution.
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public | encapsulates |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inlineme/ValidatorTest.java | {
"start": 27068,
"end": 27754
} | class ____ {
@Deprecated
@InlineMe(replacement = "this.after(arg0, arg1)")
// BUG: Diagnostic contains: `arg[0-9]+`
public void before(int arg0, int arg1) {
after(arg0, arg1);
}
public void after(int arg0, int arg1) {}
}
""")
.doTest();
}
@Test
public void cleanupInlineMes_records() {
getHelperInCleanupMode()
.allowBreakingChanges()
.addInputLines(
"Client.java",
"""
package com.google.frobber;
import com.google.errorprone.annotations.InlineMe;
public final | Client |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.