language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FileJournalManager.java | {
"start": 2479,
"end": 2584
} | class ____ not thread-safe and should be externally
* synchronized.
*/
@InterfaceAudience.Private
public | is |
java | google__guava | guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java | {
"start": 31455,
"end": 32409
} | class ____ {
private final Map<Integer, Object> arguments = new HashMap<>();
@CanIgnoreReturnValue
final DefaultValueChecker runTester() {
new NullPointerTester().testInstanceMethods(this, Visibility.PACKAGE);
return this;
}
final void assertNonNullValues(Object... expectedValues) {
assertEquals(expectedValues.length, arguments.size());
for (int i = 0; i < expectedValues.length; i++) {
assertEquals("Default value for parameter #" + i, expectedValues[i], arguments.get(i));
}
}
final Object getDefaultParameterValue(int position) {
return arguments.get(position);
}
final void calledWith(Object... args) {
for (int i = 0; i < args.length; i++) {
if (args[i] != null) {
arguments.put(i, args[i]);
}
}
for (Object arg : args) {
checkNotNull(arg); // to fulfill null check
}
}
}
private | DefaultValueChecker |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/URLEqualsHashCodeTest.java | {
"start": 5664,
"end": 6507
} | class ____ {
private Url() {
// no impl
}
}
// Set and HashSet of non-URL class.
public void setOfUrl() {
Set<Url> urlSet;
}
public void hashsetOfUrl() {
HashSet<Url> urlSet;
}
// Collection(s) of type URL
public void collectionOfURL() {
Collection<URL> urlSet;
}
public void listOfURL() {
List<URL> urlSet;
}
public void arraylistOfURL() {
ArrayList<URL> urlSet;
}
public void hashmapWithURLAsValue() {
HashMap<String, java.net.URL> stringToUrlMap;
}
private static | Url |
java | reactor__reactor-core | reactor-core-micrometer/src/main/java/reactor/core/observability/micrometer/MicrometerMeterListener.java | {
"start": 1486,
"end": 11539
} | class ____<T> implements SignalListener<T> {
final MicrometerMeterListenerConfiguration configuration;
final @Nullable DistributionSummary requestedCounter;
final @Nullable Timer onNextIntervalTimer;
@SuppressWarnings("NotNullFieldNotInitialized") // initialized in onSubscribe
Timer.Sample subscribeToTerminateSample;
long lastNextEventNanos = -1L;
boolean valued;
MicrometerMeterListener(MicrometerMeterListenerConfiguration configuration) {
this.configuration = configuration;
this.valued = false;
if (configuration.isMono) {
//for Mono we don't record onNextInterval (since there is at most 1 onNext).
//Note that we still need a mean to distinguish between empty Mono and valued Mono for recordOnCompleteEmpty
onNextIntervalTimer = null;
//we also don't count the number of request calls (there should be only one)
requestedCounter = null;
}
else {
this.onNextIntervalTimer = Timer.builder(MicrometerMeterListenerDocumentation.ON_NEXT_DELAY.getName(configuration.sequenceName))
.tags(configuration.commonTags)
.register(configuration.registry);
if (!Micrometer.DEFAULT_METER_PREFIX.equals(configuration.sequenceName)) {
this.requestedCounter = DistributionSummary.builder(MicrometerMeterListenerDocumentation.REQUESTED_AMOUNT.getName(configuration.sequenceName))
.tags(configuration.commonTags)
.register(configuration.registry);
}
else {
requestedCounter = null;
}
}
}
@Override
public void doOnCancel() {
//we don't record the time between last onNext and cancel,
// because it would skew the onNext count by one
recordCancel(configuration.sequenceName, configuration.commonTags, configuration.registry, subscribeToTerminateSample);
}
@Override
public void doOnComplete() {
//we don't record the time between last onNext and onComplete,
// because it would skew the onNext count by one.
// We differentiate between empty completion and value completion, however, via tags.
if (!valued) {
recordOnCompleteEmpty(configuration.sequenceName, configuration.commonTags, configuration.registry, subscribeToTerminateSample);
}
else if (!configuration.isMono) {
//recordOnComplete is done directly in onNext for the Mono(valued) case
recordOnComplete(configuration.sequenceName, configuration.commonTags, configuration.registry, subscribeToTerminateSample);
}
}
@Override
public void doOnMalformedOnComplete() {
recordMalformed(configuration.sequenceName, configuration.commonTags, configuration.registry);
}
@Override
public void doOnError(Throwable e) {
//we don't record the time between last onNext and onError,
// because it would skew the onNext count by one
recordOnError(configuration.sequenceName, configuration.commonTags, configuration.registry, subscribeToTerminateSample, e);
}
@Override
public void doOnMalformedOnError(Throwable e) {
recordMalformed(configuration.sequenceName, configuration.commonTags, configuration.registry);
}
@Override
public void doOnNext(T t) {
valued = true;
if (onNextIntervalTimer == null) { //NB: interval timer is only null if isMono
//record valued completion directly
recordOnComplete(configuration.sequenceName, configuration.commonTags, configuration.registry, subscribeToTerminateSample);
return;
}
//record the delay since previous onNext/onSubscribe. This also records the count.
long last = this.lastNextEventNanos;
this.lastNextEventNanos = configuration.registry.config().clock().monotonicTime();
this.onNextIntervalTimer.record(lastNextEventNanos - last, TimeUnit.NANOSECONDS);
}
@Override
public void doOnMalformedOnNext(T value) {
recordMalformed(configuration.sequenceName, configuration.commonTags, configuration.registry);
}
@Override
public void doOnSubscription() {
recordOnSubscribe(configuration.sequenceName, configuration.commonTags, configuration.registry);
this.subscribeToTerminateSample = Timer.start(configuration.registry);
this.lastNextEventNanos = configuration.registry.config().clock().monotonicTime();
}
@Override
public void doOnRequest(long l) {
if (requestedCounter != null) {
requestedCounter.record(l);
}
}
//unused hooks
@Override
public void doFirst() {
// NO-OP
}
@Override
public void doOnFusion(int negotiatedFusion) throws Throwable {
// NO-OP
//TODO metrics counting fused (with ASYNC/SYNC tags) could be implemented to supplement METER_SUBSCRIBED
}
@Override
public void doFinally(SignalType terminationType) {
// NO-OP
}
@Override
public void doAfterComplete() {
// NO-OP
}
@Override
public void doAfterError(Throwable error) {
// NO-OP
}
@Override
public void handleListenerError(Throwable listenerError) {
// NO-OP
}
// == from KeyNames to Tags
static final Tags DEFAULT_TAGS_FLUX = Tags.of(TYPE.asString(), TAG_TYPE_FLUX);
static final Tags DEFAULT_TAGS_MONO = Tags.of(TYPE.asString(), TAG_TYPE_MONO);
static final Tag TAG_ON_ERROR = Tag.of(STATUS.asString(), TAG_STATUS_ERROR);
static final Tags TAG_ON_COMPLETE = Tags.of(STATUS.asString(), TAG_STATUS_COMPLETED, EXCEPTION.asString(), "");
static final Tags TAG_ON_COMPLETE_EMPTY = Tags.of(STATUS.asString(), TAG_STATUS_COMPLETED_EMPTY, EXCEPTION.asString(), "");
static final Tags TAG_CANCEL = Tags.of(STATUS.asString(), TAG_STATUS_CANCELLED, EXCEPTION.asString(), "");
// === Record methods ===
/*
* This method calls the registry, which can be costly. However the cancel signal is only expected
* once per Subscriber. So the net effect should be that the registry is only called once, which
* is equivalent to registering the meter as a final field, with the added benefit of paying that
* cost only in case of cancellation.
*/
static void recordCancel(String name, Tags commonTags, MeterRegistry registry, Timer.Sample flowDuration) {
Timer timer = Timer.builder(MicrometerMeterListenerDocumentation.FLOW_DURATION.getName(name))
.tags(commonTags.and(TAG_CANCEL))
.description(
"Times the duration elapsed between a subscription and the cancellation of the sequence")
.register(registry);
flowDuration.stop(timer);
}
/*
* This method calls the registry, which can be costly. However a malformed signal is generally
* not expected, or at most once per Subscriber. So the net effect should be that the registry
* is only called once, which is equivalent to registering the meter as a final field,
* with the added benefit of paying that cost only in case of onNext/onError after termination.
*/
static void recordMalformed(String name, Tags commonTags, MeterRegistry registry) {
registry.counter(MicrometerMeterListenerDocumentation.MALFORMED_SOURCE_EVENTS.getName(name), commonTags)
.increment();
}
/*
* This method calls the registry, which can be costly. However the onError signal is expected
* at most once per Subscriber. So the net effect should be that the registry is only called once,
* which is equivalent to registering the meter as a final field, with the added benefit of paying
* that cost only in case of error.
*/
static void recordOnError(String name, Tags commonTags, MeterRegistry registry, Timer.Sample flowDuration,
Throwable e) {
Timer timer = Timer.builder(MicrometerMeterListenerDocumentation.FLOW_DURATION.getName(name))
.tags(commonTags.and(TAG_ON_ERROR))
.tag(MicrometerMeterListenerDocumentation.TerminationTags.EXCEPTION.asString(),
e.getClass().getName())
.description(
"Times the duration elapsed between a subscription and the onError termination of the sequence, with the exception name as a tag.")
.register(registry);
flowDuration.stop(timer);
}
/*
* This method calls the registry, which can be costly. However the onComplete signal is expected
* at most once per Subscriber. So the net effect should be that the registry is only called once,
* which is equivalent to registering the meter as a final field, with the added benefit of paying
* that cost only in case of completion (which is not always occurring).
*/
static void recordOnComplete(String name, Tags commonTags, MeterRegistry registry, Timer.Sample flowDuration) {
Timer timer = Timer.builder(MicrometerMeterListenerDocumentation.FLOW_DURATION.getName(name))
.tags(commonTags.and(TAG_ON_COMPLETE))
.description(
"Times the duration elapsed between a subscription and the onComplete termination of a sequence that did emit some elements")
.register(registry);
flowDuration.stop(timer);
}
/*
* This method calls the registry, which can be costly. However the onComplete signal is expected
* at most once per Subscriber. So the net effect should be that the registry is only called once,
* which is equivalent to registering the meter as a final field, with the added benefit of paying
* that cost only in case of completion (which is not always occurring).
*/
static void recordOnCompleteEmpty(String name, Tags commonTags, MeterRegistry registry, Timer.Sample flowDuration) {
Timer timer = Timer.builder(MicrometerMeterListenerDocumentation.FLOW_DURATION.getName(name))
.tags(commonTags.and(TAG_ON_COMPLETE_EMPTY))
.description(
"Times the duration elapsed between a subscription and the onComplete termination of a sequence that didn't emit any element")
.register(registry);
flowDuration.stop(timer);
}
/*
* This method calls the registry, which can be costly. However the onSubscribe signal is expected
* at most once per Subscriber. So the net effect should be that the registry is only called once,
* which is equivalent to registering the meter as a final field, with the added benefit of paying
* that cost only in case of subscription.
*/
static void recordOnSubscribe(String name, Tags commonTags, MeterRegistry registry) {
Counter.builder(MicrometerMeterListenerDocumentation.SUBSCRIBED.getName(name))
.tags(commonTags)
.register(registry)
.increment();
}
}
| MicrometerMeterListener |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/catalog/ResolvedCatalogBaseTable.java | {
"start": 1949,
"end": 2353
} | class ____ a
* hybrid of resolved and unresolved schema information. It has been replaced by the new
* {@link ResolvedSchema} which is resolved by the framework and accessible via {@link
* #getResolvedSchema()}.
*/
@Deprecated
default TableSchema getSchema() {
return TableSchema.fromResolvedSchema(getResolvedSchema(), DefaultSqlFactory.INSTANCE);
}
}
| was |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/filter/log/Slf4jLogFilterTest.java | {
"start": 172,
"end": 2101
} | class ____ extends TestCase {
public void test_slf4j() throws Exception {
Slf4jLogFilter filter = new Slf4jLogFilter();
assertEquals("druid.sql.DataSource", filter.getDataSourceLoggerName());
assertEquals("druid.sql.Connection", filter.getConnectionLoggerName());
assertEquals("druid.sql.Statement", filter.getStatementLoggerName());
assertEquals("druid.sql.ResultSet", filter.getResultSetLoggerName());
filter.setDataSourceLoggerName("x.sql.DataSource");
filter.setConnectionLoggerName("x.sql.Connection");
filter.setStatementLoggerName("x.sql.Statement");
filter.setResultSetLoggerName("x.sql.ResultSet");
assertEquals("x.sql.DataSource", filter.getDataSourceLoggerName());
assertEquals("x.sql.Connection", filter.getConnectionLoggerName());
assertEquals("x.sql.Statement", filter.getStatementLoggerName());
assertEquals("x.sql.ResultSet", filter.getResultSetLoggerName());
filter.setDataSourceLogger(LoggerFactory.getLogger("y.sql.DataSource"));
filter.setConnectionLogger(LoggerFactory.getLogger("y.sql.Connection"));
filter.setStatementLogger(LoggerFactory.getLogger("y.sql.Statement"));
filter.setResultSetLogger(LoggerFactory.getLogger("y.sql.ResultSet"));
assertEquals("y.sql.DataSource", filter.getDataSourceLoggerName());
assertEquals("y.sql.Connection", filter.getConnectionLoggerName());
assertEquals("y.sql.Statement", filter.getStatementLoggerName());
assertEquals("y.sql.ResultSet", filter.getResultSetLoggerName());
filter.isDataSourceLogEnabled();
filter.isConnectionLogEnabled();
filter.isConnectionLogErrorEnabled();
filter.isStatementLogEnabled();
filter.isStatementLogErrorEnabled();
filter.isResultSetLogEnabled();
filter.isResultSetLogErrorEnabled();
}
}
| Slf4jLogFilterTest |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/openshiftai/request/completion/OpenShiftAiChatCompletionRequest.java | {
"start": 1308,
"end": 3271
} | class ____ implements Request {
private final OpenShiftAiChatCompletionModel model;
private final UnifiedChatInput chatInput;
/**
* Constructs a new OpenShiftAiChatCompletionRequest with the specified chat input and model.
*
* @param chatInput the chat input containing the messages and parameters for the completion request
* @param model the OpenShift AI chat completion model to be used for the request
*/
public OpenShiftAiChatCompletionRequest(UnifiedChatInput chatInput, OpenShiftAiChatCompletionModel model) {
this.chatInput = Objects.requireNonNull(chatInput);
this.model = Objects.requireNonNull(model);
}
@Override
public HttpRequest createHttpRequest() {
HttpPost httpPost = new HttpPost(model.getServiceSettings().uri());
ByteArrayEntity byteEntity = new ByteArrayEntity(
Strings.toString(new OpenShiftAiChatCompletionRequestEntity(chatInput, model.getServiceSettings().modelId()))
.getBytes(StandardCharsets.UTF_8)
);
httpPost.setEntity(byteEntity);
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, XContentType.JSON.mediaTypeWithoutParameters());
httpPost.setHeader(createAuthBearerHeader(model.getSecretSettings().apiKey()));
return new HttpRequest(httpPost, getInferenceEntityId());
}
@Override
public URI getURI() {
return model.getServiceSettings().uri();
}
@Override
public Request truncate() {
// No truncation for OpenShift AI chat completions
return this;
}
@Override
public boolean[] getTruncationInfo() {
// No truncation for OpenShift AI chat completions
return null;
}
@Override
public String getInferenceEntityId() {
return model.getInferenceEntityId();
}
@Override
public boolean isStreaming() {
return chatInput.stream();
}
}
| OpenShiftAiChatCompletionRequest |
java | google__auto | value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java | {
"start": 3257,
"end": 4527
} | class ____ extends AbstractProcessor {
public AutoAnnotationProcessor() {}
private Elements elementUtils;
private Types typeUtils;
private TypeMirror javaLangObject;
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public ImmutableSet<String> getSupportedOptions() {
return ImmutableSet.of(Nullables.NULLABLE_OPTION);
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
this.elementUtils = processingEnv.getElementUtils();
this.typeUtils = processingEnv.getTypeUtils();
this.javaLangObject = elementUtils.getTypeElement("java.lang.Object").asType();
}
/**
* Issue a compilation error. This method does not throw an exception, since we want to continue
* processing and perhaps report other errors.
*/
@FormatMethod
private void reportError(Element e, String msg, Object... msgParams) {
String formattedMessage = String.format(msg, msgParams);
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, formattedMessage, e);
}
/**
* Issue a compilation error and return an exception that, when thrown, will cause the processing
* of this | AutoAnnotationProcessor |
java | quarkusio__quarkus | extensions/smallrye-fault-tolerance/deployment/src/test/java/io/quarkus/smallrye/faulttolerance/test/retry/beforeretry/BeforeRetryHandlerTest.java | {
"start": 361,
"end": 899
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(BeforeRetryHandlerService.class, MyDependency.class));
@Inject
BeforeRetryHandlerService service;
@Test
public void test() {
assertThrows(IllegalArgumentException.class, service::hello);
assertThat(BeforeRetryHandlerService.ids)
.hasSize(3)
.containsExactly(1, 2, 3);
}
}
| BeforeRetryHandlerTest |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationTokenTests.java | {
"start": 1044,
"end": 3888
} | class ____ {
@Test
public void testPreAuthenticatedAuthenticationTokenRequestWithDetails() {
Object principal = "dummyUser";
Object credentials = "dummyCredentials";
Object details = "dummyDetails";
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
token.setDetails(details);
assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials);
assertThat(token.getDetails()).isEqualTo(details);
assertThat(token.getAuthorities()).isEmpty();
}
@Test
public void testPreAuthenticatedAuthenticationTokenRequestWithoutDetails() {
Object principal = "dummyUser";
Object credentials = "dummyCredentials";
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials);
assertThat(token.getDetails()).isNull();
assertThat(token.getAuthorities()).isEmpty();
}
@Test
public void testPreAuthenticatedAuthenticationTokenResponse() {
Object principal = "dummyUser";
Object credentials = "dummyCredentials";
List<GrantedAuthority> gas = AuthorityUtils.createAuthorityList("Role1");
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials,
gas);
assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials);
assertThat(token.getDetails()).isNull();
assertThat(token.getAuthorities()).isNotNull();
Collection<GrantedAuthority> resultColl = token.getAuthorities();
assertThat(gas.containsAll(resultColl) && resultColl.containsAll(gas))
.withFailMessage("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + gas)
.isTrue();
}
@Test
public void toBuilderWhenApplyThenCopies() {
PreAuthenticatedAuthenticationToken factorOne = new PreAuthenticatedAuthenticationToken("alice", "pass",
AuthorityUtils.createAuthorityList("FACTOR_ONE"));
PreAuthenticatedAuthenticationToken factorTwo = new PreAuthenticatedAuthenticationToken("bob", "ssap",
AuthorityUtils.createAuthorityList("FACTOR_TWO"));
PreAuthenticatedAuthenticationToken result = factorOne.toBuilder()
.authorities((a) -> a.addAll(factorTwo.getAuthorities()))
.principal(factorTwo.getPrincipal())
.credentials(factorTwo.getCredentials())
.build();
Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities());
assertThat(result.getPrincipal()).isSameAs(factorTwo.getPrincipal());
assertThat(result.getCredentials()).isSameAs(factorTwo.getCredentials());
assertThat(authorities).containsExactlyInAnyOrder("FACTOR_ONE", "FACTOR_TWO");
}
}
| PreAuthenticatedAuthenticationTokenTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ErroneousBitwiseExpressionTest.java | {
"start": 1472,
"end": 1578
} | class ____ {
double flags = 2 & 10;
}
""")
.doTest();
}
}
| Test |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java | {
"start": 11853,
"end": 11939
} | class ____ must be an implementation of " + strategyType);
}
return result;
}
}
| name |
java | junit-team__junit5 | junit-jupiter-api/src/main/java/org/junit/jupiter/api/condition/AbstractJreRangeCondition.java | {
"start": 694,
"end": 816
} | class ____ {@link EnabledForJreRangeCondition} and
* {@link DisabledForJreRangeCondition}.
*
* @since 5.12
*/
abstract | for |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/descriptors/DescriptorValidator.java | {
"start": 1189,
"end": 1341
} | interface ____ {
/** Performs basic validation such as completeness tests. */
void validate(DescriptorProperties properties);
}
| DescriptorValidator |
java | spring-projects__spring-security | docs/src/test/java/org/springframework/security/docs/servlet/test/testmethodwithuserdetails/WithCustomUserDetailsTests.java | {
"start": 1930,
"end": 2541
} | class ____ {
@Autowired
MessageService messageService;
// tag::custom-user-details-service[]
@Test
@WithUserDetails(value="customUsername", userDetailsServiceBeanName="myUserDetailsService")
void getMessageWithUserDetailsServiceBeanName() {
String message = messageService.getMessage();
assertThat(message).contains("customUsername");
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
assertThat(principal).isInstanceOf(CustomUserDetails.class);
}
// end::custom-user-details-service[]
@EnableWebSecurity
@Configuration
static | WithCustomUserDetailsTests |
java | apache__camel | components/camel-huawei/camel-huaweicloud-functiongraph/src/main/java/org/apache/camel/FunctionGraphUtils.java | {
"start": 961,
"end": 1919
} | class ____ {
private FunctionGraphUtils() {
}
/**
* Gets the fieldName from the jsonString and returns it as a String
*
* @param jsonString
* @param fieldName
* @return
*/
public static String extractJsonFieldAsString(String jsonString, String fieldName) {
Gson gson = new Gson();
return gson.fromJson(jsonString, JsonObject.class).getAsJsonObject(fieldName).toString();
}
/**
* Returns the urn based on urnFormat and clientConfigurations
*
* @param urnFormat
* @param clientConfigurations
* @return
*/
public static String composeUrn(String urnFormat, ClientConfigurations clientConfigurations) {
return String.format(urnFormat, clientConfigurations.getRegion(),
clientConfigurations.getProjectId(), clientConfigurations.getFunctionPackage(),
clientConfigurations.getFunctionName());
}
}
| FunctionGraphUtils |
java | apache__kafka | tools/src/main/java/org/apache/kafka/tools/filter/PartitionFilter.java | {
"start": 870,
"end": 1065
} | interface ____ {
/**
* Used to filter partitions based on a certain criteria, for example, a set of partition ids.
*/
boolean isPartitionAllowed(int partition);
| PartitionFilter |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/ExtTypes.java | {
"start": 477,
"end": 1259
} | enum ____ implements SQLType {
INTERVAL_YEAR(101),
INTERVAL_MONTH(102),
INTERVAL_DAY(103),
INTERVAL_HOUR(104),
INTERVAL_MINUTE(105),
INTERVAL_SECOND(106),
INTERVAL_YEAR_TO_MONTH(107),
INTERVAL_DAY_TO_HOUR(108),
INTERVAL_DAY_TO_MINUTE(109),
INTERVAL_DAY_TO_SECOND(110),
INTERVAL_HOUR_TO_MINUTE(111),
INTERVAL_HOUR_TO_SECOND(112),
INTERVAL_MINUTE_TO_SECOND(113),
GEOMETRY(114);
private final Integer type;
ExtTypes(Integer type) {
this.type = type;
}
@Override
public String getName() {
return name();
}
@Override
public String getVendor() {
return "org.elasticsearch";
}
@Override
public Integer getVendorTypeNumber() {
return type;
}
}
| ExtTypes |
java | spring-projects__spring-boot | module/spring-boot-web-server/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java | {
"start": 5999,
"end": 6276
} | class ____<T extends WebServerFactory> implements WebServerFactoryCustomizer<T> {
private boolean called;
@Override
public void customize(T factory) {
this.called = true;
}
boolean wasCalled() {
return this.called;
}
}
static | MockWebServerFactoryCustomizer |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/factories/UnregisteredJobManagerJobMetricGroupFactory.java | {
"start": 1227,
"end": 1527
} | enum ____ implements JobManagerJobMetricGroupFactory {
INSTANCE;
@Override
public JobManagerJobMetricGroup create(@Nonnull ExecutionPlan executionPlan) {
return UnregisteredMetricGroups.createUnregisteredJobManagerJobMetricGroup();
}
}
| UnregisteredJobManagerJobMetricGroupFactory |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/DisposableTest.java | {
"start": 831,
"end": 4899
} | class ____ {
@Test
public void compositeDisposableAddAllDefault() {
FakeDisposable d1 = new FakeDisposable();
FakeDisposable d2 = new FakeDisposable();
Disposable.Composite cd = new Disposable.Composite() {
volatile boolean disposed;
volatile int size;
@Override
public boolean add(Disposable d) {
size++;
return true;
}
@Override
public boolean remove(Disposable d) {
return false;
}
@Override
public int size() {
return size;
}
@Override
public void dispose() {
this.disposed = true;
}
@Override
public boolean isDisposed() {
return disposed;
}
};
assertThat(cd.size()).isZero();
boolean added = cd.addAll(Arrays.asList(d1, d2));
assertThat(added).isTrue();
assertThat(cd.size()).isEqualTo(2);
assertThat(d1.isDisposed()).isFalse();
assertThat(d2.isDisposed()).isFalse();
}
@Test
public void compositeDisposableAddAllDefaultAfterDispose() throws Exception {
final FakeDisposable d1 = new FakeDisposable();
final FakeDisposable d2 = new FakeDisposable();
Disposable.Composite cd = new Disposable.Composite() {
volatile boolean disposed;
volatile int size;
@Override
public boolean add(Disposable d) {
size++;
return true;
}
@Override
public boolean remove(Disposable d) {
return false;
}
@Override
public int size() {
return size;
}
@Override
public void dispose() {
this.disposed = true;
}
@Override
public boolean isDisposed() {
return disposed;
}
};
cd.dispose();
boolean added = cd.addAll(Arrays.asList(d1, d2));
assertThat(added).isFalse();
assertThat(cd.size()).isZero();
assertThat(d1.isDisposed()).isTrue();
assertThat(d2.isDisposed()).isTrue();
}
@Test
public void compositeDisposableAddAllDefaultDuringDispose() throws Exception {
final FakeDisposable d1 = new FakeDisposable();
final FakeDisposable d2 = new FakeDisposable();
final FakeDisposable d3 = new FakeDisposable();
Disposable.Composite cd = new Disposable.Composite() {
volatile boolean disposed;
volatile int size;
@Override
public boolean add(Disposable d) {
if (d == d2) {
disposed = true;
}
if (disposed) {
d.dispose();
return false;
}
size++;
return true;
}
@Override
public boolean remove(Disposable d) {
return false;
}
@Override
public int size() {
return size;
}
@Override
public void dispose() {
this.disposed = true;
}
@Override
public boolean isDisposed() {
return disposed;
}
};
boolean added = cd.addAll(Arrays.asList(d1, d2, d3));
assertThat(added).isFalse();
//not atomic: first element added
assertThat(cd.size()).isEqualTo(1);
assertThat(d1.isDisposed()).isFalse();
assertThat(d2.isDisposed()).isTrue();
assertThat(d3.isDisposed()).isTrue();
}
@Test
public void singleDisposableInitiallyNotDisposed() {
Disposable single = Disposables.single();
assertThat(single.isDisposed()).isFalse();
}
@Test
public void singleDisposableCanBeDisposed() {
Disposable single = Disposables.single();
assertThat(single.isDisposed()).isFalse();
single.dispose();
assertThat(single.isDisposed()).isTrue();
}
@Test
public void singleDisposableCreatesInstances() {
assertThat(Disposables.single()).isNotSameAs(Disposables.single());
}
@Test
public void disposedInitiallyDisposed() {
assertThat(Disposables.disposed().isDisposed()).isTrue();
}
@Test
public void disposedCreatesInstances() {
assertThat(Disposables.disposed()).isNotSameAs(Disposables.disposed());
}
@Test
public void neverInitiallyNotDisposed() {
assertThat(Disposables.never().isDisposed()).isFalse();
}
@Test
public void neverImmutable() {
Disposable never = Disposables.never();
assertThat(never.isDisposed()).isFalse();
never.dispose();
assertThat(never.isDisposed()).isFalse();
}
@Test
public void neverCreatesInstances() {
assertThat(Disposables.never()).isNotSameAs(Disposables.never());
}
}
| DisposableTest |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-spring-boot/src/test/java/org/assertj/tests/core/api/recursive/comparison/Issue_3533_Test.java | {
"start": 1685,
"end": 2576
} | class ____ {
@Autowired
private PersonRepository personRepository;
@Autowired
private CityRepository cityRepository;
@Test
void test() {
// Create and save a City
City city = new City();
city.setName("Paris");
city.setPostalCode("75000");
city = cityRepository.save(city);
// Create and save a User
Person person = new Person();
person.setFirstName("John");
person.setLastName("Doe");
person.setBirthCities(Set.of(city));
personRepository.save(person);
Person retrievedUser = personRepository.findById(1L).orElse(null);
// Verify the fields of the retrieved user
assertThat(retrievedUser).isNotNull()
.usingRecursiveComparison()
.comparingOnlyFields("firstName", "lastName")
.isEqualTo(person);
}
@Entity
static | Issue_3533_Test |
java | elastic__elasticsearch | x-pack/plugin/esql/qa/server/single-node/src/javaRestTest/java/org/elasticsearch/xpack/esql/qa/single_node/GenerativeMetricsIT.java | {
"start": 808,
"end": 1396
} | class ____ extends GenerativeRestTest {
@ClassRule
public static ElasticsearchCluster cluster = Clusters.testCluster();
@Override
protected String getTestRestCluster() {
return cluster.getHttpAddresses();
}
@Override
protected boolean supportsSourceFieldMapping() {
return cluster.getNumNodes() == 1;
}
@Override
protected CommandGenerator sourceCommand() {
return EsqlQueryGenerator.timeSeriesSourceCommand();
}
@Override
protected boolean requiresTimeSeries() {
return true;
}
}
| GenerativeMetricsIT |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/jsontype/TypeDeserializer.java | {
"start": 858,
"end": 2229
} | class ____
{
/*
/**********************************************************
/* Initialization
/**********************************************************
*/
/**
* Method called to create contextual version, to be used for
* values of given property. This may be the type itself
* (as is the case for bean properties), or values contained
* (for {@link java.util.Collection} or {@link java.util.Map}
* valued properties).
*/
public abstract TypeDeserializer forProperty(BeanProperty prop);
/*
/**********************************************************
/* Introspection
/**********************************************************
*/
/**
* Accessor for type information inclusion method
* that deserializer uses; indicates how type information
* is (expected to be) embedded in JSON input.
*/
public abstract As getTypeInclusion();
/**
* Name of property that contains type information, if
* property-based inclusion is used.
*/
public abstract String getPropertyName();
/**
* Accessor for object that handles conversions between
* types and matching type ids.
*/
public abstract TypeIdResolver getTypeIdResolver();
/**
* Accessor for "default implementation" type; optionally defined
* | TypeDeserializer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/CheckReturnValueTest.java | {
"start": 5213,
"end": 5286
} | class ____ extends MyObject {
MySubObject2() {}
}
| MySubObject2 |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/state/internals/SegmentIterator.java | {
"start": 1179,
"end": 3516
} | class ____<S extends Segment> implements KeyValueIterator<Bytes, byte[]> {
private final Bytes from;
private final Bytes to;
private final boolean forward;
protected final Iterator<S> segments;
protected final HasNextCondition hasNextCondition;
private S currentSegment;
KeyValueIterator<Bytes, byte[]> currentIterator;
SegmentIterator(final Iterator<S> segments,
final HasNextCondition hasNextCondition,
final Bytes from,
final Bytes to,
final boolean forward) {
this.segments = segments;
this.hasNextCondition = hasNextCondition;
this.from = from;
this.to = to;
this.forward = forward;
}
@Override
public void close() {
if (currentIterator != null) {
currentIterator.close();
currentIterator = null;
}
}
@Override
public Bytes peekNextKey() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return currentIterator.peekNextKey();
}
@Override
public boolean hasNext() {
boolean hasNext = false;
while ((currentIterator == null || !(hasNext = hasNextConditionHasNext()) || !currentSegment.isOpen())
&& segments.hasNext()) {
close();
currentSegment = segments.next();
try {
if (forward) {
currentIterator = currentSegment.range(from, to);
} else {
currentIterator = currentSegment.reverseRange(from, to);
}
} catch (final InvalidStateStoreException e) {
// segment may have been closed so we ignore it.
}
}
return currentIterator != null && hasNext;
}
private boolean hasNextConditionHasNext() {
boolean hasNext = false;
try {
hasNext = hasNextCondition.hasNext(currentIterator);
} catch (final InvalidStateStoreException e) {
// already closed so ignore
}
return hasNext;
}
@Override
public KeyValue<Bytes, byte[]> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return currentIterator.next();
}
}
| SegmentIterator |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/indices/TermsLookupTests.java | {
"start": 856,
"end": 3454
} | class ____ extends ESTestCase {
public void testTermsLookup() {
String index = randomAlphaOfLengthBetween(1, 10);
String id = randomAlphaOfLengthBetween(1, 10);
String path = randomAlphaOfLengthBetween(1, 10);
String routing = randomAlphaOfLengthBetween(1, 10);
TermsLookup termsLookup = new TermsLookup(index, id, path);
termsLookup.routing(routing);
assertEquals(index, termsLookup.index());
assertEquals(id, termsLookup.id());
assertEquals(path, termsLookup.path());
assertEquals(routing, termsLookup.routing());
}
public void testIllegalArguments() {
String id = randomAlphaOfLength(5);
String path = randomAlphaOfLength(5);
String index = randomAlphaOfLength(5);
switch (randomIntBetween(0, 2)) {
case 0 -> id = null;
case 1 -> path = null;
case 2 -> index = null;
default -> fail("unknown case");
}
try {
new TermsLookup(index, id, path);
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("[terms] query lookup element requires specifying"));
}
}
public void testSerialization() throws IOException {
TermsLookup termsLookup = randomTermsLookup();
try (BytesStreamOutput output = new BytesStreamOutput()) {
termsLookup.writeTo(output);
try (StreamInput in = output.bytes().streamInput()) {
TermsLookup deserializedLookup = new TermsLookup(in);
assertEquals(deserializedLookup, termsLookup);
assertEquals(deserializedLookup.hashCode(), termsLookup.hashCode());
assertNotSame(deserializedLookup, termsLookup);
}
}
}
public void testXContentParsing() throws IOException {
try (XContentParser parser = createParser(JsonXContent.jsonXContent, """
{ "index" : "index", "id" : "id", "path" : "path", "routing" : "routing" }""")) {
TermsLookup tl = TermsLookup.parseTermsLookup(parser);
assertEquals("index", tl.index());
assertEquals("id", tl.id());
assertEquals("path", tl.path());
assertEquals("routing", tl.routing());
}
}
public static TermsLookup randomTermsLookup() {
return new TermsLookup(randomAlphaOfLength(10), randomAlphaOfLength(10), randomAlphaOfLength(10).replace('.', '_')).routing(
randomBoolean() ? randomAlphaOfLength(10) : null
);
}
}
| TermsLookupTests |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/cglib/core/ClassNameReader.java | {
"start": 920,
"end": 1104
} | class ____ {
private ClassNameReader() {
}
private static final EarlyExitException EARLY_EXIT = new EarlyExitException();
@SuppressWarnings("serial")
private static | ClassNameReader |
java | micronaut-projects__micronaut-core | inject-java/src/test/java/io/micronaut/aop/around/noproxytarget/ByteBuddyNoProxyTargetWithConstructorProxyingClass.java | {
"start": 236,
"end": 483
} | class ____<A extends CharSequence> extends NoProxyTargetClass<A> {
private final Bar bar;
public ByteBuddyNoProxyTargetWithConstructorProxyingClass(Bar bar) {
this.bar = bar;
}
}
| ByteBuddyNoProxyTargetWithConstructorProxyingClass |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/record/UnalignedFileRecordsTest.java | {
"start": 1280,
"end": 2891
} | class ____ {
private final byte[][] values = new byte[][] {
"foo".getBytes(),
"bar".getBytes()
};
private FileRecords fileRecords;
@BeforeEach
public void setup() throws IOException {
this.fileRecords = createFileRecords(values);
}
@AfterEach
public void cleanup() throws IOException {
this.fileRecords.close();
}
@Test
public void testWriteTo() throws IOException {
org.apache.kafka.common.requests.ByteBufferChannel channel = new org.apache.kafka.common.requests.ByteBufferChannel(fileRecords.sizeInBytes());
int size = fileRecords.sizeInBytes();
UnalignedFileRecords records1 = fileRecords.sliceUnaligned(0, size / 2);
UnalignedFileRecords records2 = fileRecords.sliceUnaligned(size / 2, size - size / 2);
records1.writeTo(channel, 0, records1.sizeInBytes());
records2.writeTo(channel, 0, records2.sizeInBytes());
channel.close();
Iterator<Record> records = MemoryRecords.readableRecords(channel.buffer()).records().iterator();
for (byte[] value : values) {
assertTrue(records.hasNext());
assertEquals(records.next().value(), ByteBuffer.wrap(value));
}
}
private FileRecords createFileRecords(byte[][] values) throws IOException {
FileRecords fileRecords = FileRecords.open(tempFile());
for (byte[] value : values) {
fileRecords.append(MemoryRecords.withRecords(Compression.NONE, new SimpleRecord(value)));
}
return fileRecords;
}
}
| UnalignedFileRecordsTest |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/datastreams/DataStreamFeatureSetUsageTests.java | {
"start": 760,
"end": 6019
} | class ____ extends AbstractWireSerializingTestCase<DataStreamFeatureSetUsage> {
@Override
protected DataStreamFeatureSetUsage createTestInstance() {
return new DataStreamFeatureSetUsage(
new DataStreamFeatureSetUsage.DataStreamStats(
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
generateRetentionStats(),
generateRetentionStats(),
randomBoolean() ? Map.of() : Map.of("default", generateGlobalRetention(), "max", generateGlobalRetention())
)
);
}
@Override
protected DataStreamFeatureSetUsage mutateInstance(DataStreamFeatureSetUsage instance) {
var totalDataStreamCount = instance.getStats().totalDataStreamCount();
var indicesBehindDataStream = instance.getStats().indicesBehindDataStream();
long failureStoreExplicitlyEnabledDataStreamCount = instance.getStats().failureStoreExplicitlyEnabledDataStreamCount();
long failureStoreEffectivelyEnabledDataStreamCount = instance.getStats().failureStoreEffectivelyEnabledDataStreamCount();
long failureStoreIndicesCount = instance.getStats().failureStoreIndicesCount();
long failuresLifecycleExplicitlyEnabledDataStreamCount = instance.getStats().failuresLifecycleExplicitlyEnabledCount();
long failuresLifecycleEffectivelyEnabledDataStreamCount = instance.getStats().failuresLifecycleEffectivelyEnabledCount();
var dataRetentionStats = instance.getStats().failuresLifecycleDataRetentionStats();
var effectiveRetentionStats = instance.getStats().failuresLifecycleEffectiveRetentionStats();
var defaultRetention = instance.getStats().globalRetentionStats().get("default");
var maxRetention = instance.getStats().globalRetentionStats().get("max");
switch (between(0, 10)) {
case 0 -> totalDataStreamCount = randomValueOtherThan(totalDataStreamCount, ESTestCase::randomNonNegativeLong);
case 1 -> indicesBehindDataStream = randomValueOtherThan(indicesBehindDataStream, ESTestCase::randomNonNegativeLong);
case 2 -> failureStoreExplicitlyEnabledDataStreamCount = randomValueOtherThan(
failureStoreExplicitlyEnabledDataStreamCount,
ESTestCase::randomNonNegativeLong
);
case 3 -> failureStoreEffectivelyEnabledDataStreamCount = randomValueOtherThan(
failureStoreEffectivelyEnabledDataStreamCount,
ESTestCase::randomNonNegativeLong
);
case 4 -> failureStoreIndicesCount = randomValueOtherThan(failureStoreIndicesCount, ESTestCase::randomNonNegativeLong);
case 5 -> failuresLifecycleExplicitlyEnabledDataStreamCount = randomValueOtherThan(
failuresLifecycleExplicitlyEnabledDataStreamCount,
ESTestCase::randomNonNegativeLong
);
case 6 -> failuresLifecycleEffectivelyEnabledDataStreamCount = randomValueOtherThan(
failuresLifecycleEffectivelyEnabledDataStreamCount,
ESTestCase::randomNonNegativeLong
);
case 7 -> dataRetentionStats = randomValueOtherThan(
dataRetentionStats,
DataStreamLifecycleFeatureSetUsageTests::generateRetentionStats
);
case 8 -> effectiveRetentionStats = randomValueOtherThan(
effectiveRetentionStats,
DataStreamLifecycleFeatureSetUsageTests::generateRetentionStats
);
case 9 -> maxRetention = randomValueOtherThan(maxRetention, DataStreamLifecycleFeatureSetUsageTests::generateGlobalRetention);
case 10 -> defaultRetention = randomValueOtherThan(
defaultRetention,
DataStreamLifecycleFeatureSetUsageTests::generateGlobalRetention
);
default -> throw new IllegalStateException("Unexpected randomisation branch");
}
Map<String, DataStreamLifecycleFeatureSetUsage.GlobalRetentionStats> map = new HashMap<>();
if (defaultRetention != null) {
map.put("default", defaultRetention);
}
if (maxRetention != null) {
map.put("max", maxRetention);
}
return new DataStreamFeatureSetUsage(
new DataStreamFeatureSetUsage.DataStreamStats(
totalDataStreamCount,
indicesBehindDataStream,
failureStoreExplicitlyEnabledDataStreamCount,
failureStoreEffectivelyEnabledDataStreamCount,
failureStoreIndicesCount,
failuresLifecycleExplicitlyEnabledDataStreamCount,
failuresLifecycleEffectivelyEnabledDataStreamCount,
dataRetentionStats,
effectiveRetentionStats,
map
)
);
}
@Override
protected Writeable.Reader<DataStreamFeatureSetUsage> instanceReader() {
return DataStreamFeatureSetUsage::new;
}
}
| DataStreamFeatureSetUsageTests |
java | apache__camel | components/camel-file/src/main/java/org/apache/camel/component/file/FileBinding.java | {
"start": 997,
"end": 2615
} | class ____ implements GenericFileBinding<File> {
private File body;
private byte[] content;
@Override
public Object getBody(GenericFile<File> file) {
// if file content has been loaded then return it
if (content != null) {
return content;
}
// as we use java.io.File itself as the body (not loading its content
// into an OutputStream etc.)
// we just store a java.io.File handle to the actual file denoted by the
// file.getAbsoluteFilePath. We must do this as the original file
// consumed can be renamed before
// being processed (preMove) and thus it points to an invalid file
// location.
// GenericFile#getAbsoluteFilePath() is always up-to-date and thus we
// use it to create a file
// handle that is correct
if (body == null || !file.getAbsoluteFilePath().equals(body.getAbsolutePath())) {
body = new File(file.getAbsoluteFilePath());
}
return body;
}
@Override
public void setBody(GenericFile<File> file, Object body) {
// noop
}
@Override
public void loadContent(Exchange exchange, GenericFile<?> file) throws IOException {
if (content == null) {
// use converter to convert the content into memory as byte array
Object data = GenericFileConverter.convertTo(byte[].class, exchange, file,
exchange.getContext().getTypeConverterRegistry());
if (data != null) {
content = (byte[]) data;
}
}
}
}
| FileBinding |
java | quarkusio__quarkus | integration-tests/smallrye-jwt-token-propagation/src/test/java/io/quarkus/it/keycloak/KeycloakRealmResourceManager.java | {
"start": 772,
"end": 5309
} | class ____ implements QuarkusTestResourceLifecycleManager {
private static final String KEYCLOAK_SERVER_URL = System.getProperty("keycloak.url", "http://localhost:8180");
private static final String KEYCLOAK_REALM = "quarkus";
@Override
public Map<String, String> start() {
RealmRepresentation realm = createRealm(KEYCLOAK_REALM);
realm.setRevokeRefreshToken(true);
realm.setRefreshTokenMaxReuse(0);
realm.setAccessTokenLifespan(3);
realm.setRequiredActions(List.of());
realm.getClients().add(createClient("quarkus-app"));
realm.getUsers().add(createUser("alice", "user"));
realm.getUsers().add(createUser("bob", "user"));
realm.getUsers().add(createUser("john", "tester"));
try {
RestAssured
.given()
.auth().oauth2(getAdminAccessToken())
.contentType("application/json")
.body(JsonSerialization.writeValueAsBytes(realm))
.when()
.post(KEYCLOAK_SERVER_URL + "/admin/realms").then()
.statusCode(201);
} catch (IOException e) {
throw new RuntimeException(e);
}
return Collections.emptyMap();
}
private static String getAdminAccessToken() {
return RestAssured
.given()
.param("grant_type", "password")
.param("username", "admin")
.param("password", "admin")
.param("client_id", "admin-cli")
.when()
.post(KEYCLOAK_SERVER_URL + "/realms/master/protocol/openid-connect/token")
.as(AccessTokenResponse.class).getToken();
}
private static RealmRepresentation createRealm(String name) {
RealmRepresentation realm = new RealmRepresentation();
realm.setRealm(name);
realm.setEnabled(true);
realm.setUsers(new ArrayList<>());
realm.setClients(new ArrayList<>());
realm.setAccessTokenLifespan(3);
realm.setRequiredActions(List.of());
RolesRepresentation roles = new RolesRepresentation();
List<RoleRepresentation> realmRoles = new ArrayList<>();
roles.setRealm(realmRoles);
realm.setRoles(roles);
realm.getRoles().getRealm().add(new RoleRepresentation("user", null, false));
realm.getRoles().getRealm().add(new RoleRepresentation("admin", null, false));
return realm;
}
private static ClientRepresentation createClient(String clientId) {
ClientRepresentation client = new ClientRepresentation();
client.setClientId(clientId);
client.setPublicClient(false);
client.setSecret("secret");
client.setDirectAccessGrantsEnabled(true);
client.setServiceAccountsEnabled(true);
client.setEnabled(true);
return client;
}
private static UserRepresentation createUser(String username, String... realmRoles) {
UserRepresentation user = new UserRepresentation();
user.setUsername(username);
user.setEnabled(true);
user.setCredentials(new ArrayList<>());
user.setRealmRoles(Arrays.asList(realmRoles));
user.setEmail(username + "@gmail.com");
user.setEmailVerified(true);
user.setRequiredActions(List.of());
CredentialRepresentation credential = new CredentialRepresentation();
credential.setType(CredentialRepresentation.PASSWORD);
credential.setValue(username);
credential.setTemporary(false);
user.getCredentials().add(credential);
return user;
}
@Override
public void stop() {
RestAssured
.given()
.auth().oauth2(getAdminAccessToken())
.when()
.delete(KEYCLOAK_SERVER_URL + "/admin/realms/" + KEYCLOAK_REALM).then().statusCode(204);
}
public static String getAccessToken(String userName) {
return RestAssured
.given()
.param("grant_type", "password")
.param("username", userName)
.param("password", userName)
.param("client_id", "quarkus-app")
.param("client_secret", "secret")
.when()
.post(KEYCLOAK_SERVER_URL + "/realms/" + KEYCLOAK_REALM + "/protocol/openid-connect/token")
.as(AccessTokenResponse.class).getToken();
}
}
| KeycloakRealmResourceManager |
java | spring-projects__spring-boot | module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/error/ErrorWebExceptionHandler.java | {
"start": 749,
"end": 913
} | interface ____ indicates that a {@link WebExceptionHandler} is used to render
* errors.
*
* @author Brian Clozel
* @since 4.0.0
*/
@FunctionalInterface
public | that |
java | google__dagger | dagger-compiler/main/java/dagger/internal/codegen/writing/SetRequestRepresentation.java | {
"start": 11370,
"end": 11463
} | interface ____ {
SetRequestRepresentation create(MultiboundSetBinding binding);
}
}
| Factory |
java | netty__netty | common/src/main/java/io/netty/util/concurrent/AbstractEventExecutor.java | {
"start": 5160,
"end": 5206
} | interface ____ extends Runnable { }
}
| LazyRunnable |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/SubTaskInitializationMetricsBuilder.java | {
"start": 1274,
"end": 2782
} | class ____ {
private final long initializationStartTs;
private final ConcurrentMap<String, Long> durationMetrics = new ConcurrentHashMap<>();
private final AtomicReference<InitializationStatus> status =
new AtomicReference<>(InitializationStatus.FAILED);
public SubTaskInitializationMetricsBuilder(long initializationStartTs) {
this.initializationStartTs = initializationStartTs;
}
public long getInitializationStartTs() {
return initializationStartTs;
}
/**
* This adds a custom "duration" type metric, handled and aggregated by the {@link
* JobInitializationMetricsBuilder}. If a metric with the given name already exists the old and
* the new values will be added together.
*/
public SubTaskInitializationMetricsBuilder addDurationMetric(String name, long value) {
durationMetrics.compute(
name, (key, oldValue) -> oldValue == null ? value : value + oldValue);
return this;
}
public SubTaskInitializationMetricsBuilder setStatus(InitializationStatus status) {
this.status.set(status);
return this;
}
public SubTaskInitializationMetrics build() {
return build(System.currentTimeMillis());
}
@VisibleForTesting
public SubTaskInitializationMetrics build(long endTs) {
return new SubTaskInitializationMetrics(
initializationStartTs, endTs, durationMetrics, status.get());
}
}
| SubTaskInitializationMetricsBuilder |
java | spring-projects__spring-boot | configuration-metadata/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/source/BaseSource.java | {
"start": 763,
"end": 1147
} | class ____ {
private boolean enabled;
private String username;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
protected abstract String getPassword();
}
| BaseSource |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/lock/PessimisticWriteWithOptionalOuterJoinBreaksRefreshTest.java | {
"start": 2291,
"end": 2471
} | class ____ {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
@ManyToOne(cascade = { CascadeType.PERSIST })
@JoinTable(name = "test")
Parent parent;
}
}
| Child |
java | apache__camel | components/camel-fhir/camel-fhir-api/src/main/java/org/apache/camel/component/fhir/api/FhirCreate.java | {
"start": 1215,
"end": 4554
} | class ____ {
private final IGenericClient client;
public FhirCreate(IGenericClient client) {
this.client = client;
}
/**
* Creates a {@link IBaseResource} on the server
*
* @param resource The resource to create
* @param url The search URL to use. The format of this URL should be of the form
* <code>[ResourceType]?[Parameters]</code>, for example:
* <code>Patient?name=Smith&identifier=13.2.4.11.4%7C847366</code>, may be null
* @param preferReturn Add a <code>Prefer</code> header to the request, which requests that the server include
* or suppress the resource body as a part of the result. If a resource is returned by the
* server it will be parsed an accessible to the client via
* {@link MethodOutcome#getResource()}, may be null
* @param extraParameters see {@link ExtraParameters} for a full list of parameters that can be passed, may be NULL
* @return The {@link MethodOutcome}
*/
public MethodOutcome resource(
IBaseResource resource, String url, PreferReturnEnum preferReturn, Map<ExtraParameters, Object> extraParameters) {
ICreateTyped createTyped = client.create().resource(resource);
processOptionalParams(url, preferReturn, createTyped);
ExtraParameters.process(extraParameters, createTyped);
return createTyped.execute();
}
/**
* Creates a {@link IBaseResource} on the server
*
* @param resourceAsString The resource to create
* @param url The search URL to use. The format of this URL should be of the form
* <code>[ResourceType]?[Parameters]</code>, for example:
* <code>Patient?name=Smith&identifier=13.2.4.11.4%7C847366</code>, may be null
* @param preferReturn Add a <code>Prefer</code> header to the request, which requests that the server include
* or suppress the resource body as a part of the result. If a resource is returned by the
* server it will be parsed an accessible to the client via
* {@link MethodOutcome#getResource()}, may be null
* @param extraParameters see {@link ExtraParameters} for a full list of parameters that can be passed, may be
* NULL
* @return The {@link MethodOutcome}
*/
public MethodOutcome resource(
String resourceAsString, String url, PreferReturnEnum preferReturn, Map<ExtraParameters, Object> extraParameters) {
ICreateTyped createTyped = client.create().resource(resourceAsString);
processOptionalParams(url, preferReturn, createTyped);
ExtraParameters.process(extraParameters, createTyped);
return createTyped.execute();
}
private void processOptionalParams(String theSearchUrl, PreferReturnEnum theReturn, ICreateTyped createTyped) {
if (theSearchUrl != null) {
createTyped.conditionalByUrl(theSearchUrl);
}
if (theReturn != null) {
createTyped.prefer(theReturn);
}
}
}
| FhirCreate |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8347TransitiveDependencyManagerTest.java | {
"start": 1424,
"end": 4897
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* We run same command with various Maven versions and based on their version assert (Maven3 was not transitive,
* Maven4 before beta-6 was broken, post Maven 4 beta-6 all should be OK).
*/
@Test
void transitiveDependencyManager() throws Exception {
File testDir = extractResources("/mng-8347-transitive-dependency-manager");
Verifier verifier = new Verifier(testDir.getAbsolutePath());
verifier.addCliArgument("-V");
verifier.addCliArgument("dependency:3.8.0:tree");
verifier.addCliArgument("-Dmaven.repo.local.tail=" + testDir + "/local-repo");
verifier.execute();
verifier.verifyErrorFreeLog();
List<String> l = verifier.loadLogLines();
// Maven 4 is transitive and should produce expected results
a(l, "[INFO] org.apache.maven.it.mresolver614:root:jar:1.0.0");
a(l, "[INFO] \\- org.apache.maven.it.mresolver614:level1:jar:1.0.0:compile");
a(l, "[INFO] \\- org.apache.maven.it.mresolver614:level2:jar:1.0.0:compile");
a(l, "[INFO] \\- org.apache.maven.it.mresolver614:level3:jar:1.0.0:compile");
a(l, "[INFO] \\- org.apache.maven.it.mresolver614:level4:jar:1.0.1:compile");
a(l, "[INFO] \\- org.apache.maven.it.mresolver614:level5:jar:1.0.2:compile");
a(l, "[INFO] \\- org.apache.maven.it.mresolver614:level6:jar:1.0.2:compile");
}
/**
* Mimic bnd-maven-plugin:7.0.0: have direct dependency on plexus-build-api:0.0.7 and observe plexus-utils.
* Beta-5 makes it 1.5.5 while correct version is 1.5.8.
*/
@Test
void useCaseBndPlugin() throws Exception {
File testDir = extractResources("/mng-8347-bnd-plugin");
Verifier verifier = new Verifier(testDir.getAbsolutePath());
verifier.addCliArgument("-V");
verifier.addCliArgument("dependency:3.8.0:tree");
verifier.addCliArgument("-Dmaven.repo.local.tail=" + testDir + "/local-repo");
verifier.execute();
verifier.verifyErrorFreeLog();
List<String> l = verifier.loadLogLines();
a(l, "[INFO] org.apache.maven.it.mresolver614:root:jar:1.0.0");
a(l, "[INFO] \\- org.sonatype.plexus:plexus-build-api:jar:0.0.7:compile");
a(l, "[INFO] \\- org.codehaus.plexus:plexus-utils:jar:1.5.8:compile");
}
/**
* Make Quarkus TLS Registry first level dependency and make sure expected stuff are present.
*/
@Test
void useCaseQuarkusTlsRegistry() throws Exception {
File testDir = extractResources("/mng-8347-quarkus-tls-registry");
Verifier verifier = new Verifier(testDir.getAbsolutePath());
verifier.addCliArgument("-V");
verifier.addCliArgument("dependency:3.8.0:tree");
verifier.addCliArgument("-Dmaven.repo.local.tail=" + testDir + "/local-repo");
verifier.execute();
verifier.verifyErrorFreeLog();
// this really boils down to "transitive" vs "non-transitive"
List<String> l = verifier.loadLogLines();
a(l, "[INFO] | | | \\- com.fasterxml.jackson.core:jackson-core:jar:2.17.2:compile");
}
/**
* Assert true, log lines contains string...
*/
protected void a(List<String> logLines, String string) {
assertTrue(logLines.contains(string), "missing " + string);
}
}
| MavenITmng8347TransitiveDependencyManagerTest |
java | square__retrofit | retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/CompletableTest.java | {
"start": 1000,
"end": 1212
} | class ____ {
@Rule public final MockWebServer server = new MockWebServer();
@Rule
public final RecordingCompletableObserver.Rule observerRule =
new RecordingCompletableObserver.Rule();
| CompletableTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/query/Chaos.java | {
"start": 1039,
"end": 2150
} | class ____ {
@Id
private Long id;
@Column(name="chaos_size")
private Long size;
private String name;
@Column(name="nick_name")
private String nickname;
@OneToMany
@JoinColumn(name="chaos_fk")
@SQLInsert( sql="UPDATE CASIMIR_PARTICULE SET chaos_fk = ? where id = ?")
@SQLDelete( sql="UPDATE CASIMIR_PARTICULE SET chaos_fk = null where id = ?")
@SQLDeleteAll( sql="UPDATE CASIMIR_PARTICULE SET chaos_fk = null where chaos_fk = ?")
private Set<CasimirParticle> particles = new HashSet<CasimirParticle>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getSize() {
return size;
}
public void setSize(Long size) {
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public Set<CasimirParticle> getParticles() {
return particles;
}
public void setParticles(Set<CasimirParticle> particles) {
this.particles = particles;
}
}
| Chaos |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/migrationsupport/conditions/IgnoreConditionTests.java | {
"start": 4362,
"end": 4572
} | class ____ {
@Test
void ignoredBecauseClassIsIgnored() {
/* no-op */
}
}
@SuppressWarnings("JUnitMalformedDeclaration")
@ExtendWith(IgnoreCondition.class)
static | IgnoredClassWithCustomMessageTestCase |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/event/JobEventManagerTest.java | {
"start": 1060,
"end": 3582
} | class ____ {
@Test
void testStartTwice() throws Exception {
TestingJobEventStore.init();
JobEventManager jobEventManager = new JobEventManager(new TestingJobEventStore());
jobEventManager.start();
assertThat(jobEventManager.isRunning()).isTrue();
assertThat(TestingJobEventStore.startTimes).isEqualTo(1);
jobEventManager.start();
assertThat(TestingJobEventStore.startTimes).isEqualTo(1);
}
@Test
void testStop() throws Exception {
TestingJobEventStore.init();
JobEventManager jobEventManager = new JobEventManager(new TestingJobEventStore());
jobEventManager.start();
assertThat(jobEventManager.isRunning()).isTrue();
jobEventManager.stop(true);
assertThat(jobEventManager.isRunning()).isFalse();
}
@Test
void testRestart() throws Exception {
TestingJobEventStore.init();
JobEventManager jobEventManager = new JobEventManager(new TestingJobEventStore());
jobEventManager.start();
jobEventManager.stop(true);
assertThat(jobEventManager.isRunning()).isFalse();
jobEventManager.start();
assertThat(jobEventManager.isRunning()).isTrue();
}
/** Test replay event and write event before call start method. */
@Test
void testInvalidInvoke() {
TestingJobEventStore.init();
JobEventManager jobEventManager = new JobEventManager(new TestingJobEventStore());
assertThat(jobEventManager.isRunning()).isFalse();
// test write event before start.
assertThatThrownBy(() -> jobEventManager.writeEvent(new TestingJobEvent(0), false))
.isInstanceOf(IllegalStateException.class);
assertThatThrownBy(
() -> {
// test replay event before start.
jobEventManager.replay(
new JobEventReplayHandler() {
@Override
public void startReplay() {}
@Override
public void replayOneEvent(JobEvent event) {}
@Override
public void finalizeReplay() {}
});
})
.isInstanceOf(IllegalStateException.class);
}
public static | JobEventManagerTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/OverridesTest.java | {
"start": 10517,
"end": 10672
} | class ____ extends SubOne {
@Override
abstract void varargsMethod(Object... xs);
}
abstract | SubTwo |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/JoinFormulaImplicitJoinTest.java | {
"start": 3183,
"end": 3867
} | class ____ {
@Id
@GeneratedValue
private Long id;
private String name;
private Integer version;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "person_id")
private Person person;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
}
| PersonVersion |
java | netty__netty | codec-http/src/test/java/io/netty/handler/codec/spdy/SpdyFrameDecoderTest.java | {
"start": 1308,
"end": 42426
} | class ____ {
private static final Random RANDOM = new Random();
private final SpdyFrameDecoderDelegate delegate = mock(SpdyFrameDecoderDelegate.class);
private final TestSpdyFrameDecoderDelegate testDelegate = new TestSpdyFrameDecoderDelegate(delegate);
private SpdyFrameDecoder decoder;
@BeforeEach
public void createDecoder() {
decoder = new SpdyFrameDecoder(SpdyVersion.SPDY_3_1, testDelegate);
}
@AfterEach
public void releaseBuffers() {
testDelegate.releaseAll();
}
private static void encodeDataFrameHeader(ByteBuf buffer, int streamId, byte flags, int length) {
buffer.writeInt(streamId & 0x7FFFFFFF);
buffer.writeByte(flags);
buffer.writeMedium(length);
}
static void encodeControlFrameHeader(ByteBuf buffer, short type, byte flags, int length) {
buffer.writeShort(0x8000 | SpdyVersion.SPDY_3_1.version());
buffer.writeShort(type);
buffer.writeByte(flags);
buffer.writeMedium(length);
}
@Test
public void testSpdyDataFrame() throws Exception {
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
byte flags = 0;
int length = 1024;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeDataFrameHeader(buf, streamId, flags, length);
for (int i = 0; i < 256; i ++) {
buf.writeInt(RANDOM.nextInt());
}
decoder.decode(buf);
verify(delegate).readDataFrame(streamId, false, buf.slice(SPDY_HEADER_SIZE, length));
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testEmptySpdyDataFrame() throws Exception {
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
byte flags = 0;
int length = 0;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeDataFrameHeader(buf, streamId, flags, length);
decoder.decode(buf);
verify(delegate).readDataFrame(streamId, false, Unpooled.EMPTY_BUFFER);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testLastSpdyDataFrame() throws Exception {
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
byte flags = 0x01; // FLAG_FIN
int length = 0;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeDataFrameHeader(buf, streamId, flags, length);
decoder.decode(buf);
verify(delegate).readDataFrame(streamId, true, Unpooled.EMPTY_BUFFER);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testUnknownSpdyDataFrameFlags() throws Exception {
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
byte flags = (byte) 0xFE; // should ignore any unknown flags
int length = 0;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeDataFrameHeader(buf, streamId, flags, length);
decoder.decode(buf);
verify(delegate).readDataFrame(streamId, false, Unpooled.EMPTY_BUFFER);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testIllegalSpdyDataFrameStreamId() throws Exception {
int streamId = 0; // illegal stream identifier
byte flags = 0;
int length = 0;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeDataFrameHeader(buf, streamId, flags, length);
decoder.decode(buf);
verify(delegate).readFrameError((String) any());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testPipelinedSpdyDataFrames() throws Exception {
int streamId1 = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int streamId2 = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
byte flags = 0;
int length = 0;
ByteBuf buf = Unpooled.buffer(2 * (SPDY_HEADER_SIZE + length));
encodeDataFrameHeader(buf, streamId1, flags, length);
encodeDataFrameHeader(buf, streamId2, flags, length);
decoder.decode(buf);
verify(delegate).readDataFrame(streamId1, false, Unpooled.EMPTY_BUFFER);
verify(delegate).readDataFrame(streamId2, false, Unpooled.EMPTY_BUFFER);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testSpdySynStreamFrame() throws Exception {
short type = 1;
byte flags = 0;
int length = 10;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
byte priority = (byte) (RANDOM.nextInt() & 0x07);
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(associatedToStreamId);
buf.writeByte(priority << 5);
buf.writeByte(0);
decoder.decode(buf);
verify(delegate).readSynStreamFrame(streamId, associatedToStreamId, priority, false, false);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testLastSpdySynStreamFrame() throws Exception {
short type = 1;
byte flags = 0x01; // FLAG_FIN
int length = 10;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
byte priority = (byte) (RANDOM.nextInt() & 0x07);
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(associatedToStreamId);
buf.writeByte(priority << 5);
buf.writeByte(0);
decoder.decode(buf);
verify(delegate).readSynStreamFrame(streamId, associatedToStreamId, priority, true, false);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testUnidirectionalSpdySynStreamFrame() throws Exception {
short type = 1;
byte flags = 0x02; // FLAG_UNIDIRECTIONAL
int length = 10;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
byte priority = (byte) (RANDOM.nextInt() & 0x07);
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(associatedToStreamId);
buf.writeByte(priority << 5);
buf.writeByte(0);
decoder.decode(buf);
verify(delegate).readSynStreamFrame(streamId, associatedToStreamId, priority, false, true);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testIndependentSpdySynStreamFrame() throws Exception {
short type = 1;
byte flags = 0;
int length = 10;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int associatedToStreamId = 0; // independent of all other streams
byte priority = (byte) (RANDOM.nextInt() & 0x07);
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(associatedToStreamId);
buf.writeByte(priority << 5);
buf.writeByte(0);
decoder.decode(buf);
verify(delegate).readSynStreamFrame(streamId, associatedToStreamId, priority, false, false);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testUnknownSpdySynStreamFrameFlags() throws Exception {
short type = 1;
byte flags = (byte) 0xFC; // undefined flags
int length = 10;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
byte priority = (byte) (RANDOM.nextInt() & 0x07);
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(associatedToStreamId);
buf.writeByte(priority << 5);
buf.writeByte(0);
decoder.decode(buf);
verify(delegate).readSynStreamFrame(streamId, associatedToStreamId, priority, false, false);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testReservedSpdySynStreamFrameBits() throws Exception {
short type = 1;
byte flags = 0;
int length = 10;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
byte priority = (byte) (RANDOM.nextInt() & 0x07);
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId | 0x80000000); // should ignore reserved bit
buf.writeInt(associatedToStreamId | 0x80000000); // should ignore reserved bit
buf.writeByte(priority << 5 | 0x1F); // should ignore reserved bits
buf.writeByte(0xFF); // should ignore reserved bits
decoder.decode(buf);
verify(delegate).readSynStreamFrame(streamId, associatedToStreamId, priority, false, false);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testInvalidSpdySynStreamFrameLength() throws Exception {
short type = 1;
byte flags = 0;
int length = 8; // invalid length
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(associatedToStreamId);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testIllegalSpdySynStreamFrameStreamId() throws Exception {
short type = 1;
byte flags = 0;
int length = 10;
int streamId = 0; // invalid stream identifier
int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
byte priority = (byte) (RANDOM.nextInt() & 0x07);
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(associatedToStreamId);
buf.writeByte(priority << 5);
buf.writeByte(0);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testSpdySynStreamFrameHeaderBlock() throws Exception {
short type = 1;
byte flags = 0;
int length = 10;
int headerBlockLength = 1024;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
byte priority = (byte) (RANDOM.nextInt() & 0x07);
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length + headerBlockLength);
encodeControlFrameHeader(buf, type, flags, length + headerBlockLength);
buf.writeInt(streamId);
buf.writeInt(associatedToStreamId);
buf.writeByte(priority << 5);
buf.writeByte(0);
ByteBuf headerBlock = Unpooled.buffer(headerBlockLength);
for (int i = 0; i < 256; i ++) {
headerBlock.writeInt(RANDOM.nextInt());
}
decoder.decode(buf);
decoder.decode(headerBlock);
verify(delegate).readSynStreamFrame(streamId, associatedToStreamId, priority, false, false);
verify(delegate).readHeaderBlock(headerBlock.slice(0, headerBlock.writerIndex()));
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
assertFalse(headerBlock.isReadable());
buf.release();
headerBlock.release();
}
@Test
public void testSpdySynReplyFrame() throws Exception {
short type = 2;
byte flags = 0;
int length = 4;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
decoder.decode(buf);
verify(delegate).readSynReplyFrame(streamId, false);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testLastSpdySynReplyFrame() throws Exception {
short type = 2;
byte flags = 0x01; // FLAG_FIN
int length = 4;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
decoder.decode(buf);
verify(delegate).readSynReplyFrame(streamId, true);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testUnknownSpdySynReplyFrameFlags() throws Exception {
short type = 2;
byte flags = (byte) 0xFE; // undefined flags
int length = 4;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
decoder.decode(buf);
verify(delegate).readSynReplyFrame(streamId, false);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testReservedSpdySynReplyFrameBits() throws Exception {
short type = 2;
byte flags = 0;
int length = 4;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId | 0x80000000); // should ignore reserved bit
decoder.decode(buf);
verify(delegate).readSynReplyFrame(streamId, false);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testInvalidSpdySynReplyFrameLength() throws Exception {
short type = 2;
byte flags = 0;
int length = 0; // invalid length
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testIllegalSpdySynReplyFrameStreamId() throws Exception {
short type = 2;
byte flags = 0;
int length = 4;
int streamId = 0; // invalid stream identifier
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testSpdySynReplyFrameHeaderBlock() throws Exception {
short type = 2;
byte flags = 0;
int length = 4;
int headerBlockLength = 1024;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length + headerBlockLength);
encodeControlFrameHeader(buf, type, flags, length + headerBlockLength);
buf.writeInt(streamId);
ByteBuf headerBlock = Unpooled.buffer(headerBlockLength);
for (int i = 0; i < 256; i ++) {
headerBlock.writeInt(RANDOM.nextInt());
}
decoder.decode(buf);
decoder.decode(headerBlock);
verify(delegate).readSynReplyFrame(streamId, false);
verify(delegate).readHeaderBlock(headerBlock.slice(0, headerBlock.writerIndex()));
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
assertFalse(headerBlock.isReadable());
buf.release();
headerBlock.release();
}
@Test
public void testSpdyRstStreamFrame() throws Exception {
short type = 3;
byte flags = 0;
int length = 8;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(statusCode);
decoder.decode(buf);
verify(delegate).readRstStreamFrame(streamId, statusCode);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testReservedSpdyRstStreamFrameBits() throws Exception {
short type = 3;
byte flags = 0;
int length = 8;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId | 0x80000000); // should ignore reserved bit
buf.writeInt(statusCode);
decoder.decode(buf);
verify(delegate).readRstStreamFrame(streamId, statusCode);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testInvalidSpdyRstStreamFrameFlags() throws Exception {
short type = 3;
byte flags = (byte) 0xFF; // invalid flags
int length = 8;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(statusCode);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testInvalidSpdyRstStreamFrameLength() throws Exception {
short type = 3;
byte flags = 0;
int length = 12; // invalid length
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(statusCode);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testIllegalSpdyRstStreamFrameStreamId() throws Exception {
short type = 3;
byte flags = 0;
int length = 8;
int streamId = 0; // invalid stream identifier
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(statusCode);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testIllegalSpdyRstStreamFrameStatusCode() throws Exception {
short type = 3;
byte flags = 0;
int length = 8;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int statusCode = 0; // invalid status code
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(statusCode);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testSpdySettingsFrame() throws Exception {
short type = 4;
byte flags = 0;
int numSettings = 2;
int length = 8 * numSettings + 4;
byte idFlags = 0;
int id = RANDOM.nextInt() & 0x00FFFFFF;
int value = RANDOM.nextInt();
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(numSettings);
for (int i = 0; i < numSettings; i++) {
buf.writeByte(idFlags);
buf.writeMedium(id);
buf.writeInt(value);
}
delegate.readSettingsEnd();
decoder.decode(buf);
verify(delegate).readSettingsFrame(false);
verify(delegate, times(numSettings)).readSetting(id, value, false, false);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testEmptySpdySettingsFrame() throws Exception {
short type = 4;
byte flags = 0;
int numSettings = 0;
int length = 8 * numSettings + 4;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(numSettings);
decoder.decode(buf);
verify(delegate).readSettingsFrame(false);
verify(delegate).readSettingsEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testSpdySettingsFrameClearFlag() throws Exception {
short type = 4;
byte flags = 0x01; // FLAG_SETTINGS_CLEAR_SETTINGS
int numSettings = 0;
int length = 8 * numSettings + 4;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(numSettings);
decoder.decode(buf);
verify(delegate).readSettingsFrame(true);
verify(delegate).readSettingsEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testSpdySettingsPersistValues() throws Exception {
short type = 4;
byte flags = 0;
int numSettings = 1;
int length = 8 * numSettings + 4;
byte idFlags = 0x01; // FLAG_SETTINGS_PERSIST_VALUE
int id = RANDOM.nextInt() & 0x00FFFFFF;
int value = RANDOM.nextInt();
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(numSettings);
for (int i = 0; i < numSettings; i++) {
buf.writeByte(idFlags);
buf.writeMedium(id);
buf.writeInt(value);
}
delegate.readSettingsEnd();
decoder.decode(buf);
verify(delegate).readSettingsFrame(false);
verify(delegate, times(numSettings)).readSetting(id, value, true, false);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testSpdySettingsPersistedValues() throws Exception {
short type = 4;
byte flags = 0;
int numSettings = 1;
int length = 8 * numSettings + 4;
byte idFlags = 0x02; // FLAG_SETTINGS_PERSISTED
int id = RANDOM.nextInt() & 0x00FFFFFF;
int value = RANDOM.nextInt();
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(numSettings);
for (int i = 0; i < numSettings; i++) {
buf.writeByte(idFlags);
buf.writeMedium(id);
buf.writeInt(value);
}
delegate.readSettingsEnd();
decoder.decode(buf);
verify(delegate).readSettingsFrame(false);
verify(delegate, times(numSettings)).readSetting(id, value, false, true);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testUnknownSpdySettingsFrameFlags() throws Exception {
short type = 4;
byte flags = (byte) 0xFE; // undefined flags
int numSettings = 0;
int length = 8 * numSettings + 4;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(numSettings);
decoder.decode(buf);
verify(delegate).readSettingsFrame(false);
verify(delegate).readSettingsEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testUnknownSpdySettingsFlags() throws Exception {
short type = 4;
byte flags = 0;
int numSettings = 1;
int length = 8 * numSettings + 4;
byte idFlags = (byte) 0xFC; // undefined flags
int id = RANDOM.nextInt() & 0x00FFFFFF;
int value = RANDOM.nextInt();
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(numSettings);
for (int i = 0; i < numSettings; i++) {
buf.writeByte(idFlags);
buf.writeMedium(id);
buf.writeInt(value);
}
delegate.readSettingsEnd();
decoder.decode(buf);
verify(delegate).readSettingsFrame(false);
verify(delegate, times(numSettings)).readSetting(id, value, false, false);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testInvalidSpdySettingsFrameLength() throws Exception {
short type = 4;
byte flags = 0;
int numSettings = 2;
int length = 8 * numSettings + 8; // invalid length
byte idFlags = 0;
int id = RANDOM.nextInt() & 0x00FFFFFF;
int value = RANDOM.nextInt();
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(numSettings);
for (int i = 0; i < numSettings; i++) {
buf.writeByte(idFlags);
buf.writeMedium(id);
buf.writeInt(value);
}
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testInvalidSpdySettingsFrameNumSettings() throws Exception {
short type = 4;
byte flags = 0;
int numSettings = 2;
int length = 8 * numSettings + 4;
byte idFlags = 0;
int id = RANDOM.nextInt() & 0x00FFFFFF;
int value = RANDOM.nextInt();
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(0); // invalid num_settings
for (int i = 0; i < numSettings; i++) {
buf.writeByte(idFlags);
buf.writeMedium(id);
buf.writeInt(value);
}
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testDiscardUnknownFrame() throws Exception {
short type = 5;
byte flags = (byte) 0xFF;
int length = 8;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeLong(RANDOM.nextLong());
decoder.decode(buf);
verifyZeroInteractions(delegate);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testDiscardUnknownEmptyFrame() throws Exception {
short type = 5;
byte flags = (byte) 0xFF;
int length = 0;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
decoder.decode(buf);
verifyZeroInteractions(delegate);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testProgressivelyDiscardUnknownEmptyFrame() throws Exception {
short type = 5;
byte flags = (byte) 0xFF;
int segment = 4;
int length = 2 * segment;
ByteBuf header = Unpooled.buffer(SPDY_HEADER_SIZE);
ByteBuf segment1 = Unpooled.buffer(segment);
ByteBuf segment2 = Unpooled.buffer(segment);
encodeControlFrameHeader(header, type, flags, length);
segment1.writeInt(RANDOM.nextInt());
segment2.writeInt(RANDOM.nextInt());
decoder.decode(header);
decoder.decode(segment1);
decoder.decode(segment2);
verifyZeroInteractions(delegate);
assertFalse(header.isReadable());
assertFalse(segment1.isReadable());
assertFalse(segment2.isReadable());
header.release();
segment1.release();
segment2.release();
}
@Test
public void testSpdyPingFrame() throws Exception {
short type = 6;
byte flags = 0;
int length = 4;
int id = RANDOM.nextInt();
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(id);
decoder.decode(buf);
verify(delegate).readPingFrame(id);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testUnknownSpdyPingFrameFlags() throws Exception {
short type = 6;
byte flags = (byte) 0xFF; // undefined flags
int length = 4;
int id = RANDOM.nextInt();
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(id);
decoder.decode(buf);
verify(delegate).readPingFrame(id);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testInvalidSpdyPingFrameLength() throws Exception {
short type = 6;
byte flags = 0;
int length = 8; // invalid length
int id = RANDOM.nextInt();
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(id);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testSpdyGoAwayFrame() throws Exception {
short type = 7;
byte flags = 0;
int length = 8;
int lastGoodStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(lastGoodStreamId);
buf.writeInt(statusCode);
decoder.decode(buf);
verify(delegate).readGoAwayFrame(lastGoodStreamId, statusCode);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testUnknownSpdyGoAwayFrameFlags() throws Exception {
short type = 7;
byte flags = (byte) 0xFF; // undefined flags
int length = 8;
int lastGoodStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(lastGoodStreamId);
buf.writeInt(statusCode);
decoder.decode(buf);
verify(delegate).readGoAwayFrame(lastGoodStreamId, statusCode);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testReservedSpdyGoAwayFrameBits() throws Exception {
short type = 7;
byte flags = 0;
int length = 8;
int lastGoodStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(lastGoodStreamId | 0x80000000); // should ignore reserved bit
buf.writeInt(statusCode);
decoder.decode(buf);
verify(delegate).readGoAwayFrame(lastGoodStreamId, statusCode);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testInvalidSpdyGoAwayFrameLength() throws Exception {
short type = 7;
byte flags = 0;
int length = 12; // invalid length
int lastGoodStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(lastGoodStreamId);
buf.writeInt(statusCode);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testSpdyHeadersFrame() throws Exception {
short type = 8;
byte flags = 0;
int length = 4;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
decoder.decode(buf);
verify(delegate).readHeadersFrame(streamId, false);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testLastSpdyHeadersFrame() throws Exception {
short type = 8;
byte flags = 0x01; // FLAG_FIN
int length = 4;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
decoder.decode(buf);
verify(delegate).readHeadersFrame(streamId, true);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testUnknownSpdyHeadersFrameFlags() throws Exception {
short type = 8;
byte flags = (byte) 0xFE; // undefined flags
int length = 4;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
decoder.decode(buf);
verify(delegate).readHeadersFrame(streamId, false);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testReservedSpdyHeadersFrameBits() throws Exception {
short type = 8;
byte flags = 0;
int length = 4;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId | 0x80000000); // should ignore reserved bit
decoder.decode(buf);
verify(delegate).readHeadersFrame(streamId, false);
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testInvalidSpdyHeadersFrameLength() throws Exception {
short type = 8;
byte flags = 0;
int length = 0; // invalid length
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testInvalidSpdyHeadersFrameStreamId() throws Exception {
short type = 8;
byte flags = 0;
int length = 4;
int streamId = 0; // invalid stream identifier
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testSpdyHeadersFrameHeaderBlock() throws Exception {
short type = 8;
byte flags = 0;
int length = 4;
int headerBlockLength = 1024;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length + headerBlockLength);
buf.writeInt(streamId);
ByteBuf headerBlock = Unpooled.buffer(headerBlockLength);
for (int i = 0; i < 256; i ++) {
headerBlock.writeInt(RANDOM.nextInt());
}
decoder.decode(buf);
decoder.decode(headerBlock);
verify(delegate).readHeadersFrame(streamId, false);
verify(delegate).readHeaderBlock(headerBlock.slice(0, headerBlock.writerIndex()));
verify(delegate).readHeaderBlockEnd();
assertFalse(buf.isReadable());
assertFalse(headerBlock.isReadable());
buf.release();
headerBlock.release();
}
@Test
public void testSpdyWindowUpdateFrame() throws Exception {
short type = 9;
byte flags = 0;
int length = 8;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF;
int deltaWindowSize = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(deltaWindowSize);
decoder.decode(buf);
verify(delegate).readWindowUpdateFrame(streamId, deltaWindowSize);
assertFalse(buf.isReadable());
}
@Test
public void testUnknownSpdyWindowUpdateFrameFlags() throws Exception {
short type = 9;
byte flags = (byte) 0xFF; // undefined flags
int length = 8;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF;
int deltaWindowSize = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(deltaWindowSize);
decoder.decode(buf);
verify(delegate).readWindowUpdateFrame(streamId, deltaWindowSize);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testReservedSpdyWindowUpdateFrameBits() throws Exception {
short type = 9;
byte flags = 0;
int length = 8;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF;
int deltaWindowSize = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId | 0x80000000); // should ignore reserved bit
buf.writeInt(deltaWindowSize | 0x80000000); // should ignore reserved bit
decoder.decode(buf);
verify(delegate).readWindowUpdateFrame(streamId, deltaWindowSize);
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testInvalidSpdyWindowUpdateFrameLength() throws Exception {
short type = 9;
byte flags = 0;
int length = 12; // invalid length
int streamId = RANDOM.nextInt() & 0x7FFFFFFF;
int deltaWindowSize = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(deltaWindowSize);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testIllegalSpdyWindowUpdateFrameDeltaWindowSize() throws Exception {
short type = 9;
byte flags = 0;
int length = 8;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF;
int deltaWindowSize = 0; // invalid delta window size
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
buf.writeInt(streamId);
buf.writeInt(deltaWindowSize);
decoder.decode(buf);
verify(delegate).readFrameError(anyString());
assertFalse(buf.isReadable());
buf.release();
}
}
| SpdyFrameDecoderTest |
java | google__guava | guava-tests/test/com/google/common/collect/LockHeldAssertingSet.java | {
"start": 1117,
"end": 4485
} | class ____<E> extends ForwardingSet<E> implements Serializable {
final Set<E> delegate;
final Object mutex;
LockHeldAssertingSet(Set<E> delegate, Object mutex) {
checkNotNull(mutex);
this.delegate = delegate;
this.mutex = mutex;
}
@Override
protected Set<E> delegate() {
return delegate;
}
@Override
public String toString() {
assertTrue(Thread.holdsLock(mutex));
return super.toString();
}
@Override
public boolean equals(@Nullable Object o) {
assertTrue(Thread.holdsLock(mutex));
return super.equals(o);
}
@Override
public int hashCode() {
assertTrue(Thread.holdsLock(mutex));
return super.hashCode();
}
@Override
public boolean add(@Nullable E o) {
assertTrue(Thread.holdsLock(mutex));
return super.add(o);
}
@Override
public boolean addAll(Collection<? extends E> c) {
assertTrue(Thread.holdsLock(mutex));
return super.addAll(c);
}
@Override
public void clear() {
assertTrue(Thread.holdsLock(mutex));
super.clear();
}
@Override
public boolean contains(@Nullable Object o) {
assertTrue(Thread.holdsLock(mutex));
return super.contains(o);
}
@Override
public boolean containsAll(Collection<?> c) {
assertTrue(Thread.holdsLock(mutex));
return super.containsAll(c);
}
@Override
public boolean isEmpty() {
assertTrue(Thread.holdsLock(mutex));
return super.isEmpty();
}
/*
* We don't assert that the lock is held during calls to iterator(), stream(), and spliterator:
* `Synchronized` doesn't guarantee that it will hold the mutex for those calls because callers
* are responsible for taking the mutex themselves:
* https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/util/Collections.html#synchronizedCollection(java.util.Collection)
*
* Similarly, we avoid having those methods *implemented* in terms of *other* TestSet methods
* that will perform holdsLock assertions:
*
* - For iterator(), we can accomplish that by not overriding iterator() at all. That way, we
* inherit an implementation that forwards to the delegate collection, which performs no
* holdsLock assertions.
*
* - For stream() and spliterator(), we have to forward to the delegate ourselves because
* ForwardingSet does not forward `default` methods, as discussed in its Javadoc.
*/
@Override
public Stream<E> stream() {
return delegate.stream();
}
@Override
public Spliterator<E> spliterator() {
return delegate.spliterator();
}
@Override
public boolean remove(@Nullable Object o) {
assertTrue(Thread.holdsLock(mutex));
return super.remove(o);
}
@Override
public boolean removeAll(Collection<?> c) {
assertTrue(Thread.holdsLock(mutex));
return super.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
assertTrue(Thread.holdsLock(mutex));
return super.retainAll(c);
}
@Override
public int size() {
assertTrue(Thread.holdsLock(mutex));
return super.size();
}
@Override
public Object[] toArray() {
assertTrue(Thread.holdsLock(mutex));
return super.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
assertTrue(Thread.holdsLock(mutex));
return super.toArray(a);
}
private static final long serialVersionUID = 0;
}
| LockHeldAssertingSet |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/nlp/QuestionAnsweringProcessor.java | {
"start": 13638,
"end": 14219
} | class ____ extends PriorityQueue<ScoreAndIndices> {
ScoreAndIndicesPriorityQueue(int maxSize) {
super(maxSize);
}
@Override
protected boolean lessThan(ScoreAndIndices a, ScoreAndIndices b) {
return a.compareTo(b) < 0;
}
}
record ScoreAndIndices(int startToken, int endToken, double score, int spanIndex) implements Comparable<ScoreAndIndices> {
@Override
public int compareTo(ScoreAndIndices o) {
return Double.compare(score, o.score);
}
}
}
| ScoreAndIndicesPriorityQueue |
java | quarkusio__quarkus | extensions/grpc/deployment/src/main/java/io/quarkus/grpc/deployment/GrpcServerProcessor.java | {
"start": 13353,
"end": 13806
} | class ____ implements io.grpc.BindableService (implementing BindableService is not mandatory)
if (service.interfaceNames().contains(GrpcDotNames.BINDABLE_SERVICE)) {
break;
}
DotName superName = service.superName();
if (superName == null) {
break;
}
service = index.getClassByName(superName);
}
return collected;
}
private | that |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/Tokenizer.java | {
"start": 1049,
"end": 1192
} | interface ____ provide a way to configure the tokenizer, and then use that configuration to
* tokenize the data in the Exchange.
*/
public | should |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/NotOptionalManyToOneTest.java | {
"start": 2275,
"end": 2550
} | class ____ {
@Id
private Integer id;
private String name;
public Child() {
}
public Child(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
}
}
| Child |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/connector/source/abilities/SupportsRowLevelModificationScan.java | {
"start": 3749,
"end": 3821
} | enum ____ {
UPDATE,
DELETE
}
}
| RowLevelModificationType |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/creators/DelegatingCreatorsTest.java | {
"start": 2648,
"end": 8148
} | class ____ {
public long time;
public String username;
@JsonCreator(mode=JsonCreator.Mode.DELEGATING) // invoked when a string is passed
public static SuperToken2353 from(String username) {
SuperToken2353 token = new SuperToken2353();
token.username = username;
token.time = System.currentTimeMillis();
return token;
}
@JsonCreator(mode=JsonCreator.Mode.PROPERTIES) // invoked when an object is passed, pre-validating property existence
public static SuperToken2353 create(
@JsonProperty("name") String username,
@JsonProperty("time") long time)
{
SuperToken2353 token = new SuperToken2353();
token.username = username;
token.time = time;
return token;
}
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final ObjectMapper MAPPER = newJsonMapper();
@Test
public void testBooleanDelegate() throws Exception
{
// should obviously work with booleans...
BooleanBean bb = MAPPER.readValue("true", BooleanBean.class);
assertEquals(Boolean.TRUE, bb.value);
// but also with value conversion from String
bb = MAPPER.readValue(q("true"), BooleanBean.class);
assertEquals(Boolean.TRUE, bb.value);
}
@Test
public void testIntegerDelegate() throws Exception
{
IntegerBean bb = MAPPER.readValue("-13", IntegerBean.class);
assertEquals(Integer.valueOf(-13), bb.value);
// but also with value conversion from String (unless blocked)
bb = MAPPER.readValue(q("127"), IntegerBean.class);
assertEquals(Integer.valueOf(127), bb.value);
}
@Test
public void testLongDelegate() throws Exception
{
LongBean bb = MAPPER.readValue("11", LongBean.class);
assertEquals(Long.valueOf(11L), bb.value);
// but also with value conversion from String (unless blocked)
bb = MAPPER.readValue(q("-99"), LongBean.class);
assertEquals(Long.valueOf(-99L), bb.value);
}
// should also work with delegate model (single non-annotated arg)
@Test
public void testWithCtorAndDelegate() throws Exception
{
ObjectMapper mapper = jsonMapperBuilder()
.injectableValues(new InjectableValues.Std()
.addValue(String.class, "Pooka"))
.build();
CtorBean711 bean = mapper.readValue("38", CtorBean711.class);
assertEquals(38, bean.age);
assertEquals("Pooka", bean.name);
}
@Test
public void testWithFactoryAndDelegate() throws Exception
{
ObjectMapper mapper = jsonMapperBuilder()
.injectableValues(new InjectableValues.Std()
.addValue(String.class, "Fygar"))
.build();
FactoryBean711 bean = mapper.readValue("38", FactoryBean711.class);
assertEquals(38, bean.age);
assertEquals("Fygar", bean.name1);
assertEquals("Fygar", bean.name2);
}
// [databind#592]
@Test
public void testDelegateWithTokenBuffer() throws Exception
{
Value592 value = MAPPER.readValue("{\"a\":1,\"b\":2}", Value592.class);
assertNotNull(value);
Object ob = value.stuff;
assertEquals(TokenBuffer.class, ob.getClass());
JsonParser p = ((TokenBuffer) ob).asParser(ObjectReadContext.empty());
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
assertEquals("a", p.currentName());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertEquals(1, p.getIntValue());
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
assertEquals("b", p.currentName());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertEquals(2, p.getIntValue());
assertToken(JsonToken.END_OBJECT, p.nextToken());
p.close();
}
@SuppressWarnings("unchecked")
@Test
public void testIssue465() throws Exception
{
final String JSON = "{\"A\":12}";
// first, test with regular Map, non empty
Map<String,Long> map = MAPPER.readValue(JSON, Map.class);
assertEquals(1, map.size());
assertEquals(Integer.valueOf(12), map.get("A"));
MapBean bean = MAPPER.readValue(JSON, MapBean.class);
assertEquals(1, bean.map.size());
assertEquals(Long.valueOf(12L), bean.map.get("A"));
// and then empty ones
final String EMPTY_JSON = "{}";
map = MAPPER.readValue(EMPTY_JSON, Map.class);
assertEquals(0, map.size());
bean = MAPPER.readValue(EMPTY_JSON, MapBean.class);
assertEquals(0, bean.map.size());
}
// [databind#2353]: allow delegating and properties-based
@Test
public void testMultipleCreators2353() throws Exception
{
// first, test delegating
SuperToken2353 result = MAPPER.readValue(q("Bob"), SuperToken2353.class);
assertEquals("Bob", result.username);
// and then properties-based
result = MAPPER.readValue(a2q("{'name':'Billy', 'time':123}"), SuperToken2353.class);
assertEquals("Billy", result.username);
assertEquals(123L, result.time);
}
}
| SuperToken2353 |
java | elastic__elasticsearch | modules/lang-painless/src/test/java/org/elasticsearch/painless/ScriptTestCase.java | {
"start": 4843,
"end": 5130
} | class ____ thrown (boxed inside ScriptException) and returns it. */
public static <T extends Throwable> T expectScriptThrows(Class<T> expectedType, ThrowingRunnable runnable) {
return expectScriptThrows(expectedType, true, runnable);
}
/** Checks a specific exception | is |
java | apache__camel | components/camel-mina/src/test/java/org/apache/camel/component/mina/MinaSpringMultipleUDPTest.java | {
"start": 1252,
"end": 2088
} | class ____ extends CamelSpringTestSupport {
private static final String LS = System.lineSeparator();
@Override
protected AbstractApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext(
"org/apache/camel/component/mina/SpringMultipleUDPTest-context.xml");
}
@Test
public void testMinaSpringProtobufEndpoint() {
MockEndpoint result = getMockEndpoint("mock:result");
result.expectedMessageCount(7);
for (int i = 0; i < 7; i++) {
template.requestBody("myMinaEndpoint", "Hello World" + i + LS);
}
// Sleep for awhile to let the messages go through.
await().atMost(3, TimeUnit.SECONDS)
.untilAsserted(() -> MockEndpoint.assertIsSatisfied(context));
}
}
| MinaSpringMultipleUDPTest |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/cdi/bcextensions/CustomStereotypeTest.java | {
"start": 813,
"end": 1293
} | class ____ {
@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder()
.buildCompatibleExtensions(new MyExtension())
.build();
@Test
public void test() {
InstanceHandle<MyService> bean = Arc.container().select(MyService.class).getHandle();
assertEquals(ApplicationScoped.class, bean.getBean().getScope());
assertEquals("Hello!", bean.get().hello());
}
public static | CustomStereotypeTest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CxfRsEndpointBuilderFactory.java | {
"start": 59525,
"end": 61687
} | class ____ and put the response object into the exchange
* for further processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param performInvocation the value to set
* @return the dsl builder
*/
default AdvancedCxfRsEndpointProducerBuilder performInvocation(String performInvocation) {
doSetProperty("performInvocation", performInvocation);
return this;
}
/**
* When the option is true, JAXRS UriInfo, HttpHeaders, Request and
* SecurityContext contexts will be available to custom CXFRS processors
* as typed Camel exchange properties. These contexts can be used to
* analyze the current requests using JAX-RS API.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param propagateContexts the value to set
* @return the dsl builder
*/
default AdvancedCxfRsEndpointProducerBuilder propagateContexts(boolean propagateContexts) {
doSetProperty("propagateContexts", propagateContexts);
return this;
}
/**
* When the option is true, JAXRS UriInfo, HttpHeaders, Request and
* SecurityContext contexts will be available to custom CXFRS processors
* as typed Camel exchange properties. These contexts can be used to
* analyze the current requests using JAX-RS API.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param propagateContexts the value to set
* @return the dsl builder
*/
default AdvancedCxfRsEndpointProducerBuilder propagateContexts(String propagateContexts) {
doSetProperty("propagateContexts", propagateContexts);
return this;
}
}
/**
* Builder for endpoint for the CXF-RS component.
*/
public | instance |
java | quarkusio__quarkus | extensions/smallrye-context-propagation/deployment/src/test/java/io/quarkus/smallrye/context/deployment/test/cdi/ContextProviderEnabledTest.java | {
"start": 697,
"end": 1846
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().overrideConfigKey("quarkus.arc.context-propagation.enabled",
"true");
@Inject
ManagedExecutor all;
@Inject
MyRequestBean bean;
@Test
public void testPropagationEnabled() throws InterruptedException, ExecutionException, TimeoutException {
ManagedContext requestContext = Arc.container().requestContext();
requestContext.activate();
assertEquals("FOO", bean.getId());
try {
assertEquals("OK",
all.completedFuture("OK").thenApplyAsync(text -> {
// Assertion error would result in an ExecutionException thrown from the CompletableFuture.get()
assertTrue(requestContext.isActive());
assertEquals("FOO", bean.getId());
return text;
}).toCompletableFuture().get(5, TimeUnit.SECONDS));
;
} finally {
requestContext.terminate();
}
}
@RequestScoped
public static | ContextProviderEnabledTest |
java | dropwizard__dropwizard | dropwizard-configuration/src/main/java/io/dropwizard/configuration/JsonConfigurationFactory.java | {
"start": 460,
"end": 1232
} | class ____<T> extends BaseConfigurationFactory<T> {
/**
* Creates a new configuration factory for the given class.
*
* @param klass the configuration class
* @param validator the validator to use
* @param objectMapper the Jackson {@link ObjectMapper} to use
* @param propertyPrefix the system property name prefix used by overrides
*/
public JsonConfigurationFactory(Class<T> klass,
Validator validator,
ObjectMapper objectMapper,
String propertyPrefix) {
super(objectMapper.getFactory(), JsonFactory.FORMAT_NAME_JSON, klass, validator, objectMapper, propertyPrefix);
}
}
| JsonConfigurationFactory |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/exceptions/PartitionUpdateException.java | {
"start": 1032,
"end": 1446
} | class ____ extends TaskManagerException {
private static final long serialVersionUID = 6248696963418276618L;
public PartitionUpdateException(String message) {
super(message);
}
public PartitionUpdateException(String message, Throwable cause) {
super(message, cause);
}
public PartitionUpdateException(Throwable cause) {
super(cause);
}
}
| PartitionUpdateException |
java | quarkusio__quarkus | extensions/vertx/deployment/src/test/java/io/quarkus/vertx/locals/LocalContextAccessTest.java | {
"start": 6282,
"end": 6939
} | class ____ {
public String getGlobal() {
return Vertx.currentContext().get("foo");
}
public void putGlobal() {
Vertx.currentContext().put("foo", "bar");
}
public void removeGlobal() {
Vertx.currentContext().remove("foo");
}
public String getLocal() {
return Vertx.currentContext().getLocal("foo");
}
public void putLocal() {
Vertx.currentContext().putLocal("foo", "bar");
}
public boolean removeLocal() {
return Vertx.currentContext().removeLocal("foo");
}
}
}
| BeanAccessingContext |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/bootstrap/BootstrapChecks.java | {
"start": 12890,
"end": 14291
} | class ____ implements BootstrapCheck {
private final int limit;
FileDescriptorCheck() {
this(65535);
}
protected FileDescriptorCheck(final int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("limit must be positive but was [" + limit + "]");
}
this.limit = limit;
}
public final BootstrapCheckResult check(BootstrapContext context) {
final long maxFileDescriptorCount = getMaxFileDescriptorCount();
if (maxFileDescriptorCount != -1 && maxFileDescriptorCount < limit) {
final String message = String.format(
Locale.ROOT,
"max file descriptors [%d] for elasticsearch process is too low, increase to at least [%d]",
getMaxFileDescriptorCount(),
limit
);
return BootstrapCheckResult.failure(message);
} else {
return BootstrapCheckResult.success();
}
}
@Override
public ReferenceDocs referenceDocs() {
return ReferenceDocs.BOOTSTRAP_CHECK_FILE_DESCRIPTOR;
}
// visible for testing
long getMaxFileDescriptorCount() {
return ProcessProbe.getMaxFileDescriptorCount();
}
}
static | FileDescriptorCheck |
java | grpc__grpc-java | grpclb/src/main/java/io/grpc/grpclb/BackendAddressGroup.java | {
"start": 772,
"end": 1472
} | class ____ {
private final EquivalentAddressGroup addresses;
@Nullable
private final String token;
BackendAddressGroup(EquivalentAddressGroup addresses, @Nullable String token) {
this.addresses = checkNotNull(addresses, "addresses");
this.token = token;
}
EquivalentAddressGroup getAddresses() {
return addresses;
}
@Nullable
String getToken() {
return token;
}
@Override
public String toString() {
// This is printed in logs. Be concise.
StringBuilder buffer = new StringBuilder();
buffer.append(addresses);
if (token != null) {
buffer.append("(").append(token).append(")");
}
return buffer.toString();
}
}
| BackendAddressGroup |
java | quarkusio__quarkus | extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/jdbc/QuarkusMSSQLDelegate.java | {
"start": 196,
"end": 756
} | class ____ extends org.quartz.impl.jdbcjobstore.MSSQLDelegate {
/**
* See the javadoc in {@link QuarkusObjectInputStream#resolveClass(ObjectStreamClass)} and
* {@link DBDelegateUtils#getObjectFromInput(InputStream)}
* on why this is needed
*/
@Override
protected Object getObjectFromBlob(ResultSet rs, String colName) throws ClassNotFoundException, IOException, SQLException {
InputStream binaryInput = rs.getBinaryStream(colName);
return DBDelegateUtils.getObjectFromInput(binaryInput);
}
}
| QuarkusMSSQLDelegate |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/cglib/transform/impl/FieldProviderTransformer.java | {
"start": 7147,
"end": 8784
} | class ____ SWITCH_STYLE_TRIE should be used
// to avoid JVM hashcode implementation incompatibilities
private void getField(String[] names) throws Exception {
final CodeEmitter e = begin_method(Constants.ACC_PUBLIC, PROVIDER_GET, null);
e.load_this();
e.load_arg(0);
EmitUtils.string_switch(e, names, Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() {
@Override
public void processCase(Object key, Label end) {
Type type = (Type)fields.get(key);
e.getfield((String)key);
e.box(type);
e.return_value();
}
@Override
public void processDefault() {
e.throw_exception(ILLEGAL_ARGUMENT_EXCEPTION, "Unknown field name");
}
});
e.end_method();
}
private void setField(String[] names) throws Exception {
final CodeEmitter e = begin_method(Constants.ACC_PUBLIC, PROVIDER_SET, null);
e.load_this();
e.load_arg(1);
e.load_arg(0);
EmitUtils.string_switch(e, names, Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() {
@Override
public void processCase(Object key, Label end) {
Type type = (Type)fields.get(key);
e.unbox(type);
e.putfield((String)key);
e.return_value();
}
@Override
public void processDefault() {
e.throw_exception(ILLEGAL_ARGUMENT_EXCEPTION, "Unknown field name");
}
});
e.end_method();
}
}
| files |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/annotation/AbstractAnnotationMetadataBuilder.java | {
"start": 8577,
"end": 8978
} | class ____.
*
* @param owningType The owningType
* @param element The element
* @return The {@link CachedAnnotationMetadata}
*/
public CachedAnnotationMetadata lookupOrBuildForMethod(T owningType, T element) {
return lookupOrBuild(new Key2<>(owningType, element), element);
}
/**
* Build the metadata for the given field element excluding any | metadata |
java | apache__flink | flink-clients/src/main/java/org/apache/flink/client/cli/CliFrontend.java | {
"start": 58050,
"end": 60326
} | interface ____ the YARN session, with a special initialization here
// to prefix all options with y/yarn.
final String flinkYarnSessionCLI = "org.apache.flink.yarn.cli.FlinkYarnSessionCli";
try {
customCommandLines.add(
loadCustomCommandLine(
flinkYarnSessionCLI,
configuration,
configurationDirectory,
"y",
"yarn"));
} catch (NoClassDefFoundError | Exception e) {
final String errorYarnSessionCLI = "org.apache.flink.yarn.cli.FallbackYarnSessionCli";
try {
LOG.info("Loading FallbackYarnSessionCli");
customCommandLines.add(loadCustomCommandLine(errorYarnSessionCLI, configuration));
} catch (Exception exception) {
LOG.warn("Could not load CLI class {}.", flinkYarnSessionCLI, e);
}
}
// Tips: DefaultCLI must be added at last, because getActiveCustomCommandLine(..) will get
// the
// active CustomCommandLine in order and DefaultCLI isActive always return true.
customCommandLines.add(new DefaultCLI());
return customCommandLines;
}
// --------------------------------------------------------------------------------------------
// Custom command-line
// --------------------------------------------------------------------------------------------
/**
* Gets the custom command-line for the arguments.
*
* @param commandLine The input to the command-line.
* @return custom command-line which is active (may only be one at a time)
*/
public CustomCommandLine validateAndGetActiveCommandLine(CommandLine commandLine) {
LOG.debug("Custom commandlines: {}", customCommandLines);
for (CustomCommandLine cli : customCommandLines) {
LOG.debug(
"Checking custom commandline {}, isActive: {}", cli, cli.isActive(commandLine));
if (cli.isActive(commandLine)) {
return cli;
}
}
throw new IllegalStateException("No valid command-line found.");
}
/**
* Loads a | of |
java | processing__processing4 | core/src/processing/opengl/PGraphicsOpenGL.java | {
"start": 211304,
"end": 215916
} | class ____ {
static final int POSITION = 0;
static final int NORMAL = 1;
static final int COLOR = 2;
static final int OTHER = 3;
PGraphicsOpenGL pg;
String name;
int kind; // POSITION, NORMAL, COLOR, OTHER
int type; // GL_INT, GL_FLOAT, GL_BOOL
int size; // number of elements (1, 2, 3, or 4)
int tessSize;
int elementSize;
VertexBuffer buf;
int glLoc;
int glUsage;
float[] fvalues;
int[] ivalues;
byte[] bvalues;
// For use in PShape
boolean modified;
int firstModified;
int lastModified;
boolean active;
VertexAttribute(PGraphicsOpenGL pg, String name, int kind, int type, int size, int usage) {
this.pg = pg;
this.name = name;
this.kind = kind;
this.type = type;
this.size = size;
if (kind == POSITION) {
tessSize = 4; // for w
} else {
tessSize = size;
}
if (type == PGL.FLOAT) {
elementSize = PGL.SIZEOF_FLOAT;
fvalues = new float[size];
} else if (type == PGL.INT) {
elementSize = PGL.SIZEOF_INT;
ivalues = new int[size];
} else if (type == PGL.BOOL) {
elementSize = PGL.SIZEOF_INT;
bvalues = new byte[size];
}
buf = null;
glLoc = -1;
glUsage = usage;
modified = false;
firstModified = PConstants.MAX_INT;
lastModified = PConstants.MIN_INT;
active = true;
}
public boolean diff(VertexAttribute attr) {
return !name.equals(attr.name) ||
kind != attr.kind ||
type != attr.type ||
size != attr.size ||
tessSize != attr.tessSize ||
elementSize != attr.elementSize;
}
boolean isPosition() {
return kind == POSITION;
}
boolean isNormal() {
return kind == NORMAL;
}
boolean isColor() {
return kind == COLOR;
}
boolean isOther() {
return kind == OTHER;
}
boolean isFloat() {
return type == PGL.FLOAT;
}
boolean isInt() {
return type == PGL.INT;
}
boolean isBool() {
return type == PGL.BOOL;
}
boolean bufferCreated() {
return buf != null && 0 < buf.glId;
}
void createBuffer(PGL pgl) {
buf = new VertexBuffer(pg, PGL.ARRAY_BUFFER, size, elementSize, glUsage, false);
}
void deleteBuffer(PGL pgl) {
if (buf.glId != 0) {
intBuffer.put(0, buf.glId);
if (pgl.threadIsCurrent()) pgl.deleteBuffers(1, intBuffer);
}
}
void bind(PGL pgl) {
pgl.enableVertexAttribArray(glLoc);
}
void unbind(PGL pgl) {
pgl.disableVertexAttribArray(glLoc);
}
boolean active(PShader shader) {
if (active) {
if (glLoc == -1) {
glLoc = shader.getAttributeLoc(name);
if (glLoc == -1) active = false;
}
}
return active;
}
int sizeInBytes(int length) {
return length * tessSize * elementSize;
}
void set(float x, float y, float z) {
fvalues[0] = x;
fvalues[1] = y;
fvalues[2] = z;
}
void set(int c) {
ivalues[0] = c;
}
void set(float[] values) {
PApplet.arrayCopy(values, 0, fvalues, 0, size);
}
void set(int[] values) {
PApplet.arrayCopy(values, 0, ivalues, 0, size);
}
void set(boolean[] values) {
for (int i = 0; i < values.length; i++) {
bvalues[i] = (byte)(values[i] ? 1 : 0);
}
}
void add(float[] dstValues, int dstIdx) {
PApplet.arrayCopy(fvalues, 0, dstValues, dstIdx, size);
}
void add(int[] dstValues, int dstIdx) {
PApplet.arrayCopy(ivalues, 0, dstValues, dstIdx, size);
}
void add(byte[] dstValues, int dstIdx) {
PApplet.arrayCopy(bvalues, 0, dstValues, dstIdx, size);
}
}
//////////////////////////////////////////////////////////////
// Input (raw) and Tessellated geometry, tessellator.
static protected InGeometry newInGeometry(PGraphicsOpenGL pg, AttributeMap attr,
int mode) {
return new InGeometry(pg, attr, mode);
}
static protected TessGeometry newTessGeometry(PGraphicsOpenGL pg,
AttributeMap attr, int mode, boolean stream) {
return new TessGeometry(pg, attr, mode, stream);
}
static protected TexCache newTexCache(PGraphicsOpenGL pg) {
return new TexCache(pg);
}
// Holds an array of textures and the range of vertex
// indices each texture applies to.
static protected | VertexAttribute |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/ast/annotation/AbstractElementAnnotationMetadata.java | {
"start": 870,
"end": 1029
} | class ____
extends AbstractMutableAnnotationMetadata<AnnotationMetadata>
implements ElementAnnotationMetadata {
}
| AbstractElementAnnotationMetadata |
java | alibaba__nacos | naming/src/main/java/com/alibaba/nacos/naming/core/v2/event/service/ServiceEvent.java | {
"start": 832,
"end": 1213
} | class ____ extends Event {
private static final long serialVersionUID = -9173247502346692418L;
private final Service service;
public ServiceEvent(Service service) {
this.service = service;
}
public Service getService() {
return service;
}
/**
* Service data changed event.
*/
public static | ServiceEvent |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/mapper/RoutingFieldTypeTests.java | {
"start": 819,
"end": 2815
} | class ____ extends FieldTypeTestCase {
public void testPrefixQuery() {
MappedFieldType ft = RoutingFieldMapper.FIELD_TYPE;
Query expected = new PrefixQuery(new Term("_routing", new BytesRef("foo*")));
assertEquals(expected, ft.prefixQuery("foo*", null, MOCK_CONTEXT));
ElasticsearchException ee = expectThrows(
ElasticsearchException.class,
() -> ft.prefixQuery("foo*", null, MOCK_CONTEXT_DISALLOW_EXPENSIVE)
);
assertEquals(
"[prefix] queries cannot be executed when 'search.allow_expensive_queries' is set to false. "
+ "For optimised prefix queries on text fields please enable [index_prefixes].",
ee.getMessage()
);
}
public void testRegexpQuery() {
MappedFieldType ft = RoutingFieldMapper.FIELD_TYPE;
Query expected = new RegexpQuery(new Term("_routing", new BytesRef("foo?")));
assertEquals(expected, ft.regexpQuery("foo?", 0, 0, 10, null, MOCK_CONTEXT));
ElasticsearchException ee = expectThrows(
ElasticsearchException.class,
() -> ft.regexpQuery("foo?", randomInt(10), 0, randomInt(10) + 1, null, MOCK_CONTEXT_DISALLOW_EXPENSIVE)
);
assertEquals("[regexp] queries cannot be executed when 'search.allow_expensive_queries' is set to false.", ee.getMessage());
}
public void testWildcardQuery() {
MappedFieldType ft = RoutingFieldMapper.FIELD_TYPE;
Query expected = new WildcardQuery(new Term("_routing", new BytesRef("foo*")));
assertEquals(expected, ft.wildcardQuery("foo*", null, MOCK_CONTEXT));
ElasticsearchException ee = expectThrows(
ElasticsearchException.class,
() -> ft.wildcardQuery("valu*", null, MOCK_CONTEXT_DISALLOW_EXPENSIVE)
);
assertEquals("[wildcard] queries cannot be executed when 'search.allow_expensive_queries' is set to false.", ee.getMessage());
}
}
| RoutingFieldTypeTests |
java | apache__avro | lang/java/compiler/src/main/java/org/apache/avro/compiler/schema/SchemaVisitorAction.java | {
"start": 857,
"end": 1261
} | enum ____ {
/**
* continue visit.
*/
CONTINUE,
/**
* terminate visit.
*/
TERMINATE,
/**
* when returned from pre non terminal visit method the children of the non
* terminal are skipped. afterVisitNonTerminal for the current schema will not
* be invoked.
*/
SKIP_SUBTREE,
/**
* Skip visiting the siblings of this schema.
*/
SKIP_SIBLINGS;
}
| SchemaVisitorAction |
java | apache__avro | lang/java/avro/src/main/java/org/apache/avro/FormattedSchemaParser.java | {
"start": 972,
"end": 1196
} | class ____ this interface, supporting text based
* schema sources.
* </p>
*
* <p>
* Implementations are located using a {@link java.util.ServiceLoader} and must
* therefore be threadsafe. See the {@code ServiceLoader} | uses |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/SubstringOfZero.java | {
"start": 1659,
"end": 2776
} | class ____ extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> SUBSTRING_CALLS =
Matchers.instanceMethod()
.onExactClass("java.lang.String")
.named("substring")
.withParameters("int");
private static final Matcher<MethodInvocationTree> ARGUMENT_IS_ZERO =
Matchers.argument(0, (tree, state) -> Objects.equals(ASTHelpers.constValue(tree), 0));
private static final Matcher<MethodInvocationTree> SUBSTRING_CALLS_WITH_ZERO_ARG =
Matchers.allOf(SUBSTRING_CALLS, ARGUMENT_IS_ZERO);
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!SUBSTRING_CALLS_WITH_ZERO_ARG.matches(tree, state)) {
return Description.NO_MATCH;
}
return describeMatch(tree, removeSubstringCall(tree, state));
}
private static Fix removeSubstringCall(MethodInvocationTree tree, VisitorState state) {
ExpressionTree originalString = ASTHelpers.getReceiver(tree);
return SuggestedFix.replace(tree, state.getSourceForNode(originalString));
}
}
| SubstringOfZero |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/attachment/HttpEmailAttachementParser.java | {
"start": 1427,
"end": 5477
} | interface ____ {
ParseField INLINE = new ParseField("inline");
ParseField REQUEST = new ParseField("request");
ParseField CONTENT_TYPE = new ParseField("content_type");
}
public static final String TYPE = "http";
private final WebhookService webhookService;
private final TextTemplateEngine templateEngine;
public HttpEmailAttachementParser(WebhookService webhookService, TextTemplateEngine templateEngine) {
this.webhookService = webhookService;
this.templateEngine = templateEngine;
}
@Override
public String type() {
return TYPE;
}
@Override
public HttpRequestAttachment parse(String id, XContentParser parser) throws IOException {
boolean inline = false;
String contentType = null;
HttpRequestTemplate requestTemplate = null;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (Fields.CONTENT_TYPE.match(currentFieldName, parser.getDeprecationHandler())) {
contentType = parser.text();
} else if (Fields.INLINE.match(currentFieldName, parser.getDeprecationHandler())) {
inline = parser.booleanValue();
} else if (Fields.REQUEST.match(currentFieldName, parser.getDeprecationHandler())) {
requestTemplate = HttpRequestTemplate.Parser.parse(parser);
} else {
String msg = "Unknown field name [" + currentFieldName + "] in http request attachment configuration";
throw new ElasticsearchParseException(msg);
}
}
if (requestTemplate != null) {
return new HttpRequestAttachment(id, requestTemplate, inline, contentType);
}
throw new ElasticsearchParseException("Could not parse http request attachment");
}
@Override
public Attachment toAttachment(WatchExecutionContext context, Payload payload, HttpRequestAttachment attachment) throws IOException {
Map<String, Object> model = Variables.createCtxParamsMap(context, payload);
HttpRequest httpRequest = attachment.getRequestTemplate().render(templateEngine, model);
HttpResponse response = webhookService.modifyAndExecuteHttpRequest(httpRequest).v2();
// check for status 200, only then append attachment
if (RestStatus.isSuccessful(response.status())) {
if (response.hasContent()) {
String contentType = attachment.getContentType();
String attachmentContentType = Strings.hasLength(contentType) ? contentType : response.contentType();
return new Attachment.Bytes(
attachment.id(),
BytesReference.toBytes(response.body()),
attachmentContentType,
attachment.inline()
);
} else {
throw new ElasticsearchException(
"Watch[{}] attachment[{}] HTTP empty response body host[{}], port[{}], " + "method[{}], path[{}], status[{}]",
context.watch().id(),
attachment.id(),
httpRequest.host(),
httpRequest.port(),
httpRequest.method(),
httpRequest.path(),
response.status()
);
}
} else {
throw new ElasticsearchException(
"Watch[{}] attachment[{}] HTTP error status host[{}], port[{}], " + "method[{}], path[{}], status[{}]",
context.watch().id(),
attachment.id(),
httpRequest.host(),
httpRequest.port(),
httpRequest.method(),
httpRequest.path(),
response.status()
);
}
}
}
| Fields |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/instant/InstantTest.java | {
"start": 1086,
"end": 3534
} | class ____ {
@Test
public void testStorage(SessionFactoryScope scope) {
final Instant now = Instant.now();
final ZoneOffset zone = ZoneOffset.ofHours(1);
scope.inTransaction( (session) -> {
final Instants instants = new Instants();
instants.instantInUtc = now;
instants.instantInLocalTimeZone = now;
instants.instantWithTimeZone = now;
instants.localDateTime = LocalDateTime.ofInstant( now, zone );
instants.offsetDateTime = OffsetDateTime.ofInstant( now, zone );
instants.localDateTimeUtc = LocalDateTime.ofInstant( now, ZoneOffset.UTC );
instants.offsetDateTimeUtc = OffsetDateTime.ofInstant( now, ZoneOffset.UTC );
session.persist( instants );
} );
scope.inTransaction( (session) -> {
final Instants instants = session.find( Instants.class, 0 );
assertEqualInstants( now, instants.instantInUtc );
assertEqualInstants( now, instants.instantInLocalTimeZone );
assertEqualInstants( now, instants.instantWithTimeZone );
assertEqualInstants( now, instants.offsetDateTime.toInstant() );
assertEqualInstants( now, instants.localDateTime.toInstant( zone ) );
assertEqualInstants( now, instants.offsetDateTimeUtc.toInstant() );
assertEqualInstants( now, instants.localDateTimeUtc.toInstant( ZoneOffset.UTC ) );
} );
}
@Test
void testQueryRestriction(SessionFactoryScope scope) {
final Instant instant = Instant.from( DateTimeFormatter.ISO_INSTANT.parse( "2025-02-27T01:01:01.123Z" ) );
scope.inTransaction( (session) -> {
session.persist( new Instants( 1, instant ) );
} );
// parameter
scope.inTransaction( (session) -> {
final String queryText = "select id from Instants where instantInUtc = :p";
final List<Long> matches = session.createSelectionQuery( queryText, Long.class )
.setParameter( "p", instant )
.list();
assertThat( matches ).hasSize( 1 );
} );
// literal
scope.inTransaction( (session) -> {
final String queryText = "select id from Instants where instantInUtc = zoned datetime 2025-02-27 01:01:01.123Z";
final List<Long> matches = session.createSelectionQuery( queryText, Long.class )
.list();
assertThat( matches ).hasSize( 1 );
} );
}
@AfterEach
void dropTestData(SessionFactoryScope scope) {
scope.dropData();
}
void assertEqualInstants(Instant x, Instant y) {
assertEquals( x.truncatedTo( ChronoUnit.SECONDS ), y.truncatedTo( ChronoUnit.SECONDS ) );
}
@Entity(name="Instants")
static | InstantTest |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/CountDistinctLongGroupingAggregatorFunctionTests.java | {
"start": 919,
"end": 2935
} | class ____ extends GroupingAggregatorFunctionTestCase {
@Override
protected AggregatorFunctionSupplier aggregatorFunction() {
return new CountDistinctLongAggregatorFunctionSupplier(40000);
}
@Override
protected String expectedDescriptionOfAggregator() {
return "count_distinct of longs";
}
@Override
protected SourceOperator simpleInput(BlockFactory blockFactory, int size) {
return new TupleLongLongBlockSourceOperator(
blockFactory,
LongStream.range(0, size).mapToObj(l -> Tuple.tuple(randomGroupId(size), randomLongBetween(0, 100_000)))
);
}
@Override
protected void assertSimpleGroup(List<Page> input, Block result, int position, Long group) {
long expected = input.stream().flatMapToLong(p -> allLongs(p, group)).distinct().count();
long count = ((LongBlock) result).getLong(position);
// HLL is an approximation algorithm and precision depends on the number of values computed and the precision_threshold param
// https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-cardinality-aggregation.html
// For a number of values close to 10k and precision_threshold=1000, precision should be less than 10%
assertThat((double) count, closeTo(expected, expected * 0.1));
}
@Override
protected void assertOutputFromNullOnly(Block b, int position) {
assertThat(b.isNull(position), equalTo(false));
assertThat(b.getValueCount(position), equalTo(1));
assertThat(((LongBlock) b).getLong(b.getFirstValueIndex(position)), equalTo(0L));
}
@Override
protected void assertOutputFromAllFiltered(Block b) {
assertThat(b.elementType(), equalTo(ElementType.LONG));
LongVector v = (LongVector) b.asVector();
for (int p = 0; p < v.getPositionCount(); p++) {
assertThat(v.getLong(p), equalTo(0L));
}
}
}
| CountDistinctLongGroupingAggregatorFunctionTests |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/AnnotationsScannerTests.java | {
"start": 23466,
"end": 23589
} | interface ____ {
@TestAnnotation2
@TestInheritedAnnotation2
void method();
}
@TestAnnotation1
static | SingleInterface |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/publisher/ParallelGroupTest.java | {
"start": 951,
"end": 3146
} | class ____ {
@Test
public void scanOperator() {
ParallelFlux<Integer> source = Flux.range(1, 4).parallel(3);
ParallelGroup<Integer> test = new ParallelGroup<>(source);
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(source);
assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(-1);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
}
@Test
public void scanInnerGroup() {
ParallelInnerGroup<Integer> test = new ParallelInnerGroup<>(1023);
CoreSubscriber<Integer> subscriber = new LambdaSubscriber<>(null, e -> {}, null,
sub -> sub.request(3));
Subscription s = Operators.emptySubscription();
test.onSubscribe(s);
test.subscribe(subscriber);
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(s);
assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(subscriber);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
//see other test for request
assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isZero();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
test.cancel();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
@Test
public void scanInnerGroupRequestNotTrackedWhenParent() {
ParallelInnerGroup<Integer> test = new ParallelInnerGroup<>(1023);
CoreSubscriber<Integer> subscriber = new LambdaSubscriber<>(null, e -> {}, null,
sub -> sub.request(3));
Subscription s = Operators.emptySubscription();
test.onSubscribe(s);
test.subscribe(subscriber);
assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isZero();
test.request(2);
assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isZero();
}
@Test
public void scanInnerGroupRequestTrackedWhenNoParent() {
ParallelInnerGroup<Integer> test = new ParallelInnerGroup<>(1023);
CoreSubscriber<Integer> subscriber = new LambdaSubscriber<>(null, e -> {}, null,
sub -> sub.request(3));
test.subscribe(subscriber);
assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(3);
test.request(2);
assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(5);
}
}
| ParallelGroupTest |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/services/AbfsClientUtils.java | {
"start": 970,
"end": 1470
} | class ____ {
private AbfsClientUtils() {
}
public static void setEncryptionContextProvider(final AbfsClient abfsClient, final EncryptionContextProvider provider) {
abfsClient.setEncryptionContextProvider(provider);
}
public static String getHeaderValue(List<AbfsHttpHeader> reqHeaders, String headerName) {
for (AbfsHttpHeader header : reqHeaders) {
if (header.getName().equals(headerName)) {
return header.getValue();
}
}
return "";
}
}
| AbfsClientUtils |
java | apache__camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpConnectTimeoutIT.java | {
"start": 1006,
"end": 1705
} | class ____ extends FtpServerTestSupport {
private String getFtpUrl() {
return "ftp://admin@localhost:{{ftp.server.port}}/timeout/?password=admin&connectTimeout=2000";
}
@Test
public void testTimeout() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
sendFile(getFtpUrl(), "Hello World", "hello.txt");
mock.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from(getFtpUrl()).to("mock:result");
}
};
}
}
| FtpConnectTimeoutIT |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/SpringServletContainerInitializer.java | {
"start": 6548,
"end": 8621
} | interface ____ been
* implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)}
* method will be invoked on each instance, delegating the {@code ServletContext} such
* that each instance may register and configure servlets such as Spring's
* {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener},
* or any other Servlet API features such as filters.
* @param webAppInitializerClasses all implementations of
* {@link WebApplicationInitializer} found on the application classpath
* @param servletContext the servlet context to be initialized
* @see WebApplicationInitializer#onStartup(ServletContext)
* @see AnnotationAwareOrderComparator
*/
@Override
public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
throws ServletException {
List<WebApplicationInitializer> initializers = Collections.emptyList();
if (webAppInitializerClasses != null) {
initializers = new ArrayList<>(webAppInitializerClasses.size());
for (Class<?> waiClass : webAppInitializerClasses) {
// Be defensive: Some servlet containers provide us with invalid classes,
// no matter what @HandlesTypes says...
if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
try {
initializers.add((WebApplicationInitializer)
ReflectionUtils.accessibleConstructor(waiClass).newInstance());
}
catch (Throwable ex) {
throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
}
}
}
}
if (initializers.isEmpty()) {
servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
return;
}
servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
AnnotationAwareOrderComparator.sort(initializers);
for (WebApplicationInitializer initializer : initializers) {
initializer.onStartup(servletContext);
}
}
}
| has |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configuration/EnableWebSecurityTests.java | {
"start": 6246,
"end": 6436
} | class ____ {
@GetMapping("/")
String principal(@AuthenticationPrincipal String principal) {
return principal;
}
}
}
@Configuration
@EnableWebSecurity
static | AuthController |
java | google__dagger | javatests/dagger/functional/producers/ComponentDependenciesTest.java | {
"start": 1849,
"end": 1924
} | interface ____ {
ListenableFuture<?> getString();
}
public | OneOverride |
java | apache__camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FileToFtpsExplicitSSLWithClientAuthIT.java | {
"start": 1127,
"end": 2323
} | class ____ extends FtpsServerExplicitSSLWithClientAuthTestSupport {
protected String getFtpUrl() {
return "ftps://admin@localhost:{{ftp.server.port}}"
+ "/tmp2/camel?password=admin&initialDelay=2000&disableSecureDataChannelDefaults=true"
+ "&securityProtocol=SSLv3&implicit=false&ftpClient.keyStore.file=./src/test/resources/server.jks&ftpClient.keyStore.type=JKS"
+ "&ftpClient.keyStore.algorithm=SunX509&ftpClient.keyStore.password=password&ftpClient.keyStore.keyPassword=password&delete=true";
}
@Disabled("CAMEL-16784:Disable testFromFileToFtp tests")
@Test
public void testFromFileToFtp() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(2);
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("file:src/test/data?noop=true").log("Got ${file:name}").to(getFtpUrl());
from(getFtpUrl()).to("mock:result");
}
};
}
}
| FileToFtpsExplicitSSLWithClientAuthIT |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBooleanPropertyTests.java | {
"start": 8109,
"end": 8295
} | class ____ extends BeanConfiguration {
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBooleanProperty(prefix = "foo", name = "test")
static | HavingValueFalseMatchIfMissingTrue |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/beanbuilder/TestInterceptorBindingRemapper.java | {
"start": 236,
"end": 617
} | class ____ implements AnnotationRemapper {
@Override
public String getPackageName() {
return "io.micronaut.inject.beanbuilder.another";
}
@Override
public List<AnnotationValue<?>> remap(AnnotationValue<?> annotation, VisitorContext visitorContext) {
return TestInterceptorBindingTransformer.ANNOTATION_VALUES;
}
}
| TestInterceptorBindingRemapper |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/license/XPackLicenseState.java | {
"start": 1200,
"end": 25208
} | class ____ {
/** Messages for each feature which are printed when the license expires. */
static final Map<String, String[]> EXPIRATION_MESSAGES;
static {
Map<String, String[]> messages = new LinkedHashMap<>();
messages.put(
XPackField.SECURITY,
new String[] {
"Cluster health, cluster stats and indices stats operations are blocked",
"All data operations (read and write) continue to work" }
);
messages.put(
XPackField.WATCHER,
new String[] {
"PUT / GET watch APIs are disabled, DELETE watch API continues to work",
"Watches execute and write to the history",
"The actions of the watches don't execute" }
);
messages.put(XPackField.MONITORING, new String[] { "The agent will stop collecting cluster and indices metrics" });
messages.put(XPackField.GRAPH, new String[] { "Graph explore APIs are disabled" });
messages.put(XPackField.MACHINE_LEARNING, new String[] { "Machine learning APIs are disabled" });
messages.put(XPackField.LOGSTASH, new String[] { "Logstash will continue to poll centrally-managed pipelines" });
messages.put(XPackField.BEATS, new String[] { "Beats will continue to poll centrally-managed configuration" });
messages.put(XPackField.DEPRECATION, new String[] { "Deprecation APIs are disabled" });
messages.put(XPackField.UPGRADE, new String[] { "Upgrade API is disabled" });
messages.put(XPackField.SQL, new String[] { "SQL support is disabled" });
messages.put(
XPackField.ENTERPRISE_SEARCH,
new String[] { "Search Applications, query rules and behavioral analytics will be disabled" }
);
messages.put(
XPackField.ROLLUP,
new String[] {
"Creating and Starting rollup jobs will no longer be allowed.",
"Stopping/Deleting existing jobs, RollupCaps API and RollupSearch continue to function." }
);
messages.put(
XPackField.TRANSFORM,
new String[] {
"Creating, starting, updating transforms will no longer be allowed.",
"Stopping/Deleting existing transforms continue to function." }
);
messages.put(XPackField.ANALYTICS, new String[] { "Aggregations provided by Analytics plugin are no longer usable." });
messages.put(
XPackField.CCR,
new String[] {
"Creating new follower indices will be blocked",
"Configuring auto-follow patterns will be blocked",
"Auto-follow patterns will no longer discover new leader indices",
"The CCR monitoring endpoint will be blocked",
"Existing follower indices will continue to replicate data" }
);
messages.put(XPackField.REDACT_PROCESSOR, new String[] { "Executing a redact processor in an ingest pipeline will fail." });
messages.put(XPackField.INFERENCE, new String[] { "The Inference API is disabled" });
EXPIRATION_MESSAGES = Collections.unmodifiableMap(messages);
}
/**
* Messages for each feature which are printed when the license type changes.
* The value is a function taking the old and new license type, and returns the messages for that feature.
*/
static final Map<String, BiFunction<OperationMode, OperationMode, String[]>> ACKNOWLEDGMENT_MESSAGES;
static {
Map<String, BiFunction<OperationMode, OperationMode, String[]>> messages = new LinkedHashMap<>();
messages.put(XPackField.SECURITY, XPackLicenseState::securityAcknowledgementMessages);
messages.put(XPackField.WATCHER, XPackLicenseState::watcherAcknowledgementMessages);
messages.put(XPackField.MONITORING, XPackLicenseState::monitoringAcknowledgementMessages);
messages.put(XPackField.GRAPH, XPackLicenseState::graphAcknowledgementMessages);
messages.put(XPackField.MACHINE_LEARNING, XPackLicenseState::machineLearningAcknowledgementMessages);
messages.put(XPackField.LOGSTASH, XPackLicenseState::logstashAcknowledgementMessages);
messages.put(XPackField.BEATS, XPackLicenseState::beatsAcknowledgementMessages);
messages.put(XPackField.SQL, XPackLicenseState::sqlAcknowledgementMessages);
messages.put(XPackField.CCR, XPackLicenseState::ccrAcknowledgementMessages);
messages.put(XPackField.ENTERPRISE_SEARCH, XPackLicenseState::enterpriseSearchAcknowledgementMessages);
messages.put(XPackField.REDACT_PROCESSOR, XPackLicenseState::redactProcessorAcknowledgementMessages);
messages.put(XPackField.ESQL, XPackLicenseState::esqlAcknowledgementMessages);
messages.put(XPackField.INFERENCE, XPackLicenseState::inferenceApiAcknowledgementMessages);
ACKNOWLEDGMENT_MESSAGES = Collections.unmodifiableMap(messages);
}
private static String[] securityAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
switch (newMode) {
case BASIC:
switch (currentMode) {
case STANDARD:
return new String[] { "Security tokens will not be supported." };
case TRIAL:
case GOLD:
case PLATINUM:
case ENTERPRISE:
return new String[] {
"Authentication will be limited to the native and file realms.",
"Security tokens will not be supported.",
"IP filtering and auditing will be disabled.",
"Field and document level access control will be disabled.",
"Custom realms will be ignored.",
"A custom authorization engine will be ignored." };
}
break;
case GOLD:
switch (currentMode) {
case BASIC:
case STANDARD:
// ^^ though technically it was already disabled, it's not bad to remind them
case TRIAL:
case PLATINUM:
case ENTERPRISE:
return new String[] {
"Field and document level access control will be disabled.",
"Custom realms will be ignored.",
"A custom authorization engine will be ignored." };
}
break;
case STANDARD:
switch (currentMode) {
case BASIC:
// ^^ though technically it doesn't change the feature set, it's not bad to remind them
case GOLD:
case PLATINUM:
case ENTERPRISE:
case TRIAL:
return new String[] {
"Authentication will be limited to the native realms.",
"IP filtering and auditing will be disabled.",
"Field and document level access control will be disabled.",
"Custom realms will be ignored.",
"A custom authorization engine will be ignored." };
}
}
return Strings.EMPTY_ARRAY;
}
private static String[] watcherAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
switch (newMode) {
case BASIC:
switch (currentMode) {
case TRIAL:
case STANDARD:
case GOLD:
case PLATINUM:
case ENTERPRISE:
return new String[] { "Watcher will be disabled" };
}
break;
}
return Strings.EMPTY_ARRAY;
}
private static String[] monitoringAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
switch (newMode) {
case BASIC:
switch (currentMode) {
case TRIAL:
case STANDARD:
case GOLD:
case PLATINUM:
case ENTERPRISE:
return new String[] {
LoggerMessageFormat.format(
"""
Multi-cluster support is disabled for clusters with [{}] license. If you are
running multiple clusters, users won't be able to access the clusters with
[{}] licenses from within a single X-Pack Kibana instance. You will have to deploy a
separate and dedicated X-pack Kibana instance for each [{}] cluster you wish to monitor.""",
newMode,
newMode,
newMode
) };
}
break;
}
return Strings.EMPTY_ARRAY;
}
private static String[] graphAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
switch (newMode) {
case BASIC:
case STANDARD:
case GOLD:
switch (currentMode) {
case TRIAL:
case PLATINUM:
case ENTERPRISE:
return new String[] { "Graph will be disabled" };
}
break;
}
return Strings.EMPTY_ARRAY;
}
private static String[] enterpriseSearchAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
switch (newMode) {
case BASIC:
case STANDARD:
case GOLD:
switch (currentMode) {
case PLATINUM:
return new String[] {
"Search Applications and behavioral analytics will be disabled.",
"Elastic Web crawler will be disabled.",
"Connector clients require at least a platinum license." };
case TRIAL:
case ENTERPRISE:
return new String[] {
"Search Applications and behavioral analytics will be disabled.",
"Query rules will be disabled.",
"Elastic Web crawler will be disabled.",
"Connector clients require at least a platinum license." };
}
break;
}
return Strings.EMPTY_ARRAY;
}
private static String[] esqlAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
/*
* Provide an acknowledgement warning to customers that downgrade from Trial or Enterprise to a lower
* license level (Basic, Standard, Gold or Premium) that they will no longer be able to do CCS in ES|QL.
*/
switch (newMode) {
case BASIC:
case STANDARD:
case GOLD:
case PLATINUM:
switch (currentMode) {
case TRIAL:
case ENTERPRISE:
return new String[] { "ES|QL cross-cluster search will be disabled." };
}
break;
}
return Strings.EMPTY_ARRAY;
}
private static String[] inferenceApiAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
/*
* Provide an acknowledgement warning to customers that downgrade from Trial or Enterprise to a lower
* license level (Basic, Standard, Gold or Premium) that they will no longer be able to use the Inference API
*/
switch (newMode) {
case TRIAL:
case ENTERPRISE:
break;
default:
switch (currentMode) {
case TRIAL:
case ENTERPRISE:
return new String[] { "The Inference API will be disabled" };
}
break;
}
return Strings.EMPTY_ARRAY;
}
private static String[] machineLearningAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
switch (newMode) {
case BASIC:
case STANDARD:
case GOLD:
switch (currentMode) {
case TRIAL:
case PLATINUM:
case ENTERPRISE:
return new String[] { "Machine learning will be disabled" };
}
break;
}
return Strings.EMPTY_ARRAY;
}
private static String[] logstashAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
switch (newMode) {
case BASIC:
if (isBasic(currentMode) == false) {
return new String[] { "Logstash will no longer poll for centrally-managed pipelines" };
}
break;
}
return Strings.EMPTY_ARRAY;
}
private static String[] beatsAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
switch (newMode) {
case BASIC:
if (isBasic(currentMode) == false) {
return new String[] { "Beats will no longer be able to use centrally-managed configuration" };
}
break;
}
return Strings.EMPTY_ARRAY;
}
private static String[] sqlAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
switch (newMode) {
case BASIC:
case STANDARD:
case GOLD:
switch (currentMode) {
case TRIAL:
case PLATINUM:
case ENTERPRISE:
return new String[] {
"JDBC and ODBC support will be disabled, but you can continue to use SQL CLI and REST endpoint" };
}
break;
}
return Strings.EMPTY_ARRAY;
}
private static String[] ccrAcknowledgementMessages(final OperationMode current, final OperationMode next) {
switch (current) {
// the current license level permits CCR
case TRIAL:
case PLATINUM:
case ENTERPRISE:
switch (next) {
// the next license level does not permit CCR
case MISSING:
case BASIC:
case STANDARD:
case GOLD:
// so CCR will be disabled
return new String[] { "Cross-Cluster Replication will be disabled" };
}
}
return Strings.EMPTY_ARRAY;
}
private static String[] redactProcessorAcknowledgementMessages(OperationMode currentMode, OperationMode newMode) {
switch (newMode) {
case BASIC:
case STANDARD:
case GOLD:
switch (currentMode) {
case TRIAL:
case PLATINUM:
case ENTERPRISE:
return new String[] { "Redact ingest pipeline processors will be disabled" };
}
break;
}
return Strings.EMPTY_ARRAY;
}
private static boolean isBasic(OperationMode mode) {
return mode == OperationMode.BASIC;
}
private final List<LicenseStateListener> listeners;
/**
* A Map of features for which usage is tracked by a feature identifier and a last-used-time.
* A last used time of {@code -1} means that the feature is "on" and should report the current time as the last-used-time
* (See: {@link #epochMillisProvider}, {@link #getLastUsed}).
*/
private final Map<FeatureUsage, Long> usage;
private final LongSupplier epochMillisProvider;
// Since xPackLicenseStatus is the only field that can be updated, we do not need to synchronize access to
// XPackLicenseState. However, if status is read multiple times in a method, it can change in between
// reads. Methods should use `executeAgainstStatus` and `checkAgainstStatus` to ensure that the status
// is only read once.
private volatile XPackLicenseStatus xPackLicenseStatus;
public XPackLicenseState(LongSupplier epochMillisProvider, XPackLicenseStatus xPackLicenseStatus) {
this(new CopyOnWriteArrayList<>(), xPackLicenseStatus, new ConcurrentHashMap<>(), epochMillisProvider);
}
public XPackLicenseState(LongSupplier epochMillisProvider) {
this.listeners = new CopyOnWriteArrayList<>();
this.usage = new ConcurrentHashMap<>();
this.epochMillisProvider = epochMillisProvider;
this.xPackLicenseStatus = new XPackLicenseStatus(OperationMode.TRIAL, true, null);
}
private XPackLicenseState(
List<LicenseStateListener> listeners,
XPackLicenseStatus xPackLicenseStatus,
Map<FeatureUsage, Long> usage,
LongSupplier epochMillisProvider
) {
this.listeners = listeners;
this.xPackLicenseStatus = xPackLicenseStatus;
this.usage = usage;
this.epochMillisProvider = epochMillisProvider;
}
/** Performs function against status, only reading the status once to avoid races */
private <T> T executeAgainstStatus(Function<XPackLicenseStatus, T> statusFn) {
return statusFn.apply(this.xPackLicenseStatus);
}
/** Performs predicate against status, only reading the status once to avoid races */
private boolean checkAgainstStatus(Predicate<XPackLicenseStatus> statusPredicate) {
return statusPredicate.test(this.xPackLicenseStatus);
}
/**
* Updates the current state of the license, which will change what features are available.
*
* @param xPackLicenseStatus The {@link XPackLicenseStatus} which controls overall state
*/
void update(XPackLicenseStatus xPackLicenseStatus) {
this.xPackLicenseStatus = xPackLicenseStatus;
listeners.forEach(LicenseStateListener::licenseStateChanged);
}
/** Add a listener to be notified on license change */
public void addListener(final LicenseStateListener listener) {
listeners.add(Objects.requireNonNull(listener));
}
/** Remove a listener */
public void removeListener(final LicenseStateListener listener) {
listeners.remove(Objects.requireNonNull(listener));
}
/** Return the current license type. */
public OperationMode getOperationMode() {
return executeAgainstStatus(statusToCheck -> statusToCheck.mode());
}
// Package private for tests
/** Return true if the license is currently within its time boundaries, false otherwise. */
public boolean isActive() {
return checkAgainstStatus(statusToCheck -> statusToCheck.active());
}
public String statusDescription() {
return executeAgainstStatus(
statusToCheck -> (statusToCheck.active() ? "active" : "expired") + ' ' + statusToCheck.mode().description() + " license"
);
}
void featureUsed(LicensedFeature feature) {
checkExpiry();
final long now = epochMillisProvider.getAsLong();
final FeatureUsage feat = new FeatureUsage(feature, null);
final Long mostRecent = usage.get(feat);
// only update if needed, to prevent ConcurrentHashMap lock-contention on writes
if (mostRecent == null || now > mostRecent) {
usage.put(feat, now);
}
}
void enableUsageTracking(LicensedFeature feature, String contextName) {
checkExpiry();
Objects.requireNonNull(contextName, "Context name cannot be null");
usage.put(new FeatureUsage(feature, contextName), -1L);
}
void disableUsageTracking(LicensedFeature feature, String contextName) {
Objects.requireNonNull(contextName, "Context name cannot be null");
usage.replace(new FeatureUsage(feature, contextName), -1L, epochMillisProvider.getAsLong());
}
void cleanupUsageTracking() {
long cutoffTime = epochMillisProvider.getAsLong() - TimeValue.timeValueHours(24).getMillis();
usage.entrySet().removeIf(e -> {
long timeMillis = e.getValue();
if (timeMillis == -1) {
return false; // feature is still on, don't remove
}
return timeMillis < cutoffTime; // true if it has not been used in more than 24 hours
});
}
// Package protected: Only allowed to be called by LicensedFeature
boolean isAllowed(LicensedFeature feature) {
return isAllowedByLicense(feature.getMinimumOperationMode(), feature.isNeedsActive());
}
void checkExpiry() {
String warning = xPackLicenseStatus.expiryWarning();
if (warning != null) {
HeaderWarning.addWarning(warning);
}
}
/**
* Returns a mapping of gold+ features to the last time that feature was used.
*
* Note that if a feature has not been used, it will not appear in the map.
*/
public Map<FeatureUsage, Long> getLastUsed() {
long currentTimeMillis = epochMillisProvider.getAsLong();
Function<Long, Long> timeConverter = v -> v == -1 ? currentTimeMillis : v;
return usage.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> timeConverter.apply(e.getValue())));
}
public static boolean isFipsAllowedForOperationMode(final OperationMode operationMode) {
return isAllowedByOperationMode(operationMode, OperationMode.PLATINUM);
}
static boolean isAllowedByOperationMode(final OperationMode operationMode, final OperationMode minimumMode) {
if (OperationMode.TRIAL == operationMode) {
return true;
}
return operationMode.compareTo(minimumMode) >= 0;
}
/**
* Creates a copy of this object based on the state at the time the method was called. The
* returned object will not be modified by a license update/expiration so it can be used to
* make multiple method calls on the license state safely. This object should not be long
* lived but instead used within a method when a consistent view of the license state
* is needed for multiple interactions with the license state.
*/
public XPackLicenseState copyCurrentLicenseState() {
return executeAgainstStatus(statusToCheck -> new XPackLicenseState(listeners, statusToCheck, usage, epochMillisProvider));
}
/**
* Test whether a feature is allowed by the status of license.
*
* @param minimumMode The minimum license to meet or exceed
* @param needActive Whether current license needs to be active
*
* @return true if feature is allowed, otherwise false
*/
@Deprecated
public boolean isAllowedByLicense(OperationMode minimumMode, boolean needActive) {
return checkAgainstStatus(statusToCheck -> {
if (needActive && false == statusToCheck.active()) {
return false;
}
return isAllowedByOperationMode(statusToCheck.mode(), minimumMode);
});
}
/**
* A convenient method to test whether a feature is by license status.
* @see #isAllowedByLicense(OperationMode, boolean)
*
* @param minimumMode The minimum license to meet or exceed
*/
public boolean isAllowedByLicense(OperationMode minimumMode) {
return isAllowedByLicense(minimumMode, true);
}
public static | XPackLicenseState |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/long_/LongAssert_isNotNegative_Test.java | {
"start": 888,
"end": 1201
} | class ____ extends LongAssertBaseTest {
@Override
protected LongAssert invoke_api_method() {
return assertions.isNotNegative();
}
@Override
protected void verify_internal_effects() {
verify(longs).assertIsNotNegative(getInfo(assertions), getActual(assertions));
}
}
| LongAssert_isNotNegative_Test |
java | spring-projects__spring-boot | module/spring-boot-quartz/src/main/java/org/springframework/boot/quartz/actuate/endpoint/QuartzEndpoint.java | {
"start": 15489,
"end": 16953
} | class ____ implements OperationResponseBody {
private final String group;
private final String name;
private final String description;
private final String className;
private final boolean durable;
private final boolean requestRecovery;
private final Map<String, Object> data;
private final List<Map<String, Object>> triggers;
QuartzJobDetailsDescriptor(JobDetail jobDetail, Map<String, Object> data, List<Map<String, Object>> triggers) {
this.group = jobDetail.getKey().getGroup();
this.name = jobDetail.getKey().getName();
this.description = jobDetail.getDescription();
this.className = jobDetail.getJobClass().getName();
this.durable = jobDetail.isDurable();
this.requestRecovery = jobDetail.requestsRecovery();
this.data = data;
this.triggers = triggers;
}
public String getGroup() {
return this.group;
}
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
public String getClassName() {
return this.className;
}
public boolean isDurable() {
return this.durable;
}
public boolean isRequestRecovery() {
return this.requestRecovery;
}
public Map<String, Object> getData() {
return this.data;
}
public List<Map<String, Object>> getTriggers() {
return this.triggers;
}
}
/**
* Description of the {@link Trigger triggers} in a given group.
*/
public static final | QuartzJobDetailsDescriptor |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/logging/structured/CommonStructuredLogFormat.java | {
"start": 869,
"end": 2038
} | enum ____ {
/**
* <a href="https://www.elastic.co/guide/en/ecs/current/ecs-log.html">Elastic Common
* Schema</a> (ECS) log format.
*/
ELASTIC_COMMON_SCHEMA("ecs"),
/**
* <a href="https://go2docs.graylog.org/current/getting_in_log_data/gelf.html">Graylog
* Extended Log Format</a> (GELF) log format.
*/
GRAYLOG_EXTENDED_LOG_FORMAT("gelf"),
/**
* The <a href=
* "https://github.com/logfellow/logstash-logback-encoder?tab=readme-ov-file#standard-fields">Logstash</a>
* log format.
*/
LOGSTASH("logstash");
private final String id;
CommonStructuredLogFormat(String id) {
this.id = id;
}
/**
* Return the ID for this format.
* @return the format identifier
*/
String getId() {
return this.id;
}
/**
* Find the {@link CommonStructuredLogFormat} for the given ID.
* @param id the format identifier
* @return the associated {@link CommonStructuredLogFormat} or {@code null}
*/
static @Nullable CommonStructuredLogFormat forId(String id) {
for (CommonStructuredLogFormat candidate : values()) {
if (candidate.getId().equalsIgnoreCase(id)) {
return candidate;
}
}
return null;
}
}
| CommonStructuredLogFormat |
java | quarkusio__quarkus | integration-tests/maven/src/test/resources-filtered/projects/multijar-module/runner/src/test/java/org/acme/ResourceTest.java | {
"start": 711,
"end": 797
} | class ____ be loaded
printer.println(new TestMessage("test message"));
}
}
| can |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/model/internal/SecondaryTableSecondPass.java | {
"start": 332,
"end": 826
} | class ____ implements SecondPass {
private final EntityBinder entityBinder;
private final PropertyHolder propertyHolder;
public SecondaryTableSecondPass(EntityBinder entityBinder, PropertyHolder propertyHolder) {
this.entityBinder = entityBinder;
this.propertyHolder = propertyHolder;
}
@Override
public void doSecondPass(Map<String, PersistentClass> persistentClasses) throws MappingException {
entityBinder.finalSecondaryTableBinding( propertyHolder );
}
}
| SecondaryTableSecondPass |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationCode.java | {
"start": 1109,
"end": 1553
} | class ____ extends AbstractOAuth2Token {
/**
* Constructs an {@code OAuth2AuthorizationCode} using the provided parameters.
* @param tokenValue the token value
* @param issuedAt the time at which the token was issued
* @param expiresAt the time at which the token expires
*/
public OAuth2AuthorizationCode(String tokenValue, Instant issuedAt, Instant expiresAt) {
super(tokenValue, issuedAt, expiresAt);
}
}
| OAuth2AuthorizationCode |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/controlbus/ControlBusStartRouteTest.java | {
"start": 1208,
"end": 4913
} | class ____ extends ContextTestSupport {
@Test
public void testControlBusStartStop() throws Exception {
assertEquals("Stopped", context.getRouteController().getRouteStatus("foo").name());
// store a pending message
getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World");
template.sendBody("seda:foo", "Hello World");
// start the route using control bus
template.sendBody("controlbus:route?routeId=foo&action=start", null);
assertMockEndpointsSatisfied();
// now stop the route, using a header
template.sendBody("controlbus:route?routeId=foo&action=stop", null);
assertEquals("Stopped", context.getRouteController().getRouteStatus("foo").name());
}
@Test
public void testControlBusSuspendResume() throws Exception {
assertEquals("Stopped", context.getRouteController().getRouteStatus("foo").name());
// store a pending message
getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World");
template.sendBody("seda:foo", "Hello World");
// start the route using control bus
template.sendBody("controlbus:route?routeId=foo&action=start", null);
assertMockEndpointsSatisfied();
// now suspend the route, using a header
template.sendBody("controlbus:route?routeId=foo&action=suspend", null);
assertEquals("Suspended", context.getRouteController().getRouteStatus("foo").name());
// now resume the route, using a header
template.sendBody("controlbus:route?routeId=foo&action=resume", null);
assertEquals("Started", context.getRouteController().getRouteStatus("foo").name());
}
@Test
public void testControlBusStatus() throws Exception {
assertEquals("Stopped", context.getRouteController().getRouteStatus("foo").name());
String status = template.requestBody("controlbus:route?routeId=foo&action=status", null, String.class);
assertEquals("Stopped", status);
context.getRouteController().startRoute("foo");
status = template.requestBody("controlbus:route?routeId=foo&action=status", null, String.class);
assertEquals("Started", status);
}
@Test
public void testControlBusCurrentRouteStatus() throws Exception {
assertTrue(context.getRouteController().getRouteStatus("current").isStarted());
MockEndpoint mock = getMockEndpoint("mock:current");
mock.expectedMessageCount(1);
mock.expectedBodiesReceived(ServiceStatus.Started.name());
sendBody("seda:current", null);
mock.assertIsSatisfied();
}
@Test
public void testControlBusStatusLevelWarn() throws Exception {
assertEquals("Stopped", context.getRouteController().getRouteStatus("foo").name());
String status
= template.requestBody("controlbus:route?routeId=foo&action=status&loggingLevel=WARN", null, String.class);
assertEquals("Stopped", status);
context.getRouteController().startRoute("foo");
status = template.requestBody("controlbus:route?routeId=foo&action=status&loggingLevel=WARN", null, String.class);
assertEquals("Started", status);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("seda:foo").routeId("foo").autoStartup(false).to("mock:foo");
from("seda:current").routeId("current").to("controlbus:route?routeId=current&action=status&loggingLevel=WARN")
.to("mock:current");
}
};
}
}
| ControlBusStartRouteTest |
java | grpc__grpc-java | api/src/test/java/io/grpc/ChoiceChannelCredentialsTest.java | {
"start": 887,
"end": 1913
} | class ____ {
@Test
public void withoutBearTokenGivesChoiceOfCredsWithoutToken() {
final ChannelCredentials creds1WithoutToken = mock(ChannelCredentials.class);
ChannelCredentials creds1 = new ChannelCredentials() {
@Override
public ChannelCredentials withoutBearerTokens() {
return creds1WithoutToken;
}
};
final ChannelCredentials creds2WithoutToken = mock(ChannelCredentials.class);
ChannelCredentials creds2 = new ChannelCredentials() {
@Override
public ChannelCredentials withoutBearerTokens() {
return creds2WithoutToken;
}
};
ChannelCredentials choice = ChoiceChannelCredentials.create(creds1, creds2);
ChannelCredentials choiceWithouToken = choice.withoutBearerTokens();
assertThat(choiceWithouToken).isInstanceOf(ChoiceChannelCredentials.class);
assertThat(((ChoiceChannelCredentials) choiceWithouToken).getCredentialsList())
.containsExactly(creds1WithoutToken, creds2WithoutToken);
}
}
| ChoiceChannelCredentialsTest |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java | {
"start": 6234,
"end": 6517
} | interface ____ should override anything where we have to
// get a superclass.
cost += 0.25f;
break;
}
cost++;
srcClass = srcClass.getSuperclass();
}
/*
* If the destination | match |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/where/DiscriminatorWhereTest.java | {
"start": 2412,
"end": 3141
} | class ____ {
@Id
@GeneratedValue
private Integer id;
private String name;
@OneToMany
@JoinColumn(name = "allC")
@SQLRestriction("type = 'C'")
private Set<EntityC> allMyC;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<EntityC> getAllMyC() {
return allMyC;
}
public void setAllMyC(Set<EntityC> allMyC) {
this.allMyC = allMyC;
}
}
@Entity(name = "EntityB")
@Table(name = "b_tab")
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue( value = "B")
public static | EntityA |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.