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
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/superclass/SuperclassInjectionTest.java
|
{
"start": 2889,
"end": 3329
}
|
class ____ {
@Inject
Head sameName;
private Head head1;
@Inject
Head head2;
Head getSuperHead() {
return sameName;
}
@Inject
void setHead(Head head) {
this.head1 = head;
}
public Head getHead1() {
return head1;
}
public Head getHead2() {
return head2;
}
}
}
|
SuperHarvester
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/producer/ProducerWithClassAndMethodLevelInterceptorsAndBindingsSourceTest.java
|
{
"start": 2368,
"end": 2683
}
|
class ____ {
String hello1() {
return "hello1";
}
String hello2() {
return "hello2";
}
String hello3() {
return "hello3";
}
String hello4() {
return "hello4";
}
}
@MyBinding1
static
|
MyNonbean
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.java
|
{
"start": 4085,
"end": 4204
}
|
interface ____ to resolve replacement values for placeholders contained in Strings.
*/
@FunctionalInterface
public
|
used
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/math/ScalbIntEvaluator.java
|
{
"start": 5394,
"end": 6181
}
|
class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory d;
private final EvalOperator.ExpressionEvaluator.Factory scaleFactor;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory d,
EvalOperator.ExpressionEvaluator.Factory scaleFactor) {
this.source = source;
this.d = d;
this.scaleFactor = scaleFactor;
}
@Override
public ScalbIntEvaluator get(DriverContext context) {
return new ScalbIntEvaluator(source, d.get(context), scaleFactor.get(context), context);
}
@Override
public String toString() {
return "ScalbIntEvaluator[" + "d=" + d + ", scaleFactor=" + scaleFactor + "]";
}
}
}
|
Factory
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test.java
|
{
"start": 1433,
"end": 3433
}
|
class ____
extends AtomicReferenceArrayAssertBaseTest {
private ObjectArrays arraysBefore;
@BeforeEach
void before() {
arraysBefore = getArrays(assertions);
}
@Override
protected AtomicReferenceArrayAssert<Object> invoke_api_method() {
return assertions.usingRecursiveFieldByFieldElementComparatorIgnoringFields("field");
}
@Override
protected void verify_internal_effects() {
then(arraysBefore).isNotSameAs(getArrays(assertions));
then(getArrays(assertions).getComparisonStrategy()).isInstanceOf(ComparatorBasedComparisonStrategy.class);
then(getObjects(assertions).getComparisonStrategy()).isInstanceOf(AtomicReferenceArrayElementComparisonStrategy.class);
RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder()
.withIgnoredFields("field")
.build();
ConfigurableRecursiveFieldByFieldComparator expectedComparator = new ConfigurableRecursiveFieldByFieldComparator(recursiveComparisonConfiguration);
then(getArrays(assertions).getComparator()).isEqualTo(expectedComparator);
then(getObjects(assertions).getComparisonStrategy()).extracting("elementComparator").isEqualTo(expectedComparator);
}
@Test
void should_ignore_given_fields_recursively() {
// GIVEN
Player rose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls");
rose.nickname = new Name("Crazy", "Dunks");
Player jalen = new Player(new Name("Jalen", "Rose"), "Chicago Bulls");
jalen.nickname = new Name("Crazy", "Defense");
// WHEN/THEN
then(list(rose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name.first", "nickname.last")
.contains(jalen);
}
}
|
AtomicReferenceArrayAssert_usingRecursiveFieldByFieldElementComparatorIgnoringFields_Test
|
java
|
dropwizard__dropwizard
|
dropwizard-views/src/main/java/io/dropwizard/views/common/ViewRenderExceptionMapper.java
|
{
"start": 572,
"end": 1570
}
|
class ____ implements ExtendedExceptionMapper<WebApplicationException> {
private static final Logger LOGGER = LoggerFactory.getLogger(ViewRenderExceptionMapper.class);
/**
* The generic HTML error page template.
*/
public static final String TEMPLATE_ERROR_MSG =
"<html>" +
"<head><title>Template Error</title></head>" +
"<body><h1>Template Error</h1><p>Something went wrong rendering the page</p></body>" +
"</html>";
@Override
public Response toResponse(WebApplicationException exception) {
LOGGER.error("Template Error", exception);
return Response.serverError()
.type(MediaType.TEXT_HTML_TYPE)
.entity(TEMPLATE_ERROR_MSG)
.build();
}
@Override
public boolean isMappable(WebApplicationException e) {
return findThrowableInChain(t -> t.getClass() == ViewRenderException.class, e).isPresent();
}
}
|
ViewRenderExceptionMapper
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableGroupJoin.java
|
{
"start": 1303,
"end": 2881
}
|
class ____<TLeft, TRight, TLeftEnd, TRightEnd, R> extends AbstractObservableWithUpstream<TLeft, R> {
final ObservableSource<? extends TRight> other;
final Function<? super TLeft, ? extends ObservableSource<TLeftEnd>> leftEnd;
final Function<? super TRight, ? extends ObservableSource<TRightEnd>> rightEnd;
final BiFunction<? super TLeft, ? super Observable<TRight>, ? extends R> resultSelector;
public ObservableGroupJoin(
ObservableSource<TLeft> source,
ObservableSource<? extends TRight> other,
Function<? super TLeft, ? extends ObservableSource<TLeftEnd>> leftEnd,
Function<? super TRight, ? extends ObservableSource<TRightEnd>> rightEnd,
BiFunction<? super TLeft, ? super Observable<TRight>, ? extends R> resultSelector) {
super(source);
this.other = other;
this.leftEnd = leftEnd;
this.rightEnd = rightEnd;
this.resultSelector = resultSelector;
}
@Override
protected void subscribeActual(Observer<? super R> observer) {
GroupJoinDisposable<TLeft, TRight, TLeftEnd, TRightEnd, R> parent =
new GroupJoinDisposable<>(observer, leftEnd, rightEnd, resultSelector);
observer.onSubscribe(parent);
LeftRightObserver left = new LeftRightObserver(parent, true);
parent.disposables.add(left);
LeftRightObserver right = new LeftRightObserver(parent, false);
parent.disposables.add(right);
source.subscribe(left);
other.subscribe(right);
}
|
ObservableGroupJoin
|
java
|
junit-team__junit5
|
junit-platform-engine/src/main/java/org/junit/platform/engine/TestExecutionResult.java
|
{
"start": 1260,
"end": 3795
}
|
enum ____ {
/**
* Indicates that the execution of a test or container was
* <em>successful</em>.
*/
SUCCESSFUL,
/**
* Indicates that the execution of a test or container was
* <em>aborted</em> (started but not finished).
*/
ABORTED,
/**
* Indicates that the execution of a test or container <em>failed</em>.
*/
FAILED
}
private static final TestExecutionResult SUCCESSFUL_RESULT = new TestExecutionResult(SUCCESSFUL, null);
/**
* Create a {@code TestExecutionResult} for a <em>successful</em> execution
* of a test or container.
*
* @return the {@code TestExecutionResult}; never {@code null}
*/
public static TestExecutionResult successful() {
return SUCCESSFUL_RESULT;
}
/**
* Create a {@code TestExecutionResult} for an <em>aborted</em> execution
* of a test or container with the supplied {@link Throwable throwable}.
*
* @param throwable the throwable that caused the aborted execution; may be
* {@code null}
* @return the {@code TestExecutionResult}; never {@code null}
*/
public static TestExecutionResult aborted(@Nullable Throwable throwable) {
return new TestExecutionResult(ABORTED, throwable);
}
/**
* Create a {@code TestExecutionResult} for a <em>failed</em> execution
* of a test or container with the supplied {@link Throwable throwable}.
*
* @param throwable the throwable that caused the failed execution; may be
* {@code null}
* @return the {@code TestExecutionResult}; never {@code null}
*/
public static TestExecutionResult failed(@Nullable Throwable throwable) {
return new TestExecutionResult(FAILED, throwable);
}
private final Status status;
private final @Nullable Throwable throwable;
private TestExecutionResult(Status status, @Nullable Throwable throwable) {
this.status = Preconditions.notNull(status, "Status must not be null");
this.throwable = throwable;
}
/**
* Get the {@linkplain Status status} of this result.
*
* @return the status; never {@code null}
*/
public Status getStatus() {
return status;
}
/**
* Get the throwable that caused this result, if available.
*
* @return an {@code Optional} containing the throwable; never {@code null}
* but potentially empty
*/
public Optional<Throwable> getThrowable() {
return Optional.ofNullable(throwable);
}
@Override
public String toString() {
// @formatter:off
return new ToStringBuilder(this)
.append("status", status)
.append("throwable", throwable)
.toString();
// @formatter:on
}
}
|
Status
|
java
|
spring-projects__spring-framework
|
spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/ConvertingEncoderDecoderSupportTests.java
|
{
"start": 2097,
"end": 6254
}
|
class ____ {
private static final String CONVERTED_TEXT = "_test";
private static final ByteBuffer CONVERTED_BYTES = ByteBuffer.wrap("~test".getBytes());
private WebApplicationContext applicationContext;
private MyType myType = new MyType("test");
@BeforeEach
void setup() {
setup(Config.class);
}
@AfterEach
void teardown() {
ContextLoaderTestUtils.setCurrentWebApplicationContext(null);
}
private void setup(Class<?> configurationClass) {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(configurationClass);
applicationContext.refresh();
this.applicationContext = applicationContext;
ContextLoaderTestUtils.setCurrentWebApplicationContext(this.applicationContext);
}
@Test
void encodeToText() throws Exception {
assertThat(new MyTextEncoder().encode(myType)).isEqualTo(CONVERTED_TEXT);
}
@Test
void encodeToTextCannotConvert() {
setup(NoConvertersConfig.class);
assertThatExceptionOfType(EncodeException.class).isThrownBy(() ->
new MyTextEncoder().encode(myType))
.withCauseInstanceOf(ConverterNotFoundException.class);
}
@Test
void encodeToBinary() throws Exception {
assertThat(new MyBinaryEncoder().encode(myType).array())
.isEqualTo(CONVERTED_BYTES.array());
}
@Test
void encodeToBinaryCannotConvert() {
setup(NoConvertersConfig.class);
assertThatExceptionOfType(EncodeException.class).isThrownBy(() ->
new MyBinaryEncoder().encode(myType))
.withCauseInstanceOf(ConverterNotFoundException.class);
}
@Test
void decodeFromText() throws Exception {
Decoder.Text<MyType> decoder = new MyTextDecoder();
assertThat(decoder.willDecode(CONVERTED_TEXT)).isTrue();
assertThat(decoder.decode(CONVERTED_TEXT)).isEqualTo(myType);
}
@Test
void decodeFromTextCannotConvert() {
setup(NoConvertersConfig.class);
Decoder.Text<MyType> decoder = new MyTextDecoder();
assertThat(decoder.willDecode(CONVERTED_TEXT)).isFalse();
assertThatExceptionOfType(DecodeException.class).isThrownBy(() ->
decoder.decode(CONVERTED_TEXT))
.withCauseInstanceOf(ConverterNotFoundException.class);
}
@Test
void decodeFromBinary() throws Exception {
Decoder.Binary<MyType> decoder = new MyBinaryDecoder();
assertThat(decoder.willDecode(CONVERTED_BYTES)).isTrue();
assertThat(decoder.decode(CONVERTED_BYTES)).isEqualTo(myType);
}
@Test
void decodeFromBinaryCannotConvert() {
setup(NoConvertersConfig.class);
Decoder.Binary<MyType> decoder = new MyBinaryDecoder();
assertThat(decoder.willDecode(CONVERTED_BYTES)).isFalse();
assertThatExceptionOfType(DecodeException.class).isThrownBy(() ->
decoder.decode(CONVERTED_BYTES))
.withCauseInstanceOf(ConverterNotFoundException.class);
}
@Test
void encodeAndDecodeText() throws Exception {
MyTextEncoderDecoder encoderDecoder = new MyTextEncoderDecoder();
String encoded = encoderDecoder.encode(myType);
assertThat(encoderDecoder.decode(encoded)).isEqualTo(myType);
}
@Test
void encodeAndDecodeBytes() throws Exception {
MyBinaryEncoderDecoder encoderDecoder = new MyBinaryEncoderDecoder();
ByteBuffer encoded = encoderDecoder.encode(myType);
assertThat(encoderDecoder.decode(encoded)).isEqualTo(myType);
}
@Test
void autowiresIntoEncoder() {
WithAutowire withAutowire = new WithAutowire();
withAutowire.init(null);
assertThat(withAutowire.config).isEqualTo(applicationContext.getBean(Config.class));
}
@Test
void cannotFindApplicationContext() {
ContextLoaderTestUtils.setCurrentWebApplicationContext(null);
WithAutowire encoder = new WithAutowire();
encoder.init(null);
assertThatIllegalStateException().isThrownBy(() ->
encoder.encode(myType))
.withMessageContaining("Unable to locate the Spring ApplicationContext");
}
@Test
void cannotFindConversionService() {
setup(NoConfig.class);
MyBinaryEncoder encoder = new MyBinaryEncoder();
encoder.init(null);
assertThatIllegalStateException().isThrownBy(() ->
encoder.encode(myType))
.withMessageContaining("Unable to find ConversionService");
}
@Configuration
public static
|
ConvertingEncoderDecoderSupportTests
|
java
|
google__guava
|
android/guava/src/com/google/common/util/concurrent/ClosingFuture.java
|
{
"start": 61729,
"end": 62187
}
|
class ____<V1 extends @Nullable Object, V2 extends @Nullable Object>
extends Combiner {
/**
* A function that returns a value when applied to the values of the two futures passed to
* {@link #whenAllSucceed(ClosingFuture, ClosingFuture)}.
*
* @param <V1> the type returned by the first future
* @param <V2> the type returned by the second future
* @param <U> the type returned by the function
*/
public
|
Combiner2
|
java
|
apache__camel
|
core/camel-core-reifier/src/main/java/org/apache/camel/reifier/errorhandler/LegacyNoErrorHandlerReifier.java
|
{
"start": 1238,
"end": 1696
}
|
class ____ extends ErrorHandlerReifier<NoErrorHandlerProperties> {
public LegacyNoErrorHandlerReifier(Route route, ErrorHandlerFactory definition) {
super(route, (NoErrorHandlerProperties) definition);
}
@Override
public Processor createErrorHandler(Processor processor) throws Exception {
ErrorHandler answer = new NoErrorHandler(processor);
configure(answer);
return answer;
}
}
|
LegacyNoErrorHandlerReifier
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/WrapperArrayHandlingDisallowTests.java
|
{
"start": 1511,
"end": 1633
}
|
class ____ {
@Id
public Integer id;
private Byte[] wrapper;
public EntityOfByteArrays() {
}
}
}
|
EntityOfByteArrays
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/FactoryUtil.java
|
{
"start": 60867,
"end": 62015
}
|
class ____ implements CatalogFactory.Context {
private final String name;
private final Map<String, String> options;
private final ReadableConfig configuration;
private final ClassLoader classLoader;
public DefaultCatalogContext(
String name,
Map<String, String> options,
ReadableConfig configuration,
ClassLoader classLoader) {
this.name = name;
this.options = options;
this.configuration = configuration;
this.classLoader = classLoader;
}
@Override
public String getName() {
return name;
}
@Override
public Map<String, String> getOptions() {
return options;
}
@Override
public ReadableConfig getConfiguration() {
return configuration;
}
@Override
public ClassLoader getClassLoader() {
return classLoader;
}
}
/** Default implementation of {@link CatalogStoreFactory.Context}. */
@Internal
public static
|
DefaultCatalogContext
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/StrTestEntity.java
|
{
"start": 422,
"end": 1537
}
|
class ____ {
@Id
@GeneratedValue
private Integer id;
@Audited
private String str;
public StrTestEntity() {
}
public StrTestEntity(String str, Integer id) {
this.str = str;
this.id = id;
}
public StrTestEntity(String str) {
this.str = str;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof StrTestEntity) ) {
return false;
}
StrTestEntity that = (StrTestEntity) o;
if ( id != null ? !id.equals( that.getId() ) : that.getId() != null ) {
return false;
}
if ( str != null ? !str.equals( that.getStr() ) : that.getStr() != null ) {
return false;
}
return true;
}
public int hashCode() {
int result;
result = (id != null ? id.hashCode() : 0);
result = 31 * result + (str != null ? str.hashCode() : 0);
return result;
}
public String toString() {
return "STE(id = " + id + ", str = " + str + ")";
}
}
|
StrTestEntity
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/search/sort/SortValue.java
|
{
"start": 2721,
"end": 4690
}
|
class ____ defined in this file.
}
@Override
public final int compareTo(SortValue other) {
int typeComparison = typeComparisonKey() - other.typeComparisonKey();
return typeComparison == 0 ? compareToSameType(other) : typeComparison;
}
/**
* Write the key as xcontent.
*/
public final XContentBuilder toXContent(XContentBuilder builder, DocValueFormat format) throws IOException {
if (format == DocValueFormat.RAW) {
return rawToXContent(builder);
}
return builder.value(format(format));
}
/**
* The java object representing the sort value.
*/
public abstract Object getKey();
/**
* Format this value using the provided format.
*/
public abstract String format(DocValueFormat format);
/**
* Write the key as xcontent using the most native type possible.
*/
protected abstract XContentBuilder rawToXContent(XContentBuilder builder) throws IOException;
/**
* Compare this sort value to another sort value of the same type.
*/
protected abstract int compareToSameType(SortValue obj);
// Force implementations to override equals for consistency with compareToSameType
@Override
public abstract boolean equals(Object obj);
// Force implementations to override hashCode for consistency with equals
@Override
public abstract int hashCode();
// Force implementations to override toString so debugging isn't a nightmare.
@Override
public abstract String toString();
// Force implementations to override typeComparisonKey and associate each subclass with an integer key
protected abstract int typeComparisonKey();
/**
* Return this {@linkplain SortValue} as a boxed {@linkplain Number}
* or {@link Double#NaN} if it isn't a number. Or if it is actually
* {@link Double#NaN}.
*/
public abstract Number numberValue();
private static
|
are
|
java
|
apache__flink
|
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/ExecutableOperation.java
|
{
"start": 1742,
"end": 1812
}
|
interface ____ stable and public
* in the future.
*/
@Internal
public
|
is
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/ExceptionDepthComparatorTests.java
|
{
"start": 3124,
"end": 3213
}
|
class ____ extends Throwable {
}
@SuppressWarnings("serial")
public
|
HighestDepthException
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/cluster/metadata/MetadataIsManagedByILMTests.java
|
{
"start": 771,
"end": 4658
}
|
class ____ extends ESTestCase {
public void testIsIndexManagedByILM() {
{
// index has no ILM policy configured
IndexMetadata indexMetadata = createIndexMetadataBuilderForIndex("test-no-ilm-policy").build();
Metadata metadata = Metadata.builder().put(indexMetadata, true).build();
assertThat(metadata.getProject().isIndexManagedByILM(indexMetadata), is(false));
}
{
// index has been deleted
IndexMetadata indexMetadata = createIndexMetadataBuilderForIndex(
"testindex",
Settings.builder().put("index.lifecycle.name", "metrics").build()
).build();
Metadata metadata = Metadata.builder().build();
assertThat(metadata.getProject().isIndexManagedByILM(indexMetadata), is(false));
}
{
// index has ILM policy configured and doesn't belong to a data stream
IndexMetadata indexMetadata = createIndexMetadataBuilderForIndex(
"testindex",
Settings.builder().put("index.lifecycle.name", "metrics").build()
).build();
Metadata metadata = Metadata.builder().put(indexMetadata, true).build();
assertThat(metadata.getProject().isIndexManagedByILM(indexMetadata), is(true));
}
{
// index has ILM policy configured and does belong to a data stream with a data stream lifecycle
// by default ILM takes precedence
String dataStreamName = "metrics-prod";
IndexMetadata indexMetadata = createIndexMetadataBuilderForIndex(
DataStream.getDefaultBackingIndexName(dataStreamName, 1),
Settings.builder().put("index.lifecycle.name", "metrics").build()
).build();
DataStream dataStream = DataStreamTestHelper.newInstance(
dataStreamName,
List.of(indexMetadata.getIndex()),
1,
null,
false,
DataStreamLifecycle.DEFAULT_DATA_LIFECYCLE
);
Metadata metadata = Metadata.builder().put(indexMetadata, true).put(dataStream).build();
assertThat(metadata.getProject().isIndexManagedByILM(indexMetadata), is(true));
}
{
// index has ILM policy configured and does belong to a data stream with a data stream lifecycle, but
// the PREFER_ILM_SETTING is configured to false
String dataStreamName = "metrics-prod";
IndexMetadata indexMetadata = createIndexMetadataBuilderForIndex(
DataStream.getDefaultBackingIndexName(dataStreamName, 1),
Settings.builder().put("index.lifecycle.name", "metrics").put(IndexSettings.PREFER_ILM, false).build()
).build();
DataStream dataStream = DataStreamTestHelper.newInstance(
dataStreamName,
List.of(indexMetadata.getIndex()),
1,
null,
false,
DataStreamLifecycle.DEFAULT_DATA_LIFECYCLE
);
Metadata metadata = Metadata.builder().put(indexMetadata, true).put(dataStream).build();
assertThat(metadata.getProject().isIndexManagedByILM(indexMetadata), is(false));
}
}
public static IndexMetadata.Builder createIndexMetadataBuilderForIndex(String index) {
return createIndexMetadataBuilderForIndex(index, Settings.EMPTY);
}
public static IndexMetadata.Builder createIndexMetadataBuilderForIndex(String index, Settings settings) {
return IndexMetadata.builder(index)
.settings(Settings.builder().put(settings).put(settings(IndexVersion.current()).build()))
.numberOfShards(1)
.numberOfReplicas(1);
}
}
|
MetadataIsManagedByILMTests
|
java
|
micronaut-projects__micronaut-core
|
core/src/main/java/io/micronaut/core/io/service/ServiceScanner.java
|
{
"start": 10785,
"end": 11911
}
|
class ____<S> extends RecursiveActionValuesCollector<S> {
private final String className;
private S result;
private Throwable throwable;
private final Function<String, S> transformer;
public ServiceInstanceLoader(String className, Function<String, S> transformer) {
this.className = className;
this.transformer = transformer;
}
@Override
protected void compute() {
try {
result = transformer.apply(className);
} catch (Throwable e) {
throwable = e;
}
}
@Override
public void consume(Consumer<? super S> consumer) {
if (throwable != null) {
throw new SoftServiceLoader.ServiceLoadingException("Failed to load a service: " + throwable.getMessage(), throwable);
}
if (result != null) {
consumer.accept(result);
}
}
}
/**
* Abstract recursive action class.
*
* @param <S> The type
*/
private abstract static
|
ServiceInstanceLoader
|
java
|
hibernate__hibernate-orm
|
hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/CUBRIDDialect.java
|
{
"start": 3062,
"end": 15078
}
|
class ____ extends Dialect {
/**
* Constructs a CUBRIDDialect
*/
public CUBRIDDialect() {
super( SimpleDatabaseVersion.ZERO_VERSION );
}
@Override
protected String columnType(int sqlTypeCode) {
return switch ( sqlTypeCode ) {
case BOOLEAN -> "bit";
case TINYINT -> "smallint";
//'timestamp' has a very limited range
//'datetime' does not support explicit precision
//(always 3, millisecond precision)
case TIMESTAMP -> "datetime";
case TIME_WITH_TIMEZONE, TIMESTAMP_WITH_TIMEZONE -> "datetimetz";
default -> super.columnType( sqlTypeCode );
};
}
@Override
protected void registerColumnTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
super.registerColumnTypes( typeContributions, serviceRegistry );
final DdlTypeRegistry ddlTypeRegistry = typeContributions.getTypeConfiguration().getDdlTypeRegistry();
//precision of a Mimer 'float(p)' represents
//decimal digits instead of binary digits
ddlTypeRegistry.addDescriptor( new BinaryFloatDdlType( this ) );
//CUBRID has no 'binary' nor 'varbinary', but 'bit' is
//intended to be used for binary data (unfortunately the
//length parameter is measured in bits, not bytes)
ddlTypeRegistry.addDescriptor( new DdlTypeImpl( BINARY, "bit($l)", this ) );
ddlTypeRegistry.addDescriptor(
CapacityDependentDdlType.builder(
VARBINARY,
CapacityDependentDdlType.LobKind.BIGGEST_LOB,
columnType( BLOB ),
this
)
.withTypeCapacity( getMaxVarbinaryLength(), "bit varying($l)" )
.build()
);
}
@Override
protected void registerDefaultKeywords() {
super.registerDefaultKeywords();
registerKeyword( "TYPE" );
registerKeyword( "YEAR" );
registerKeyword( "MONTH" );
registerKeyword( "ALIAS" );
registerKeyword( "VALUE" );
registerKeyword( "FIRST" );
registerKeyword( "ROLE" );
registerKeyword( "CLASS" );
registerKeyword( "BIT" );
registerKeyword( "TIME" );
registerKeyword( "QUERY" );
registerKeyword( "DATE" );
registerKeyword( "USER" );
registerKeyword( "ACTION" );
registerKeyword( "SYS_USER" );
registerKeyword( "ZONE" );
registerKeyword( "LANGUAGE" );
registerKeyword( "DICTIONARY" );
registerKeyword( "DATA" );
registerKeyword( "TEST" );
registerKeyword( "SUPERCLASS" );
registerKeyword( "SECTION" );
registerKeyword( "LOWER" );
registerKeyword( "LIST" );
registerKeyword( "OID" );
registerKeyword( "DAY" );
registerKeyword( "IF" );
registerKeyword( "ATTRIBUTE" );
registerKeyword( "STRING" );
registerKeyword( "SEARCH" );
}
public CUBRIDDialect(DialectResolutionInfo info) {
this();
registerKeywords( info );
}
@Override
public int getDefaultStatementBatchSize() {
return 15;
}
@Override
public int getMaxVarcharLength() {
return 1_073_741_823;
}
@Override
public int getMaxVarbinaryLength() {
//note that the length of BIT VARYING in CUBRID is actually in bits
return 1_073_741_823;
}
@Override
public JdbcType resolveSqlTypeDescriptor(
String columnTypeName,
int jdbcTypeCode,
int precision,
int scale,
JdbcTypeRegistry jdbcTypeRegistry) {
if ( jdbcTypeCode == Types.BIT ) {
return jdbcTypeRegistry.getDescriptor( Types.BOOLEAN );
}
return super.resolveSqlTypeDescriptor(
columnTypeName,
jdbcTypeCode,
precision,
scale,
jdbcTypeRegistry
);
}
@Override
public int getPreferredSqlTypeCodeForBoolean() {
return Types.BIT;
}
//not used for anything right now, but it
//could be used for timestamp literal format
@Override
public int getDefaultTimestampPrecision() {
return 3;
}
@Override
public int getFloatPrecision() {
return 21; // -> 7 decimal digits
}
@Override
public void initializeFunctionRegistry(FunctionContributions functionContributions) {
super.initializeFunctionRegistry(functionContributions);
CommonFunctionFactory functionFactory = new CommonFunctionFactory(functionContributions);
functionFactory.trim2();
functionFactory.space();
functionFactory.reverse();
functionFactory.repeat();
functionFactory.crc32();
functionFactory.cot();
functionFactory.log2();
functionFactory.log10();
functionFactory.pi();
//rand() returns an integer between 0 and 231 on CUBRID
// functionFactory.rand();
functionFactory.radians();
functionFactory.degrees();
functionFactory.systimestamp();
//TODO: CUBRID also has systime()/sysdate() returning TIME/DATE
functionFactory.localtimeLocaltimestamp();
functionFactory.hourMinuteSecond();
functionFactory.yearMonthDay();
functionFactory.dayofweekmonthyear();
functionFactory.lastDay();
functionFactory.weekQuarter();
functionFactory.octetLength();
functionFactory.bitLength();
functionFactory.md5();
functionFactory.trunc();
// functionFactory.truncate();
functionFactory.toCharNumberDateTimestamp();
functionFactory.substr();
//also natively supports ANSI-style substring()
functionFactory.instr();
functionFactory.translate();
functionFactory.ceiling_ceil();
functionFactory.sha1();
functionFactory.sha2();
functionFactory.ascii();
functionFactory.char_chr();
functionFactory.position();
// functionFactory.concat_pipeOperator();
functionFactory.insert();
functionFactory.nowCurdateCurtime();
functionFactory.makedateMaketime();
functionFactory.bitandorxornot_bitAndOrXorNot();
functionFactory.median();
functionFactory.stddev();
functionFactory.stddevPopSamp();
functionFactory.variance();
functionFactory.varPopSamp();
functionFactory.datediff();
functionFactory.adddateSubdateAddtimeSubtime();
functionFactory.addMonths();
functionFactory.monthsBetween();
functionFactory.rownumInstOrderbyGroupbyNum();
functionFactory.regexpLike();
}
@Override
public boolean supportsColumnCheck() {
return false;
}
@Override
public SequenceSupport getSequenceSupport() {
return CUBRIDSequenceSupport.INSTANCE;
}
@Override
public String getDropForeignKeyString() {
return "drop foreign key";
}
@Override
public String getDropUniqueKeyString() {
return "drop index";
}
@Override
public boolean qualifyIndexName() {
return false;
}
@Override
public boolean supportsExistsInSelect() {
return false;
}
@Override
public String getQuerySequencesString() {
return "select * from db_serial";
}
@Override
public SequenceInformationExtractor getSequenceInformationExtractor() {
return SequenceInformationExtractorCUBRIDDatabaseImpl.INSTANCE;
}
@Override
public char openQuote() {
return '[';
}
@Override
public char closeQuote() {
return ']';
}
@Override
public LockingSupport getLockingSupport() {
return LockingSupportSimple.STANDARD_SUPPORT;
}
@Override
public String getForUpdateString() {
return "";
}
@Override
public boolean supportsCurrentTimestampSelection() {
return true;
}
@Override
public String getCurrentTimestampSelectString() {
return "select now()";
}
@Override
public boolean isCurrentTimestampSelectStringCallable() {
return false;
}
@Override
public boolean supportsIfExistsBeforeTableName() {
return true;
}
@Override
public boolean supportsTupleDistinctCounts() {
return false;
}
@Override
public boolean supportsOffsetInSubquery() {
return true;
}
@Override
public boolean supportsTemporaryTables() {
return false;
}
@Override
public SqlAstTranslatorFactory getSqlAstTranslatorFactory() {
return new StandardSqlAstTranslatorFactory() {
@Override
protected <T extends JdbcOperation> SqlAstTranslator<T> buildTranslator(
SessionFactoryImplementor sessionFactory, Statement statement) {
return new CUBRIDSqlAstTranslator<>( sessionFactory, statement );
}
};
}
@Override
public LimitHandler getLimitHandler() {
return LimitLimitHandler.INSTANCE;
}
@Override
public IdentityColumnSupport getIdentityColumnSupport() {
return CUBRIDIdentityColumnSupport.INSTANCE;
}
@Override
public boolean supportsPartitionBy() {
return true;
}
@Override
public void appendDatetimeFormat(SqlAppender appender, String format) {
//I do not know if CUBRID supports FM, but it
//seems that it does pad by default, so it needs it!
appender.appendSql(
OracleDialect.datetimeFormat( format, true, false )
.replace("SSSSSS", "FF")
.replace("SSSSS", "FF")
.replace("SSSS", "FF")
.replace("SSS", "FF")
.replace("SS", "FF")
.replace("S", "FF")
.result()
);
}
@Override
public long getFractionalSecondPrecisionInNanos() {
return 1_000_000; //milliseconds
}
/**
* CUBRID supports a limited list of temporal fields in the
* extract() function, but we can emulate some of them by
* using the appropriate named functions instead of
* extract().
*
* Thus, the additional supported fields are
* {@link TemporalUnit#DAY_OF_YEAR},
* {@link TemporalUnit#DAY_OF_MONTH},
* {@link TemporalUnit#DAY_OF_YEAR}.
*
* In addition, the field {@link TemporalUnit#SECOND} is
* redefined to include milliseconds.
*/
@Override
public String extractPattern(TemporalUnit unit) {
return switch (unit) {
case SECOND -> "(second(?2)+extract(millisecond from ?2)/1e3)";
case DAY_OF_WEEK -> "dayofweek(?2)";
case DAY_OF_MONTH ->"dayofmonth(?2)";
case DAY_OF_YEAR -> "dayofyear(?2)";
case WEEK -> "week(?2,3)"; //mode 3 is the ISO week
default -> "?1(?2)";
};
}
@Override
public TimeZoneSupport getTimeZoneSupport() {
return TimeZoneSupport.NATIVE;
}
@Override
public String timestampaddPattern(TemporalUnit unit, TemporalType temporalType, IntervalType intervalType) {
return switch (unit) {
case NANOSECOND -> "adddate(?3,interval (?2)/1e6 millisecond)";
case NATIVE -> "adddate(?3,interval ?2 millisecond)";
default -> "adddate(?3,interval ?2 ?1)";
};
}
@Override
public String timestampdiffPattern(TemporalUnit unit, TemporalType fromTemporalType, TemporalType toTemporalType) {
StringBuilder pattern = new StringBuilder();
switch ( unit ) {
case DAY:
//note: datediff() is backwards on CUBRID
return "datediff(?3,?2)";
case HOUR:
timediff(pattern, HOUR, unit);
break;
case MINUTE:
pattern.append("(");
timediff(pattern, MINUTE, unit);
pattern.append("+");
timediff(pattern, HOUR, unit);
pattern.append(")");
break;
case SECOND:
pattern.append("(");
timediff(pattern, SECOND, unit);
pattern.append("+");
timediff(pattern, MINUTE, unit);
pattern.append("+");
timediff(pattern, HOUR, unit);
pattern.append(")");
break;
case NATIVE:
case NANOSECOND:
pattern.append("(");
timediff(pattern, unit, unit);
pattern.append("+");
timediff(pattern, SECOND, unit);
pattern.append("+");
timediff(pattern, MINUTE, unit);
pattern.append("+");
timediff(pattern, HOUR, unit);
pattern.append(")");
break;
default:
throw new SemanticException("unsupported temporal unit for CUBRID: " + unit);
}
return pattern.toString();
}
private void timediff(
StringBuilder sqlAppender,
TemporalUnit diffUnit,
TemporalUnit toUnit) {
if ( diffUnit == NANOSECOND ) {
sqlAppender.append("1e6*");
}
sqlAppender.append("extract(");
if ( diffUnit == NANOSECOND || diffUnit == NATIVE ) {
sqlAppender.append("millisecond");
}
else {
sqlAppender.append("?1");
}
//note: timediff() is backwards on CUBRID
sqlAppender.append(",timediff(?3,?2))");
sqlAppender.append( diffUnit.conversionFactor( toUnit, this ) );
}
@Override
public String getDual() {
//TODO: is this really needed?
//TODO: would "from table({0})" be better?
return "db_root";
}
@Override
public String getFromDualForSelectOnly() {
return " from " + getDual();
}
@Override
public boolean supportsRowValueConstructorSyntax() {
return false;
}
@Override
public boolean supportsRowValueConstructorSyntaxInQuantifiedPredicates() {
return false;
}
@Override
public boolean supportsRowValueConstructorSyntaxInInList() {
return false;
}
}
|
CUBRIDDialect
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring/src/main/java/org/apache/camel/spring/SpringCamelContext.java
|
{
"start": 5738,
"end": 7630
}
|
interface ____
// would invoke start() method, but in order to do that
// SpringCamelContext needs to implement SmartLifecycle
// (look at DefaultLifecycleProcessor::startBeans), but it
// cannot implement it as it already implements
// RuntimeConfiguration, and both SmartLifecycle and
// RuntimeConfiguration declare isAutoStartup method but
// with boolean and Boolean return types, and covariant
// methods with primitive types are not allowed by the JLS
// so we need to listen for ContextRefreshedEvent and start
// on its reception
start();
}
if (eventComponent != null) {
eventComponent.onApplicationEvent(event);
}
}
@Override
public int getOrder() {
// SpringCamelContext implements Ordered so that it's the last
// in ApplicationListener to receive events, this is important
// for startup as we want all resources to be ready and all
// routes added to the context (see
// org.apache.camel.spring.boot.RoutesCollector)
// and we need to be after CamelContextFactoryBean
return LOWEST_PRECEDENCE;
}
// Properties
// -----------------------------------------------------------------------
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
ClassLoader cl;
// set the application context classloader
if (applicationContext != null && applicationContext.getClassLoader() != null) {
cl = applicationContext.getClassLoader();
} else {
LOG.warn("Cannot find the
|
that
|
java
|
spring-cloud__spring-cloud-gateway
|
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/handler/predicate/MethodRoutePredicateFactory.java
|
{
"start": 1902,
"end": 2120
}
|
class ____ {
private HttpMethod[] methods = new HttpMethod[0];
public HttpMethod[] getMethods() {
return methods;
}
public void setMethods(HttpMethod... methods) {
this.methods = methods;
}
}
}
|
Config
|
java
|
micronaut-projects__micronaut-core
|
http-server-netty/src/main/java/io/micronaut/http/server/netty/binders/NettyCompletableFutureBodyBinder.java
|
{
"start": 1453,
"end": 3652
}
|
class ____
implements NonBlockingBodyArgumentBinder<CompletableFuture<?>> {
private static final Argument<CompletableFuture<?>> TYPE = (Argument) Argument.of(CompletableFuture.class);
private final NettyBodyAnnotationBinder<Object> nettyBodyAnnotationBinder;
/**
* @param nettyBodyAnnotationBinder The body binder
*/
NettyCompletableFutureBodyBinder(NettyBodyAnnotationBinder<Object> nettyBodyAnnotationBinder) {
this.nettyBodyAnnotationBinder = nettyBodyAnnotationBinder;
}
@NonNull
@Override
public List<Class<?>> superTypes() {
return Arrays.asList(CompletionStage.class, Future.class);
}
@Override
public Argument<CompletableFuture<?>> argumentType() {
return TYPE;
}
@Override
public BindingResult<CompletableFuture<?>> bind(ArgumentConversionContext<CompletableFuture<?>> context, HttpRequest<?> source) {
if (source instanceof NettyHttpRequest<?> nhr) {
ByteBody rootBody = nhr.byteBody();
if (rootBody.expectedLength().orElse(-1) == 0) {
return BindingResult.empty();
}
Optional<Argument<?>> firstTypeParameter = context.getFirstTypeVariable();
Argument<?> targetType = firstTypeParameter.orElse(Argument.OBJECT_ARGUMENT);
CompletableFuture<Object> future = InternalByteBody.bufferFlow(rootBody)
.map(bytes -> {
Optional<Object> value;
try {
//noinspection unchecked
value = nettyBodyAnnotationBinder.transform(nhr, (ArgumentConversionContext<Object>) context.with(targetType), bytes);
} catch (RuntimeException e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(e);
}
return value.orElseThrow(() -> NettyPublisherBodyBinder.extractError(null, context));
}).toCompletableFuture();
return () -> Optional.of(future);
} else {
return BindingResult.empty();
}
}
}
|
NettyCompletableFutureBodyBinder
|
java
|
elastic__elasticsearch
|
libs/entitlement/tools/public-callers-finder/src/main/java/org/elasticsearch/entitlement/tools/publiccallersfinder/FindUsagesClassVisitor.java
|
{
"start": 3291,
"end": 4894
}
|
class ____ extends MethodVisitor {
private final String methodName;
private int line;
private final String methodDescriptor;
private final int methodAccess;
protected FindUsagesMethodVisitor(MethodVisitor mv, String methodName, String methodDescriptor, int methodAccess) {
super(ASM9, mv);
this.methodName = methodName;
this.methodDescriptor = methodDescriptor;
this.methodAccess = methodAccess;
}
@Override
public void visitMethodInsn(int opcode, String owner, String name, String descriptor, boolean isInterface) {
super.visitMethodInsn(opcode, owner, name, descriptor, isInterface);
if (methodToFind.className.equals(owner)
&& methodToFind.methodName.equals(name)
&& (methodToFind.methodDescriptor == null || methodToFind.methodDescriptor.equals(descriptor))) {
MethodDescriptor method = new MethodDescriptor(className, methodName, methodDescriptor);
EnumSet<ExternalAccess> externalAccess = ExternalAccess.fromPermissions(
isPublicAccessible.test(method),
(methodAccess & ACC_PUBLIC) != 0,
(methodAccess & ACC_PROTECTED) != 0
);
callers.accept(source, line, method, externalAccess);
}
}
@Override
public void visitLineNumber(int line, Label start) {
super.visitLineNumber(line, start);
this.line = line;
}
}
}
|
FindUsagesMethodVisitor
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayAutoTypeTest.java
|
{
"start": 320,
"end": 1565
}
|
class ____ extends TestCase {
public void test_for_issue_x() throws Exception {
String json = "[\"@type\":\"B\",\"chengchao\",1001]";
A a = JSON.parseObject(json, A.class, Feature.SupportAutoType, Feature.SupportArrayToBean);
B b = (B) a;
}
public void test_for_issue() throws Exception {
Model m = new Model();
m.value = new B(1001, "chengchao");
String json = JSON.toJSONString(m);
assertEquals("{\"value\":[\"@type\":\"B\",\"chengchao\",1001]}", json);
Model m1 = JSON.parseObject(json, Model.class, Feature.SupportAutoType);
assertEquals(m.value.getClass(), m1.value.getClass());
assertEquals(json, JSON.toJSONString(m1));
}
public void test_for_issue_1() throws Exception {
Model m = new Model();
m.value = new C(1001, 58);
String json = JSON.toJSONString(m);
assertEquals("{\"value\":[\"@type\":\"C\",58,1001]}", json);
Model m1 = JSON.parseObject(json, Model.class, Feature.SupportAutoType);
assertEquals(m.value.getClass(), m1.value.getClass());
assertEquals(json, JSON.toJSONString(m1));
}
@JSONType(seeAlso = {B.class, C.class})
public static
|
BeanToArrayAutoTypeTest
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/tools/GetUserMappingsProtocol.java
|
{
"start": 1225,
"end": 1666
}
|
interface ____ {
/**
* Version 1: Initial version.
*/
public static final long versionID = 1L;
/**
* Get the groups which are mapped to the given user.
* @param user The user to get the groups for.
* @return The set of groups the user belongs to.
* @throws IOException raised on errors performing I/O.
*/
@Idempotent
public String[] getGroupsForUser(String user) throws IOException;
}
|
GetUserMappingsProtocol
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/assumptions/BDDAssumptionsTest.java
|
{
"start": 15660,
"end": 15867
}
|
class ____ specific assertion
thenCode(() -> given(actual).isNotNull()).doesNotThrowAnyException();
}
@Test
void should_ignore_test_when_assumption_fails() {
// FIXME replace with
|
loader
|
java
|
apache__kafka
|
server/src/test/java/org/apache/kafka/server/share/fetch/DelayedShareFetchKeyTest.java
|
{
"start": 1171,
"end": 2763
}
|
class ____ {
@Test
public void testDelayedShareFetchEqualsAndHashcode() {
Uuid topicUuid = Uuid.randomUuid();
TopicIdPartition tp0 = new TopicIdPartition(topicUuid, new TopicPartition("topic", 0));
TopicIdPartition tp1 = new TopicIdPartition(topicUuid, new TopicPartition("topic", 1));
TopicIdPartition tp2 = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("topic2", 0));
Map<String, DelayedShareFetchKey> keyMap = Map.of(
"key0", new DelayedShareFetchGroupKey("grp", tp0.topicId(), tp0.partition()),
"key1", new DelayedShareFetchGroupKey("grp", tp1.topicId(), tp1.partition()),
"key2", new DelayedShareFetchGroupKey("grp", tp2.topicId(), tp2.partition()),
"key3", new DelayedShareFetchGroupKey("grp2", tp0.topicId(), tp0.partition()),
"key4", new DelayedShareFetchGroupKey("grp2", tp1.topicId(), tp1.partition()),
"key5", new DelayedShareFetchPartitionKey(tp0.topicId(), tp0.partition()),
"key6", new DelayedShareFetchPartitionKey(tp1.topicId(), tp1.partition()),
"key7", new DelayedShareFetchPartitionKey(tp2.topicId(), tp2.partition())
);
keyMap.forEach((key1, value1) -> keyMap.forEach((key2, value2) -> {
if (key1.equals(key2)) {
assertEquals(value1, value2);
assertEquals(value1.hashCode(), value2.hashCode());
} else {
assertNotEquals(value1, value2);
}
}));
}
}
|
DelayedShareFetchKeyTest
|
java
|
alibaba__fastjson
|
src/main/java/com/alibaba/fastjson/serializer/AnnotationSerializer.java
|
{
"start": 406,
"end": 4067
}
|
class ____ implements ObjectSerializer {
private static volatile Class sun_AnnotationType = null;
private static volatile boolean sun_AnnotationType_error = false;
private static volatile Method sun_AnnotationType_getInstance = null;
private static volatile Method sun_AnnotationType_members = null;
public static AnnotationSerializer instance = new AnnotationSerializer();
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
Class objClass = object.getClass();
Class[] interfaces = objClass.getInterfaces();
if (interfaces.length == 1 && interfaces[0].isAnnotation()) {
Class annotationClass = interfaces[0];
if (sun_AnnotationType == null && !sun_AnnotationType_error) {
try {
sun_AnnotationType = Class.forName("sun.reflect.annotation.AnnotationType");
} catch (Throwable ex) {
sun_AnnotationType_error = true;
throw new JSONException("not support Type Annotation.", ex);
}
}
if (sun_AnnotationType == null) {
throw new JSONException("not support Type Annotation.");
}
if (sun_AnnotationType_getInstance == null && !sun_AnnotationType_error) {
try {
sun_AnnotationType_getInstance = sun_AnnotationType.getMethod("getInstance", Class.class);
} catch (Throwable ex) {
sun_AnnotationType_error = true;
throw new JSONException("not support Type Annotation.", ex);
}
}
if (sun_AnnotationType_members == null && !sun_AnnotationType_error) {
try {
sun_AnnotationType_members = sun_AnnotationType.getMethod("members");
} catch (Throwable ex) {
sun_AnnotationType_error = true;
throw new JSONException("not support Type Annotation.", ex);
}
}
if (sun_AnnotationType_getInstance == null || sun_AnnotationType_error) {
throw new JSONException("not support Type Annotation.");
}
Object type;
try {
type = sun_AnnotationType_getInstance.invoke(null, annotationClass);
} catch (Throwable ex) {
sun_AnnotationType_error = true;
throw new JSONException("not support Type Annotation.", ex);
}
Map<String, Method> members;
try {
members = (Map<String, Method>) sun_AnnotationType_members.invoke(type);
} catch (Throwable ex) {
sun_AnnotationType_error = true;
throw new JSONException("not support Type Annotation.", ex);
}
JSONObject json = new JSONObject(members.size());
Iterator<Map.Entry<String, Method>> iterator = members.entrySet().iterator();
Map.Entry<String, Method> entry;
Object val = null;
while (iterator.hasNext()) {
entry = iterator.next();
try {
val = entry.getValue().invoke(object);
} catch (IllegalAccessException e) {
// skip
} catch (InvocationTargetException e) {
// skip
}
json.put(entry.getKey(), JSON.toJSON(val));
}
serializer.write(json);
return;
}
}
}
|
AnnotationSerializer
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LanguageEndpointBuilderFactory.java
|
{
"start": 17208,
"end": 17535
}
|
class ____ extends AbstractEndpointBuilder implements LanguageEndpointBuilder, AdvancedLanguageEndpointBuilder {
public LanguageEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new LanguageEndpointBuilderImpl(path);
}
}
|
LanguageEndpointBuilderImpl
|
java
|
apache__logging-log4j2
|
log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/util/NoOpJULHandler.java
|
{
"start": 1024,
"end": 1326
}
|
class ____ extends Handler {
public AtomicLong count = new AtomicLong();
@Override
public void publish(final LogRecord record) {
count.incrementAndGet();
}
@Override
public void flush() {}
@Override
public void close() throws SecurityException {}
}
|
NoOpJULHandler
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/deployment/ResultPartitionDeploymentDescriptorTest.java
|
{
"start": 2057,
"end": 6498
}
|
class ____ {
private static final IntermediateDataSetID resultId = new IntermediateDataSetID();
private static final int numberOfPartitions = 5;
private static final IntermediateResultPartitionID partitionId =
new IntermediateResultPartitionID();
private static final ExecutionAttemptID producerExecutionId = createExecutionAttemptId();
private static final ResultPartitionType partitionType = ResultPartitionType.PIPELINED;
private static final int numberOfSubpartitions = 24;
private static final int connectionIndex = 10;
private static final boolean isBroadcast = false;
private static final boolean isAllToAllDistribution = true;
private static final PartitionDescriptor partitionDescriptor =
new PartitionDescriptor(
resultId,
numberOfPartitions,
partitionId,
partitionType,
numberOfSubpartitions,
connectionIndex,
isBroadcast,
isAllToAllDistribution,
false);
private static final ResultPartitionID resultPartitionID =
new ResultPartitionID(partitionId, producerExecutionId);
private static final ResourceID producerLocation = new ResourceID("producerLocation");
private static final InetSocketAddress address = new InetSocketAddress("localhost", 10000);
private static final ConnectionID connectionID =
new ConnectionID(producerLocation, address, connectionIndex);
/** Tests simple de/serialization with {@link UnknownShuffleDescriptor}. */
@Test
void testSerializationOfUnknownShuffleDescriptor() throws IOException {
ShuffleDescriptor shuffleDescriptor = new UnknownShuffleDescriptor(resultPartitionID);
ShuffleDescriptor shuffleDescriptorCopy =
CommonTestUtils.createCopySerializable(shuffleDescriptor);
assertThat(shuffleDescriptorCopy).isInstanceOf(UnknownShuffleDescriptor.class);
assertThat(resultPartitionID).isEqualTo(shuffleDescriptorCopy.getResultPartitionID());
assertThat(shuffleDescriptorCopy.isUnknown()).isTrue();
}
/** Tests simple de/serialization with {@link NettyShuffleDescriptor}. */
@Test
void testSerializationWithNettyShuffleDescriptor() throws IOException {
ShuffleDescriptor shuffleDescriptor =
new NettyShuffleDescriptor(
producerLocation,
new NetworkPartitionConnectionInfo(address, connectionIndex),
resultPartitionID);
ResultPartitionDeploymentDescriptor copy =
createCopyAndVerifyResultPartitionDeploymentDescriptor(shuffleDescriptor);
assertThat(copy.getShuffleDescriptor()).isInstanceOf(NettyShuffleDescriptor.class);
NettyShuffleDescriptor shuffleDescriptorCopy =
(NettyShuffleDescriptor) copy.getShuffleDescriptor();
assertThat(resultPartitionID).isEqualTo(shuffleDescriptorCopy.getResultPartitionID());
assertThat(shuffleDescriptorCopy.isUnknown()).isFalse();
assertThat(shuffleDescriptorCopy.isLocalTo(producerLocation)).isTrue();
assertThat(connectionID).isEqualTo(shuffleDescriptorCopy.getConnectionId());
}
private static ResultPartitionDeploymentDescriptor
createCopyAndVerifyResultPartitionDeploymentDescriptor(
ShuffleDescriptor shuffleDescriptor) throws IOException {
ResultPartitionDeploymentDescriptor orig =
new ResultPartitionDeploymentDescriptor(
partitionDescriptor, shuffleDescriptor, numberOfSubpartitions);
ResultPartitionDeploymentDescriptor copy = CommonTestUtils.createCopySerializable(orig);
verifyResultPartitionDeploymentDescriptorCopy(copy);
return copy;
}
private static void verifyResultPartitionDeploymentDescriptorCopy(
ResultPartitionDeploymentDescriptor copy) {
assertThat(resultId).isEqualTo(copy.getResultId());
assertThat(numberOfPartitions).isEqualTo(copy.getTotalNumberOfPartitions());
assertThat(partitionId).isEqualTo(copy.getPartitionId());
assertThat(partitionType).isEqualTo(copy.getPartitionType());
assertThat(numberOfSubpartitions).isEqualTo(copy.getNumberOfSubpartitions());
}
}
|
ResultPartitionDeploymentDescriptorTest
|
java
|
google__error-prone
|
check_api/src/test/java/com/google/errorprone/util/FindIdentifiersTest.java
|
{
"start": 20129,
"end": 20222
}
|
enum ____ {
FOO,
BAR,
BAZ;
static
|
MyEnum
|
java
|
apache__kafka
|
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/ExactlyOnceWorkerSourceTask.java
|
{
"start": 23641,
"end": 25029
}
|
class ____ implements AutoCloseable {
private final Sensor transactionSize;
private int size;
private final ConnectMetrics.MetricGroup metricGroup;
public TransactionMetricsGroup(ConnectorTaskId id, ConnectMetrics connectMetrics) {
ConnectMetricsRegistry registry = connectMetrics.registry();
metricGroup = connectMetrics.group(registry.sourceTaskGroupName(),
registry.connectorTagName(), id.connector(),
registry.taskTagName(), Integer.toString(id.task()));
transactionSize = metricGroup.sensor("transaction-size");
transactionSize.add(metricGroup.metricName(registry.transactionSizeAvg), new Avg());
transactionSize.add(metricGroup.metricName(registry.transactionSizeMin), new Min());
transactionSize.add(metricGroup.metricName(registry.transactionSizeMax), new Max());
}
@Override
public void close() {
metricGroup.close();
}
void addRecord() {
size++;
}
void abortTransaction() {
size = 0;
}
void commitTransaction() {
transactionSize.record(size);
size = 0;
}
protected ConnectMetrics.MetricGroup metricGroup() {
return metricGroup;
}
}
}
|
TransactionMetricsGroup
|
java
|
spring-projects__spring-security
|
core/src/main/java/org/springframework/security/authorization/method/NullReturningMethodAuthorizationDeniedHandler.java
|
{
"start": 1087,
"end": 1730
}
|
class ____ implements MethodAuthorizationDeniedHandler {
@Override
public @Nullable Object handleDeniedInvocation(MethodInvocation methodInvocation,
AuthorizationResult authorizationResult) {
if (authorizationResult instanceof AuthorizationDeniedException exception) {
throw exception;
}
return null;
}
@Override
public @Nullable Object handleDeniedInvocationResult(MethodInvocationResult methodInvocationResult,
AuthorizationResult authorizationResult) {
if (authorizationResult instanceof AuthorizationDeniedException exception) {
throw exception;
}
return null;
}
}
|
NullReturningMethodAuthorizationDeniedHandler
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_3331/Vehicle.java
|
{
"start": 737,
"end": 1091
}
|
class ____ extends Vehicle {
private final boolean allowedForMinor;
public Motorbike(String name, boolean allowedForMinor) {
super( name );
this.allowedForMinor = allowedForMinor;
}
public boolean isAllowedForMinor() {
return allowedForMinor;
}
}
public static
|
Motorbike
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/contract/ftp/TestFTPContractRename.java
|
{
"start": 1115,
"end": 2140
}
|
class ____ extends AbstractContractRenameTest {
@Override
protected AbstractFSContract createContract(Configuration conf) {
return new FTPContract(conf);
}
/**
* Check the exception was about cross-directory renames
* -if not, rethrow it.
* @param e exception raised
* @throws IOException
*/
private void verifyUnsupportedDirRenameException(IOException e) throws IOException {
if (!e.toString().contains(FTPFileSystem.E_SAME_DIRECTORY_ONLY)) {
throw e;
}
}
@Override
public void testRenameDirIntoExistingDir() throws Throwable {
try {
super.testRenameDirIntoExistingDir();
fail("Expected a failure");
} catch (IOException e) {
verifyUnsupportedDirRenameException(e);
}
}
@Override
public void testRenameFileNonexistentDir() throws Throwable {
try {
super.testRenameFileNonexistentDir();
fail("Expected a failure");
} catch (IOException e) {
verifyUnsupportedDirRenameException(e);
}
}
}
|
TestFTPContractRename
|
java
|
mockito__mockito
|
mockito-core/src/main/java/org/mockito/internal/debugging/LocationImpl.java
|
{
"start": 5650,
"end": 6740
}
|
class ____ implements StackFrameMetadata, Serializable {
private static final long serialVersionUID = 8491903719411428648L;
private final StackFrame stackFrame;
private MetadataShim(StackFrame stackFrame) {
this.stackFrame = stackFrame;
}
@Override
public String getClassName() {
return stackFrame.getClassName();
}
@Override
public String getMethodName() {
return stackFrame.getMethodName();
}
@Override
public String getFileName() {
return stackFrame.getFileName();
}
@Override
public int getLineNumber() {
return stackFrame.getLineNumber();
}
@Override
public String toString() {
return stackFrame.toString();
}
/**
* Ensure that this type remains serializable.
*/
private Object writeReplace() {
return new SerializableShim(stackFrame.toStackTraceElement());
}
}
private static final
|
MetadataShim
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/javadoc/EmptyBlockTagTest.java
|
{
"start": 5633,
"end": 5961
}
|
interface ____ {
/**
* @return A value
*/
int foo();
}
""")
.doTest();
}
@Test
public void keeps_deprecatedWithDescription() {
compilationTestHelper
.addSourceLines(
"Test.java",
"""
|
Test
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/util/internal/PrivateMaxEntriesMap.java
|
{
"start": 33743,
"end": 34386
}
|
class ____ implements Iterator<V> {
final Iterator<Node<K, V>> iterator = data.values().iterator();
Node<K, V> current;
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public V next() {
current = iterator.next();
return current.getValue();
}
@Override
public void remove() {
checkState(current != null);
PrivateMaxEntriesMap.this.remove(current.key);
current = null;
}
}
/** An adapter to safely externalize the entries. */
final
|
ValueIterator
|
java
|
hibernate__hibernate-orm
|
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh18829/AutoGeneratedIdClassTest.java
|
{
"start": 2692,
"end": 2882
}
|
class ____ be a record" );
assertArrayEquals(
idComponentNames,
Arrays.stream( idClass.getRecordComponents() ).map( RecordComponent::getName ).toArray( String[]::new )
);
}
}
|
should
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/state/changelog/LocalChangelogRegistry.java
|
{
"start": 1193,
"end": 2399
}
|
interface ____ extends Closeable {
LocalChangelogRegistry NO_OP =
new LocalChangelogRegistry() {
@Override
public void register(StreamStateHandle handle, long checkpointID) {}
@Override
public void discardUpToCheckpoint(long upTo) {}
@Override
public void close() throws IOException {}
};
/**
* Called upon ChangelogKeyedStateBackend#notifyCheckpointComplete.
*
* @param handle handle to register.
* @param checkpointID latest used checkpointID.
*/
void register(StreamStateHandle handle, long checkpointID);
/**
* Called upon ChangelogKeyedStateBackend#notifyCheckpointComplete and
* ChangelogKeyedStateBackend#notifyCheckpointSubsumed. Remote dstl handles are unregistered
* when {@link CompletedCheckpointStore#addCheckpointAndSubsumeOldestOne}, local dtsl handles
* are unregistered when the checkpoint completes, because only one checkpoint is kept for local
* recovery.
*
* @param upTo lowest CheckpointID which is still valid.
*/
void discardUpToCheckpoint(long upTo);
}
|
LocalChangelogRegistry
|
java
|
micronaut-projects__micronaut-core
|
http-client-tck/src/main/java/io/micronaut/http/client/tck/tests/ContentLengthHeaderTest.java
|
{
"start": 3258,
"end": 4044
}
|
class ____ implements HttpHandler {
private String header(Headers requestHeaders, String name) {
if (requestHeaders.containsKey(name)) {
return String.join(", ", requestHeaders.get(name));
} else {
return "";
}
}
@Override
public void handle(HttpExchange exchange) throws IOException {
String method = exchange.getRequestMethod();
String contentLength = header(exchange.getRequestHeaders(), CONTENT_LENGTH);
exchange.sendResponseHeaders(200, 0);
try (var os = exchange.getResponseBody()) {
os.write("%s:%s".formatted(method, contentLength).getBytes());
}
exchange.close();
}
}
}
|
MyHandler
|
java
|
apache__kafka
|
streams/src/main/java/org/apache/kafka/streams/kstream/internals/foreignkeyjoin/ForeignKeyExtractor.java
|
{
"start": 952,
"end": 1201
}
|
interface ____ extracting foreign keys from input records during foreign key joins in Kafka Streams.
* This extractor is used to determine the key of the foreign table to join with based on the primary
* table's record key and value.
* <p>
* The
|
for
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java
|
{
"start": 25667,
"end": 25769
}
|
class ____ {
@GetMapping("/")
String home() {
return "home";
}
}
static
|
HomeController
|
java
|
redisson__redisson
|
redisson/src/test/java/org/redisson/RedissonSetCacheReactiveTest.java
|
{
"start": 601,
"end": 11348
}
|
class ____ implements Serializable {
private Long lng;
public Long getLng() {
return lng;
}
public void setLng(Long lng) {
this.lng = lng;
}
}
@Test
public void testBatchScriptCache() throws InterruptedException {
Config config = new Config();
config.setUseScriptCache(true);
config.useSingleServer()
.setAddress(redisson.getConfig().useSingleServer().getAddress());
RedissonReactiveClient client = Redisson.create(config).reactive();
RBatchReactive batch = client.createBatch();
Mono<Boolean> setResult = batch.getSetCache("test2",
StringCodec.INSTANCE)
.add("setValue", 10, TimeUnit.SECONDS);
Thread.sleep(400);
Mono<Integer> monoMsSetSize = batch.getSetCache("test2",
StringCodec.INSTANCE).size();
batch.execute().subscribe();
Integer v = Mono.zip(setResult, monoMsSetSize).flatMap(touple -> {
return Mono.just(touple.getT2());
}).block();
assertThat(v).isEqualTo(1);
client.shutdown();
}
@Test
public void testAddBean() throws InterruptedException, ExecutionException {
SimpleBean sb = new SimpleBean();
sb.setLng(1L);
RSetCacheReactive<SimpleBean> set = redisson.getSetCache("simple");
sync(set.add(sb));
Assertions.assertEquals(sb.getLng(), toIterator(set.iterator()).next().getLng());
}
@Test
public void testAddExpire() throws InterruptedException, ExecutionException {
RSetCacheReactive<String> set = redisson.getSetCache("simple3");
sync(set.add("123", 1, TimeUnit.SECONDS));
assertThat(sync(set)).containsOnly("123");
Thread.sleep(1000);
Assertions.assertFalse(sync(set.contains("123")));
}
@Test
public void testAddExpireTwise() throws InterruptedException, ExecutionException {
RSetCacheReactive<String> set = redisson.getSetCache("simple31");
sync(set.add("123", 1, TimeUnit.SECONDS));
Thread.sleep(1000);
Assertions.assertFalse(sync(set.contains("123")));
sync(set.add("4341", 1, TimeUnit.SECONDS));
Thread.sleep(1000);
Assertions.assertFalse(sync(set.contains("4341")));
}
@Test
public void testExpireOverwrite() throws InterruptedException, ExecutionException {
RSetCacheReactive<String> set = redisson.getSetCache("simple");
assertThat(sync(set.add("123", 1, TimeUnit.SECONDS))).isTrue();
Thread.sleep(800);
assertThat(sync(set.add("123", 1, TimeUnit.SECONDS))).isFalse();
Thread.sleep(800);
assertThat(sync(set.contains("123"))).isTrue();
Thread.sleep(250);
assertThat(sync(set.contains("123"))).isFalse();
}
@Test
public void testRemove() throws InterruptedException, ExecutionException {
RSetCacheReactive<Integer> set = redisson.getSetCache("simple");
sync(set.add(1, 1, TimeUnit.SECONDS));
sync(set.add(3, 2, TimeUnit.SECONDS));
sync(set.add(7, 3, TimeUnit.SECONDS));
Assertions.assertTrue(sync(set.remove(1)));
Assertions.assertFalse(sync(set.contains(1)));
assertThat(sync(set)).contains(3, 7);
Assertions.assertFalse(sync(set.remove(1)));
assertThat(sync(set)).contains(3, 7);
Assertions.assertTrue(sync(set.remove(3)));
Assertions.assertFalse(sync(set.contains(3)));
assertThat(sync(set)).contains(7);
Assertions.assertEquals(1, sync(set.size()).intValue());
}
@Test
public void testIteratorSequence() throws InterruptedException {
RSetCacheReactive<Long> set = redisson.getSetCache("set");
for (int i = 0; i < 1000; i++) {
sync(set.add(Long.valueOf(i)));
}
Thread.sleep(1000);
assertThat(sync(set.size())).isEqualTo(1000);
Set<Long> setCopy = new HashSet<Long>();
for (int i = 0; i < 1000; i++) {
setCopy.add(Long.valueOf(i));
}
checkIterator(set, setCopy);
}
private void checkIterator(RSetCacheReactive<Long> set, Set<Long> setCopy) {
for (Iterator<Long> iterator = toIterator(set.iterator()); iterator.hasNext();) {
Long value = iterator.next();
if (!setCopy.remove(value)) {
Assertions.fail();
}
}
Assertions.assertEquals(0, setCopy.size());
}
@Test
public void testRetainAll() {
RSetCacheReactive<Integer> set = redisson.getSetCache("set");
for (int i = 0; i < 10000; i++) {
sync(set.add(i));
sync(set.add(i*10, 10, TimeUnit.SECONDS));
}
Assertions.assertTrue(sync(set.retainAll(Arrays.asList(1, 2))));
assertThat(sync(set)).contains(1, 2);
Assertions.assertEquals(2, sync(set.size()).intValue());
}
@Test
public void testContainsAll() {
RSetCacheReactive<Integer> set = redisson.getSetCache("set");
for (int i = 0; i < 200; i++) {
sync(set.add(i));
}
Assertions.assertTrue(sync(set.containsAll(Collections.emptyList())));
Assertions.assertTrue(sync(set.containsAll(Arrays.asList(30, 11))));
Assertions.assertFalse(sync(set.containsAll(Arrays.asList(30, 711, 11))));
}
@Test
public void testContains() throws InterruptedException {
RSetCacheReactive<TestObject> set = redisson.getSetCache("set");
sync(set.add(new TestObject("1", "2")));
sync(set.add(new TestObject("1", "2")));
sync(set.add(new TestObject("2", "3"), 1, TimeUnit.SECONDS));
sync(set.add(new TestObject("3", "4")));
sync(set.add(new TestObject("5", "6")));
Thread.sleep(1000);
Assertions.assertFalse(sync(set.contains(new TestObject("2", "3"))));
Assertions.assertTrue(sync(set.contains(new TestObject("1", "2"))));
Assertions.assertFalse(sync(set.contains(new TestObject("1", "9"))));
}
@Test
public void testDuplicates() {
RSetCacheReactive<TestObject> set = redisson.getSetCache("set");
sync(set.add(new TestObject("1", "2")));
sync(set.add(new TestObject("1", "2")));
sync(set.add(new TestObject("2", "3")));
sync(set.add(new TestObject("3", "4")));
sync(set.add(new TestObject("5", "6")));
Assertions.assertEquals(4, sync(set.size()).intValue());
}
@Test
public void testSize() {
RSetCacheReactive<Integer> set = redisson.getSetCache("set");
Assertions.assertEquals(true, sync(set.add(1)));
Assertions.assertEquals(true, sync(set.add(2)));
Assertions.assertEquals(true, sync(set.add(3)));
Assertions.assertEquals(false, sync(set.add(3)));
Assertions.assertEquals(false, sync(set.add(3)));
Assertions.assertEquals(true, sync(set.add(4)));
Assertions.assertEquals(true, sync(set.add(5)));
Assertions.assertEquals(false, sync(set.add(5)));
Assertions.assertEquals(5, sync(set.size()).intValue());
}
@Test
public void testRetainAllEmpty() {
RSetCacheReactive<Integer> set = redisson.getSetCache("set");
sync(set.add(1));
sync(set.add(2));
sync(set.add(3));
sync(set.add(4));
sync(set.add(5));
Assertions.assertTrue(sync(set.retainAll(Collections.<Integer>emptyList())));
Assertions.assertEquals(0, sync(set.size()).intValue());
}
@Test
public void testRetainAllNoModify() {
RSetCacheReactive<Integer> set = redisson.getSetCache("set");
sync(set.add(1));
sync(set.add(2));
Assertions.assertFalse(sync(set.retainAll(Arrays.asList(1, 2)))); // nothing changed
assertThat(sync(set)).contains(1, 2);
}
@Test
public void testExpiredIterator() throws InterruptedException {
RSetCacheReactive<String> cache = redisson.getSetCache("simple");
sync(cache.add("0"));
sync(cache.add("1", 1, TimeUnit.SECONDS));
sync(cache.add("2", 3, TimeUnit.SECONDS));
sync(cache.add("3", 4, TimeUnit.SECONDS));
sync(cache.add("4", 1, TimeUnit.SECONDS));
Thread.sleep(1000);
assertThat(sync(cache)).contains("0", "2", "3");
}
@Test
public void testExpire() throws InterruptedException {
RSetCacheReactive<String> cache = redisson.getSetCache("simple");
sync(cache.add("8", 1, TimeUnit.SECONDS));
sync(cache.expire(100, TimeUnit.MILLISECONDS));
Thread.sleep(500);
Assertions.assertEquals(0, sync(cache.size()).intValue());
}
@Test
public void testExpireAt() throws InterruptedException {
RSetCacheReactive<String> cache = redisson.getSetCache("simple");
sync(cache.add("8", 1, TimeUnit.SECONDS));
sync(cache.expireAt(System.currentTimeMillis() + 100));
Thread.sleep(500);
Assertions.assertEquals(0, sync(cache.size()).intValue());
}
@Test
public void testClearExpire() throws InterruptedException {
RSetCacheReactive<String> cache = redisson.getSetCache("simple");
sync(cache.add("8", 1, TimeUnit.SECONDS));
sync(cache.expireAt(System.currentTimeMillis() + 100));
sync(cache.clearExpire());
Thread.sleep(500);
Assertions.assertEquals(1, sync(cache.size()).intValue());
}
@Test
public void testScheduler() throws InterruptedException {
RSetCacheReactive<String> cache = redisson.getSetCache("simple33");
Assertions.assertFalse(sync(cache.contains("33")));
Assertions.assertTrue(sync(cache.add("33", 5, TimeUnit.SECONDS)));
Thread.sleep(11000);
Assertions.assertEquals(0, sync(cache.size()).intValue());
}
@Test
public void testAddIfAbsentWithMapParam() throws InterruptedException {
sync(redisson.getKeys().flushall());
RSetCacheReactive<String> cache = redisson.getSetCache("cache");
Map<String, Duration> map = new HashMap<>();
map.put("key1", Duration.ofMinutes(1));
map.put("key2", Duration.ofMinutes(1));
assertThat(sync(cache.addIfAbsent(map))).isTrue();
map = new HashMap<>();
map.put("key1", Duration.ofMinutes(1));
assertThat(sync(cache.addIfAbsent(map))).isFalse();
map = new HashMap<>();
map.put("key3", Duration.ofSeconds(1));
assertThat(sync(cache.addIfAbsent(map))).isTrue();
Thread.sleep(1200);
assertThat(sync(cache.addIfAbsent(map))).isTrue();
sync((redisson.getKeys().flushall()));
}
}
|
SimpleBean
|
java
|
quarkusio__quarkus
|
extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/CompletionStageTest.java
|
{
"start": 2656,
"end": 4853
}
|
class ____ {
@Query
public CompletionStage<List<Book>> getBooks() {
return CompletableFuture.supplyAsync(() -> new ArrayList<>(BOOKS.values()));
}
@Query
public CompletionStage<Book> getBook(String name) {
return CompletableFuture.supplyAsync(() -> BOOKS.get(name));
}
public CompletionStage<String> getBuyLink(@Source Book book) {
String title = book.title.replaceAll(" ", "+");
return CompletableFuture.supplyAsync(() -> String.format(AMAZON_SEARCH_FORMAT, title));
}
public CompletionStage<List<List<Author>>> getAsyncAuthors(@Source List<Book> books) {
List<List<Author>> authorsOfAllBooks = new ArrayList<>();
for (Book book : books) {
List<Author> authors = new ArrayList<>();
for (String name : book.authors) {
authors.add(AUTHORS.get(name));
}
authorsOfAllBooks.add(authors);
}
return CompletableFuture.supplyAsync(() -> authorsOfAllBooks);
}
private static final String AMAZON_SEARCH_FORMAT = "https://www.amazon.com/s?k=%s&i=stripbooks-intl-ship";
private static Map<String, Book> BOOKS = new HashMap<>();
private static Map<String, Author> AUTHORS = new HashMap<>();
static {
Book book1 = new Book("0-571-05686-5", "Lord of the Flies", LocalDate.of(1954, Month.SEPTEMBER, 17),
"William Golding");
BOOKS.put(book1.title, book1);
AUTHORS.put("William Golding", new Author("William Golding", "William Gerald Golding",
LocalDate.of(1911, Month.SEPTEMBER, 19), "Newquay, Cornwall, England"));
Book book2 = new Book("0-582-53008-3", "Animal Farm", LocalDate.of(1945, Month.AUGUST, 17),
"George Orwell");
BOOKS.put(book2.title, book2);
AUTHORS.put("George Orwell", new Author("George Orwell", "Eric Arthur Blair", LocalDate.of(1903, Month.JUNE, 25),
"Motihari, Bengal Presidency, British India"));
}
}
public static
|
BookGraphQLApi
|
java
|
apache__camel
|
components/camel-jpa/src/test/java/org/apache/camel/processor/jpa/JpaWireTapTest.java
|
{
"start": 1145,
"end": 2804
}
|
class ____ extends AbstractJpaTest {
protected static final String SELECT_ALL_STRING = "select x from " + SendEmail.class.getName() + " x";
@Test
public void testRouteJpa() throws Exception {
// should auto setup transaction manager and entity factory
JpaComponent jpa = context.getComponent("jpa", JpaComponent.class);
assertNotNull(jpa.getEntityManagerFactory(), "Should have been auto assigned");
assertNotNull(jpa.getTransactionStrategy(), "Should have been auto assigned");
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(2);
template.sendBody("direct:start", new SendEmail("someone@somewhere.org"));
MockEndpoint.assertIsSatisfied(context);
assertEntityInDB(2);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start")
.to("jpa://" + SendEmail.class.getName())
.wireTap("direct:tap")
.to("mock:result");
from("direct:tap")
.delay(constant("1000"))
.setBody(constant(new SendEmail("me@you.org")))
.to("jpa://" + SendEmail.class.getName())
.to("mock:result");
}
};
}
@Override
protected String routeXml() {
return "org/apache/camel/processor/jpa/springJpaRouteTest.xml";
}
@Override
protected String selectAllString() {
return SELECT_ALL_STRING;
}
}
|
JpaWireTapTest
|
java
|
apache__kafka
|
streams/src/main/java/org/apache/kafka/streams/state/StateSerdes.java
|
{
"start": 1763,
"end": 7469
}
|
class ____ the value type
* @param <K> the key type
* @param <V> the value type
* @return a new instance of {@link StateSerdes}
*/
public static <K, V> StateSerdes<K, V> withBuiltinTypes(
final String topic,
final Class<K> keyClass,
final Class<V> valueClass) {
return new StateSerdes<>(topic, Serdes.serdeFrom(keyClass), Serdes.serdeFrom(valueClass));
}
private final String topic;
private final Serde<K> keySerde;
private final Serde<V> valueSerde;
/**
* Create a context for serialization using the specified serializers and deserializers which
* <em>must</em> match the key and value types used as parameters for this object; the state changelog topic
* is provided to bind this serde factory to, so that future calls for serialize / deserialize do not
* need to provide the topic name any more.
*
* @param topic the topic name
* @param keySerde the serde for keys; cannot be null
* @param valueSerde the serde for values; cannot be null
* @throws IllegalArgumentException if key or value serde is null
*/
public StateSerdes(final String topic,
final Serde<K> keySerde,
final Serde<V> valueSerde) {
Objects.requireNonNull(topic, "topic cannot be null");
Objects.requireNonNull(keySerde, "key serde cannot be null");
Objects.requireNonNull(valueSerde, "value serde cannot be null");
this.topic = topic;
this.keySerde = keySerde;
this.valueSerde = valueSerde;
}
/**
* Return the key serde.
*
* @return the key serde
*/
public Serde<K> keySerde() {
return keySerde;
}
/**
* Return the value serde.
*
* @return the value serde
*/
public Serde<V> valueSerde() {
return valueSerde;
}
/**
* Return the key deserializer.
*
* @return the key deserializer
*/
public Deserializer<K> keyDeserializer() {
return keySerde.deserializer();
}
/**
* Return the key serializer.
*
* @return the key serializer
*/
public Serializer<K> keySerializer() {
return keySerde.serializer();
}
/**
* Return the value deserializer.
*
* @return the value deserializer
*/
public Deserializer<V> valueDeserializer() {
return valueSerde.deserializer();
}
/**
* Return the value serializer.
*
* @return the value serializer
*/
public Serializer<V> valueSerializer() {
return valueSerde.serializer();
}
/**
* Return the topic.
*
* @return the topic
*/
public String topic() {
return topic;
}
/**
* Deserialize the key from raw bytes.
*
* @param rawKey the key as raw bytes
* @return the key as typed object
*/
public K keyFrom(final byte[] rawKey) {
return keySerde.deserializer().deserialize(topic, rawKey);
}
/**
* Deserialize the value from raw bytes.
*
* @param rawValue the value as raw bytes
* @return the value as typed object
*/
public V valueFrom(final byte[] rawValue) {
return valueSerde.deserializer().deserialize(topic, rawValue);
}
/**
* Serialize the given key.
*
* @param key the key to be serialized
* @return the serialized key
*/
public byte[] rawKey(final K key) {
try {
return keySerde.serializer().serialize(topic, key);
} catch (final ClassCastException e) {
final String keyClass = key == null ? "unknown because key is null" : key.getClass().getName();
throw new StreamsException(
String.format("A serializer (%s) is not compatible to the actual key type " +
"(key type: %s). Change the default Serdes in StreamConfig or " +
"provide correct Serdes via method parameters.",
keySerializer().getClass().getName(),
keyClass),
e);
}
}
/**
* Serialize the given value.
*
* @param value the value to be serialized
* @return the serialized value
*/
@SuppressWarnings("rawtypes")
public byte[] rawValue(final V value) {
try {
return valueSerde.serializer().serialize(topic, value);
} catch (final ClassCastException e) {
final String valueClass;
final Class<? extends Serializer> serializerClass;
if (valueSerializer() instanceof ValueAndTimestampSerializer) {
serializerClass = ((ValueAndTimestampSerializer<?>) valueSerializer()).valueSerializer.getClass();
valueClass = value == null ? "unknown because value is null" : ((ValueAndTimestamp) value).value().getClass().getName();
} else {
serializerClass = valueSerializer().getClass();
valueClass = value == null ? "unknown because value is null" : value.getClass().getName();
}
throw new StreamsException(
String.format("A serializer (%s) is not compatible to the actual value type " +
"(value type: %s). Change the default Serdes in StreamConfig or " +
"provide correct Serdes via method parameters.",
serializerClass.getName(),
valueClass),
e);
}
}
}
|
of
|
java
|
grpc__grpc-java
|
binder/src/main/java/io/grpc/binder/internal/ServiceBinding.java
|
{
"start": 2225,
"end": 2443
}
|
class ____ implements Bindable, ServiceConnection {
private static final Logger logger = Logger.getLogger(ServiceBinding.class.getName());
// States can only ever transition in one direction.
private
|
ServiceBinding
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/api/AbstractSoftAssertions.java
|
{
"start": 896,
"end": 4835
}
|
class ____ extends DefaultAssertionErrorCollector
implements SoftAssertionsProvider, InstanceOfAssertFactories {
final SoftProxies proxies;
protected AbstractSoftAssertions() {
// pass itself as an AssertionErrorCollector instance
proxies = new SoftProxies(this);
}
private static final AssertionErrorCreator ASSERTION_ERROR_CREATOR = new AssertionErrorCreator();
public static void assertAll(AssertionErrorCollector collector) {
List<AssertionError> errors = collector.assertionErrorsCollected();
if (!errors.isEmpty()) throw ASSERTION_ERROR_CREATOR.multipleSoftAssertionsError(errors);
}
@Override
public void assertAll() {
assertAll(this);
}
@Override
public <SELF extends Assert<? extends SELF, ? extends ACTUAL>, ACTUAL> SELF proxy(Class<SELF> assertClass,
Class<ACTUAL> actualClass, ACTUAL actual) {
return proxies.createSoftAssertionProxy(assertClass, actualClass, actual);
}
/**
* Fails with the given message.
*
* @param <T> dummy return value type
* @param failureMessage error message.
* @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> softly.fail("boom")));}.
* @since 2.6.0 / 3.6.0
*/
@CanIgnoreReturnValue
@Contract("_ -> fail")
public <T> T fail(String failureMessage) {
AssertionError error = Failures.instance().failure(failureMessage);
collectAssertionError(error);
return null;
}
/**
* Fails with an empty message to be used in code like:
* <pre><code class='java'> doSomething(optional.orElseGet(() -> softly.fail()));</code></pre>
*
* @param <T> dummy return value type
* @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> softly.fail()));}.
* @since 3.26.0
*/
@CanIgnoreReturnValue
@Contract(" -> fail")
public <T> T fail() {
// pass an empty string because passing null results in a "null" error message.
return fail("");
}
/**
* Fails with the given message built like {@link String#format(String, Object...)}.
*
* @param <T> dummy return value type
* @param failureMessage error message.
* @param args Arguments referenced by the format specifiers in the format string.
* @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> softly.fail("boom")));}.
* @since 2.6.0 / 3.6.0
*/
@CanIgnoreReturnValue
@Contract("_, _ -> fail")
public <T> T fail(String failureMessage, Object... args) {
return fail(failureMessage.formatted(args));
}
/**
* Fails with the given message and with the {@link Throwable} that caused the failure.
*
* @param <T> dummy return value type
* @param failureMessage error message.
* @param realCause cause of the error.
* @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> softly.fail("boom")));}.
* @since 2.6.0 / 3.6.0
*/
@CanIgnoreReturnValue
@Contract("_, _ -> fail")
public <T> T fail(String failureMessage, Throwable realCause) {
AssertionError error = Failures.instance().failure(failureMessage);
error.initCause(realCause);
collectAssertionError(error);
return null;
}
/**
* Fails with the {@link Throwable} that caused the failure and an empty message.
* <p>
* Example:
* <pre><code class='java'> doSomething(optional.orElseGet(() -> softly.fail(cause)));</code></pre>
*
* @param <T> dummy return value type
* @param realCause cause of the error.
* @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> softly.fail(cause)));}.
* @since 3.26.0
*/
@CanIgnoreReturnValue
@Contract("_ -> fail")
public <T> T fail(Throwable realCause) {
return fail("", realCause);
}
/**
* Fails with a message explaining that a {@link Throwable} of given
|
AbstractSoftAssertions
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/ActiveProfilesTestClassScopedExtensionContextNestedTests.java
|
{
"start": 4070,
"end": 4422
}
|
class ____ {
@Autowired
List<String> localStrings;
@Test
void test() {
assertThat(strings).containsExactlyInAnyOrder("X", "A1");
assertThat(this.localStrings).containsExactlyInAnyOrder("X", "Y", "Z", "A2");
}
}
@Nested
@NestedTestConfiguration(INHERIT)
|
TripleNestedWithInheritedConfigButOverriddenProfilesTests
|
java
|
apache__logging-log4j2
|
log4j-core/src/main/java/org/apache/logging/log4j/core/filter/BurstFilter.java
|
{
"start": 9716,
"end": 11064
}
|
class ____ implements Delayed {
LogDelay(final long expireTime) {
this.expireTime = expireTime;
}
private long expireTime;
public void setDelay(final long delay) {
this.expireTime = delay + System.nanoTime();
}
@Override
public long getDelay(final TimeUnit timeUnit) {
return timeUnit.convert(expireTime - System.nanoTime(), TimeUnit.NANOSECONDS);
}
@Override
public int compareTo(final Delayed delayed) {
final long diff = this.expireTime - ((LogDelay) delayed).expireTime;
return Long.signum(diff);
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final LogDelay logDelay = (LogDelay) o;
if (expireTime != logDelay.expireTime) {
return false;
}
return true;
}
@Override
public int hashCode() {
return (int) (expireTime ^ (expireTime >>> HASH_SHIFT));
}
}
@PluginBuilderFactory
public static Builder newBuilder() {
return new Builder();
}
public static
|
LogDelay
|
java
|
quarkusio__quarkus
|
extensions/smallrye-reactive-messaging/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/deployment/WiringHelper.java
|
{
"start": 3953,
"end": 9195
}
|
class ____ the outbound connector interface
*/
static boolean isOutboundConnector(ClassInfo ci) {
return ci.interfaceNames().contains(ReactiveMessagingDotNames.OUTGOING_CONNECTOR_FACTORY)
|| ci.interfaceNames().contains(ReactiveMessagingDotNames.OUTBOUND_CONNECTOR);
}
/**
* Collects connector attributes from the given connector implementation.
*
* @param bi the bean implementing the connector interfaces
* @param index the index
* @param directions the attribute direction to includes in the result
* @return the list of connector attributes, empty if none
*/
static List<ConnectorAttribute> getConnectorAttributes(BeanInfo bi, CombinedIndexBuildItem index,
ConnectorAttribute.Direction... directions) {
List<AnnotationInstance> attributes = bi.getImplClazz()
.declaredAnnotationsWithRepeatable(ReactiveMessagingDotNames.CONNECTOR_ATTRIBUTES, index.getIndex())
.stream().flatMap(ai -> Arrays.stream(ai.value().asNestedArray())).collect(Collectors.toList());
if (attributes.isEmpty()) {
AnnotationInstance attribute = bi.getImplClazz().declaredAnnotation(ReactiveMessagingDotNames.CONNECTOR_ATTRIBUTE);
if (attribute != null) {
attributes = Collections.singletonList(attribute);
}
}
List<ConnectorAttribute> att = new ArrayList<>();
for (AnnotationInstance instance : attributes) {
ConnectorAttribute.Direction direction = ConnectorAttribute.Direction
.valueOf(instance.value("direction").asString().toUpperCase());
if (Arrays.asList(directions).contains(direction)) {
ConnectorAttribute literal = createConnectorAttribute(instance, direction);
att.add(literal);
}
}
return att;
}
/**
* Creates a {@code ConnectorAttribute} literal for the given instance.
*
* @param instance the instance
* @param direction the direction
* @return the connector attribute.
*/
private static ConnectorAttribute createConnectorAttribute(AnnotationInstance instance,
ConnectorAttribute.Direction direction) {
String name = instance.value("name").asString();
String type = instance.value("type").asString();
String description = instance.value("description").asString();
boolean hidden = getBooleanValueOrDefault(instance, "hidden");
boolean mandatory = getBooleanValueOrDefault(instance, "hidden");
boolean deprecated = getBooleanValueOrDefault(instance, "deprecated");
String defaultValue = getStringValueOrDefault(instance, "defaultValue");
String alias = getStringValueOrDefault(instance, "alias");
return ConnectorAttributeLiteral.create(name, description, hidden, mandatory,
direction, defaultValue, deprecated, alias, type);
}
private static String getStringValueOrDefault(AnnotationInstance instance, String attribute) {
AnnotationValue value = instance.value(attribute);
if (value != null) {
return value.asString();
}
return ConnectorAttribute.NO_VALUE;
}
private static boolean getBooleanValueOrDefault(AnnotationInstance instance, String attribute) {
AnnotationValue value = instance.value(attribute);
if (value != null) {
return value.asBoolean();
}
return false;
}
/**
* Finds a connector by name and direction in the given list.
*
* @param connectors the list of connectors
* @param name the name
* @param direction the direction
* @return the found connector, {@code null} otherwise
*/
static ConnectorBuildItem find(List<ConnectorBuildItem> connectors, String name, ChannelDirection direction) {
for (ConnectorBuildItem connector : connectors) {
if (connector.getDirection() == direction && connector.getName().equalsIgnoreCase(name)) {
return connector;
}
}
return null;
}
static boolean hasConnector(List<ConnectorBuildItem> connectors, ChannelDirection direction, String name) {
return connectors.stream().anyMatch(c -> c.getName().equalsIgnoreCase(name) && c.getDirection() == direction);
}
static boolean isSynthetic(MethodInfo method) {
short flag = method.flags();
return (flag & Opcodes.ACC_SYNTHETIC) != 0;
}
static Optional<AnnotationInstance> getAnnotation(TransformedAnnotationsBuildItem transformedAnnotations,
InjectionPointInfo injectionPoint,
DotName annotationName) {
// For field IP -> set of field annotations
// For method param IP -> set of param annotations
Collection<AnnotationInstance> annotations = transformedAnnotations
.getAnnotations(injectionPoint.getAnnotationTarget());
for (AnnotationInstance annotation : annotations) {
if (annotationName.equals(annotation.name())) {
return Optional.of(annotation);
}
}
return Optional.empty();
}
}
|
implements
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/inheritance/hierarchy/MultipleInterceptorMethodDeclaredOnSuperclassTest.java
|
{
"start": 1295,
"end": 1508
}
|
class ____ extends Bravo {
@AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception {
return "a/" + ctx.proceed() + "/a";
}
}
static
|
AlphaInterceptor
|
java
|
apache__camel
|
components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramComponentParametersTest.java
|
{
"start": 1204,
"end": 3507
}
|
class ____ extends TelegramTestSupport {
@Test
public void testDefaultsAndOverrides() throws Exception {
TelegramComponent component = (TelegramComponent) context().getComponent("telegram");
component.setAuthorizationToken("DEFAULT");
TelegramEndpoint ep1 = (TelegramEndpoint) component.createEndpoint("telegram:bots");
assertEquals("DEFAULT", ep1.getConfiguration().getAuthorizationToken());
assertEquals(TelegramProxyType.HTTP, ep1.getConfiguration().getProxyType());
TelegramEndpoint ep2 = (TelegramEndpoint) component.createEndpoint("telegram:bots?authorizationToken=CUSTOM");
assertEquals("CUSTOM", ep2.getConfiguration().getAuthorizationToken());
TelegramEndpoint ep3 = (TelegramEndpoint) component
.createEndpoint("telegram:bots?authorizationToken=ANOTHER&chatId=123");
assertEquals("ANOTHER", ep3.getConfiguration().getAuthorizationToken());
}
@Test
public void testNonDefaultConfig() {
TelegramComponent component = (TelegramComponent) context().getComponent("telegram");
component.setAuthorizationToken(null);
assertThrows(IllegalArgumentException.class, () -> {
component.createEndpoint("telegram:bots");
});
}
@Test
public void testWrongURI1() {
TelegramComponent component = (TelegramComponent) context().getComponent("telegram");
component.setAuthorizationToken("ANY");
assertThrows(IllegalArgumentException.class, () -> {
component.createEndpoint("telegram:bots/ ");
});
}
@Test
public void testWrongURI2() {
TelegramComponent component = (TelegramComponent) context().getComponent("telegram");
component.setAuthorizationToken("ANY");
assertThrows(IllegalArgumentException.class, () -> {
component.createEndpoint("telegram:bots/token/s");
});
}
@Test
public void testWrongURI3() {
TelegramComponent component = (TelegramComponent) context().getComponent("telegram");
component.setAuthorizationToken("ANY");
assertThrows(PropertyBindingException.class, () -> {
component.createEndpoint("telegram:bots?proxyType=ANY");
});
}
}
|
TelegramComponentParametersTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopFloatIntAggregator.java
|
{
"start": 3138,
"end": 4372
}
|
class ____ implements GroupingAggregatorState {
private final FloatIntBucketedSort sort;
private GroupingState(BigArrays bigArrays, int limit, boolean ascending) {
this.sort = new FloatIntBucketedSort(bigArrays, ascending ? SortOrder.ASC : SortOrder.DESC, limit);
}
public void add(int groupId, float value, int outputValue) {
sort.collect(value, outputValue, groupId);
}
@Override
public void toIntermediate(Block[] blocks, int offset, IntVector selected, DriverContext driverContext) {
sort.toBlocks(driverContext.blockFactory(), blocks, offset, selected);
}
Block toBlock(BlockFactory blockFactory, IntVector selected) {
Block[] blocks = new Block[2];
sort.toBlocks(blockFactory, blocks, 0, selected);
Releasables.close(blocks[0]);
return blocks[1];
}
@Override
public void enableGroupIdTracking(SeenGroupIds seen) {
// we figure out seen values from nulls on the values block
}
@Override
public void close() {
Releasables.closeExpectNoException(sort);
}
}
public static
|
GroupingState
|
java
|
spring-projects__spring-security
|
access/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java
|
{
"start": 1576,
"end": 6309
}
|
class ____ {
@Test
public void testCannotSetEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
assertThatIllegalArgumentException().isThrownBy(() -> {
cdm.setChannelProcessors(new Vector());
cdm.afterPropertiesSet();
}).withMessage("A list of ChannelProcessors is required");
}
@Test
public void testCannotSetIncorrectObjectTypesIntoChannelProcessorsList() {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
List list = new Vector();
list.add("THIS IS NOT A CHANNELPROCESSOR");
assertThatIllegalArgumentException().isThrownBy(() -> cdm.setChannelProcessors(list));
}
@Test
public void testCannotSetNullChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
assertThatIllegalArgumentException().isThrownBy(() -> {
cdm.setChannelProcessors(null);
cdm.afterPropertiesSet();
}).withMessage("A list of ChannelProcessors is required");
}
@Test
public void testDecideIsOperational() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", true);
List list = new Vector();
list.add(cpXyz);
list.add(cpAbc);
cdm.setChannelProcessors(list);
cdm.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
List<ConfigAttribute> cad = SecurityConfig.createList("xyz");
cdm.decide(fi, cad);
Assertions.assertThat(fi.getResponse().isCommitted()).isTrue();
}
@Test
public void testAnyChannelAttributeCausesProcessorsToBeSkipped() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", true);
List list = new Vector();
list.add(cpAbc);
cdm.setChannelProcessors(list);
cdm.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
cdm.decide(fi, SecurityConfig.createList(new String[] { "abc", "ANY_CHANNEL" }));
Assertions.assertThat(fi.getResponse().isCommitted()).isFalse();
}
@Test
public void testDecideIteratesAllProcessorsIfNoneCommitAResponse() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false);
List list = new Vector();
list.add(cpXyz);
list.add(cpAbc);
cdm.setChannelProcessors(list);
cdm.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
cdm.decide(fi, SecurityConfig.createList("SOME_ATTRIBUTE_NO_PROCESSORS_SUPPORT"));
Assertions.assertThat(fi.getResponse().isCommitted()).isFalse();
}
@Test
public void testDelegatesSupports() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false);
List list = new Vector();
list.add(cpXyz);
list.add(cpAbc);
cdm.setChannelProcessors(list);
cdm.afterPropertiesSet();
assertThat(cdm.supports(new SecurityConfig("xyz"))).isTrue();
assertThat(cdm.supports(new SecurityConfig("abc"))).isTrue();
assertThat(cdm.supports(new SecurityConfig("UNSUPPORTED"))).isFalse();
}
@Test
public void testGettersSetters() {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
assertThat(cdm.getChannelProcessors()).isNull();
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false);
List list = new Vector();
list.add(cpXyz);
list.add(cpAbc);
cdm.setChannelProcessors(list);
assertThat(cdm.getChannelProcessors()).isEqualTo(list);
}
@Test
public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
assertThatIllegalArgumentException().isThrownBy(cdm::afterPropertiesSet)
.withMessage("A list of ChannelProcessors is required");
}
private
|
ChannelDecisionManagerImplTests
|
java
|
quarkusio__quarkus
|
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/InterceptorInfo.java
|
{
"start": 10493,
"end": 10941
}
|
class ____ last.
*
* @return the interceptor methods
*/
public List<MethodInfo> getPostConstructs() {
return postConstructs;
}
/**
* Returns all methods annotated with {@link jakarta.annotation.PreDestroy} found in the hierarchy of the interceptor class.
* <p>
* The returned list is sorted. The method declared on the most general superclass is first. The method declared on the
* interceptor
|
is
|
java
|
alibaba__nacos
|
naming/src/main/java/com/alibaba/nacos/naming/push/v2/executor/SpiPushExecutor.java
|
{
"start": 797,
"end": 1166
}
|
interface ____ extends PushExecutor {
/**
* Whether SPI push executor is interest this push.
*
* @param clientId client id of push
* @param subscriber subscribe info
* @return {@code true} if this SPI push executor should execute, otherwise false.
*/
boolean isInterest(String clientId, Subscriber subscriber);
}
|
SpiPushExecutor
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/impl/DefaultCamelContextSuspendResumeRouteTest.java
|
{
"start": 1255,
"end": 3455
}
|
class ____ extends ContextTestSupport {
@Test
public void testSuspendResume() throws Exception {
assertFalse(context.isSuspended());
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("A");
template.sendBody("seda:foo", "A");
assertMockEndpointsSatisfied();
log.info("Suspending");
// now suspend and dont expect a message to be routed
resetMocks();
mock.expectedMessageCount(0);
context.suspend();
// even though we wait for the route to suspend, there is a race condition where the consumer
// may still process messages while it's being suspended due to asynchronous message handling.
// as a result, we need to wait a bit longer to ensure that the seda consumer is suspended before
// sending the next message.
Thread.sleep(1000L);
// need to give seda consumer thread time to idle
Awaitility.await().atMost(200, TimeUnit.MILLISECONDS)
.pollDelay(100, TimeUnit.MILLISECONDS)
.untilAsserted(() -> Assertions.assertDoesNotThrow(() -> template.sendBody("seda:foo", "B")));
mock.assertIsSatisfied(1000);
assertTrue(context.isSuspended());
assertFalse(context.getStatus().isStarted());
assertTrue(context.getStatus().isSuspended());
assertFalse(context.getStatus().isStopped());
log.info("Resuming");
// now resume and expect the previous message to be routed
resetMocks();
mock.expectedBodiesReceived("B");
context.resume();
assertMockEndpointsSatisfied();
assertFalse(context.isSuspended());
assertTrue(context.getStatus().isStarted());
assertFalse(context.getStatus().isSuspended());
assertFalse(context.getStatus().isStopped());
context.stop();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("seda:foo").to("log:foo").to("mock:result");
}
};
}
}
|
DefaultCamelContextSuspendResumeRouteTest
|
java
|
apache__camel
|
components/camel-xmlsecurity/src/main/java/org/apache/camel/component/xmlsecurity/api/DefaultXAdESSignatureProperties.java
|
{
"start": 1295,
"end": 2930
}
|
class ____
extends XAdESSignatureProperties
implements CamelContextAware {
private final KeyStoreAndAlias keyStoreAndAlias = new KeyStoreAndAlias();
private CamelContext context;
public DefaultXAdESSignatureProperties() {
}
public void setKeystore(KeyStore keystore) {
keyStoreAndAlias.setKeyStore(keystore);
}
public void setAlias(String alias) {
keyStoreAndAlias.setAlias(alias);
}
public void setKeyStoreParameters(KeyStoreParameters parameters)
throws GeneralSecurityException, IOException {
if (parameters != null) {
keyStoreAndAlias.setKeyStore(parameters.createKeyStore());
}
}
@Override
protected X509Certificate getSigningCertificate() throws Exception {
if (keyStoreAndAlias.getKeyStore() == null) {
throw new XmlSignatureException("No keystore has been configured");
}
X509Certificate cert = (X509Certificate) keyStoreAndAlias.getKeyStore().getCertificate(keyStoreAndAlias.getAlias());
if (cert == null) {
throw new XmlSignatureException(
String.format("No certificate found in keystore for alias '%s'", keyStoreAndAlias.getAlias()));
}
return cert;
}
@Override
protected X509Certificate[] getSigningCertificateChain() throws Exception {
return null;
}
@Override
public CamelContext getCamelContext() {
return context;
}
@Override
public void setCamelContext(CamelContext context) {
this.context = context;
}
}
|
DefaultXAdESSignatureProperties
|
java
|
spring-projects__spring-framework
|
spring-jdbc/src/main/java/org/springframework/jdbc/support/rowset/ResultSetWrappingSqlRowSet.java
|
{
"start": 2110,
"end": 2493
}
|
class ____ only uses
* the column name, ignoring any column labels. {@code ResultSetWrappingSqlRowSet}
* will translate column labels to the correct column index to provide better support for
* {@code com.sun.rowset.CachedRowSetImpl} which is the default implementation used by
* {@link org.springframework.jdbc.core.JdbcTemplate} when working with RowSets.
*
* <p>Note: This
|
which
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/AmbiguousMethodReference.java
|
{
"start": 1910,
"end": 3589
}
|
class ____ extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
ClassSymbol origin = getSymbol(tree);
Types types = state.getTypes();
Iterable<Symbol> members =
types.membersClosure(getType(tree), /* skipInterface= */ false).getSymbols();
// collect declared and inherited methods, grouped by reference descriptor
Map<String, List<MethodSymbol>> methods =
Streams.stream(members)
.filter(MethodSymbol.class::isInstance)
.map(MethodSymbol.class::cast)
.filter(m -> m.isConstructor() || m.owner.equals(origin))
.collect(
groupingBy(m -> methodReferenceDescriptor(state, m), toCollection(ArrayList::new)));
// look for groups of ambiguous method references
for (Tree member : tree.getMembers()) {
if (!(member instanceof MethodTree methodTree)) {
continue;
}
MethodSymbol msym = getSymbol(methodTree);
if (isSuppressed(msym, state)) {
continue;
}
List<MethodSymbol> clash = methods.remove(methodReferenceDescriptor(state, msym));
if (clash == null) {
continue;
}
// If the clashing group has 1 or 0 non-private methods, method references outside the file
// are unambiguous.
int nonPrivateMethodCount = 0;
for (MethodSymbol method : clash) {
if (!method.isPrivate()) {
nonPrivateMethodCount++;
}
}
if (nonPrivateMethodCount < 2) {
continue;
}
clash.remove(msym);
// ignore overridden inherited methods and hidden
|
AmbiguousMethodReference
|
java
|
quarkusio__quarkus
|
extensions/elytron-security-oauth2/runtime/src/main/java/io/quarkus/elytron/security/oauth2/runtime/auth/OAuth2AuthMechanism.java
|
{
"start": 1006,
"end": 3295
}
|
class ____ implements HttpAuthenticationMechanism {
private static final Logger LOG = Logger.getLogger(OAuth2AuthMechanism.class);
private static final String BEARER_PREFIX = "Bearer ";
protected static final ChallengeData CHALLENGE_DATA = new ChallengeData(
HttpResponseStatus.UNAUTHORIZED.code(),
HttpHeaderNames.WWW_AUTHENTICATE,
"Bearer {token}");
/**
* Extract the Authorization header and validate the bearer token if it exists. If it does, and is validated, this
* builds the org.jboss.security.SecurityContext authenticated Subject that drives the container APIs as well as
* the authorization layers.
*
* @param context - the http request exchange object
* @param identityProviderManager - the current security context that
* @return one of AUTHENTICATED, NOT_AUTHENTICATED or NOT_ATTEMPTED depending on the header and authentication outcome.
*/
@Override
public Uni<SecurityIdentity> authenticate(RoutingContext context,
IdentityProviderManager identityProviderManager) {
String authHeader = context.request().headers().get("Authorization");
if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) {
// No suitable bearer token has been found in this request
LOG.debug("Bearer access token is not available");
return Uni.createFrom().nullItem();
}
String bearerToken = authHeader.substring(BEARER_PREFIX.length());
// Install the OAuth2 principal as the caller
return identityProviderManager
.authenticate(new TokenAuthenticationRequest(new TokenCredential(bearerToken, "bearer")));
}
@Override
public Uni<ChallengeData> getChallenge(RoutingContext context) {
return Uni.createFrom().item(CHALLENGE_DATA);
}
@Override
public Set<Class<? extends AuthenticationRequest>> getCredentialTypes() {
return Collections.singleton(TokenAuthenticationRequest.class);
}
@Override
public Uni<HttpCredentialTransport> getCredentialTransport(RoutingContext context) {
return Uni.createFrom().item(new HttpCredentialTransport(HttpCredentialTransport.Type.AUTHORIZATION, "bearer"));
}
}
|
OAuth2AuthMechanism
|
java
|
quarkusio__quarkus
|
devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/extension-codestarts/messaging-codestart/java/src/main/java/org/acme/MyMessagingApplication.java
|
{
"start": 298,
"end": 1299
}
|
class ____ {
@Inject
@Channel("words-out")
Emitter<String> emitter;
/**
* Sends message to the "words-out" channel, can be used from a JAX-RS resource or any bean of your application.
* Messages are sent to the broker.
**/
void onStart(@Observes StartupEvent ev) {
Stream.of("Hello", "with", "Quarkus", "Messaging", "message").forEach(string -> emitter.send(string));
}
/**
* Consume the message from the "words-in" channel, uppercase it and send it to the uppercase channel.
* Messages come from the broker.
**/
@Incoming("words-in")
@Outgoing("uppercase")
public Message<String> toUpperCase(Message<String> message) {
return message.withPayload(message.getPayload().toUpperCase());
}
/**
* Consume the uppercase channel (in-memory) and print the messages.
**/
@Incoming("uppercase")
public void sink(String word) {
System.out.println(">> " + word);
}
}
|
MyMessagingApplication
|
java
|
apache__camel
|
components/camel-netty/src/test/java/org/apache/camel/component/netty/Netty2978IssueTest.java
|
{
"start": 3883,
"end": 4450
}
|
class ____ {
private final Endpoint endpoint;
private final ProducerTemplate producerTemplate;
CamelClient(CamelContext camelContext) {
this.endpoint = camelContext.getEndpoint("netty:tcp://localhost:{{port}}?sync=true");
this.producerTemplate = camelContext.createProducerTemplate();
}
public void close() {
producerTemplate.stop();
}
public String lookup(int num) {
return producerTemplate.requestBody(endpoint, num, String.class);
}
}
}
|
CamelClient
|
java
|
spring-projects__spring-framework
|
spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/CompositeDatabasePopulatorTests.java
|
{
"start": 1077,
"end": 3446
}
|
class ____ {
private final Connection mockedConnection = mock();
private final DatabasePopulator mockedDatabasePopulator1 = mock();
private final DatabasePopulator mockedDatabasePopulator2 = mock();
@Test
void addPopulators() throws SQLException {
CompositeDatabasePopulator populator = new CompositeDatabasePopulator();
populator.addPopulators(mockedDatabasePopulator1, mockedDatabasePopulator2);
populator.populate(mockedConnection);
verify(mockedDatabasePopulator1, times(1)).populate(mockedConnection);
verify(mockedDatabasePopulator2, times(1)).populate(mockedConnection);
}
@Test
void setPopulatorsWithMultiple() throws SQLException {
CompositeDatabasePopulator populator = new CompositeDatabasePopulator();
populator.setPopulators(mockedDatabasePopulator1, mockedDatabasePopulator2); // multiple
populator.populate(mockedConnection);
verify(mockedDatabasePopulator1, times(1)).populate(mockedConnection);
verify(mockedDatabasePopulator2, times(1)).populate(mockedConnection);
}
@Test
void setPopulatorsForOverride() throws SQLException {
CompositeDatabasePopulator populator = new CompositeDatabasePopulator();
populator.setPopulators(mockedDatabasePopulator1);
populator.setPopulators(mockedDatabasePopulator2); // override
populator.populate(mockedConnection);
verify(mockedDatabasePopulator1, times(0)).populate(mockedConnection);
verify(mockedDatabasePopulator2, times(1)).populate(mockedConnection);
}
@Test
void constructWithVarargs() throws SQLException {
CompositeDatabasePopulator populator =
new CompositeDatabasePopulator(mockedDatabasePopulator1, mockedDatabasePopulator2);
populator.populate(mockedConnection);
verify(mockedDatabasePopulator1, times(1)).populate(mockedConnection);
verify(mockedDatabasePopulator2, times(1)).populate(mockedConnection);
}
@Test
void constructWithCollection() throws SQLException {
Set<DatabasePopulator> populators = new LinkedHashSet<>();
populators.add(mockedDatabasePopulator1);
populators.add(mockedDatabasePopulator2);
CompositeDatabasePopulator populator = new CompositeDatabasePopulator(populators);
populator.populate(mockedConnection);
verify(mockedDatabasePopulator1, times(1)).populate(mockedConnection);
verify(mockedDatabasePopulator2, times(1)).populate(mockedConnection);
}
}
|
CompositeDatabasePopulatorTests
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/clients/admin/DescribeConsumerGroupsOptions.java
|
{
"start": 989,
"end": 1443
}
|
class ____ extends AbstractOptions<DescribeConsumerGroupsOptions> {
private boolean includeAuthorizedOperations;
public DescribeConsumerGroupsOptions includeAuthorizedOperations(boolean includeAuthorizedOperations) {
this.includeAuthorizedOperations = includeAuthorizedOperations;
return this;
}
public boolean includeAuthorizedOperations() {
return includeAuthorizedOperations;
}
}
|
DescribeConsumerGroupsOptions
|
java
|
apache__maven
|
its/core-it-suite/src/test/resources/mng-6118-submodule-invocation-full-reactor/lib/src/main/java/org/apache/its/mng6118/Helper.java
|
{
"start": 1657,
"end": 1746
}
|
class ____ {
public Object generateObject() {
return new Object();
}
}
|
Helper
|
java
|
elastic__elasticsearch
|
qa/smoke-test-http/src/internalClusterTest/java/org/elasticsearch/http/ClusterStatsRestCancellationIT.java
|
{
"start": 5611,
"end": 6137
}
|
class ____ extends Plugin implements EnginePlugin {
@Override
public Optional<EngineFactory> getEngineFactory(IndexSettings indexSettings) {
if (BLOCK_STATS_SETTING.get(indexSettings.getSettings())) {
return Optional.of(StatsBlockingEngine::new);
}
return Optional.empty();
}
@Override
public List<Setting<?>> getSettings() {
return singletonList(BLOCK_STATS_SETTING);
}
}
private static
|
StatsBlockingPlugin
|
java
|
spring-projects__spring-framework
|
spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java
|
{
"start": 3916,
"end": 47408
}
|
interface ____ {
}
static Stream<Arguments> arguments() {
return Stream.of(
argumentSet("Reactor Netty", new ReactorClientHttpConnector()),
argumentSet("JDK", new JdkClientHttpConnector()),
argumentSet("Jetty", new JettyClientHttpConnector()),
argumentSet("HttpComponents", new HttpComponentsClientHttpConnector())
);
}
private MockWebServer server;
private WebClient webClient;
private void startServer(ClientHttpConnector connector) throws IOException {
this.server = new MockWebServer();
this.server.start();
this.webClient = WebClient
.builder()
.clientConnector(connector)
.baseUrl(this.server.url("/").toString())
.build();
}
@AfterEach
void shutdown() {
if (server != null) {
this.server.close();
}
}
@ParameterizedWebClientTest
void retrieve(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder
.setHeader("Content-Type", "text/plain")
.body("Hello Spring!"));
Mono<String> result = this.webClient.get()
.uri("/greeting")
.cookie("testkey", "testvalue")
.header("X-Test-Header", "testvalue")
.retrieve()
.bodyToMono(String.class);
StepVerifier.create(result)
.expectNext("Hello Spring!")
.expectComplete()
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.COOKIE)).isEqualTo("testkey=testvalue");
assertThat(request.getHeaders().get("X-Test-Header")).isEqualTo("testvalue");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/greeting");
});
}
@ParameterizedWebClientTest
void retrieveJson(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json")
.body("{\"bar\":\"barbar\",\"foo\":\"foofoo\"}"));
Mono<Pojo> result = this.webClient.get()
.uri("/pojo")
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Pojo.class);
StepVerifier.create(result)
.expectNext(new Pojo("foofoo", "barbar"))
.expectComplete()
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/pojo");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void applyAttributesToNativeRequest(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(Function.identity());
final AtomicReference<Object> nativeRequest = new AtomicReference<>();
Mono<Void> result = this.webClient.get()
.uri("/pojo")
.attribute("foo","bar")
.httpRequest(clientHttpRequest -> {
if (clientHttpRequest instanceof ChannelOperations<?,?> nettyReq) {
nativeRequest.set(nettyReq.channel().attr(ReactorClientHttpConnector.ATTRIBUTES_KEY));
}
else {
nativeRequest.set(clientHttpRequest.getNativeRequest());
}
})
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(result).expectComplete().verify();
if (nativeRequest.get() instanceof Attribute<?>) {
@SuppressWarnings("unchecked")
Attribute<Map<String, Object>> attributes = (Attribute<Map<String, Object>>) nativeRequest.get();
assertThat(attributes.get()).isNotNull();
assertThat(attributes.get()).containsEntry("foo", "bar");
}
else if (nativeRequest.get() instanceof Request nativeReq) {
assertThat(nativeReq.getAttributes()).containsEntry("foo", "bar");
}
else if (nativeRequest.get() instanceof org.apache.hc.core5.http.HttpRequest) {
// Attributes are not in the request, but in separate HttpClientContext
}
}
@ParameterizedWebClientTest
void retrieveJsonWithParameterizedTypeReference(ClientHttpConnector connector) throws IOException {
startServer(connector);
String content = "{\"containerValue\":{\"bar\":\"barbar\",\"foo\":\"foofoo\"}}";
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json")
.body(content));
Mono<ValueContainer<Pojo>> result = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(result)
.assertNext(c -> assertThat(c.getContainerValue()).isEqualTo(new Pojo("foofoo", "barbar")))
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/json");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void retrieveJsonAsResponseEntity(ClientHttpConnector connector) throws IOException {
startServer(connector);
String content = "{\"bar\":\"barbar\",\"foo\":\"foofoo\"}";
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json")
.body(content));
Mono<ResponseEntity<String>> result = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.toEntity(String.class);
StepVerifier.create(result)
.consumeNextWith(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(entity.getHeaders().getContentLength()).isEqualTo(31);
assertThat(entity.getBody()).isEqualTo(content);
})
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/json");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void retrieveJsonAsBodilessEntity(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json")
.body("{\"bar\":\"barbar\",\"foo\":\"foofoo\"}"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.toBodilessEntity();
StepVerifier.create(result)
.consumeNextWith(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(entity.getHeaders().getContentLength()).isEqualTo(31);
assertThat(entity.getBody()).isNull();
})
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/json");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void retrieveJsonArray(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json")
.body("[{\"bar\":\"bar1\",\"foo\":\"foo1\"},{\"bar\":\"bar2\",\"foo\":\"foo2\"}]"));
Flux<Pojo> result = this.webClient.get()
.uri("/pojos")
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(Pojo.class);
StepVerifier.create(result)
.consumeNextWith(p -> assertThat(p.getBar()).isEqualTo("bar1"))
.consumeNextWith(p -> assertThat(p.getBar()).isEqualTo("bar2"))
.expectComplete()
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/pojos");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void retrieveJsonArrayAsResponseEntityList(ClientHttpConnector connector) throws IOException {
startServer(connector);
String content = "[{\"bar\":\"bar1\",\"foo\":\"foo1\"}, {\"bar\":\"bar2\",\"foo\":\"foo2\"}]";
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json")
.body(content));
Mono<ResponseEntity<List<Pojo>>> result = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.toEntityList(Pojo.class);
StepVerifier.create(result)
.consumeNextWith(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(entity.getHeaders().getContentLength()).isEqualTo(58);
Pojo pojo1 = new Pojo("foo1", "bar1");
Pojo pojo2 = new Pojo("foo2", "bar2");
assertThat(entity.getBody()).isEqualTo(Arrays.asList(pojo1, pojo2));
})
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/json");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void retrieveJsonArrayAsResponseEntityFlux(ClientHttpConnector connector) throws IOException {
startServer(connector);
String content = "[{\"bar\":\"bar1\",\"foo\":\"foo1\"}, {\"bar\":\"bar2\",\"foo\":\"foo2\"}]";
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json")
.body(content));
ResponseEntity<Flux<Pojo>> entity = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.toEntityFlux(Pojo.class)
.block(Duration.ofSeconds(3));
assertThat(entity).isNotNull();
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(entity.getHeaders().getContentLength()).isEqualTo(58);
assertThat(entity.getBody()).isNotNull();
StepVerifier.create(entity.getBody())
.expectNext(new Pojo("foo1", "bar1"))
.expectNext(new Pojo("foo2", "bar2"))
.expectComplete()
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/json");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void retrieveJsonArrayAsResponseEntityFluxWithBodyExtractor(ClientHttpConnector connector) throws IOException {
startServer(connector);
String content = "[{\"bar\":\"bar1\",\"foo\":\"foo1\"}, {\"bar\":\"bar2\",\"foo\":\"foo2\"}]";
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json")
.body(content));
ResponseEntity<Flux<Pojo>> entity = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.toEntityFlux(BodyExtractors.toFlux(Pojo.class))
.block(Duration.ofSeconds(3));
assertThat(entity).isNotNull();
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(entity.getHeaders().getContentLength()).isEqualTo(58);
assertThat(entity.getBody()).isNotNull();
StepVerifier.create(entity.getBody())
.expectNext(new Pojo("foo1", "bar1"))
.expectNext(new Pojo("foo2", "bar2"))
.expectComplete()
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/json");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@Test // gh-24788
void retrieveJsonArrayAsBodilessEntityShouldReleasesConnection() throws IOException {
// Constrain connection pool and make consecutive requests.
// 2nd request should hang if response was not drained.
ConnectionProvider connectionProvider = ConnectionProvider.create("test", 1);
this.server = new MockWebServer();
this.server.start();
WebClient webClient = WebClient
.builder()
.clientConnector(new ReactorClientHttpConnector(HttpClient.create(connectionProvider)))
.baseUrl(this.server.url("/").toString())
.build();
for (int i=1 ; i <= 2; i++) {
// Response must be large enough to circumvent eager prefetching
String json = Flux.just("{\"bar\":\"bar\",\"foo\":\"foo\"}")
.repeat(100)
.collect(Collectors.joining(",", "[", "]"))
.block();
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json")
.body(json));
Mono<ResponseEntity<Void>> result = webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.toBodilessEntity();
StepVerifier.create(result)
.consumeNextWith(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(entity.getHeaders().getContentLength()).isEqualTo(2627);
assertThat(entity.getBody()).isNull();
})
.expectComplete()
.verify(Duration.ofSeconds(3));
expectRequestCount(i);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/json");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
}
@ParameterizedWebClientTest
void retrieveJsonAsSerializedText(ClientHttpConnector connector) throws IOException {
startServer(connector);
String content = "{\"bar\":\"barbar\",\"foo\":\"foofoo\"}";
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json")
.body(content));
Mono<String> result = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class);
StepVerifier.create(result)
.expectNext(content)
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/json");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
@SuppressWarnings("rawtypes")
void retrieveJsonNull(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder
.code(200)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body("null"));
Mono<Map> result = this.webClient.get()
.uri("/null")
.retrieve()
.bodyToMono(Map.class);
StepVerifier.create(result).expectComplete().verify(Duration.ofSeconds(3));
}
@ParameterizedWebClientTest // SPR-15946
void retrieve404(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder
.code(404)
.setHeader("Content-Type", "text/plain"));
Mono<String> result = this.webClient.get().uri("/greeting")
.retrieve()
.bodyToMono(String.class);
StepVerifier.create(result)
.expectError(WebClientResponseException.class)
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/greeting");
});
}
@ParameterizedWebClientTest
void retrieve404WithBody(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder
.code(404)
.setHeader("Content-Type", "text/plain")
.body("Not Found"));
Mono<String> result = this.webClient.get()
.uri("/greeting")
.retrieve()
.bodyToMono(String.class);
StepVerifier.create(result)
.expectError(WebClientResponseException.class)
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/greeting");
});
}
@ParameterizedWebClientTest
@SuppressWarnings("deprecation")
void retrieve500(ClientHttpConnector connector) throws IOException {
startServer(connector);
String errorMessage = "Internal Server error";
prepareResponse(builder -> builder.code(500)
.setHeader("Content-Type", "text/plain").body(errorMessage));
String path = "/greeting";
Mono<String> result = this.webClient.get()
.uri(path)
.retrieve()
.bodyToMono(String.class);
StepVerifier.create(result)
.expectErrorSatisfies(throwable -> {
assertThat(throwable).isInstanceOf(WebClientResponseException.class);
WebClientResponseException ex = (WebClientResponseException) throwable;
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(ex.getStatusText()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
assertThat(ex.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN);
assertThat(ex.getResponseBodyAsString()).isEqualTo(errorMessage);
HttpRequest request = ex.getRequest();
assertThat(request.getMethod()).isEqualTo(HttpMethod.GET);
assertThat(request.getURI()).isEqualTo(URI.create(this.server.url(path).toString()));
assertThat(request.getHeaders()).isNotNull();
})
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo(path);
});
}
@ParameterizedWebClientTest
void retrieve500AsEntity(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.code(500)
.setHeader("Content-Type", "text/plain").body("Internal Server error"));
Mono<ResponseEntity<String>> result = this.webClient.get()
.uri("/").accept(MediaType.APPLICATION_JSON)
.retrieve()
.toEntity(String.class);
StepVerifier.create(result)
.expectError(WebClientResponseException.class)
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void retrieve500AsEntityList(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.code(500)
.setHeader("Content-Type", "text/plain").body("Internal Server error"));
Mono<ResponseEntity<List<String>>> result = this.webClient.get()
.uri("/").accept(MediaType.APPLICATION_JSON)
.retrieve()
.toEntityList(String.class);
StepVerifier.create(result)
.expectError(WebClientResponseException.class)
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void retrieve500AsBodilessEntity(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.code(500)
.setHeader("Content-Type", "text/plain").body("Internal Server error"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.uri("/").accept(MediaType.APPLICATION_JSON)
.retrieve()
.toBodilessEntity();
StepVerifier.create(result)
.expectError(WebClientResponseException.class)
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
@SuppressWarnings("deprecation")
void retrieve555UnknownStatus(ClientHttpConnector connector) throws IOException {
startServer(connector);
int errorStatus = 555;
assertThat(HttpStatus.resolve(errorStatus)).isNull();
String errorMessage = "Something went wrong";
prepareResponse(builder -> builder
.code(errorStatus)
.setHeader("Content-Type", "text/plain")
.body(errorMessage));
Mono<String> result = this.webClient.get().uri("/unknownPage").retrieve().bodyToMono(String.class);
StepVerifier.create(result)
.expectErrorSatisfies(throwable -> {
assertThat(throwable).isInstanceOf(UnknownHttpStatusCodeException.class);
UnknownHttpStatusCodeException ex = (UnknownHttpStatusCodeException) throwable;
assertThat(ex.getMessage()).isEqualTo(("Unknown status code ["+errorStatus+"]"));
assertThat(ex.getStatusText()).isEmpty();
assertThat(ex.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN);
assertThat(ex.getResponseBodyAsString()).isEqualTo(errorMessage);
})
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/unknownPage");
});
}
@ParameterizedWebClientTest // gh-31202
void retrieve929UnknownStatusCode(ClientHttpConnector connector) throws IOException {
startServer(connector);
int errorStatus = 929;
assertThat(HttpStatus.resolve(errorStatus)).isNull();
String errorMessage = "Something went wrong";
prepareResponse(builder ->
builder.code(errorStatus)
.setHeader("Content-Type", "text/plain")
.body(errorMessage));
Mono<String> result = this.webClient.get().uri("/unknownPage").retrieve().bodyToMono(String.class);
StepVerifier.create(result)
.expectErrorSatisfies(throwable -> {
assertThat(throwable).isInstanceOf(UnknownHttpStatusCodeException.class);
UnknownHttpStatusCodeException ex = (UnknownHttpStatusCodeException) throwable;
assertThat(ex.getMessage()).isEqualTo(("Unknown status code ["+errorStatus+"]"));
assertThat(ex.getStatusCode().value()).isEqualTo(errorStatus);
assertThat(ex.getStatusText()).isEmpty();
assertThat(ex.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN);
assertThat(ex.getResponseBodyAsString()).isEqualTo(errorMessage);
})
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/unknownPage");
});
}
@ParameterizedWebClientTest
void postPojoAsJson(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.setHeader("Content-Type", "application/json")
.body("{\"bar\":\"BARBAR\",\"foo\":\"FOOFOO\"}"));
Mono<Pojo> result = this.webClient.post()
.uri("/pojo/capitalize")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(new Pojo("foofoo", "barbar"))
.retrieve()
.bodyToMono(Pojo.class);
StepVerifier.create(result)
.consumeNextWith(p -> assertThat(p.getBar()).isEqualTo("BARBAR"))
.expectComplete()
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/pojo/capitalize");
assertThat(request.getBody().utf8()).isEqualTo("{\"foo\":\"foofoo\",\"bar\":\"barbar\"}");
assertThat(request.getHeaders().get(HttpHeaders.CONTENT_LENGTH)).isEqualTo("31");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
assertThat(request.getHeaders().get(HttpHeaders.CONTENT_TYPE)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest // SPR-16246
void postLargeTextFile(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(Function.identity());
Resource resource = new ClassPathResource("largeTextFile.txt", getClass());
Flux<DataBuffer> body = DataBufferUtils.read(resource, DefaultDataBufferFactory.sharedInstance, 4096);
Mono<Void> result = this.webClient.post()
.uri("/")
.body(body, DataBuffer.class)
.retrieve()
.bodyToMono(Void.class);
StepVerifier.create(result)
.expectComplete()
.verify(Duration.ofSeconds(5));
expectRequest(request -> {
try {
String actual = request.getBody().utf8();
String expected = Files.readString(resource.getFile().toPath(), StandardCharsets.UTF_8);
assertThat(actual).isEqualTo(expected);
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
});
}
@ParameterizedWebClientTest
void statusHandler(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.code(500)
.setHeader("Content-Type", "text/plain").body("Internal Server error"));
Mono<String> result = this.webClient.get()
.uri("/greeting")
.retrieve()
.onStatus(HttpStatusCode::is5xxServerError, response -> Mono.just(new MyException("500 error!")))
.bodyToMono(String.class);
StepVerifier.create(result)
.expectError(MyException.class)
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/greeting");
});
}
@ParameterizedWebClientTest
void statusHandlerParameterizedTypeReference(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.code(500)
.setHeader("Content-Type", "text/plain").body("Internal Server error"));
Mono<String> result = this.webClient.get()
.uri("/greeting")
.retrieve()
.onStatus(HttpStatusCode::is5xxServerError, response -> Mono.just(new MyException("500 error!")))
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(result)
.expectError(MyException.class)
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/greeting");
});
}
@ParameterizedWebClientTest
void statusHandlerWithErrorBodyTransformation(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder
.code(500)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body("{\"bar\":\"barbar\",\"foo\":\"foofoo\"}")
);
Mono<String> result = this.webClient.get()
.uri("/json")
.retrieve()
.onStatus(HttpStatusCode::isError,
response -> response.bodyToMono(Pojo.class)
.flatMap(pojo -> Mono.error(new MyException(pojo.getFoo())))
)
.bodyToMono(String.class);
StepVerifier.create(result)
.consumeErrorWith(throwable -> {
assertThat(throwable).isInstanceOf(MyException.class);
MyException error = (MyException) throwable;
assertThat(error.getMessage()).isEqualTo("foofoo");
})
.verify(Duration.ofSeconds(3));
}
@ParameterizedWebClientTest
void statusHandlerRawStatus(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.code(500)
.setHeader("Content-Type", "text/plain").body("Internal Server error")
);
Mono<String> result = this.webClient.get()
.uri("/greeting")
.retrieve()
.onRawStatus(value -> value >= 500 && value < 600, response -> Mono.just(new MyException("500 error!")))
.bodyToMono(String.class);
StepVerifier.create(result)
.expectError(MyException.class)
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/greeting");
});
}
@ParameterizedWebClientTest
void statusHandlerSuppressedErrorSignal(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.code(500)
.setHeader("Content-Type", "text/plain").body("Internal Server error"));
Mono<String> result = this.webClient.get()
.uri("/greeting")
.retrieve()
.onStatus(HttpStatusCode::is5xxServerError, response -> Mono.empty())
.bodyToMono(String.class);
StepVerifier.create(result)
.expectNext("Internal Server error")
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/greeting");
});
}
@ParameterizedWebClientTest
void statusHandlerSuppressedErrorSignalWithFlux(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.code(500)
.setHeader("Content-Type", "text/plain").body("Internal Server error"));
Flux<String> result = this.webClient.get()
.uri("/greeting")
.retrieve()
.onStatus(HttpStatusCode::is5xxServerError, response -> Mono.empty())
.bodyToFlux(String.class);
StepVerifier.create(result)
.expectNext("Internal Server error")
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/greeting");
});
}
@ParameterizedWebClientTest
void statusHandlerSuppressedErrorSignalWithEntity(ClientHttpConnector connector) throws IOException {
startServer(connector);
String content = "Internal Server error";
prepareResponse(builder -> builder.code(500)
.setHeader("Content-Type", "text/plain").body(content));
Mono<ResponseEntity<String>> result = this.webClient.get()
.uri("/").accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(HttpStatusCode::is5xxServerError, response -> Mono.empty())// use normal response
.toEntity(String.class);
StepVerifier.create(result)
.consumeNextWith(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(entity.getBody()).isEqualTo(content);
})
.expectComplete()
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void exchangeForPlainText(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.body("Hello Spring!"));
Mono<String> result = this.webClient.get()
.uri("/greeting")
.header("X-Test-Header", "testvalue")
.retrieve().bodyToMono(String.class);
StepVerifier.create(result)
.expectNext("Hello Spring!")
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get("X-Test-Header")).isEqualTo("testvalue");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/greeting");
});
}
@ParameterizedWebClientTest
void exchangeForJsonAsResponseEntity(ClientHttpConnector connector) throws IOException {
startServer(connector);
String content = "{\"bar\":\"barbar\",\"foo\":\"foofoo\"}";
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json").body(content));
Mono<ResponseEntity<Pojo>> result = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve().toEntity(Pojo.class);
StepVerifier.create(result)
.consumeNextWith(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(entity.getHeaders().getContentLength()).isEqualTo(31);
assertThat(entity.getBody()).isEqualTo(new Pojo("foofoo", "barbar"));
})
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/json");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void exchangeForJsonAsBodilessEntity(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json").body("{\"bar\":\"barbar\",\"foo\":\"foofoo\"}"));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve().toBodilessEntity();
StepVerifier.create(result)
.consumeNextWith(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(entity.getHeaders().getContentLength()).isEqualTo(31);
assertThat(entity.getBody()).isNull();
})
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/json");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void exchangeForJsonArrayAsResponseEntity(ClientHttpConnector connector) throws IOException {
startServer(connector);
String content = "[{\"bar\":\"bar1\",\"foo\":\"foo1\"}, {\"bar\":\"bar2\",\"foo\":\"foo2\"}]";
prepareResponse(builder -> builder
.setHeader("Content-Type", "application/json").body(content));
Mono<ResponseEntity<List<Pojo>>> result = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve().toEntityList(Pojo.class);
StepVerifier.create(result)
.consumeNextWith(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(entity.getHeaders().getContentLength()).isEqualTo(58);
Pojo pojo1 = new Pojo("foo1", "bar1");
Pojo pojo2 = new Pojo("foo2", "bar2");
assertThat(entity.getBody()).isEqualTo(Arrays.asList(pojo1, pojo2));
})
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getTarget()).isEqualTo("/json");
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
@ParameterizedWebClientTest
void exchangeForEmptyBodyAsVoidEntity(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.addHeader("Content-Length", "0").body(""));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.uri("/noContent")
.retrieve().toBodilessEntity();
StepVerifier.create(result)
.assertNext(r -> assertThat(r.getStatusCode().is2xxSuccessful()).isTrue())
.expectComplete().verify(Duration.ofSeconds(3));
}
@ParameterizedWebClientTest
void exchangeFor404(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.code(404)
.setHeader("Content-Type", "text/plain").body("Not Found"));
Mono<ResponseEntity<Void>> result = this.webClient.get().uri("/greeting")
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.consumeNextWith(entity -> assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND))
.expectComplete()
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/greeting");
});
}
@ParameterizedWebClientTest
void exchangeForUnknownStatusCode(ClientHttpConnector connector) throws IOException {
startServer(connector);
int errorStatus = 555;
assertThat(HttpStatus.resolve(errorStatus)).isNull();
String errorMessage = "Something went wrong";
prepareResponse(builder -> builder.code(errorStatus)
.setHeader("Content-Type", "text/plain").body(errorMessage));
Mono<ResponseEntity<Void>> result = this.webClient.get()
.uri("/unknownPage")
.exchangeToMono(ClientResponse::toBodilessEntity);
StepVerifier.create(result)
.consumeNextWith(entity -> assertThat(entity.getStatusCode().value()).isEqualTo(555))
.expectComplete()
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> {
assertThat(request.getHeaders().get(HttpHeaders.ACCEPT)).isEqualTo("*/*");
assertThat(request.getTarget()).isEqualTo("/unknownPage");
});
}
@ParameterizedWebClientTest
void filter(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder.setHeader("Content-Type", "text/plain")
.body("Hello Spring!"));
WebClient filteredClient = this.webClient.mutate()
.filter((request, next) -> {
ClientRequest filteredRequest =
ClientRequest.from(request).header("foo", "bar").build();
return next.exchange(filteredRequest);
})
.build();
Mono<String> result = filteredClient.get()
.uri("/greeting")
.retrieve()
.bodyToMono(String.class);
StepVerifier.create(result)
.expectNext("Hello Spring!")
.expectComplete()
.verify(Duration.ofSeconds(3));
expectRequestCount(1);
expectRequest(request -> assertThat(request.getHeaders().get("foo")).isEqualTo("bar"));
}
@ParameterizedWebClientTest
void filterForErrorHandling(ClientHttpConnector connector) throws IOException {
startServer(connector);
ExchangeFilterFunction filter = ExchangeFilterFunction.ofResponseProcessor(
clientResponse -> {
List<String> headerValues = clientResponse.headers().header("Foo");
return headerValues.isEmpty() ? Mono.error(
new MyException("Response does not contain Foo header")) :
Mono.just(clientResponse);
}
);
WebClient filteredClient = this.webClient.mutate().filter(filter).build();
// header not present
prepareResponse(builder -> builder
.setHeader("Content-Type", "text/plain")
.body("Hello Spring!"));
Mono<String> result = filteredClient.get()
.uri("/greeting")
.retrieve()
.bodyToMono(String.class);
StepVerifier.create(result)
.expectError(MyException.class).verify(Duration.ofSeconds(3));
// header present
prepareResponse(builder -> builder.setHeader("Content-Type", "text/plain")
.setHeader("Foo", "Bar")
.body("Hello Spring!"));
result = filteredClient.get()
.uri("/greeting")
.retrieve().bodyToMono(String.class);
StepVerifier.create(result)
.expectNext("Hello Spring!")
.expectComplete().verify(Duration.ofSeconds(3));
expectRequestCount(2);
}
@ParameterizedWebClientTest
void exchangeResponseCookies(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder
.setHeader("Content-Type", "text/plain")
.addHeader("Set-Cookie", "testkey1=testvalue1") // TODO invalid ";" at the end
.addHeader("Set-Cookie", "testkey2=testvalue2; Max-Age=42; HttpOnly; SameSite=Lax; Secure")
.body("test"));
this.webClient.get()
.uri("/test")
.exchangeToMono(response -> {
assertThat(response.cookies()).containsOnlyKeys("testkey1", "testkey2");
ResponseCookie cookie1 = response.cookies().get("testkey1").get(0);
assertThat(cookie1.getValue()).isEqualTo("testvalue1");
assertThat(cookie1.isSecure()).isFalse();
assertThat(cookie1.isHttpOnly()).isFalse();
assertThat(cookie1.getMaxAge().getSeconds()).isEqualTo(-1);
ResponseCookie cookie2 = response.cookies().get("testkey2").get(0);
assertThat(cookie2.getValue()).isEqualTo("testvalue2");
assertThat(cookie2.isSecure()).isTrue();
assertThat(cookie2.isHttpOnly()).isTrue();
assertThat(cookie2.getSameSite()).isEqualTo("Lax");
assertThat(cookie2.getMaxAge().getSeconds()).isEqualTo(42);
return response.releaseBody();
})
.block(Duration.ofSeconds(3));
expectRequestCount(1);
}
@ParameterizedWebClientTest
void malformedResponseChunksOnBodilessEntity(ClientHttpConnector connector) {
Mono<?> result = doMalformedChunkedResponseTest(connector, ResponseSpec::toBodilessEntity);
StepVerifier.create(result)
.expectErrorSatisfies(throwable -> {
assertThat(throwable).isInstanceOf(WebClientException.class);
WebClientException ex = (WebClientException) throwable;
assertThat(ex.getCause()).isInstanceOf(IOException.class);
})
.verify(Duration.ofSeconds(3));
}
@ParameterizedWebClientTest
void malformedResponseChunksOnEntityWithBody(ClientHttpConnector connector) {
Mono<?> result = doMalformedChunkedResponseTest(connector, spec -> spec.toEntity(String.class));
StepVerifier.create(result)
.expectErrorSatisfies(throwable -> {
assertThat(throwable).isInstanceOf(WebClientException.class);
WebClientException ex = (WebClientException) throwable;
assertThat(ex.getCause()).isInstanceOf(IOException.class);
})
.verify(Duration.ofSeconds(3));
}
@ParameterizedWebClientTest
void retrieveTextDecodedToFlux(ClientHttpConnector connector) throws IOException {
startServer(connector);
prepareResponse(builder -> builder
.addHeader("Content-Type", "text/plain")
.body("Hey now"));
Flux<String> result = this.webClient.get()
.uri("/")
.accept(MediaType.TEXT_PLAIN)
.retrieve()
.bodyToFlux(String.class);
StepVerifier.create(result)
.expectNext("Hey now")
.expectComplete()
.verify(Duration.ofSeconds(3));
}
private <T> Mono<T> doMalformedChunkedResponseTest(
ClientHttpConnector connector, Function<ResponseSpec, Mono<T>> handler) {
Sinks.One<Integer> portSink = Sinks.one();
Thread serverThread = new Thread(() -> {
// No way to simulate a malformed chunked response through MockWebServer.
try (ServerSocket serverSocket = new ServerSocket(0)) {
Sinks.EmitResult result = portSink.tryEmitValue(serverSocket.getLocalPort());
assertThat(result).isEqualTo(Sinks.EmitResult.OK);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
//noinspection ResultOfMethodCallIgnored
is.read(new byte[4096]);
OutputStream os = socket.getOutputStream();
os.write("""
HTTP/1.1 200 OK
Transfer-Encoding: chunked
lskdu018973t09sylgasjkfg1][]'./.sdlv"""
.replace("\n", "\r\n").getBytes(StandardCharsets.UTF_8));
socket.close();
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
});
serverThread.start();
return portSink.asMono().flatMap(port -> {
WebClient client = WebClient.builder()
.clientConnector(connector)
.baseUrl("http://localhost:" + port)
.build();
return handler.apply(client.post().retrieve());
});
}
private void prepareResponse(Function<MockResponse.Builder, MockResponse.Builder> f) {
MockResponse.Builder builder = new MockResponse.Builder();
this.server.enqueue(f.apply(builder).build());
}
private void expectRequest(Consumer<RecordedRequest> consumer) {
try {
consumer.accept(this.server.takeRequest());
}
catch (InterruptedException ex) {
throw new IllegalStateException(ex);
}
}
private void expectRequestCount(int count) {
assertThat(this.server.getRequestCount()).isEqualTo(count);
}
@SuppressWarnings("serial")
private static
|
ParameterizedWebClientTest
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/UngroupedOverloadsTest.java
|
{
"start": 19536,
"end": 19885
}
|
class ____ {
void foo() {}
void bar() {}
@SuppressWarnings("UngroupedOverloads")
void foo(int x) {}
}
""")
.doTest();
}
@Test
public void javadoc() {
refactoringHelper
.addInputLines(
"in/Test.java",
"""
|
Test
|
java
|
elastic__elasticsearch
|
libs/core/src/main/java/org/elasticsearch/core/Glob.java
|
{
"start": 557,
"end": 4974
}
|
class ____ {
private Glob() {}
/**
* Match a String against the given pattern, supporting the following simple
* pattern styles: "xxx*", "*xxx", "*xxx*" and "xxx*yyy" matches (with an
* arbitrary number of pattern parts), as well as direct equality.
*
* @param pattern the pattern to match against
* @param str the String to match
* @return whether the String matches the given pattern
*/
public static boolean globMatch(String pattern, String str) {
if (pattern == null || str == null) {
return false;
}
int patternIndex = pattern.indexOf('*');
if (patternIndex == -1) {
// Nothing to glob
return pattern.equals(str);
}
if (patternIndex == 0) {
// If the pattern is a literal '*' then it matches any input
if (pattern.length() == 1) {
return true;
}
} else {
if (str.regionMatches(0, pattern, 0, patternIndex) == false) {
// If the pattern starts with a literal (i.e. not '*') then the input string must also start with that
return false;
}
if (patternIndex == pattern.length() - 1) {
// The pattern is "something*", so if the starting region matches, then the whole pattern matches
return true;
}
}
int strIndex = patternIndex;
while (strIndex < str.length()) {
assert pattern.charAt(patternIndex) == '*' : "Expected * at index " + patternIndex + " of [" + pattern + "]";
// skip over the '*'
patternIndex++;
if (patternIndex == pattern.length()) {
// The pattern ends in '*' (that is, "something*" or "*some*thing*", etc)
// Since we already matched everything up to the '*' we know the string matches (whatever is left over must match '*')
// so we're automatically done
return true;
}
// Look for the next '*'
int nextStar = pattern.indexOf('*', patternIndex);
while (nextStar == patternIndex) {
// Two (or more) stars in sequence, just skip the subsequent ones
patternIndex++;
nextStar = pattern.indexOf('*', patternIndex);
}
if (nextStar == -1) {
// We've come to the last '*' in a pattern (.e.g the 2nd one in "*some*thing")
// In this case we match if the input string ends in "thing" (but constrained by the current position)
final int len = pattern.length() - patternIndex;
final int strSuffixStart = str.length() - len;
if (strSuffixStart < strIndex) {
// The suffix would start before the current position. That means it's not a match
// e.g. "abc" is not a match for "ab*bc" even though "abc" does end with "bc"
return false;
}
return str.regionMatches(strSuffixStart, pattern, patternIndex, len);
} else {
// There is another star, with a literal in between the current position and that '*'
// That is, we have "*literal*"
// We want the first '*' to consume everything up until the first occurrence of "literal" in the input string
int match = str.indexOf(pattern.substring(patternIndex, nextStar), strIndex);
if (match == -1) {
// If "literal" isn't there, then the match fails.
return false;
}
// Move both index (pointer) values to the end of the literal
strIndex = match + (nextStar - patternIndex);
patternIndex = nextStar;
}
}
// We might have trailing '*'s in the pattern after completing a literal match at the end of the input string
// e.g. a glob of "el*ic*" matching "elastic" - we need to consume that last '*' without it matching anything
while (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') {
patternIndex++;
}
// The match is successful only if we have consumed the entire pattern.
return patternIndex == pattern.length();
}
}
|
Glob
|
java
|
netty__netty
|
transport-native-io_uring/src/test/java/io/netty/channel/uring/IoUringSocketFixedLengthEchoTest.java
|
{
"start": 1010,
"end": 1379
}
|
class ____ extends SocketFixedLengthEchoTest {
@BeforeAll
public static void loadJNI() {
assumeTrue(IoUring.isAvailable());
}
@Override
protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() {
return IoUringSocketTestPermutation.INSTANCE.socket();
}
}
|
IoUringSocketFixedLengthEchoTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/voyageai/response/VoyageAIEmbeddingsResponseEntity.java
|
{
"start": 1615,
"end": 8321
}
|
class ____ {
private static final String VALID_EMBEDDING_TYPES_STRING = supportedEmbeddingTypes();
private static String supportedEmbeddingTypes() {
String[] validTypes = new String[] {
toLowerCase(VoyageAIEmbeddingType.FLOAT),
toLowerCase(VoyageAIEmbeddingType.INT8),
toLowerCase(VoyageAIEmbeddingType.BIT) };
Arrays.sort(validTypes);
return String.join(", ", validTypes);
}
record EmbeddingInt8Result(List<EmbeddingInt8ResultEntry> entries) {
@SuppressWarnings("unchecked")
public static final ConstructingObjectParser<EmbeddingInt8Result, Void> PARSER = new ConstructingObjectParser<>(
EmbeddingInt8Result.class.getSimpleName(),
true,
args -> new EmbeddingInt8Result((List<EmbeddingInt8ResultEntry>) args[0])
);
static {
PARSER.declareObjectArray(constructorArg(), EmbeddingInt8ResultEntry.PARSER::apply, new ParseField("data"));
}
}
record EmbeddingInt8ResultEntry(Integer index, List<Integer> embedding) {
@SuppressWarnings("unchecked")
public static final ConstructingObjectParser<EmbeddingInt8ResultEntry, Void> PARSER = new ConstructingObjectParser<>(
EmbeddingInt8ResultEntry.class.getSimpleName(),
true,
args -> new EmbeddingInt8ResultEntry((Integer) args[0], (List<Integer>) args[1])
);
static {
PARSER.declareInt(constructorArg(), new ParseField("index"));
PARSER.declareIntArray(constructorArg(), new ParseField("embedding"));
}
private static void checkByteBounds(Integer value) {
if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
throw new IllegalArgumentException("Value [" + value + "] is out of range for a byte");
}
}
public DenseEmbeddingByteResults.Embedding toInferenceByteEmbedding() {
embedding.forEach(EmbeddingInt8ResultEntry::checkByteBounds);
return DenseEmbeddingByteResults.Embedding.of(embedding.stream().map(Integer::byteValue).toList());
}
}
record EmbeddingFloatResult(List<EmbeddingFloatResultEntry> entries) {
@SuppressWarnings("unchecked")
public static final ConstructingObjectParser<EmbeddingFloatResult, Void> PARSER = new ConstructingObjectParser<>(
EmbeddingFloatResult.class.getSimpleName(),
true,
args -> new EmbeddingFloatResult((List<EmbeddingFloatResultEntry>) args[0])
);
static {
PARSER.declareObjectArray(constructorArg(), EmbeddingFloatResultEntry.PARSER::apply, new ParseField("data"));
}
}
record EmbeddingFloatResultEntry(Integer index, List<Float> embedding) {
@SuppressWarnings("unchecked")
public static final ConstructingObjectParser<EmbeddingFloatResultEntry, Void> PARSER = new ConstructingObjectParser<>(
EmbeddingFloatResultEntry.class.getSimpleName(),
true,
args -> new EmbeddingFloatResultEntry((Integer) args[0], (List<Float>) args[1])
);
static {
PARSER.declareInt(constructorArg(), new ParseField("index"));
PARSER.declareFloatArray(constructorArg(), new ParseField("embedding"));
}
public DenseEmbeddingFloatResults.Embedding toInferenceFloatEmbedding() {
return DenseEmbeddingFloatResults.Embedding.of(embedding);
}
}
/**
* Parses the VoyageAI json response.
* For a request like:
*
* <pre>
* <code>
* {
* "input": [
* "Sample text 1",
* "Sample text 2"
* ],
* "model": "voyage-3-large"
* }
* </code>
* </pre>
*
* The response would look like:
*
* <pre>
* <code>
* {
* "object": "list",
* "data": [
* {
* "object": "embedding",
* "embedding": [
* -0.009327292,
* -0.0028842222,
* ],
* "index": 0
* },
* {
* "object": "embedding",
* "embedding": [ ... ],
* "index": 1
* }
* ],
* "model": "voyage-3-large",
* "usage": {
* "total_tokens": 10
* }
* }
* </code>
* </pre>
*/
public static InferenceServiceResults fromResponse(Request request, HttpResult response) throws IOException {
var parserConfig = XContentParserConfiguration.EMPTY.withDeprecationHandler(LoggingDeprecationHandler.INSTANCE);
VoyageAIEmbeddingType embeddingType = ((VoyageAIEmbeddingsRequest) request).getServiceSettings().getEmbeddingType();
try (XContentParser jsonParser = XContentFactory.xContent(XContentType.JSON).createParser(parserConfig, response.body())) {
if (embeddingType == null || embeddingType == VoyageAIEmbeddingType.FLOAT) {
var embeddingResult = EmbeddingFloatResult.PARSER.apply(jsonParser, null);
List<DenseEmbeddingFloatResults.Embedding> embeddingList = embeddingResult.entries.stream()
.map(EmbeddingFloatResultEntry::toInferenceFloatEmbedding)
.toList();
return new DenseEmbeddingFloatResults(embeddingList);
} else if (embeddingType == VoyageAIEmbeddingType.INT8) {
var embeddingResult = EmbeddingInt8Result.PARSER.apply(jsonParser, null);
List<DenseEmbeddingByteResults.Embedding> embeddingList = embeddingResult.entries.stream()
.map(EmbeddingInt8ResultEntry::toInferenceByteEmbedding)
.toList();
return new DenseEmbeddingByteResults(embeddingList);
} else if (embeddingType == VoyageAIEmbeddingType.BIT || embeddingType == VoyageAIEmbeddingType.BINARY) {
var embeddingResult = EmbeddingInt8Result.PARSER.apply(jsonParser, null);
List<DenseEmbeddingByteResults.Embedding> embeddingList = embeddingResult.entries.stream()
.map(EmbeddingInt8ResultEntry::toInferenceByteEmbedding)
.toList();
return new DenseEmbeddingBitResults(embeddingList);
} else {
throw new IllegalArgumentException(
"Illegal embedding_type value: " + embeddingType + ". Supported types are: " + VALID_EMBEDDING_TYPES_STRING
);
}
}
}
private VoyageAIEmbeddingsResponseEntity() {}
}
|
VoyageAIEmbeddingsResponseEntity
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/JobIntermediateDatasetReuseTest.java
|
{
"start": 10453,
"end": 11327
}
|
class ____ extends AbstractInvokable {
public Receiver(Environment environment) {
super(environment);
}
@Override
public void invoke() throws Exception {
int index = getIndexInSubtaskGroup();
final RecordReader<IntValue> reader =
new RecordReader<>(
getEnvironment().getInputGate(0),
IntValue.class,
getEnvironment().getTaskManagerInfo().getTmpDirectories());
for (int i = index; i < index + 100; ++i) {
final int value = reader.next().getValue();
LOG.debug("Receiver({}) received {}", index, value);
Assertions.assertThat(value).isEqualTo(i);
}
Assertions.assertThat(reader.next()).isNull();
}
}
}
|
Receiver
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/QueueACLsManager.java
|
{
"start": 1602,
"end": 3776
}
|
class ____ {
ResourceScheduler scheduler;
boolean isACLsEnable;
YarnAuthorizationProvider authorizer;
@VisibleForTesting
public QueueACLsManager(Configuration conf) {
this(null, new Configuration());
}
public QueueACLsManager(ResourceScheduler scheduler, Configuration conf) {
this.scheduler = scheduler;
this.isACLsEnable = conf.getBoolean(YarnConfiguration.YARN_ACL_ENABLE,
YarnConfiguration.DEFAULT_YARN_ACL_ENABLE);
this.authorizer = YarnAuthorizationProvider.getInstance(conf);
}
/**
* Get queue acl manager corresponding to the scheduler.
* @param scheduler the scheduler for which the queue acl manager is required
* @param conf Configuration.
* @return {@link QueueACLsManager}
*/
public static QueueACLsManager getQueueACLsManager(
ResourceScheduler scheduler, Configuration conf) {
if (scheduler instanceof CapacityScheduler) {
return new CapacityQueueACLsManager(scheduler, conf);
} else if (scheduler instanceof FairScheduler) {
return new FairQueueACLsManager(scheduler, conf);
} else {
return new GenericQueueACLsManager(scheduler, conf);
}
}
public abstract boolean checkAccess(UserGroupInformation callerUGI,
QueueACL acl, RMApp app, String remoteAddress,
List<String> forwardedAddresses);
/**
* Check access to a targetQueue in the case of a move of an application.
* The application cannot contain the destination queue since it has not
* been moved yet, thus need to pass it in separately.
*
* @param callerUGI the caller UGI
* @param acl the acl for the Queue to check
* @param app the application to move
* @param remoteAddress server ip address
* @param forwardedAddresses forwarded adresses
* @param targetQueue the name of the queue to move the application to
* @return true: if submission is allowed and queue exists,
* false: in all other cases (also non existing target queue)
*/
public abstract boolean checkAccess(UserGroupInformation callerUGI,
QueueACL acl, RMApp app, String remoteAddress,
List<String> forwardedAddresses, String targetQueue);
}
|
QueueACLsManager
|
java
|
netty__netty
|
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketFrameDecoder.java
|
{
"start": 955,
"end": 1021
}
|
interface ____ extends ChannelInboundHandler {
}
|
WebSocketFrameDecoder
|
java
|
apache__camel
|
components/camel-mock/src/main/java/org/apache/camel/component/mock/MockExpressionClauseSupport.java
|
{
"start": 1039,
"end": 1314
}
|
class ____ building expression clauses.
* <p/>
* This implementation is a derived copy of the <tt>org.apache.camel.builder.ExpressionClauseSupport</tt> from
* camel-core, that are specialized for being used with the mock component and separated from camel-core.
*/
public
|
for
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/dialect/hive/stmt/HiveCreateFunctionStatement.java
|
{
"start": 352,
"end": 2348
}
|
class ____ extends SQLCreateFunctionStatement implements SQLCreateStatement {
protected boolean declare;
protected SQLExpr className;
protected SQLExpr location;
protected SQLExpr symbol;
protected ResourceType resourceType;
protected String code;
public HiveCreateFunctionStatement() {
}
public void accept0(SQLASTVisitor visitor) {
if (visitor instanceof HiveASTVisitor) {
accept0((HiveASTVisitor) visitor);
} else {
super.accept0(visitor);
}
}
protected void accept0(HiveASTVisitor visitor) {
if (visitor.visit(this)) {
this.acceptChild(visitor, name);
this.acceptChild(visitor, className);
this.acceptChild(visitor, location);
this.acceptChild(visitor, symbol);
}
visitor.endVisit(this);
}
public SQLExpr getClassName() {
return className;
}
public void setClassName(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.className = x;
}
public SQLExpr getLocation() {
return location;
}
public void setLocation(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.location = x;
}
public SQLExpr getSymbol() {
return symbol;
}
public void setSymbol(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.symbol = x;
}
public ResourceType getResourceType() {
return resourceType;
}
public void setResourceType(ResourceType resourceType) {
this.resourceType = resourceType;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public boolean isDeclare() {
return declare;
}
public void setDeclare(boolean declare) {
this.declare = declare;
}
public static
|
HiveCreateFunctionStatement
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/TestSequenceFile.java
|
{
"start": 22620,
"end": 30052
}
|
class ____ extends FSDataInputStream {
private boolean closed = false;
private TestFSDataInputStream(InputStream in) throws IOException {
super(in);
}
@Override
public void close() throws IOException {
closed = true;
super.close();
}
public boolean isClosed() {
return closed;
}
}
@SuppressWarnings("deprecation")
@Test
public void testCloseForErroneousSequenceFile()
throws IOException {
Configuration conf = new Configuration();
LocalFileSystem fs = FileSystem.getLocal(conf);
// create an empty file (which is not a valid sequence file)
Path path = new Path(GenericTestUtils.getTempPath("broken.seq"));
fs.create(path).close();
// try to create SequenceFile.Reader
final TestFSDataInputStream[] openedFile = new TestFSDataInputStream[1];
try {
new SequenceFile.Reader(fs, path, conf) {
// this method is called by the SequenceFile.Reader constructor, overwritten, so we can access the opened file
@Override
protected FSDataInputStream openFile(FileSystem fs, Path file, int bufferSize, long length) throws IOException {
final InputStream in = super.openFile(fs, file, bufferSize, length);
openedFile[0] = new TestFSDataInputStream(in);
return openedFile[0];
}
};
fail("IOException expected.");
} catch (IOException expected) {}
assertNotNull(openedFile[0], path + " should have been opened.");
assertTrue(openedFile[0].isClosed(), "InputStream for " + path + " should have been closed.");
}
/**
* Test to makes sure zero length sequence file is handled properly while
* initializing.
*/
@Test
public void testInitZeroLengthSequenceFile() throws IOException {
Configuration conf = new Configuration();
LocalFileSystem fs = FileSystem.getLocal(conf);
// create an empty file (which is not a valid sequence file)
Path path = new Path(GenericTestUtils.getTempPath("zerolength.seq"));
fs.create(path).close();
try {
new SequenceFile.Reader(conf, SequenceFile.Reader.file(path));
fail("IOException expected.");
} catch (IOException expected) {
assertTrue(expected instanceof EOFException);
}
}
/**
* Test that makes sure createWriter succeeds on a file that was
* already created
* @throws IOException
*/
@SuppressWarnings("deprecation")
@Test
public void testCreateWriterOnExistingFile() throws IOException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.getLocal(conf);
Path name = new Path(new Path(GenericTestUtils.getTempPath(
"createWriterOnExistingFile")), "file");
fs.create(name);
SequenceFile.createWriter(fs, conf, name, RandomDatum.class,
RandomDatum.class, 512, (short) 1, 4096, false,
CompressionType.NONE, null, new Metadata());
}
@SuppressWarnings("deprecation")
@Test
public void testRecursiveSeqFileCreate() throws IOException {
FileSystem fs = FileSystem.getLocal(conf);
Path parentDir = new Path(GenericTestUtils.getTempPath(
"recursiveCreateDir"));
Path name = new Path(parentDir, "file");
boolean createParent = false;
try {
SequenceFile.createWriter(fs, conf, name, RandomDatum.class,
RandomDatum.class, 512, (short) 1, 4096, createParent,
CompressionType.NONE, null, new Metadata());
fail("Expected an IOException due to missing parent");
} catch (IOException ioe) {
// Expected
}
try {
createParent = true;
SequenceFile.createWriter(fs, conf, name, RandomDatum.class,
RandomDatum.class, 512, (short) 1, 4096, createParent,
CompressionType.NONE, null, new Metadata());
// should succeed, fails if exception thrown
} finally {
fs.deleteOnExit(parentDir);
fs.close();
}
}
@Test
public void testSerializationAvailability() throws IOException {
Configuration conf = new Configuration();
Path path = new Path(GenericTestUtils.getTempPath(
"serializationAvailability"));
// Check if any serializers aren't found.
try {
SequenceFile.createWriter(
conf,
SequenceFile.Writer.file(path),
SequenceFile.Writer.keyClass(String.class),
SequenceFile.Writer.valueClass(NullWritable.class));
// Note: This may also fail someday if JavaSerialization
// is activated by default.
fail("Must throw IOException for missing serializer for the Key class");
} catch (IOException e) {
assertTrue(e.getMessage().startsWith(
"Could not find a serializer for the Key class: '" +
String.class.getName() + "'."));
}
try {
SequenceFile.createWriter(
conf,
SequenceFile.Writer.file(path),
SequenceFile.Writer.keyClass(NullWritable.class),
SequenceFile.Writer.valueClass(String.class));
// Note: This may also fail someday if JavaSerialization
// is activated by default.
fail("Must throw IOException for missing serializer for the Value class");
} catch (IOException e) {
assertTrue(e.getMessage().startsWith(
"Could not find a serializer for the Value class: '" +
String.class.getName() + "'."));
}
// Write a simple file to test deserialization failures with
writeTest(FileSystem.get(conf), 1, 1, path, CompressionType.NONE, null);
// Remove Writable serializations, to enforce error.
conf.setStrings(CommonConfigurationKeys.IO_SERIALIZATIONS_KEY,
AvroReflectSerialization.class.getName());
// Now check if any deserializers aren't found.
try {
new SequenceFile.Reader(
conf,
SequenceFile.Reader.file(path));
fail("Must throw IOException for missing deserializer for the Key class");
} catch (IOException e) {
assertTrue(e.getMessage().startsWith(
"Could not find a deserializer for the Key class: '" +
RandomDatum.class.getName() + "'."));
}
}
@Test
public void testSequenceFileWriter() throws Exception {
Configuration conf = new Configuration();
// This test only works with Raw File System and not Local File System
FileSystem fs = FileSystem.getLocal(conf).getRaw();
Path p = new Path(GenericTestUtils
.getTempPath("testSequenceFileWriter.seq"));
try(SequenceFile.Writer writer = SequenceFile.createWriter(
fs, conf, p, LongWritable.class, Text.class)) {
assertThat(writer.hasCapability
(StreamCapabilities.HSYNC)).isEqualTo(true);
assertThat(writer.hasCapability(
StreamCapabilities.HFLUSH)).isEqualTo(true);
LongWritable key = new LongWritable();
key.set(1);
Text value = new Text();
value.set("somevalue");
writer.append(key, value);
writer.flush();
writer.hflush();
writer.hsync();
assertThat(fs.getFileStatus(p).getLen()).isGreaterThan(0);
}
}
@Test
public void testSerializationUsingWritableNameAlias() throws IOException {
Configuration config = new Configuration();
config.set(CommonConfigurationKeys.IO_SERIALIZATIONS_KEY, SimpleSerializer.class.getName());
Path path = new Path(System.getProperty("test.build.data", "."),
"SerializationUsingWritableNameAlias");
// write with the original serializable
|
TestFSDataInputStream
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileStatus.java
|
{
"start": 2099,
"end": 16933
}
|
enum ____ {
/** ACL information available for this entity. */
HAS_ACL,
/** Entity is encrypted. */
HAS_CRYPT,
/** Entity is stored erasure-coded. */
HAS_EC,
/** Snapshot capability enabled. */
SNAPSHOT_ENABLED,
}
/**
* Shared, empty set of attributes (a common case for FileStatus).
*/
public static final Set<AttrFlags> NONE = Collections.<AttrFlags>emptySet();
/**
* Convert boolean attributes to a set of flags.
* @param acl See {@link AttrFlags#HAS_ACL}.
* @param crypt See {@link AttrFlags#HAS_CRYPT}.
* @param ec See {@link AttrFlags#HAS_EC}.
* @param sn See {@link AttrFlags#SNAPSHOT_ENABLED}.
* @return converted set of flags.
*/
public static Set<AttrFlags> attributes(boolean acl, boolean crypt,
boolean ec, boolean sn) {
if (!(acl || crypt || ec || sn)) {
return NONE;
}
EnumSet<AttrFlags> ret = EnumSet.noneOf(AttrFlags.class);
if (acl) {
ret.add(AttrFlags.HAS_ACL);
}
if (crypt) {
ret.add(AttrFlags.HAS_CRYPT);
}
if (ec) {
ret.add(AttrFlags.HAS_EC);
}
if (sn) {
ret.add(AttrFlags.SNAPSHOT_ENABLED);
}
return ret;
}
public FileStatus() { this(0, false, 0, 0, 0, 0, null, null, null, null); }
//We should deprecate this soon?
public FileStatus(long length, boolean isdir, int block_replication,
long blocksize, long modification_time, Path path) {
this(length, isdir, block_replication, blocksize, modification_time,
0, null, null, null, path);
}
/**
* Constructor for file systems on which symbolic links are not supported
*
* @param length length.
* @param isdir isdir.
* @param block_replication block replication.
* @param blocksize block size.
* @param modification_time modification time.
* @param access_time access_time.
* @param permission permission.
* @param owner owner.
* @param group group.
* @param path the path.
*/
public FileStatus(long length, boolean isdir,
int block_replication,
long blocksize, long modification_time, long access_time,
FsPermission permission, String owner, String group,
Path path) {
this(length, isdir, block_replication, blocksize, modification_time,
access_time, permission, owner, group, null, path);
}
public FileStatus(long length, boolean isdir,
int block_replication,
long blocksize, long modification_time, long access_time,
FsPermission permission, String owner, String group,
Path symlink,
Path path) {
this(length, isdir, block_replication, blocksize, modification_time,
access_time, permission, owner, group, symlink, path,
false, false, false);
}
public FileStatus(long length, boolean isdir, int block_replication,
long blocksize, long modification_time, long access_time,
FsPermission permission, String owner, String group, Path symlink,
Path path, boolean hasAcl, boolean isEncrypted, boolean isErasureCoded) {
this(length, isdir, block_replication, blocksize, modification_time,
access_time, permission, owner, group, symlink, path,
attributes(hasAcl, isEncrypted, isErasureCoded, false));
}
public FileStatus(long length, boolean isdir, int block_replication,
long blocksize, long modification_time, long access_time,
FsPermission permission, String owner, String group, Path symlink,
Path path, Set<AttrFlags> attr) {
this.length = length;
this.isdir = isdir;
this.block_replication = (short)block_replication;
this.blocksize = blocksize;
this.modification_time = modification_time;
this.access_time = access_time;
if (permission != null) {
this.permission = permission;
} else if (isdir) {
this.permission = FsPermission.getDirDefault();
} else if (symlink != null) {
this.permission = FsPermission.getDefault();
} else {
this.permission = FsPermission.getFileDefault();
}
this.owner = (owner == null) ? "" : owner;
this.group = (group == null) ? "" : group;
this.symlink = symlink;
this.path = path;
this.attr = attr;
// The variables isdir and symlink indicate the type:
// 1. isdir implies directory, in which case symlink must be null.
// 2. !isdir implies a file or symlink, symlink != null implies a
// symlink, otherwise it's a file.
assert (isdir && symlink == null) || !isdir;
}
/**
* Copy constructor.
*
* @param other FileStatus to copy
* @throws IOException raised on errors performing I/O.
*/
public FileStatus(FileStatus other) throws IOException {
// It's important to call the getters here instead of directly accessing the
// members. Subclasses like ViewFsFileStatus can override the getters.
this(other.getLen(), other.isDirectory(), other.getReplication(),
other.getBlockSize(), other.getModificationTime(), other.getAccessTime(),
other.getPermission(), other.getOwner(), other.getGroup(),
(other.isSymlink() ? other.getSymlink() : null),
other.getPath());
}
/**
* Get the length of this file, in bytes.
* @return the length of this file, in bytes.
*/
public long getLen() {
return length;
}
/**
* Is this a file?
* @return true if this is a file
*/
public boolean isFile() {
return !isDirectory() && !isSymlink();
}
/**
* Is this a directory?
* @return true if this is a directory
*/
public boolean isDirectory() {
return isdir;
}
/**
* Old interface, instead use the explicit {@link FileStatus#isFile()},
* {@link FileStatus#isDirectory()}, and {@link FileStatus#isSymlink()}
* @return true if this is a directory.
* @deprecated Use {@link FileStatus#isFile()},
* {@link FileStatus#isDirectory()}, and {@link FileStatus#isSymlink()}
* instead.
*/
@Deprecated
public final boolean isDir() {
return isDirectory();
}
/**
* Is this a symbolic link?
* @return true if this is a symbolic link
*/
public boolean isSymlink() {
return symlink != null;
}
/**
* Get the block size of the file.
* @return the number of bytes
*/
public long getBlockSize() {
return blocksize;
}
/**
* Get the replication factor of a file.
* @return the replication factor of a file.
*/
public short getReplication() {
return block_replication;
}
/**
* Get the modification time of the file.
* @return the modification time of file in milliseconds since January 1, 1970 UTC.
*/
public long getModificationTime() {
return modification_time;
}
/**
* Get the access time of the file.
* @return the access time of file in milliseconds since January 1, 1970 UTC.
*/
public long getAccessTime() {
return access_time;
}
/**
* Get FsPermission associated with the file.
* @return permission. If a filesystem does not have a notion of permissions
* or if permissions could not be determined, then default
* permissions equivalent of "rwxrwxrwx" is returned.
*/
public FsPermission getPermission() {
return permission;
}
/**
* Tell whether the underlying file or directory has ACLs set.
*
* @return true if the underlying file or directory has ACLs set.
*/
public boolean hasAcl() {
return attr.contains(AttrFlags.HAS_ACL);
}
/**
* Tell whether the underlying file or directory is encrypted or not.
*
* @return true if the underlying file is encrypted.
*/
public boolean isEncrypted() {
return attr.contains(AttrFlags.HAS_CRYPT);
}
/**
* Tell whether the underlying file or directory is erasure coded or not.
*
* @return true if the underlying file or directory is erasure coded.
*/
public boolean isErasureCoded() {
return attr.contains(AttrFlags.HAS_EC);
}
/**
* Check if directory is Snapshot enabled or not.
*
* @return true if directory is snapshot enabled
*/
public boolean isSnapshotEnabled() {
return attr.contains(AttrFlags.SNAPSHOT_ENABLED);
}
/**
* Get the owner of the file.
* @return owner of the file. The string could be empty if there is no
* notion of owner of a file in a filesystem or if it could not
* be determined (rare).
*/
public String getOwner() {
return owner;
}
/**
* Get the group associated with the file.
* @return group for the file. The string could be empty if there is no
* notion of group of a file in a filesystem or if it could not
* be determined (rare).
*/
public String getGroup() {
return group;
}
public Path getPath() {
return path;
}
public void setPath(final Path p) {
path = p;
}
/* These are provided so that these values could be loaded lazily
* by a filesystem (e.g. local file system).
*/
/**
* Sets permission.
* @param permission if permission is null, default value is set
*/
protected void setPermission(FsPermission permission) {
this.permission = (permission == null) ?
FsPermission.getFileDefault() : permission;
}
/**
* Sets owner.
* @param owner if it is null, default value is set
*/
protected void setOwner(String owner) {
this.owner = (owner == null) ? "" : owner;
}
/**
* Sets group.
* @param group if it is null, default value is set
*/
protected void setGroup(String group) {
this.group = (group == null) ? "" : group;
}
/**
* @return The contents of the symbolic link.
*
* @throws IOException raised on errors performing I/O.
*/
public Path getSymlink() throws IOException {
if (!isSymlink()) {
throw new IOException("Path " + path + " is not a symbolic link");
}
return symlink;
}
public void setSymlink(final Path p) {
symlink = p;
}
/**
* Compare this FileStatus to another FileStatus based on lexicographical
* order of path.
* @param o the FileStatus to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*/
public int compareTo(FileStatus o) {
return this.getPath().compareTo(o.getPath());
}
/**
* Compare this FileStatus to another FileStatus based on lexicographical
* order of path.
* This method was added back by HADOOP-14683 to keep binary compatibility.
*
* @param o the FileStatus to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
* @throws ClassCastException if the specified object is not FileStatus
*/
@Override
public int compareTo(Object o) {
FileStatus other = (FileStatus) o;
return compareTo(other);
}
/** Compare if this object is equal to another object
* @param o the object to be compared.
* @return true if two file status has the same path name; false if not.
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof FileStatus)) {
return false;
}
if (this == o) {
return true;
}
FileStatus other = (FileStatus)o;
return this.getPath().equals(other.getPath());
}
/**
* Returns a hash code value for the object, which is defined as
* the hash code of the path name.
*
* @return a hash code value for the path name.
*/
@Override
public int hashCode() {
return getPath().hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName())
.append("{")
.append("path=" + path)
.append("; isDirectory=" + isdir);
if(!isDirectory()){
sb.append("; length=" + length)
.append("; replication=" + block_replication)
.append("; blocksize=" + blocksize);
}
sb.append("; modification_time=" + modification_time)
.append("; access_time=" + access_time)
.append("; owner=" + owner)
.append("; group=" + group)
.append("; permission=" + permission)
.append("; isSymlink=" + isSymlink());
if(isSymlink()) {
try {
sb.append("; symlink=" + getSymlink());
} catch (IOException e) {
throw new RuntimeException("Unexpected exception", e);
}
}
sb.append("; hasAcl=" + hasAcl())
.append("; isEncrypted=" + isEncrypted())
.append("; isErasureCoded=" + isErasureCoded())
.append("}");
return sb.toString();
}
/**
* Read instance encoded as protobuf from stream.
* @param in Input stream
* @see PBHelper#convert(FileStatus)
* @deprecated Use the {@link PBHelper} and protobuf serialization directly.
*/
@Override
@Deprecated
public void readFields(DataInput in) throws IOException {
int size = in.readInt();
if (size < 0) {
throw new IOException("Can't read FileStatusProto with negative " +
"size of " + size);
}
byte[] buf = new byte[size];
in.readFully(buf);
FileStatusProto proto = FileStatusProto.parseFrom(buf);
FileStatus other = PBHelper.convert(proto);
isdir = other.isDirectory();
length = other.getLen();
block_replication = other.getReplication();
blocksize = other.getBlockSize();
modification_time = other.getModificationTime();
access_time = other.getAccessTime();
setPermission(other.getPermission());
setOwner(other.getOwner());
setGroup(other.getGroup());
setSymlink((other.isSymlink() ? other.getSymlink() : null));
setPath(other.getPath());
attr = attributes(other.hasAcl(), other.isEncrypted(),
other.isErasureCoded(), other.isSnapshotEnabled());
assert !(isDirectory() && isSymlink()) : "A directory cannot be a symlink";
}
/**
* Write instance encoded as protobuf to stream.
* @param out Output stream
* @see PBHelper#convert(FileStatus)
* @deprecated Use the {@link PBHelper} and protobuf serialization directly.
*/
@Override
@Deprecated
public void write(DataOutput out) throws IOException {
FileStatusProto proto = PBHelper.convert(this);
int size = proto.getSerializedSize();
out.writeInt(size);
out.write(proto.toByteArray());
}
@Override
public void validateObject() throws InvalidObjectException {
if (null == path) {
throw new InvalidObjectException("No Path in deserialized FileStatus");
}
if (null == isdir) {
throw new InvalidObjectException("No type in deserialized FileStatus");
}
}
}
|
AttrFlags
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DMSEndpointBuilderFactory.java
|
{
"start": 18083,
"end": 20554
}
|
interface ____
extends
EndpointProducerBuilder {
default DMSEndpointBuilder basic() {
return (DMSEndpointBuilder) this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedDMSEndpointBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedDMSEndpointBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
}
public
|
AdvancedDMSEndpointBuilder
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/DeserializationFeature.java
|
{
"start": 808,
"end": 7043
}
|
enum ____ implements ConfigFeature
{
/*
/**********************************************************************
/* Value (mostly scalar) mapping features
/**********************************************************************
*/
/**
* Feature that determines whether JSON floating point numbers
* are to be deserialized into {@link java.math.BigDecimal}s
* if only generic type description (either {@link Object} or
* {@link Number}, or within untyped {@link java.util.Map}
* or {@link java.util.Collection} context) is available.
* If enabled such values will be deserialized as {@link java.math.BigDecimal}s;
* if disabled, will be deserialized as {@link Double}s.
*<p>
* NOTE: one related aspect of {@link java.math.BigDecimal} handling that may need
* configuring is whether trailing zeroes are trimmed:
* {@link tools.jackson.databind.cfg.JsonNodeFeature#STRIP_TRAILING_BIGDECIMAL_ZEROES}
* is used for optionally enabling this for {@link tools.jackson.databind.JsonNode}
* values.
*<p>
* Feature is disabled by default, meaning that "untyped" floating
* point numbers will by default be deserialized as {@link Double}s
* (choice is for performance reason -- BigDecimals are slower than
* Doubles).
*/
USE_BIG_DECIMAL_FOR_FLOATS(false),
/**
* Feature that determines whether JSON integral (non-floating-point)
* numbers are to be deserialized into {@link java.math.BigInteger}s
* if only generic type description (either {@link Object} or
* {@link Number}, or within untyped {@link java.util.Map}
* or {@link java.util.Collection} context) is available.
* If enabled such values will be deserialized as
* {@link java.math.BigInteger}s;
* if disabled, will be deserialized as "smallest" available type,
* which is either {@link Integer}, {@link Long} or
* {@link java.math.BigInteger}, depending on number of digits.
* <p>
* Feature is disabled by default, meaning that "untyped" integral
* numbers will by default be deserialized using whatever
* is the most compact integral type, to optimize efficiency.
*/
USE_BIG_INTEGER_FOR_INTS(false),
/**
* Feature that determines how "small" JSON integral (non-floating-point)
* numbers -- ones that fit in 32-bit signed integer (`int`) -- are bound
* when target type is loosely typed as {@link Object} or {@link Number}
* (or within untyped {@link java.util.Map} or {@link java.util.Collection} context).
* If enabled, such values will be deserialized as {@link java.lang.Long};
* if disabled, they will be deserialized as "smallest" available type,
* {@link Integer}.
*<p>
* Note: if {@link #USE_BIG_INTEGER_FOR_INTS} is enabled, it has precedence
* over this setting, forcing use of {@link java.math.BigInteger} for all
* integral values.
*<p>
* Feature is disabled by default, meaning that "untyped" integral
* numbers will by default be deserialized using {@link java.lang.Integer}
* if value fits.
*/
USE_LONG_FOR_INTS(false),
/**
* Feature that determines whether JSON Array is mapped to
* <code>Object[]</code> or {@code List<Object>} when binding
* "untyped" objects (ones with nominal type of <code>java.lang.Object</code>).
* If true, binds as <code>Object[]</code>; if false, as {@code List<Object>}.
*<p>
* Feature is disabled by default, meaning that JSON arrays are bound as
* {@link java.util.List}s.
*/
USE_JAVA_ARRAY_FOR_JSON_ARRAY(false),
/**
* Feature that determines whether deserialization of "Reference Types"
* (such as {@link java.util.Optional}, {@link java.util.concurrent.atomic.AtomicReference},
* and Kotlin/Scala equivalents) should return Java {@code null} in case
* of value missing from incoming JSON. If disabled, reference type's
* "absent" value is returned (for example, {@link java.util.Optional#empty()}.
*<p>
* NOTE: this feature only affects handling of missing values; not explicit
* JSON {@code null}s.
* Also note that this feature only affects deserialization when reference value
* is passed via Creator (constructor or factory method) parameter; when
* Setter methods or fields are used, the reference type is left un-assigned
* (this is not specifically related to reference types, but general behavior).
*
* @since 3.1
*/
USE_NULL_FOR_MISSING_REFERENCE_VALUES(false),
/*
/**********************************************************************
/* Error handling features
/**********************************************************************
*/
/**
* Feature that determines whether encountering of unknown
* properties (ones that do not map to a property, and there is
* no "any setter" or handler that can handle it)
* should result in a failure (by throwing a
* {@link DatabindException}) or not.
* This setting only takes effect after all other handling
* methods for unknown properties have been tried, and
* property remains unhandled.
* Enabling this feature means that a {@link DatabindException}
* will be thrown if an unknown property is encountered.
*<p>
* Feature is disabled by default as of Jackson 3.0 (in 2.x it was enabled).
*/
FAIL_ON_UNKNOWN_PROPERTIES(false),
/**
* Feature that determines whether encountering of JSON null
* is an error when deserializing into Java primitive types
* (like 'int' or 'double'). If it is, a {@link DatabindException}
* is thrown to indicate this; if not, default value is used
* (0 for 'int', 0.0 for double, same defaulting as what JVM uses).
*<p>
* Feature is enabled by default as of Jackson 3.0 (in 2.x it was disabled).
*/
FAIL_ON_NULL_FOR_PRIMITIVES(true),
/**
* Feature that determines what happens when type of a polymorphic
* value (indicated for example by {@link com.fasterxml.jackson.annotation.JsonTypeInfo})
* cannot be found (missing) or resolved (invalid
|
DeserializationFeature
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/parameters/converters/ParameterConverterSupplier.java
|
{
"start": 116,
"end": 222
}
|
interface ____ extends Supplier<ParameterConverter> {
String getClassName();
}
|
ParameterConverterSupplier
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/longarray/LongArrayAssert_contains_at_Index_Test.java
|
{
"start": 1001,
"end": 1388
}
|
class ____ extends LongArrayAssertBaseTest {
private final Index index = someIndex();
@Override
protected LongArrayAssert invoke_api_method() {
return assertions.contains(8L, index);
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertContains(getInfo(assertions), getActual(assertions), 8L, index);
}
}
|
LongArrayAssert_contains_at_Index_Test
|
java
|
bumptech__glide
|
library/src/main/java/com/bumptech/glide/load/engine/EngineJob.java
|
{
"start": 13606,
"end": 15110
}
|
class ____
implements Iterable<ResourceCallbackAndExecutor> {
private final List<ResourceCallbackAndExecutor> callbacksAndExecutors;
ResourceCallbacksAndExecutors() {
this(new ArrayList<ResourceCallbackAndExecutor>(2));
}
ResourceCallbacksAndExecutors(List<ResourceCallbackAndExecutor> callbacksAndExecutors) {
this.callbacksAndExecutors = callbacksAndExecutors;
}
void add(ResourceCallback cb, Executor executor) {
callbacksAndExecutors.add(new ResourceCallbackAndExecutor(cb, executor));
}
void remove(ResourceCallback cb) {
callbacksAndExecutors.remove(defaultCallbackAndExecutor(cb));
}
boolean contains(ResourceCallback cb) {
return callbacksAndExecutors.contains(defaultCallbackAndExecutor(cb));
}
boolean isEmpty() {
return callbacksAndExecutors.isEmpty();
}
int size() {
return callbacksAndExecutors.size();
}
void clear() {
callbacksAndExecutors.clear();
}
ResourceCallbacksAndExecutors copy() {
return new ResourceCallbacksAndExecutors(new ArrayList<>(callbacksAndExecutors));
}
private static ResourceCallbackAndExecutor defaultCallbackAndExecutor(ResourceCallback cb) {
return new ResourceCallbackAndExecutor(cb, Executors.directExecutor());
}
@NonNull
@Override
public Iterator<ResourceCallbackAndExecutor> iterator() {
return callbacksAndExecutors.iterator();
}
}
static final
|
ResourceCallbacksAndExecutors
|
java
|
netty__netty
|
codec-native-quic/src/test/java/io/netty/handler/codec/quic/QuicTest.java
|
{
"start": 1106,
"end": 2753
}
|
class ____ extends AbstractQuicTest {
@Test
public void test() {
Quic.ensureAvailability();
assertNotNull(Quiche.quiche_version());
}
@Test
public void testVersionSupported() {
// Only v1 should be supported.
assertFalse(Quic.isVersionSupported(0xff00_001c));
assertFalse(Quic.isVersionSupported(0xff00_001d));
assertFalse(Quic.isVersionSupported(0xff00_001c));
assertTrue(Quic.isVersionSupported(0x0000_0001));
}
@Test
public void testToAttributesArrayDoesCopy() {
AttributeKey<String> key = AttributeKey.valueOf(UUID.randomUUID().toString());
String value = "testValue";
Map<AttributeKey<?>, Object> attributes = new HashMap<>();
attributes.put(key, value);
Map.Entry<AttributeKey<?>, Object>[] array = Quic.toAttributesArray(attributes);
assertEquals(1, array.length);
attributes.put(key, "newTestValue");
Map.Entry<AttributeKey<?>, Object> entry = array[0];
assertEquals(key, entry.getKey());
assertEquals(value, entry.getValue());
}
@Test
public void testToOptionsArrayDoesCopy() {
Map<ChannelOption<?>, Object> options = new HashMap<>();
options.put(ChannelOption.AUTO_READ, true);
Map.Entry<ChannelOption<?>, Object>[] array = Quic.toOptionsArray(options);
assertEquals(1, array.length);
options.put(ChannelOption.AUTO_READ, false);
Map.Entry<ChannelOption<?>, Object> entry = array[0];
assertEquals(ChannelOption.AUTO_READ, entry.getKey());
assertEquals(true, entry.getValue());
}
}
|
QuicTest
|
java
|
mapstruct__mapstruct
|
processor/src/test/resources/fixtures/org/mapstruct/ap/test/updatemethods/OrganizationMapperImpl.java
|
{
"start": 433,
"end": 2399
}
|
class ____ implements OrganizationMapper {
private final DepartmentEntityFactory departmentEntityFactory = new DepartmentEntityFactory();
@Override
public void toOrganizationEntity(OrganizationDto dto, OrganizationEntity entity) {
if ( dto == null ) {
return;
}
if ( dto.getCompany() != null ) {
if ( entity.getCompany() == null ) {
entity.setCompany( new CompanyEntity() );
}
toCompanyEntity( dto.getCompany(), entity.getCompany() );
}
else {
entity.setCompany( null );
}
if ( entity.getType() == null ) {
entity.setType( new OrganizationTypeEntity() );
}
toName( "commercial", entity.getType() );
if ( entity.getTypeNr() == null ) {
entity.setTypeNr( new OrganizationTypeNrEntity() );
}
toNumber( Integer.parseInt( "5" ), entity.getTypeNr() );
}
@Override
public void toCompanyEntity(CompanyDto dto, CompanyEntity entity) {
if ( dto == null ) {
return;
}
entity.setName( dto.getName() );
entity.setDepartment( toDepartmentEntity( dto.getDepartment() ) );
}
@Override
public DepartmentEntity toDepartmentEntity(DepartmentDto dto) {
if ( dto == null ) {
return null;
}
DepartmentEntity departmentEntity = departmentEntityFactory.createDepartmentEntity();
departmentEntity.setName( dto.getName() );
return departmentEntity;
}
@Override
public void toName(String type, OrganizationTypeEntity entity) {
if ( type == null ) {
return;
}
entity.setType( type );
}
@Override
public void toNumber(Integer number, OrganizationTypeNrEntity entity) {
if ( number == null ) {
return;
}
entity.setNumber( number );
}
}
|
OrganizationMapperImpl
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/balancer/KeyManager.java
|
{
"start": 1851,
"end": 1944
}
|
class ____ utilities for key and token management.
*/
@InterfaceAudience.Private
public
|
provides
|
java
|
apache__dubbo
|
dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java
|
{
"start": 10716,
"end": 13409
}
|
interface ____'s dependency jar is missing
return;
}
for (Method method : methods) {
if (ConfigurationUtils.hasSubProperties(configProperties, method.getName())) {
MethodConfig methodConfig = getMethodByName(method.getName());
// Add method config if not found
if (methodConfig == null) {
methodConfig = new MethodConfig();
methodConfig.setName(method.getName());
this.addMethod(methodConfig);
}
// Add argument config
// dubbo.service.{interfaceName}.{methodName}.{arg-index}.xxx=xxx
java.lang.reflect.Parameter[] arguments = method.getParameters();
for (int i = 0; i < arguments.length; i++) {
if (getArgumentByIndex(methodConfig, i) == null
&& hasArgumentConfigProps(configProperties, methodConfig.getName(), i)) {
ArgumentConfig argumentConfig = new ArgumentConfig();
argumentConfig.setIndex(i);
methodConfig.addArgument(argumentConfig);
}
}
}
}
// refresh MethodConfigs
List<MethodConfig> methodConfigs = this.getMethods();
if (methodConfigs != null && methodConfigs.size() > 0) {
// whether ignore invalid method config
Object ignoreInvalidMethodConfigVal = getEnvironment()
.getConfiguration()
.getProperty(ConfigKeys.DUBBO_CONFIG_IGNORE_INVALID_METHOD_CONFIG, "false");
boolean ignoreInvalidMethodConfig = Boolean.parseBoolean(ignoreInvalidMethodConfigVal.toString());
Class<?> finalInterfaceClass = interfaceClass;
List<MethodConfig> validMethodConfigs = methodConfigs.stream()
.filter(methodConfig -> {
methodConfig.setParentPrefix(preferredPrefix);
methodConfig.setScopeModel(getScopeModel());
methodConfig.refresh();
// verify method config
return verifyMethodConfig(methodConfig, finalInterfaceClass, ignoreInvalidMethodConfig);
})
.collect(Collectors.toList());
this.setMethods(validMethodConfigs);
}
}
}
/**
* it is used for skipping the check of
|
class
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/legacy/ComponentNotNull.java
|
{
"start": 243,
"end": 1504
}
|
class ____ {
/*
* I've flatten several components in one class, this is kind of ugly but
* I don't have to write tons of classes
*/
private String prop1Nullable;
private String prop2Nullable;
private ComponentNotNull supercomp;
private ComponentNotNull subcomp;
private String prop1Subcomp;
/**
* @return
*/
public String getProp1Nullable() {
return prop1Nullable;
}
/**
* @return
*/
public String getProp1Subcomp() {
return prop1Subcomp;
}
/**
* @return
*/
public String getProp2Nullable() {
return prop2Nullable;
}
/**
* @return
*/
public ComponentNotNull getSubcomp() {
return subcomp;
}
/**
* @return
*/
public ComponentNotNull getSupercomp() {
return supercomp;
}
/**
* @param string
*/
public void setProp1Nullable(String string) {
prop1Nullable = string;
}
/**
* @param string
*/
public void setProp1Subcomp(String string) {
prop1Subcomp = string;
}
/**
* @param string
*/
public void setProp2Nullable(String string) {
prop2Nullable = string;
}
/**
* @param null1
*/
public void setSubcomp(ComponentNotNull null1) {
subcomp = null1;
}
/**
* @param null1
*/
public void setSupercomp(ComponentNotNull null1) {
supercomp = null1;
}
}
|
ComponentNotNull
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringToDynamicTest.java
|
{
"start": 1034,
"end": 1283
}
|
class ____ extends ToDynamicTest {
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/spring/processor/SpringToDynamicTest.xml");
}
}
|
SpringToDynamicTest
|
java
|
dropwizard__dropwizard
|
dropwizard-e2e/src/main/java/com/example/app1/CustomClassBodyWriter.java
|
{
"start": 640,
"end": 1552
}
|
class ____ implements MessageBodyWriter<CustomClass> {
private static final byte[] RESPONSE = "I'm a custom class".getBytes(StandardCharsets.UTF_8);
@Override
public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return true;
}
@Override
public long getSize(
CustomClass customClass,
Class<?> aClass,
Type type,
Annotation[] annotations,
MediaType mediaType
) {
return RESPONSE.length;
}
@Override
public void writeTo(
CustomClass customClass,
Class<?> aClass,
Type type,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> multivaluedMap,
OutputStream outputStream
) throws IOException, WebApplicationException {
outputStream.write(RESPONSE);
}
}
|
CustomClassBodyWriter
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAnonymousTests.java
|
{
"start": 5577,
"end": 6016
}
|
class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((requests) -> requests
.requestMatchers("/key").anonymous()
.anyRequest().denyAll())
.anonymous((anonymous) -> anonymous.key("AnonymousKeyConfig"));
return http.build();
// @formatter:on
}
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static
|
AnonymousKeyConfig
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/ComponentProcessorTest.java
|
{
"start": 41774,
"end": 42085
}
|
class ____ {",
" @Inject SomeInjectableType() {}",
"}");
Source componentSupertype = CompilerTests.javaSource("test.Supertype",
"package test;",
"",
"import dagger.Component;",
"",
"@Component",
"
|
SomeInjectableType
|
java
|
spring-projects__spring-framework
|
spring-websocket/src/main/java/org/springframework/web/socket/messaging/WebSocketAnnotationMethodMessageHandler.java
|
{
"start": 3100,
"end": 4041
}
|
class ____ implements MessagingAdviceBean {
private final ControllerAdviceBean adviceBean;
private MessagingControllerAdviceBean(ControllerAdviceBean adviceBean) {
this.adviceBean = adviceBean;
}
public static List<MessagingAdviceBean> createFromList(List<ControllerAdviceBean> beans) {
List<MessagingAdviceBean> result = new ArrayList<>(beans.size());
for (ControllerAdviceBean bean : beans) {
result.add(new MessagingControllerAdviceBean(bean));
}
return result;
}
@Override
public @Nullable Class<?> getBeanType() {
return this.adviceBean.getBeanType();
}
@Override
public Object resolveBean() {
return this.adviceBean.resolveBean();
}
@Override
public boolean isApplicableToBeanType(Class<?> beanType) {
return this.adviceBean.isApplicableToBeanType(beanType);
}
@Override
public int getOrder() {
return this.adviceBean.getOrder();
}
}
}
|
MessagingControllerAdviceBean
|
java
|
spring-projects__spring-framework
|
spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscovererTests.java
|
{
"start": 7694,
"end": 12089
}
|
class ____ {
@Test
void atThis() {
assertParameterNames(getMethod("oneAnnotation"),"@this(a)", "a");
}
@Test
void atTarget() {
assertParameterNames(getMethod("oneAnnotation"),"@target(a)", "a");
}
@Test
void atArgs() {
assertParameterNames(getMethod("oneAnnotation"),"@args(a)", "a");
}
@Test
void atWithin() {
assertParameterNames(getMethod("oneAnnotation"),"@within(a)", "a");
}
@Test
void atWithincode() {
assertParameterNames(getMethod("oneAnnotation"),"@withincode(a)", "a");
}
@Test
void atAnnotation() {
assertParameterNames(getMethod("oneAnnotation"),"@annotation(a)", "a");
}
@Test
void ambiguousAnnotationTwoVars() {
assertException(getMethod("twoAnnotations"),"@annotation(a) && @this(x)", AmbiguousBindingException.class,
"Found 2 potential annotation variable(s) and 2 potential argument slots");
}
@Test
void ambiguousAnnotationOneVar() {
assertException(getMethod("oneAnnotation"),"@annotation(a) && @this(x)",IllegalArgumentException.class,
"Found 2 candidate annotation binding variables but only one potential argument binding slot");
}
@Test
void annotationMedley() {
assertParameterNamesExtended(getMethod("annotationMedley"),"@annotation(a) && args(count) && this(foo)",
null, "ex", "ex", "foo", "count", "a");
}
@Test
void annotationBinding() {
assertParameterNames(getMethod("pjpAndAnAnnotation"),
"execution(* *(..)) && @annotation(ann)", "thisJoinPoint", "ann");
}
}
private Method getMethod(String name) {
// Assumes no overloading of test methods...
for (Method candidate : getClass().getMethods()) {
if (candidate.getName().equals(name)) {
return candidate;
}
}
throw new AssertionError("Bad test specification, no method '" + name + "' found in test class");
}
private void assertParameterNames(Method method, String pointcut, String... parameterNames) {
assertParameterNamesExtended(method, pointcut, null, null, parameterNames);
}
private void assertParameterNamesExtended(
Method method, String pointcut, String returning, String throwing, String... parameterNames) {
assertThat(parameterNames)
.as("bad test specification, must have same number of parameter names as method arguments")
.hasSize(method.getParameterCount());
AspectJAdviceParameterNameDiscoverer discoverer = new AspectJAdviceParameterNameDiscoverer(pointcut);
discoverer.setRaiseExceptions(true);
discoverer.setReturningName(returning);
discoverer.setThrowingName(throwing);
assertThat(discoverer.getParameterNames(method)).isEqualTo(parameterNames);
}
private void assertException(Method method, String pointcut, Class<? extends Throwable> exceptionType, String message) {
assertException(method, pointcut, null, null, exceptionType, message);
}
private void assertException(Method method, String pointcut, String returning,
String throwing, Class<? extends Throwable> exceptionType, String message) {
AspectJAdviceParameterNameDiscoverer discoverer = new AspectJAdviceParameterNameDiscoverer(pointcut);
discoverer.setRaiseExceptions(true);
discoverer.setReturningName(returning);
discoverer.setThrowingName(throwing);
assertThatExceptionOfType(exceptionType)
.isThrownBy(() -> discoverer.getParameterNames(method))
.withMessageContaining(message);
}
// Methods to discover parameter names for
public void noArgs() {
}
public void tjp(JoinPoint jp) {
}
public void tjpsp(JoinPoint.StaticPart tjpsp) {
}
public void twoJoinPoints(JoinPoint jp1, JoinPoint jp2) {
}
public void oneThrowable(Exception ex) {
}
public void jpAndOneThrowable(JoinPoint jp, Exception ex) {
}
public void jpAndTwoThrowables(JoinPoint jp, Exception ex, Error err) {
}
public void oneObject(Object x) {
}
public void twoObjects(Object x, Object y) {
}
public void onePrimitive(int x) {
}
public void oneObjectOnePrimitive(Object x, int y) {
}
public void oneThrowableOnePrimitive(Throwable x, int y) {
}
public void theBigOne(JoinPoint jp, Throwable x, int y, Object foo) {
}
public void oneAnnotation(MyAnnotation ann) {}
public void twoAnnotations(MyAnnotation ann, MyAnnotation anotherAnn) {}
public void annotationMedley(Throwable t, Object foo, int x, MyAnnotation ma) {}
public void pjpAndAnAnnotation(ProceedingJoinPoint pjp, MyAnnotation ann) {}
@
|
AnnotationTests
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/FilterClassIntrospector.java
|
{
"start": 518,
"end": 1362
}
|
class ____ {
private final ClassLoader classLoader;
public FilterClassIntrospector(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public boolean usesGetResourceMethod(MethodInfo methodInfo) {
String className = methodInfo.declaringClass().name().toString();
final String resourceName = fromClassNameToResourceName(className);
try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
ClassReader configClassReader = new ClassReader(is);
FilterClassVisitor classVisitor = new FilterClassVisitor(methodInfo.descriptor());
configClassReader.accept(classVisitor, 0);
return classVisitor.usesGetResourceMethod();
} catch (IOException e) {
throw new UncheckedIOException(className + "
|
FilterClassIntrospector
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.